summaryrefslogtreecommitdiffstats
path: root/devtools/client/netmonitor
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 19:33:14 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 19:33:14 +0000
commit36d22d82aa202bb199967e9512281e9a53db42c9 (patch)
tree105e8c98ddea1c1e4784a60a5a6410fa416be2de /devtools/client/netmonitor
parentInitial commit. (diff)
downloadfirefox-esr-36d22d82aa202bb199967e9512281e9a53db42c9.tar.xz
firefox-esr-36d22d82aa202bb199967e9512281e9a53db42c9.zip
Adding upstream version 115.7.0esr.upstream/115.7.0esr
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'devtools/client/netmonitor')
-rw-r--r--devtools/client/netmonitor/docs/architecture.md30
-rw-r--r--devtools/client/netmonitor/index.html17
-rw-r--r--devtools/client/netmonitor/initializer.js109
-rw-r--r--devtools/client/netmonitor/moz.build19
-rw-r--r--devtools/client/netmonitor/panel.js37
-rw-r--r--devtools/client/netmonitor/src/actions/batching.js50
-rw-r--r--devtools/client/netmonitor/src/actions/filters.js58
-rw-r--r--devtools/client/netmonitor/src/actions/http-custom-request.js128
-rw-r--r--devtools/client/netmonitor/src/actions/index.js32
-rw-r--r--devtools/client/netmonitor/src/actions/messages.js188
-rw-r--r--devtools/client/netmonitor/src/actions/moz.build18
-rw-r--r--devtools/client/netmonitor/src/actions/request-blocking.js155
-rw-r--r--devtools/client/netmonitor/src/actions/requests.js183
-rw-r--r--devtools/client/netmonitor/src/actions/search.js316
-rw-r--r--devtools/client/netmonitor/src/actions/selection.js80
-rw-r--r--devtools/client/netmonitor/src/actions/sort.js20
-rw-r--r--devtools/client/netmonitor/src/actions/timing-markers.js22
-rw-r--r--devtools/client/netmonitor/src/actions/ui.js257
-rw-r--r--devtools/client/netmonitor/src/api.js216
-rw-r--r--devtools/client/netmonitor/src/app.js135
-rw-r--r--devtools/client/netmonitor/src/assets/icons/arrow-up.svg6
-rw-r--r--devtools/client/netmonitor/src/assets/icons/play.svg8
-rw-r--r--devtools/client/netmonitor/src/assets/icons/shield.svg6
-rw-r--r--devtools/client/netmonitor/src/assets/icons/turtle.svg6
-rw-r--r--devtools/client/netmonitor/src/assets/styles/CustomRequestPanel.css181
-rw-r--r--devtools/client/netmonitor/src/assets/styles/HTTPCustomRequestPanel.css379
-rw-r--r--devtools/client/netmonitor/src/assets/styles/HeadersPanel.css210
-rw-r--r--devtools/client/netmonitor/src/assets/styles/NetworkActionBar.css11
-rw-r--r--devtools/client/netmonitor/src/assets/styles/NetworkDetailsBar.css574
-rw-r--r--devtools/client/netmonitor/src/assets/styles/RequestBlockingPanel.css184
-rw-r--r--devtools/client/netmonitor/src/assets/styles/RequestList.css653
-rw-r--r--devtools/client/netmonitor/src/assets/styles/StatisticsPanel.css171
-rw-r--r--devtools/client/netmonitor/src/assets/styles/StatusBar.css62
-rw-r--r--devtools/client/netmonitor/src/assets/styles/StatusCode.css100
-rw-r--r--devtools/client/netmonitor/src/assets/styles/Toolbar.css102
-rw-r--r--devtools/client/netmonitor/src/assets/styles/UrlPreview.css100
-rw-r--r--devtools/client/netmonitor/src/assets/styles/messages.css165
-rw-r--r--devtools/client/netmonitor/src/assets/styles/netmonitor.css84
-rw-r--r--devtools/client/netmonitor/src/assets/styles/search.css155
-rw-r--r--devtools/client/netmonitor/src/assets/styles/variables.css45
-rw-r--r--devtools/client/netmonitor/src/components/App.js119
-rw-r--r--devtools/client/netmonitor/src/components/CustomRequestPanel.js371
-rw-r--r--devtools/client/netmonitor/src/components/DropHarHandler.js141
-rw-r--r--devtools/client/netmonitor/src/components/MonitorPanel.js271
-rw-r--r--devtools/client/netmonitor/src/components/NetworkActionBar.js136
-rw-r--r--devtools/client/netmonitor/src/components/SecurityState.js78
-rw-r--r--devtools/client/netmonitor/src/components/SourceEditor.js137
-rw-r--r--devtools/client/netmonitor/src/components/StatisticsPanel.js413
-rw-r--r--devtools/client/netmonitor/src/components/StatusBar.js175
-rw-r--r--devtools/client/netmonitor/src/components/StatusCode.js129
-rw-r--r--devtools/client/netmonitor/src/components/TabboxPanel.js242
-rw-r--r--devtools/client/netmonitor/src/components/Toolbar.js688
-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
-rw-r--r--devtools/client/netmonitor/src/components/moz.build28
-rw-r--r--devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js511
-rw-r--r--devtools/client/netmonitor/src/components/new-request/InputMap.js211
-rw-r--r--devtools/client/netmonitor/src/components/new-request/moz.build8
-rw-r--r--devtools/client/netmonitor/src/components/previews/FontPreview.js135
-rw-r--r--devtools/client/netmonitor/src/components/previews/HtmlPreview.js75
-rw-r--r--devtools/client/netmonitor/src/components/previews/ImagePreview.js91
-rw-r--r--devtools/client/netmonitor/src/components/previews/SourcePreview.js178
-rw-r--r--devtools/client/netmonitor/src/components/previews/UrlPreview.js290
-rw-r--r--devtools/client/netmonitor/src/components/previews/moz.build11
-rw-r--r--devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js350
-rw-r--r--devtools/client/netmonitor/src/components/request-blocking/moz.build7
-rw-r--r--devtools/client/netmonitor/src/components/request-details/CachePanel.js144
-rw-r--r--devtools/client/netmonitor/src/components/request-details/CookiesPanel.js225
-rw-r--r--devtools/client/netmonitor/src/components/request-details/HeadersPanel.js850
-rw-r--r--devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js106
-rw-r--r--devtools/client/netmonitor/src/components/request-details/PropertiesView.js247
-rw-r--r--devtools/client/netmonitor/src/components/request-details/RequestPanel.js301
-rw-r--r--devtools/client/netmonitor/src/components/request-details/ResponsePanel.js496
-rw-r--r--devtools/client/netmonitor/src/components/request-details/SecurityPanel.js283
-rw-r--r--devtools/client/netmonitor/src/components/request-details/StackTracePanel.js81
-rw-r--r--devtools/client/netmonitor/src/components/request-details/TimingsPanel.js229
-rw-r--r--devtools/client/netmonitor/src/components/request-details/moz.build16
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestList.js50
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js38
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.js61
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js66
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js91
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js65
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js33
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js36
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.js43
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.js43
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js59
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js38
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.js61
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js39
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js91
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js99
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js45
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js89
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js209
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListContent.js524
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js107
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListHeader.js731
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListItem.js412
-rw-r--r--devtools/client/netmonitor/src/components/request-list/moz.build29
-rw-r--r--devtools/client/netmonitor/src/components/search/SearchPanel.js264
-rw-r--r--devtools/client/netmonitor/src/components/search/StatusBar.js97
-rw-r--r--devtools/client/netmonitor/src/components/search/Toolbar.js160
-rw-r--r--devtools/client/netmonitor/src/components/search/moz.build10
-rw-r--r--devtools/client/netmonitor/src/components/search/search-provider.js91
-rw-r--r--devtools/client/netmonitor/src/connector/firefox-data-provider.js832
-rw-r--r--devtools/client/netmonitor/src/connector/har-metadata-collector.js97
-rw-r--r--devtools/client/netmonitor/src/connector/index.js543
-rw-r--r--devtools/client/netmonitor/src/connector/moz.build9
-rw-r--r--devtools/client/netmonitor/src/constants.js597
-rw-r--r--devtools/client/netmonitor/src/create-store.js172
-rw-r--r--devtools/client/netmonitor/src/har/README.md42
-rw-r--r--devtools/client/netmonitor/src/har/har-automation.js253
-rw-r--r--devtools/client/netmonitor/src/har/har-builder-utils.js30
-rw-r--r--devtools/client/netmonitor/src/har/har-builder.js656
-rw-r--r--devtools/client/netmonitor/src/har/har-collector.js488
-rw-r--r--devtools/client/netmonitor/src/har/har-exporter.js230
-rw-r--r--devtools/client/netmonitor/src/har/har-importer.js166
-rw-r--r--devtools/client/netmonitor/src/har/har-menu-utils.js118
-rw-r--r--devtools/client/netmonitor/src/har/har-utils.js167
-rw-r--r--devtools/client/netmonitor/src/har/moz.build19
-rw-r--r--devtools/client/netmonitor/src/har/test/browser-harautomation.ini16
-rw-r--r--devtools/client/netmonitor/src/har/test/browser.ini29
-rw-r--r--devtools/client/netmonitor/src/har/test/browser_harautomation_simple.js35
-rw-r--r--devtools/client/netmonitor/src/har/test/browser_net_har_copy_all_as_har.js220
-rw-r--r--devtools/client/netmonitor/src/har/test/browser_net_har_import.js149
-rw-r--r--devtools/client/netmonitor/src/har/test/browser_net_har_import_no-mime.js78
-rw-r--r--devtools/client/netmonitor/src/har/test/browser_net_har_multipage.js153
-rw-r--r--devtools/client/netmonitor/src/har/test/browser_net_har_post_data.js51
-rw-r--r--devtools/client/netmonitor/src/har/test/browser_net_har_post_data_on_get.js43
-rw-r--r--devtools/client/netmonitor/src/har/test/browser_net_har_throttle_upload.js69
-rw-r--r--devtools/client/netmonitor/src/har/test/head.js45
-rw-r--r--devtools/client/netmonitor/src/har/test/html_har_import-test-page.html51
-rw-r--r--devtools/client/netmonitor/src/har/test/html_har_multipage_iframe.html24
-rw-r--r--devtools/client/netmonitor/src/har/test/html_har_multipage_page.html30
-rw-r--r--devtools/client/netmonitor/src/har/test/html_har_post-data-test-page.html55
-rw-r--r--devtools/client/netmonitor/src/har/test/sjs_cache-test-server.sjs14
-rw-r--r--devtools/client/netmonitor/src/har/test/sjs_cookies-test-server.sjs10
-rw-r--r--devtools/client/netmonitor/src/middleware/batching.js146
-rw-r--r--devtools/client/netmonitor/src/middleware/event-telemetry.js192
-rw-r--r--devtools/client/netmonitor/src/middleware/moz.build11
-rw-r--r--devtools/client/netmonitor/src/middleware/prefs.js116
-rw-r--r--devtools/client/netmonitor/src/middleware/request-blocking.js58
-rw-r--r--devtools/client/netmonitor/src/middleware/throttling.js26
-rw-r--r--devtools/client/netmonitor/src/moz.build23
-rw-r--r--devtools/client/netmonitor/src/reducers/batching.js27
-rw-r--r--devtools/client/netmonitor/src/reducers/filters.js102
-rw-r--r--devtools/client/netmonitor/src/reducers/index.js47
-rw-r--r--devtools/client/netmonitor/src/reducers/messages.js335
-rw-r--r--devtools/client/netmonitor/src/reducers/moz.build16
-rw-r--r--devtools/client/netmonitor/src/reducers/request-blocking.js187
-rw-r--r--devtools/client/netmonitor/src/reducers/requests.js313
-rw-r--r--devtools/client/netmonitor/src/reducers/search.js118
-rw-r--r--devtools/client/netmonitor/src/reducers/sort.js48
-rw-r--r--devtools/client/netmonitor/src/reducers/timing-markers.js78
-rw-r--r--devtools/client/netmonitor/src/reducers/ui.js260
-rw-r--r--devtools/client/netmonitor/src/selectors/index.js13
-rw-r--r--devtools/client/netmonitor/src/selectors/messages.js162
-rw-r--r--devtools/client/netmonitor/src/selectors/moz.build12
-rw-r--r--devtools/client/netmonitor/src/selectors/requests.js198
-rw-r--r--devtools/client/netmonitor/src/selectors/search.js33
-rw-r--r--devtools/client/netmonitor/src/selectors/timing-markers.js18
-rw-r--r--devtools/client/netmonitor/src/selectors/ui.js81
-rw-r--r--devtools/client/netmonitor/src/utils/context-menu-utils.js32
-rw-r--r--devtools/client/netmonitor/src/utils/doc-utils.js224
-rw-r--r--devtools/client/netmonitor/src/utils/filter-autocomplete-provider.js209
-rw-r--r--devtools/client/netmonitor/src/utils/filter-predicates.js137
-rw-r--r--devtools/client/netmonitor/src/utils/filter-text-utils.js291
-rw-r--r--devtools/client/netmonitor/src/utils/firefox/moz.build8
-rw-r--r--devtools/client/netmonitor/src/utils/firefox/open-request-in-tab.js67
-rw-r--r--devtools/client/netmonitor/src/utils/format-utils.js132
-rw-r--r--devtools/client/netmonitor/src/utils/headers-provider.js90
-rw-r--r--devtools/client/netmonitor/src/utils/l10n.js11
-rw-r--r--devtools/client/netmonitor/src/utils/moz.build27
-rw-r--r--devtools/client/netmonitor/src/utils/open-request-in-tab.js63
-rw-r--r--devtools/client/netmonitor/src/utils/powershell.js142
-rw-r--r--devtools/client/netmonitor/src/utils/prefs.js18
-rw-r--r--devtools/client/netmonitor/src/utils/request-blocking.js13
-rw-r--r--devtools/client/netmonitor/src/utils/request-utils.js769
-rw-r--r--devtools/client/netmonitor/src/utils/sort-predicates.js319
-rw-r--r--devtools/client/netmonitor/src/utils/sort-utils.js42
-rw-r--r--devtools/client/netmonitor/src/utils/tooltips.js18
-rw-r--r--devtools/client/netmonitor/src/widgets/HeadersPanelContextMenu.js137
-rw-r--r--devtools/client/netmonitor/src/widgets/PropertiesViewContextMenu.js113
-rw-r--r--devtools/client/netmonitor/src/widgets/RequestBlockingContextMenu.js78
-rw-r--r--devtools/client/netmonitor/src/widgets/RequestListContextMenu.js793
-rw-r--r--devtools/client/netmonitor/src/widgets/RequestListHeaderContextMenu.js105
-rw-r--r--devtools/client/netmonitor/src/widgets/WaterfallBackground.js163
-rw-r--r--devtools/client/netmonitor/src/widgets/moz.build12
-rw-r--r--devtools/client/netmonitor/src/workers/moz.build8
-rw-r--r--devtools/client/netmonitor/src/workers/search/index.js25
-rw-r--r--devtools/client/netmonitor/src/workers/search/moz.build10
-rw-r--r--devtools/client/netmonitor/src/workers/search/search.js349
-rw-r--r--devtools/client/netmonitor/src/workers/search/worker.js17
-rw-r--r--devtools/client/netmonitor/test/.eslintrc.js7
-rw-r--r--devtools/client/netmonitor/test/OstrichLicense.txt41
-rw-r--r--devtools/client/netmonitor/test/browser.ini330
-rw-r--r--devtools/client/netmonitor/test/browser_http3.ini11
-rw-r--r--devtools/client/netmonitor/test/browser_net-ws-filter-freetext.js93
-rw-r--r--devtools/client/netmonitor/test/browser_net_accessibility-01.js87
-rw-r--r--devtools/client/netmonitor/test/browser_net_accessibility-02.js137
-rw-r--r--devtools/client/netmonitor/test/browser_net_api-calls.js47
-rw-r--r--devtools/client/netmonitor/test/browser_net_autoscroll.js114
-rw-r--r--devtools/client/netmonitor/test/browser_net_background_update.js57
-rw-r--r--devtools/client/netmonitor/test/browser_net_basic-search.js68
-rw-r--r--devtools/client/netmonitor/test/browser_net_block-context.js135
-rw-r--r--devtools/client/netmonitor/test/browser_net_block-csp.js111
-rw-r--r--devtools/client/netmonitor/test/browser_net_block-draganddrop.js159
-rw-r--r--devtools/client/netmonitor/test/browser_net_block-extensions.js103
-rw-r--r--devtools/client/netmonitor/test/browser_net_block-pattern.js106
-rw-r--r--devtools/client/netmonitor/test/browser_net_block-serviceworker.js58
-rw-r--r--devtools/client/netmonitor/test/browser_net_block.js169
-rw-r--r--devtools/client/netmonitor/test/browser_net_brotli.js81
-rw-r--r--devtools/client/netmonitor/test/browser_net_cache_details.js102
-rw-r--r--devtools/client/netmonitor/test/browser_net_cached-status.js130
-rw-r--r--devtools/client/netmonitor/test/browser_net_cause_redirect.js80
-rw-r--r--devtools/client/netmonitor/test/browser_net_cause_source_map.js60
-rw-r--r--devtools/client/netmonitor/test/browser_net_charts-01.js153
-rw-r--r--devtools/client/netmonitor/test/browser_net_charts-02.js72
-rw-r--r--devtools/client/netmonitor/test/browser_net_charts-03.js195
-rw-r--r--devtools/client/netmonitor/test/browser_net_charts-04.js117
-rw-r--r--devtools/client/netmonitor/test/browser_net_charts-05.js94
-rw-r--r--devtools/client/netmonitor/test/browser_net_charts-06.js62
-rw-r--r--devtools/client/netmonitor/test/browser_net_charts-07.js97
-rw-r--r--devtools/client/netmonitor/test/browser_net_clear.js145
-rw-r--r--devtools/client/netmonitor/test/browser_net_column-resize-fit.js95
-rw-r--r--devtools/client/netmonitor/test/browser_net_column_headers_tooltips.js30
-rw-r--r--devtools/client/netmonitor/test/browser_net_column_slow-request-indicator.js69
-rw-r--r--devtools/client/netmonitor/test/browser_net_columns_last_column.js64
-rw-r--r--devtools/client/netmonitor/test/browser_net_columns_pref.js59
-rw-r--r--devtools/client/netmonitor/test/browser_net_columns_reset.js43
-rw-r--r--devtools/client/netmonitor/test/browser_net_columns_showhide.js181
-rw-r--r--devtools/client/netmonitor/test/browser_net_columns_time.js61
-rw-r--r--devtools/client/netmonitor/test/browser_net_complex-params.js310
-rw-r--r--devtools/client/netmonitor/test/browser_net_content-type.js358
-rw-r--r--devtools/client/netmonitor/test/browser_net_cookies_sorted.js85
-rw-r--r--devtools/client/netmonitor/test/browser_net_copy_as_curl.js242
-rw-r--r--devtools/client/netmonitor/test/browser_net_copy_as_fetch.js92
-rw-r--r--devtools/client/netmonitor/test/browser_net_copy_as_powershell.js167
-rw-r--r--devtools/client/netmonitor/test/browser_net_copy_headers.js105
-rw-r--r--devtools/client/netmonitor/test/browser_net_copy_image_as_data_uri.js41
-rw-r--r--devtools/client/netmonitor/test/browser_net_copy_params.js167
-rw-r--r--devtools/client/netmonitor/test/browser_net_copy_response.js38
-rw-r--r--devtools/client/netmonitor/test/browser_net_copy_svg_image_as_data_uri.js48
-rw-r--r--devtools/client/netmonitor/test/browser_net_copy_url.js50
-rw-r--r--devtools/client/netmonitor/test/browser_net_cors_requests.js54
-rw-r--r--devtools/client/netmonitor/test/browser_net_curl-utils.js385
-rw-r--r--devtools/client/netmonitor/test/browser_net_cyrillic-01.js64
-rw-r--r--devtools/client/netmonitor/test/browser_net_cyrillic-02.js76
-rw-r--r--devtools/client/netmonitor/test/browser_net_decode-params.js35
-rw-r--r--devtools/client/netmonitor/test/browser_net_decode-url.js42
-rw-r--r--devtools/client/netmonitor/test/browser_net_details_copy.js295
-rw-r--r--devtools/client/netmonitor/test/browser_net_domain-not-found.js41
-rw-r--r--devtools/client/netmonitor/test/browser_net_edit_resend_cancel.js68
-rw-r--r--devtools/client/netmonitor/test/browser_net_edit_resend_caret.js102
-rw-r--r--devtools/client/netmonitor/test/browser_net_edit_resend_with_filtering.js153
-rw-r--r--devtools/client/netmonitor/test/browser_net_edit_resend_xhr.js135
-rw-r--r--devtools/client/netmonitor/test/browser_net_error-boundary-01.js31
-rw-r--r--devtools/client/netmonitor/test/browser_net_filter-01.js558
-rw-r--r--devtools/client/netmonitor/test/browser_net_filter-02.js307
-rw-r--r--devtools/client/netmonitor/test/browser_net_filter-03.js163
-rw-r--r--devtools/client/netmonitor/test/browser_net_filter-04.js80
-rw-r--r--devtools/client/netmonitor/test/browser_net_filter-autocomplete.js207
-rw-r--r--devtools/client/netmonitor/test/browser_net_filter-flags.js435
-rw-r--r--devtools/client/netmonitor/test/browser_net_filter-sts-search.js59
-rw-r--r--devtools/client/netmonitor/test/browser_net_filter-value-preserved.js55
-rw-r--r--devtools/client/netmonitor/test/browser_net_fission_switch_target.js54
-rw-r--r--devtools/client/netmonitor/test/browser_net_fonts.js84
-rw-r--r--devtools/client/netmonitor/test/browser_net_footer-summary.js114
-rw-r--r--devtools/client/netmonitor/test/browser_net_frame.js272
-rw-r--r--devtools/client/netmonitor/test/browser_net_header-docs.js74
-rw-r--r--devtools/client/netmonitor/test/browser_net_header-ref-policy.js62
-rw-r--r--devtools/client/netmonitor/test/browser_net_header-request-priority.js43
-rw-r--r--devtools/client/netmonitor/test/browser_net_headers-alignment.js65
-rw-r--r--devtools/client/netmonitor/test/browser_net_headers-link_clickable.js44
-rw-r--r--devtools/client/netmonitor/test/browser_net_headers-resize.js279
-rw-r--r--devtools/client/netmonitor/test/browser_net_headers_filter.js80
-rw-r--r--devtools/client/netmonitor/test/browser_net_headers_sorted.js194
-rw-r--r--devtools/client/netmonitor/test/browser_net_html-preview.js176
-rw-r--r--devtools/client/netmonitor/test/browser_net_http3_request_details.js153
-rw-r--r--devtools/client/netmonitor/test/browser_net_image-tooltip.js117
-rw-r--r--devtools/client/netmonitor/test/browser_net_image_cache.js76
-rw-r--r--devtools/client/netmonitor/test/browser_net_initiator.js291
-rw-r--r--devtools/client/netmonitor/test/browser_net_internal-stylesheet.js37
-rw-r--r--devtools/client/netmonitor/test/browser_net_json-b64.js103
-rw-r--r--devtools/client/netmonitor/test/browser_net_json-empty.js79
-rw-r--r--devtools/client/netmonitor/test/browser_net_json-long.js174
-rw-r--r--devtools/client/netmonitor/test/browser_net_json-malformed.js97
-rw-r--r--devtools/client/netmonitor/test/browser_net_json-nogrip.js51
-rw-r--r--devtools/client/netmonitor/test/browser_net_json-null.js114
-rw-r--r--devtools/client/netmonitor/test/browser_net_json-xssi-protection.js96
-rw-r--r--devtools/client/netmonitor/test/browser_net_json_custom_mime.js133
-rw-r--r--devtools/client/netmonitor/test/browser_net_json_text_mime.js136
-rw-r--r--devtools/client/netmonitor/test/browser_net_jsonp.js179
-rw-r--r--devtools/client/netmonitor/test/browser_net_large-response.js92
-rw-r--r--devtools/client/netmonitor/test/browser_net_leak_on_tab_close.js20
-rw-r--r--devtools/client/netmonitor/test/browser_net_new_request_panel.js98
-rw-r--r--devtools/client/netmonitor/test/browser_net_new_request_panel_clear_button.js87
-rw-r--r--devtools/client/netmonitor/test/browser_net_new_request_panel_content-length.js94
-rw-r--r--devtools/client/netmonitor/test/browser_net_new_request_panel_context_menu.js208
-rw-r--r--devtools/client/netmonitor/test/browser_net_new_request_panel_persisted_content.js149
-rw-r--r--devtools/client/netmonitor/test/browser_net_new_request_panel_send_request.js166
-rw-r--r--devtools/client/netmonitor/test/browser_net_new_request_panel_sync_url_params.js194
-rw-r--r--devtools/client/netmonitor/test/browser_net_open_in_debugger.js40
-rw-r--r--devtools/client/netmonitor/test/browser_net_open_in_style_editor.js44
-rw-r--r--devtools/client/netmonitor/test/browser_net_open_request_in_tab.js264
-rw-r--r--devtools/client/netmonitor/test/browser_net_pane-collapse.js68
-rw-r--r--devtools/client/netmonitor/test/browser_net_pane-network-details.js149
-rw-r--r--devtools/client/netmonitor/test/browser_net_pane-toggle.js107
-rw-r--r--devtools/client/netmonitor/test/browser_net_params_sorted.js83
-rw-r--r--devtools/client/netmonitor/test/browser_net_pause.js151
-rw-r--r--devtools/client/netmonitor/test/browser_net_persistent_logs.js77
-rw-r--r--devtools/client/netmonitor/test/browser_net_post-data-json-payloads.js105
-rw-r--r--devtools/client/netmonitor/test/browser_net_post-data-raw-payloads-with-upload-stream-headers.js202
-rw-r--r--devtools/client/netmonitor/test/browser_net_post-data-raw-payloads.js89
-rw-r--r--devtools/client/netmonitor/test/browser_net_post-data.js195
-rw-r--r--devtools/client/netmonitor/test/browser_net_prefs-and-l10n.js78
-rw-r--r--devtools/client/netmonitor/test/browser_net_prefs-reload.js327
-rw-r--r--devtools/client/netmonitor/test/browser_net_raw_headers.js132
-rw-r--r--devtools/client/netmonitor/test/browser_net_reload-button.js30
-rw-r--r--devtools/client/netmonitor/test/browser_net_reload-markers.js34
-rw-r--r--devtools/client/netmonitor/test/browser_net_req-resp-bodies.js83
-rw-r--r--devtools/client/netmonitor/test/browser_net_resend.js385
-rw-r--r--devtools/client/netmonitor/test/browser_net_resend_cors.js132
-rw-r--r--devtools/client/netmonitor/test/browser_net_resend_csp.js153
-rw-r--r--devtools/client/netmonitor/test/browser_net_resend_headers.js89
-rw-r--r--devtools/client/netmonitor/test/browser_net_resend_hidden_headers.js88
-rw-r--r--devtools/client/netmonitor/test/browser_net_resend_xhr.js57
-rw-r--r--devtools/client/netmonitor/test/browser_net_response_CORS_blocked.js117
-rw-r--r--devtools/client/netmonitor/test/browser_net_response_node-expanded.js57
-rw-r--r--devtools/client/netmonitor/test/browser_net_search-results.js233
-rw-r--r--devtools/client/netmonitor/test/browser_net_security-details.js116
-rw-r--r--devtools/client/netmonitor/test/browser_net_security-error.js38
-rw-r--r--devtools/client/netmonitor/test/browser_net_security-icon-click.js75
-rw-r--r--devtools/client/netmonitor/test/browser_net_security-redirect.js67
-rw-r--r--devtools/client/netmonitor/test/browser_net_security-state.js109
-rw-r--r--devtools/client/netmonitor/test/browser_net_security-tab-deselect.js67
-rw-r--r--devtools/client/netmonitor/test/browser_net_security-tab-visibility.js142
-rw-r--r--devtools/client/netmonitor/test/browser_net_security-warnings.js66
-rw-r--r--devtools/client/netmonitor/test/browser_net_send-beacon-other-tab.js49
-rw-r--r--devtools/client/netmonitor/test/browser_net_send-beacon.js44
-rw-r--r--devtools/client/netmonitor/test/browser_net_server_timings.js74
-rw-r--r--devtools/client/netmonitor/test/browser_net_service-worker-status.js112
-rw-r--r--devtools/client/netmonitor/test/browser_net_set-cookie-same-site.js85
-rw-r--r--devtools/client/netmonitor/test/browser_net_simple-request-data.js488
-rw-r--r--devtools/client/netmonitor/test/browser_net_simple-request-details.js388
-rw-r--r--devtools/client/netmonitor/test/browser_net_simple-request.js99
-rw-r--r--devtools/client/netmonitor/test/browser_net_sort-01.js316
-rw-r--r--devtools/client/netmonitor/test/browser_net_sort-02.js460
-rw-r--r--devtools/client/netmonitor/test/browser_net_sort-reset.js284
-rw-r--r--devtools/client/netmonitor/test/browser_net_sse-basic.js119
-rw-r--r--devtools/client/netmonitor/test/browser_net_stacktraces-visibility.js86
-rw-r--r--devtools/client/netmonitor/test/browser_net_statistics-01.js65
-rw-r--r--devtools/client/netmonitor/test/browser_net_statistics-02.js74
-rw-r--r--devtools/client/netmonitor/test/browser_net_statistics-edge-case.js112
-rw-r--r--devtools/client/netmonitor/test/browser_net_status-bar-transferred-size.js77
-rw-r--r--devtools/client/netmonitor/test/browser_net_status-bar.js60
-rw-r--r--devtools/client/netmonitor/test/browser_net_status-codes.js213
-rw-r--r--devtools/client/netmonitor/test/browser_net_streaming-response.js89
-rw-r--r--devtools/client/netmonitor/test/browser_net_tabbar_focus.js90
-rw-r--r--devtools/client/netmonitor/test/browser_net_telemetry_edit_resend.js71
-rw-r--r--devtools/client/netmonitor/test/browser_net_telemetry_filters_changed.js100
-rw-r--r--devtools/client/netmonitor/test/browser_net_telemetry_persist_toggle_changed.js81
-rw-r--r--devtools/client/netmonitor/test/browser_net_telemetry_select_ws_frame.js83
-rw-r--r--devtools/client/netmonitor/test/browser_net_telemetry_sidepanel_changed.js61
-rw-r--r--devtools/client/netmonitor/test/browser_net_telemetry_throttle_changed.js50
-rw-r--r--devtools/client/netmonitor/test/browser_net_throttle.js60
-rw-r--r--devtools/client/netmonitor/test/browser_net_throttling_profiles.js67
-rw-r--r--devtools/client/netmonitor/test/browser_net_timeline_ticks.js208
-rw-r--r--devtools/client/netmonitor/test/browser_net_timing-division.js67
-rw-r--r--devtools/client/netmonitor/test/browser_net_tracking-resources.js50
-rw-r--r--devtools/client/netmonitor/test/browser_net_truncate-post-data.js78
-rw-r--r--devtools/client/netmonitor/test/browser_net_truncate.js59
-rw-r--r--devtools/client/netmonitor/test/browser_net_url-preview.js203
-rw-r--r--devtools/client/netmonitor/test/browser_net_use_as_fetch.js85
-rw-r--r--devtools/client/netmonitor/test/browser_net_view-source-debugger.js80
-rw-r--r--devtools/client/netmonitor/test/browser_net_waterfall-click.js36
-rw-r--r--devtools/client/netmonitor/test/browser_net_websocket_stacks.js94
-rw-r--r--devtools/client/netmonitor/test/browser_net_worker_stacks.js119
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-basic.js79
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-clear.js84
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-connection-closed.js54
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-early-connection.js62
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-filter-dropdown.js136
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-filter-regex.js76
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-json-action-cable-payload.js109
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-json-payload.js112
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-json-stomp-payload.js115
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-keep-future-frames.js87
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-limit-frames.js63
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-limit-payload.js80
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-messages-navigation.js106
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-sockjs-stomp-payload.js115
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-sse-persist-columns.js268
-rw-r--r--devtools/client/netmonitor/test/browser_net_ws-stomp-payload.js115
-rw-r--r--devtools/client/netmonitor/test/dropmarker.svg6
-rw-r--r--devtools/client/netmonitor/test/file_ws_backend_wsh.py13
-rw-r--r--devtools/client/netmonitor/test/head.js1493
-rw-r--r--devtools/client/netmonitor/test/html_api-calls-test-page.html45
-rw-r--r--devtools/client/netmonitor/test/html_brotli-test-page.html41
-rw-r--r--devtools/client/netmonitor/test/html_cache-test-page.html28
-rw-r--r--devtools/client/netmonitor/test/html_cause-test-page.html98
-rw-r--r--devtools/client/netmonitor/test/html_content-type-without-cache-test-page.html47
-rw-r--r--devtools/client/netmonitor/test/html_copy-as-curl.html33
-rw-r--r--devtools/client/netmonitor/test/html_cors-test-page.html34
-rw-r--r--devtools/client/netmonitor/test/html_csp-frame-test-page.html9
-rw-r--r--devtools/client/netmonitor/test/html_csp-resend-test-page.html25
-rw-r--r--devtools/client/netmonitor/test/html_csp-test-page.html18
-rw-r--r--devtools/client/netmonitor/test/html_curl-utils.html136
-rw-r--r--devtools/client/netmonitor/test/html_custom-get-page.html48
-rw-r--r--devtools/client/netmonitor/test/html_cyrillic-test-page.html42
-rw-r--r--devtools/client/netmonitor/test/html_filter-test-page.html58
-rw-r--r--devtools/client/netmonitor/test/html_fonts-test-page.html45
-rw-r--r--devtools/client/netmonitor/test/html_frame-subdocument.html50
-rw-r--r--devtools/client/netmonitor/test/html_frame-test-page.html51
-rw-r--r--devtools/client/netmonitor/test/html_header-test-page.html43
-rw-r--r--devtools/client/netmonitor/test/html_image-cache.html7
-rw-r--r--devtools/client/netmonitor/test/html_image-tooltip-test-page.html29
-rw-r--r--devtools/client/netmonitor/test/html_infinite-get-page.html50
-rw-r--r--devtools/client/netmonitor/test/html_internal-stylesheet.html15
-rw-r--r--devtools/client/netmonitor/test/html_json-b64.html41
-rw-r--r--devtools/client/netmonitor/test/html_json-basic.html43
-rw-r--r--devtools/client/netmonitor/test/html_json-custom-mime-test-page.html41
-rw-r--r--devtools/client/netmonitor/test/html_json-empty.html42
-rw-r--r--devtools/client/netmonitor/test/html_json-long-test-page.html41
-rw-r--r--devtools/client/netmonitor/test/html_json-malformed-test-page.html41
-rw-r--r--devtools/client/netmonitor/test/html_json-text-mime-test-page.html41
-rw-r--r--devtools/client/netmonitor/test/html_json-xssi-protection.html42
-rw-r--r--devtools/client/netmonitor/test/html_jsonp-test-page.html42
-rw-r--r--devtools/client/netmonitor/test/html_maps-test-page.html24
-rw-r--r--devtools/client/netmonitor/test/html_navigate-test-page.html18
-rw-r--r--devtools/client/netmonitor/test/html_open-request-in-tab.html33
-rw-r--r--devtools/client/netmonitor/test/html_params-test-page.html78
-rw-r--r--devtools/client/netmonitor/test/html_pause-test-page.html36
-rw-r--r--devtools/client/netmonitor/test/html_post-array-data-test-page.html34
-rw-r--r--devtools/client/netmonitor/test/html_post-data-test-page.html82
-rw-r--r--devtools/client/netmonitor/test/html_post-json-test-page.html48
-rw-r--r--devtools/client/netmonitor/test/html_post-raw-test-page.html43
-rw-r--r--devtools/client/netmonitor/test/html_post-raw-with-headers-test-page.html67
-rw-r--r--devtools/client/netmonitor/test/html_send-beacon.html26
-rw-r--r--devtools/client/netmonitor/test/html_simple-test-page.html18
-rw-r--r--devtools/client/netmonitor/test/html_single-get-page.html40
-rw-r--r--devtools/client/netmonitor/test/html_slow-requests-test-page.html15
-rw-r--r--devtools/client/netmonitor/test/html_sorting-test-page.html18
-rw-r--r--devtools/client/netmonitor/test/html_sse-test-page.html31
-rw-r--r--devtools/client/netmonitor/test/html_statistics-edge-case-page.html23
-rw-r--r--devtools/client/netmonitor/test/html_statistics-test-page.html42
-rw-r--r--devtools/client/netmonitor/test/html_status-codes-test-page.html55
-rw-r--r--devtools/client/netmonitor/test/html_tracking-protection.html21
-rw-r--r--devtools/client/netmonitor/test/html_websocket-test-page.html10
-rw-r--r--devtools/client/netmonitor/test/html_worker-test-page.html13
-rw-r--r--devtools/client/netmonitor/test/html_ws-early-connection-page.html24
-rw-r--r--devtools/client/netmonitor/test/html_ws-sse-test-page.html59
-rw-r--r--devtools/client/netmonitor/test/html_ws-test-page.html56
-rw-r--r--devtools/client/netmonitor/test/js_websocket-worker-test.js6
-rw-r--r--devtools/client/netmonitor/test/js_worker-test.js30
-rw-r--r--devtools/client/netmonitor/test/js_worker-test2.js3
-rw-r--r--devtools/client/netmonitor/test/node/jest.config.js12
-rw-r--r--devtools/client/netmonitor/test/node/package.json15
-rw-r--r--devtools/client/netmonitor/test/node/reducers/sort.spec.js28
-rw-r--r--devtools/client/netmonitor/test/node/yarn.lock3553
-rw-r--r--devtools/client/netmonitor/test/ostrich-black.ttfbin0 -> 12872 bytes
-rw-r--r--devtools/client/netmonitor/test/ostrich-regular.ttfbin0 -> 12476 bytes
-rw-r--r--devtools/client/netmonitor/test/service-workers/status-codes-service-worker.js16
-rw-r--r--devtools/client/netmonitor/test/service-workers/status-codes.html62
-rw-r--r--devtools/client/netmonitor/test/sjs_content-type-test-server.sjs421
-rw-r--r--devtools/client/netmonitor/test/sjs_cors-test-server.sjs18
-rw-r--r--devtools/client/netmonitor/test/sjs_hsts-test-server.sjs23
-rw-r--r--devtools/client/netmonitor/test/sjs_https-redirect-test-server.sjs19
-rw-r--r--devtools/client/netmonitor/test/sjs_json-test-server.sjs28
-rw-r--r--devtools/client/netmonitor/test/sjs_long-polling-server.sjs35
-rw-r--r--devtools/client/netmonitor/test/sjs_method-test-server.sjs35
-rw-r--r--devtools/client/netmonitor/test/sjs_search-test-server.sjs10
-rw-r--r--devtools/client/netmonitor/test/sjs_set-cookie-same-site.sjs11
-rw-r--r--devtools/client/netmonitor/test/sjs_simple-test-server.sjs22
-rw-r--r--devtools/client/netmonitor/test/sjs_simple-unsorted-cookies-test-server.sjs20
-rw-r--r--devtools/client/netmonitor/test/sjs_slow-script-server.sjs18
-rw-r--r--devtools/client/netmonitor/test/sjs_slow-test-server.sjs20
-rw-r--r--devtools/client/netmonitor/test/sjs_sorting-test-server.sjs36
-rw-r--r--devtools/client/netmonitor/test/sjs_sse-test-server.sjs7
-rw-r--r--devtools/client/netmonitor/test/sjs_status-codes-test-server.sjs71
-rw-r--r--devtools/client/netmonitor/test/sjs_timings-test-server.sjs45
-rw-r--r--devtools/client/netmonitor/test/sjs_truncate-test-server.sjs21
-rw-r--r--devtools/client/netmonitor/test/test-image.pngbin0 -> 580 bytes
-rw-r--r--devtools/client/netmonitor/test/xhr_bundle.js91
-rw-r--r--devtools/client/netmonitor/test/xhr_bundle.js.map1
-rw-r--r--devtools/client/netmonitor/test/xhr_original.js13
-rw-r--r--devtools/client/netmonitor/test/xpcshell/.eslintrc.js6
-rw-r--r--devtools/client/netmonitor/test/xpcshell/test_doc-utils.js62
-rw-r--r--devtools/client/netmonitor/test/xpcshell/test_request-utils-fetchNetworkUpdatePacket.js54
-rw-r--r--devtools/client/netmonitor/test/xpcshell/test_request-utils-js-getFormattedProtocol.js235
-rw-r--r--devtools/client/netmonitor/test/xpcshell/test_request-utils-parseJSON.js78
-rw-r--r--devtools/client/netmonitor/test/xpcshell/xpcshell.ini10
538 files changed, 67027 insertions, 0 deletions
diff --git a/devtools/client/netmonitor/docs/architecture.md b/devtools/client/netmonitor/docs/architecture.md
new file mode 100644
index 0000000000..e625168982
--- /dev/null
+++ b/devtools/client/netmonitor/docs/architecture.md
@@ -0,0 +1,30 @@
+# Network Monitor
+
+The Network Monitor (netmonitor) shows you all the network requests Firefox makes (for example, when a page is loaded or when an XMLHttpRequest is performed) , how long each request takes, and details of each request. You can edit the method, query, header and resend the request as well. Read [more](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/) to learn all the features and how to use the tool.
+
+## UI
+
+The Network Monitor UI is built using [React](http://searchfox.org/mozilla-central/source/devtools/docs/frontend/react.md) components (in `src/components/`).
+
+* **MonitorPanel** in `MonitorPanel.js` is the root element.
+* Three major container components are
+ - **Toolbar** Panel related functions.
+ - **RequestList** Show each request information.
+ - **NetworkDetailsBar** Show detailed information per request.
+ - **StatusBar** Show statistics while loading.
+* `src/assets` Styles that affect the Network Monitor panel.
+
+We prefer stateless component (define by function) instead of stateful component (define by class) unless the component has to maintain its internal state.
+
+## State
+
+![](https://hacks.mozilla.org/files/2017/06/image8.png)
+
+Besides the UI, the Network Monitor manages the app state via [Redux](http://searchfox.org/mozilla-central/source/devtools/docs/frontend/redux.md). The following locations define the app state:
+
+* `src/constants.js` constants used across the tool including action and event names.
+* `src/actions/` for all actions that change the state.
+* `src/reducers/` for all reducers that change the state.
+* `src/selectors/` functions that return a formatted version of parts of the app state.
+
+We use [reselect](https://github.com/reactjs/reselect) library to perform state calculations efficiently.
diff --git a/devtools/client/netmonitor/index.html b/devtools/client/netmonitor/index.html
new file mode 100644
index 0000000000..2ccd9973f7
--- /dev/null
+++ b/devtools/client/netmonitor/index.html
@@ -0,0 +1,17 @@
+<!-- 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/. -->
+<!DOCTYPE html>
+<html dir="">
+ <head>
+ <link
+ rel="stylesheet"
+ href="chrome://devtools/content/netmonitor/src/assets/styles/netmonitor.css"
+ />
+ <script src="chrome://devtools/content/shared/theme-switching.js"></script>
+ </head>
+ <body class="theme-body" role="application">
+ <div id="mount"></div>
+ <script src="resource://devtools/client/netmonitor/initializer.js"></script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/initializer.js b/devtools/client/netmonitor/initializer.js
new file mode 100644
index 0000000000..c6a8a246f5
--- /dev/null
+++ b/devtools/client/netmonitor/initializer.js
@@ -0,0 +1,109 @@
+/* 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/. */
+/* exported initialize */
+
+"use strict";
+
+/**
+ * This script is the entry point of Network monitor panel.
+ * See README.md for more information.
+ */
+const { BrowserLoader } = ChromeUtils.import(
+ "resource://devtools/shared/loader/browser-loader.js"
+);
+
+const require = (window.windowRequire = BrowserLoader({
+ baseURI: "resource://devtools/client/netmonitor/",
+ window,
+}).require);
+
+const {
+ NetMonitorAPI,
+} = require("resource://devtools/client/netmonitor/src/api.js");
+const {
+ NetMonitorApp,
+} = require("resource://devtools/client/netmonitor/src/app.js");
+const EventEmitter = require("resource://devtools/shared/event-emitter.js");
+
+// Inject EventEmitter into global window.
+EventEmitter.decorate(window);
+
+/**
+ * This is the initialization point for the Network monitor.
+ *
+ * @param {Object} api Allows reusing existing API object.
+ */
+function initialize(api) {
+ const app = new NetMonitorApp(api);
+
+ // Inject to global window for testing
+ window.Netmonitor = app;
+ window.api = api;
+ window.store = app.api.store;
+ window.connector = app.api.connector;
+ window.actions = app.api.actions;
+
+ return app;
+}
+
+/**
+ * The following code is used to open Network monitor in a tab.
+ * Like the Launchpad, but without Launchpad.
+ *
+ * For example:
+ * chrome://devtools/content/netmonitor/index.html?type=process
+ * loads the netmonitor for the parent process, exactly like the
+ * one in the browser toolbox
+ *
+ * It's also possible to connect to a tab.
+ * 1) go in about:debugging
+ * 2) In menu Tabs, click on a Debug button for particular tab
+ *
+ * This will open an about:devtools-toolbox url, from which you can
+ * take type and id query parameters and reuse them for the chrome url
+ * of the netmonitor
+ *
+ * chrome://devtools/content/netmonitor/index.html?type=tab&id=1234 URLs
+ * where 1234 is the tab id, you can retrieve from about:debugging#tabs links.
+ * Simply copy the id from about:devtools-toolbox?type=tab&id=1234 URLs.
+ */
+
+// URL constructor doesn't support chrome: scheme
+const href = window.location.href.replace(/chrome:/, "http://");
+const url = new window.URL(href);
+
+// If query parameters are given in a chrome tab, the inspector
+// is running in standalone.
+if (window.location.protocol === "chrome:" && url.search.length > 1) {
+ const {
+ commandsFromURL,
+ } = require("resource://devtools/client/framework/commands-from-url.js");
+
+ (async function () {
+ try {
+ const commands = await commandsFromURL(url);
+ const target = await commands.descriptorFront.getTarget();
+ // Create a fake toolbox object
+ const toolbox = {
+ target,
+ viewSourceInDebugger() {
+ throw new Error(
+ "toolbox.viewSourceInDebugger is not implement from a tab"
+ );
+ },
+ commands,
+ };
+
+ const api = new NetMonitorAPI();
+ await api.connect(toolbox);
+ const app = window.initialize(api);
+ app.bootstrap({
+ toolbox,
+ document: window.document,
+ });
+ } catch (err) {
+ window.alert("Unable to start the network monitor:" + err);
+ }
+ })();
+}
diff --git a/devtools/client/netmonitor/moz.build b/devtools/client/netmonitor/moz.build
new file mode 100644
index 0000000000..949c84c0ce
--- /dev/null
+++ b/devtools/client/netmonitor/moz.build
@@ -0,0 +1,19 @@
+# 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 += ["src"]
+
+DevToolsModules("initializer.js", "panel.js")
+
+XPCSHELL_TESTS_MANIFESTS += ["test/xpcshell/xpcshell.ini"]
+
+BROWSER_CHROME_MANIFESTS += [
+ "test/browser.ini",
+ "test/browser_http3.ini",
+]
+
+with Files("**"):
+ BUG_COMPONENT = ("DevTools", "Netmonitor")
+
+SPHINX_TREES["/devtools/netmonitor"] = "docs"
diff --git a/devtools/client/netmonitor/panel.js b/devtools/client/netmonitor/panel.js
new file mode 100644
index 0000000000..827f84eee9
--- /dev/null
+++ b/devtools/client/netmonitor/panel.js
@@ -0,0 +1,37 @@
+/* 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";
+
+function NetMonitorPanel(iframeWindow, toolbox, commands) {
+ this.panelWin = iframeWindow;
+ this.toolbox = toolbox;
+ this.commands = commands;
+}
+
+NetMonitorPanel.prototype = {
+ async open() {
+ // Reuse an existing Network monitor API object if available.
+ // It could have been created for WE API before Net panel opens.
+ const api = await this.toolbox.getNetMonitorAPI();
+ const app = this.panelWin.initialize(api);
+
+ // Connect the application object to the UI.
+ await app.bootstrap({
+ toolbox: this.toolbox,
+ document: this.panelWin.document,
+ win: this.panelWin,
+ });
+
+ // Ready to go!
+ return this;
+ },
+
+ destroy() {
+ this.panelWin.Netmonitor.destroy();
+ this.emit("destroyed");
+ },
+};
+
+exports.NetMonitorPanel = NetMonitorPanel;
diff --git a/devtools/client/netmonitor/src/actions/batching.js b/devtools/client/netmonitor/src/actions/batching.js
new file mode 100644
index 0000000000..f3b84f950d
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/batching.js
@@ -0,0 +1,50 @@
+/* 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 {
+ BATCH_ACTIONS,
+ BATCH_ENABLE,
+ BATCH_RESET,
+ BATCH_FLUSH,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * Process multiple actions at once as part of one dispatch, and produce only one
+ * state update at the end. This action is not processed by any reducer, but by a
+ * special store enhancer.
+ */
+function batchActions(actions) {
+ return {
+ type: BATCH_ACTIONS,
+ actions,
+ };
+}
+
+function batchEnable(enabled) {
+ return {
+ type: BATCH_ENABLE,
+ enabled,
+ };
+}
+
+function batchReset() {
+ return {
+ type: BATCH_RESET,
+ };
+}
+
+function batchFlush() {
+ return {
+ type: BATCH_FLUSH,
+ };
+}
+
+module.exports = {
+ batchActions,
+ batchEnable,
+ batchReset,
+ batchFlush,
+};
diff --git a/devtools/client/netmonitor/src/actions/filters.js b/devtools/client/netmonitor/src/actions/filters.js
new file mode 100644
index 0000000000..5aa5a99c10
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/filters.js
@@ -0,0 +1,58 @@
+/* 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 {
+ ENABLE_REQUEST_FILTER_TYPE_ONLY,
+ TOGGLE_REQUEST_FILTER_TYPE,
+ SET_REQUEST_FILTER_TEXT,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * Toggle an existing filter type state.
+ * If type 'all' is specified, all the other filter types are set to false.
+ * Available filter types are defined in filters reducer.
+ *
+ * @param {string} filter - A filter type is going to be updated
+ */
+function toggleRequestFilterType(filter) {
+ return {
+ type: TOGGLE_REQUEST_FILTER_TYPE,
+ filter,
+ };
+}
+
+/**
+ * Enable filter type exclusively.
+ * Except filter type is set to true, all the other filter types are set
+ * to false.
+ * Available filter types are defined in filters reducer.
+ *
+ * @param {string} filter - A filter type is going to be updated
+ */
+function enableRequestFilterTypeOnly(filter) {
+ return {
+ type: ENABLE_REQUEST_FILTER_TYPE_ONLY,
+ filter,
+ };
+}
+
+/**
+ * Set filter text in toolbar.
+ *
+ * @param {string} text - A filter text is going to be set
+ */
+function setRequestFilterText(text) {
+ return {
+ type: SET_REQUEST_FILTER_TEXT,
+ text,
+ };
+}
+
+module.exports = {
+ enableRequestFilterTypeOnly,
+ toggleRequestFilterType,
+ setRequestFilterText,
+};
diff --git a/devtools/client/netmonitor/src/actions/http-custom-request.js b/devtools/client/netmonitor/src/actions/http-custom-request.js
new file mode 100644
index 0000000000..e045107410
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/http-custom-request.js
@@ -0,0 +1,128 @@
+/* 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 {
+ OPEN_ACTION_BAR,
+ SELECT_ACTION_BAR_TAB,
+ PANELS,
+ RIGHT_CLICK_REQUEST,
+ PRESELECT_REQUEST,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const {
+ selectRequest,
+} = require("resource://devtools/client/netmonitor/src/actions/selection.js");
+
+const {
+ openNetworkDetails,
+} = require("resource://devtools/client/netmonitor/src/actions/ui.js");
+
+const {
+ getRequestById,
+ getRequestByChannelId,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+/**
+ * Open the entire HTTP Custom Request panel
+ * @returns {Function}
+ */
+function openHTTPCustomRequest(isOpen) {
+ return ({ dispatch, getState }) => {
+ dispatch({ type: OPEN_ACTION_BAR, open: isOpen });
+
+ dispatch({
+ type: SELECT_ACTION_BAR_TAB,
+ id: PANELS.HTTP_CUSTOM_REQUEST,
+ });
+ };
+}
+
+/**
+ * Toggle visibility of New Custom Request panel in network panel
+ */
+function toggleHTTPCustomRequestPanel() {
+ return ({ dispatch, getState }) => {
+ const state = getState();
+
+ const shouldClose =
+ state.ui.networkActionOpen &&
+ state.ui.selectedActionBarTabId === PANELS.HTTP_CUSTOM_REQUEST;
+ dispatch({ type: OPEN_ACTION_BAR, open: !shouldClose });
+
+ // reset the right clicked request
+ dispatch({ type: RIGHT_CLICK_REQUEST, id: null });
+
+ dispatch({
+ type: SELECT_ACTION_BAR_TAB,
+ id: PANELS.HTTP_CUSTOM_REQUEST,
+ });
+ };
+}
+
+/**
+ * Send a new HTTP request using the data in the custom request form.
+ */
+function sendHTTPCustomRequest(request) {
+ return async ({ dispatch, getState, connector, commands }) => {
+ if (!request) {
+ return;
+ }
+
+ // Fetch request headers and post data from the backend, if needed.
+ // This is only needed if we are resending a request without editing.
+
+ if (request.requestHeadersAvailable || request.requestPostDataAvailable) {
+ await fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestHeaders",
+ "requestPostData",
+ ]);
+
+ // Get the request again, to get all the updated data
+ request = getRequestById(getState(), request.id);
+ }
+
+ // Send a new HTTP request using the data in the custom request form
+ const data = {
+ cause: request.cause || {},
+ url: request.url,
+ method: request.method,
+ httpVersion: request.httpVersion,
+ };
+
+ if (request.requestHeaders) {
+ data.headers = request.requestHeaders.headers;
+ }
+
+ if (request.requestPostData) {
+ data.body = request.requestPostData.postData?.text;
+ }
+
+ const { channelId } = await commands.networkCommand.sendHTTPRequest(data);
+
+ const newRequest = getRequestByChannelId(getState(), channelId);
+ // If the new custom request is available already select the request, else
+ // preselect the request.
+ if (newRequest) {
+ await dispatch(selectRequest(newRequest.id));
+ } else {
+ await dispatch({
+ type: PRESELECT_REQUEST,
+ id: channelId,
+ });
+ }
+ dispatch(openNetworkDetails(true));
+ };
+}
+
+module.exports = {
+ openHTTPCustomRequest,
+ toggleHTTPCustomRequestPanel,
+ sendHTTPCustomRequest,
+};
diff --git a/devtools/client/netmonitor/src/actions/index.js b/devtools/client/netmonitor/src/actions/index.js
new file mode 100644
index 0000000000..6e28281ab7
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/index.js
@@ -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/. */
+
+"use strict";
+
+const batching = require("resource://devtools/client/netmonitor/src/actions/batching.js");
+const filters = require("resource://devtools/client/netmonitor/src/actions/filters.js");
+const httpCustomRequest = require("resource://devtools/client/netmonitor/src/actions/http-custom-request.js");
+const requests = require("resource://devtools/client/netmonitor/src/actions/requests.js");
+const selection = require("resource://devtools/client/netmonitor/src/actions/selection.js");
+const sort = require("resource://devtools/client/netmonitor/src/actions/sort.js");
+const timingMarkers = require("resource://devtools/client/netmonitor/src/actions/timing-markers.js");
+const ui = require("resource://devtools/client/netmonitor/src/actions/ui.js");
+const messages = require("resource://devtools/client/netmonitor/src/actions/messages.js");
+const search = require("resource://devtools/client/netmonitor/src/actions/search.js");
+const requestBlocking = require("resource://devtools/client/netmonitor/src/actions/request-blocking.js");
+
+Object.assign(
+ exports,
+ batching,
+ filters,
+ httpCustomRequest,
+ requests,
+ search,
+ selection,
+ sort,
+ timingMarkers,
+ ui,
+ messages,
+ requestBlocking
+);
diff --git a/devtools/client/netmonitor/src/actions/messages.js b/devtools/client/netmonitor/src/actions/messages.js
new file mode 100644
index 0000000000..a8f49e9735
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/messages.js
@@ -0,0 +1,188 @@
+/* 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 {
+ MSG_ADD,
+ MSG_SELECT,
+ MSG_OPEN_DETAILS,
+ MSG_CLEAR,
+ MSG_TOGGLE_FILTER_TYPE,
+ MSG_TOGGLE_CONTROL,
+ MSG_SET_FILTER_TEXT,
+ MSG_TOGGLE_COLUMN,
+ MSG_RESET_COLUMNS,
+ MSG_CLOSE_CONNECTION,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const {
+ getDisplayedMessages,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const PAGE_SIZE_ITEM_COUNT_RATIO = 5;
+
+/**
+ * Add message into state.
+ */
+function addMessage(httpChannelId, data, batch) {
+ return {
+ type: MSG_ADD,
+ httpChannelId,
+ data,
+ meta: { batch },
+ };
+}
+
+/**
+ * Select message.
+ */
+function selectMessage(message) {
+ return {
+ type: MSG_SELECT,
+ open: true,
+ message,
+ };
+}
+
+/**
+ * Open message details panel.
+ *
+ * @param {boolean} open - expected message details panel open state
+ */
+function openMessageDetails(open) {
+ return {
+ type: MSG_OPEN_DETAILS,
+ open,
+ };
+}
+
+/**
+ * Clear all messages from the MessageListContent
+ * component belonging to the current channelId
+ */
+function clearMessages() {
+ return {
+ type: MSG_CLEAR,
+ };
+}
+
+/**
+ * Show filtered messages from the MessageListContent
+ * component belonging to the current channelId
+ */
+function toggleMessageFilterType(filter) {
+ return {
+ type: MSG_TOGGLE_FILTER_TYPE,
+ filter,
+ };
+}
+
+/**
+ * Show control frames from the MessageListContent
+ * component belonging to the current channelId
+ */
+function toggleControlFrames() {
+ return {
+ type: MSG_TOGGLE_CONTROL,
+ };
+}
+
+/**
+ * Set filter text in toolbar.
+ *
+ */
+function setMessageFilterText(text) {
+ return {
+ type: MSG_SET_FILTER_TEXT,
+ text,
+ };
+}
+
+/**
+ * Resets all Messages columns to their default state.
+ *
+ */
+function resetMessageColumns() {
+ return {
+ type: MSG_RESET_COLUMNS,
+ };
+}
+
+/**
+ * Toggles a Message column
+ *
+ * @param {string} column - The column that is going to be toggled
+ */
+function toggleMessageColumn(column) {
+ return {
+ type: MSG_TOGGLE_COLUMN,
+ column,
+ };
+}
+
+/**
+ * Sets current connection status to closed
+ *
+ * @param {number} httpChannelId - Unique id identifying the channel
+ * @param {boolean} wasClean - False if connection terminated due to error
+ * @param {number} code - Error code
+ * @param {string} reason
+ */
+function closeConnection(httpChannelId, wasClean, code, reason) {
+ return {
+ type: MSG_CLOSE_CONNECTION,
+ httpChannelId,
+ wasClean,
+ code,
+ reason,
+ };
+}
+
+/**
+ * Move the selection up to down according to the "delta" parameter. Possible values:
+ * - Number: positive or negative, move up or down by specified distance
+ * - "PAGE_UP" | "PAGE_DOWN" (String): page up or page down
+ * - +Infinity | -Infinity: move to the start or end of the list
+ */
+function selectMessageDelta(delta) {
+ return ({ dispatch, getState }) => {
+ const state = getState();
+ const messages = getDisplayedMessages(state);
+
+ if (messages.length === 0) {
+ return;
+ }
+
+ const selIndex = messages.findIndex(
+ r => r === state.messages.selectedMessage
+ );
+
+ if (delta === "PAGE_DOWN") {
+ delta = Math.ceil(messages.length / PAGE_SIZE_ITEM_COUNT_RATIO);
+ } else if (delta === "PAGE_UP") {
+ delta = -Math.ceil(messages.length / PAGE_SIZE_ITEM_COUNT_RATIO);
+ }
+
+ const newIndex = Math.min(
+ Math.max(0, selIndex + delta),
+ messages.length - 1
+ );
+ const newItem = messages[newIndex];
+ dispatch(selectMessage(newItem));
+ };
+}
+
+module.exports = {
+ addMessage,
+ clearMessages,
+ closeConnection,
+ openMessageDetails,
+ resetMessageColumns,
+ selectMessage,
+ selectMessageDelta,
+ setMessageFilterText,
+ toggleControlFrames,
+ toggleMessageColumn,
+ toggleMessageFilterType,
+};
diff --git a/devtools/client/netmonitor/src/actions/moz.build b/devtools/client/netmonitor/src/actions/moz.build
new file mode 100644
index 0000000000..fc74e8cc56
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/moz.build
@@ -0,0 +1,18 @@
+# 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(
+ "batching.js",
+ "filters.js",
+ "http-custom-request.js",
+ "index.js",
+ "messages.js",
+ "request-blocking.js",
+ "requests.js",
+ "search.js",
+ "selection.js",
+ "sort.js",
+ "timing-markers.js",
+ "ui.js",
+)
diff --git a/devtools/client/netmonitor/src/actions/request-blocking.js b/devtools/client/netmonitor/src/actions/request-blocking.js
new file mode 100644
index 0000000000..502999c79f
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/request-blocking.js
@@ -0,0 +1,155 @@
+/* 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 {
+ ADD_BLOCKED_URL,
+ TOGGLE_BLOCKING_ENABLED,
+ TOGGLE_BLOCKED_URL,
+ UPDATE_BLOCKED_URL,
+ REMOVE_BLOCKED_URL,
+ REMOVE_ALL_BLOCKED_URLS,
+ ENABLE_ALL_BLOCKED_URLS,
+ DISABLE_ALL_BLOCKED_URLS,
+ DISABLE_MATCHING_URLS,
+ SYNCED_BLOCKED_URLS,
+ OPEN_ACTION_BAR,
+ SELECT_ACTION_BAR_TAB,
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+function toggleRequestBlockingPanel() {
+ return async ({ dispatch, getState }) => {
+ const state = getState();
+ if (
+ state.ui.networkActionOpen &&
+ state.ui.selectedActionBarTabId === PANELS.BLOCKING
+ ) {
+ dispatch(closeRequestBlocking());
+ } else {
+ dispatch(await openRequestBlocking());
+ }
+ };
+}
+
+function toggleBlockingEnabled(enabled) {
+ return {
+ type: TOGGLE_BLOCKING_ENABLED,
+ enabled,
+ };
+}
+
+function removeBlockedUrl(url) {
+ return {
+ type: REMOVE_BLOCKED_URL,
+ url,
+ };
+}
+
+function removeAllBlockedUrls() {
+ return { type: REMOVE_ALL_BLOCKED_URLS };
+}
+
+function enableAllBlockedUrls() {
+ return { type: ENABLE_ALL_BLOCKED_URLS };
+}
+
+function disableAllBlockedUrls() {
+ return { type: DISABLE_ALL_BLOCKED_URLS };
+}
+
+function addBlockedUrl(url) {
+ return {
+ type: ADD_BLOCKED_URL,
+ url,
+ };
+}
+
+function toggleBlockedUrl(url) {
+ return {
+ type: TOGGLE_BLOCKED_URL,
+ url,
+ };
+}
+
+function updateBlockedUrl(oldUrl, newUrl) {
+ return {
+ type: UPDATE_BLOCKED_URL,
+ oldUrl,
+ newUrl,
+ };
+}
+
+async function openRequestBlocking() {
+ return async ({ dispatch, getState, commands }) => {
+ const state = getState();
+ if (!state.requestBlocking.blockingSynced) {
+ const blockedUrls = state.requestBlocking.blockedUrls;
+ const responses = await commands.networkCommand.getBlockedUrls();
+ const urls = responses.flat();
+ if (urls.length !== blockedUrls.length) {
+ urls.forEach(url => dispatch(addBlockedUrl(url)));
+ }
+ dispatch({ type: SYNCED_BLOCKED_URLS, synced: true });
+ }
+
+ dispatch({ type: OPEN_ACTION_BAR, open: true });
+ dispatch({
+ type: SELECT_ACTION_BAR_TAB,
+ id: PANELS.BLOCKING,
+ });
+ };
+}
+
+function closeRequestBlocking() {
+ return ({ dispatch }) => {
+ dispatch({ type: OPEN_ACTION_BAR, open: false });
+ dispatch({
+ type: SELECT_ACTION_BAR_TAB,
+ id: PANELS.BLOCKING,
+ });
+ };
+}
+
+function openRequestBlockingAndAddUrl(url) {
+ return async ({ dispatch, getState }) => {
+ const showBlockingPanel = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.requestBlocking"
+ );
+
+ if (showBlockingPanel) {
+ dispatch(await openRequestBlocking());
+ }
+ dispatch({ type: ADD_BLOCKED_URL, url });
+ };
+}
+
+function openRequestBlockingAndDisableUrls(url) {
+ return async ({ dispatch, getState }) => {
+ const showBlockingPanel = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.requestBlocking"
+ );
+
+ if (showBlockingPanel) {
+ dispatch(await openRequestBlocking());
+ }
+
+ dispatch({ type: DISABLE_MATCHING_URLS, url });
+ };
+}
+
+module.exports = {
+ toggleRequestBlockingPanel,
+ addBlockedUrl,
+ toggleBlockingEnabled,
+ toggleBlockedUrl,
+ removeBlockedUrl,
+ removeAllBlockedUrls,
+ enableAllBlockedUrls,
+ disableAllBlockedUrls,
+ updateBlockedUrl,
+ openRequestBlockingAndAddUrl,
+ openRequestBlockingAndDisableUrls,
+};
diff --git a/devtools/client/netmonitor/src/actions/requests.js b/devtools/client/netmonitor/src/actions/requests.js
new file mode 100644
index 0000000000..838f2509a9
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/requests.js
@@ -0,0 +1,183 @@
+/* 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 {
+ ADD_REQUEST,
+ CLEAR_REQUESTS,
+ CLONE_REQUEST,
+ CLONE_SELECTED_REQUEST,
+ REMOVE_SELECTED_CUSTOM_REQUEST,
+ RIGHT_CLICK_REQUEST,
+ SEND_CUSTOM_REQUEST,
+ SET_EVENT_STREAM_FLAG,
+ SET_RECORDING_STATE,
+ UPDATE_REQUEST,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ getSelectedRequest,
+ getRequestById,
+ getRecordingState,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+function addRequest(id, data, batch) {
+ return {
+ type: ADD_REQUEST,
+ id,
+ data,
+ meta: { batch },
+ };
+}
+
+function updateRequest(id, data, batch) {
+ return {
+ type: UPDATE_REQUEST,
+ id,
+ data,
+ meta: { batch },
+ };
+}
+
+function setEventStreamFlag(id, batch) {
+ return {
+ type: SET_EVENT_STREAM_FLAG,
+ id,
+ meta: { batch },
+ };
+}
+
+/**
+ * Clone request by id. Used when cloning a request
+ * through the "Edit and Resend" option present in the context menu.
+ */
+function cloneRequest(id) {
+ return {
+ id,
+ type: CLONE_REQUEST,
+ };
+}
+
+/**
+ * Right click a request without selecting it.
+ */
+function rightClickRequest(id) {
+ return {
+ id,
+ type: RIGHT_CLICK_REQUEST,
+ };
+}
+
+/**
+ * Clone the currently selected request, set the "isCustom" attribute.
+ * Used by the "Edit and Resend" feature.
+ */
+function cloneSelectedRequest() {
+ return {
+ type: CLONE_SELECTED_REQUEST,
+ };
+}
+
+/**
+ * Send a new HTTP request using the data in the custom request form.
+ */
+function sendCustomRequest(requestId = null) {
+ return async ({ dispatch, getState, connector, commands }) => {
+ let request;
+ if (requestId) {
+ request = getRequestById(getState(), requestId);
+ } else {
+ request = getSelectedRequest(getState());
+ }
+
+ if (!request) {
+ return;
+ }
+
+ // Fetch request headers and post data from the backend.
+ await fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestHeaders",
+ "requestPostData",
+ ]);
+
+ // Reload the request from the store to get the headers.
+ request = getRequestById(getState(), request.id);
+
+ // Send a new HTTP request using the data in the custom request form
+ const data = {
+ cause: request.cause,
+ url: request.url,
+ method: request.method,
+ httpVersion: request.httpVersion,
+ };
+
+ if (request.requestHeaders) {
+ data.headers = request.requestHeaders.headers;
+ }
+
+ if (request.requestPostData) {
+ data.body = request.requestPostData.postData.text;
+ }
+
+ const { channelId } = await commands.networkCommand.sendHTTPRequest(data);
+
+ dispatch({
+ type: SEND_CUSTOM_REQUEST,
+ id: channelId,
+ });
+ };
+}
+
+/**
+ * Remove a request from the list. Supports removing only cloned requests with a
+ * "isCustom" attribute. Other requests never need to be removed.
+ */
+function removeSelectedCustomRequest() {
+ return {
+ type: REMOVE_SELECTED_CUSTOM_REQUEST,
+ };
+}
+/**
+ * Clear all requests
+ */
+function clearRequests() {
+ return ({ dispatch, connector }) => {
+ dispatch({ type: CLEAR_REQUESTS });
+ connector.clear();
+ };
+}
+
+/**
+ * Toggle monitoring
+ */
+function toggleRecording() {
+ return async ({ dispatch, getState, connector }) => {
+ const recording = !getRecordingState(getState());
+ if (recording) {
+ await connector.resume();
+ } else {
+ connector.pause();
+ }
+ dispatch({
+ type: SET_RECORDING_STATE,
+ recording,
+ });
+ };
+}
+
+module.exports = {
+ addRequest,
+ clearRequests,
+ cloneRequest,
+ cloneSelectedRequest,
+ rightClickRequest,
+ removeSelectedCustomRequest,
+ sendCustomRequest,
+ setEventStreamFlag,
+ toggleRecording,
+ updateRequest,
+};
diff --git a/devtools/client/netmonitor/src/actions/search.js b/devtools/client/netmonitor/src/actions/search.js
new file mode 100644
index 0000000000..97b123d361
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/search.js
@@ -0,0 +1,316 @@
+/* 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 {
+ ADD_SEARCH_QUERY,
+ ADD_SEARCH_RESULT,
+ CLEAR_SEARCH_RESULTS,
+ ADD_ONGOING_SEARCH,
+ OPEN_ACTION_BAR,
+ UPDATE_SEARCH_STATUS,
+ SEARCH_STATUS,
+ SET_TARGET_SEARCH_RESULT,
+ SELECT_ACTION_BAR_TAB,
+ TOGGLE_SEARCH_CASE_SENSITIVE_SEARCH,
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const {
+ getDisplayedRequests,
+ getOngoingSearch,
+ getSearchStatus,
+ getRequestById,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+const {
+ selectRequest,
+} = require("resource://devtools/client/netmonitor/src/actions/selection.js");
+const {
+ selectDetailsPanelTab,
+} = require("resource://devtools/client/netmonitor/src/actions/ui.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ searchInResource,
+} = require("resource://devtools/client/netmonitor/src/workers/search/index.js");
+
+/**
+ * Search through all resources. This is the main action exported
+ * from this module and consumed by Network panel UI.
+ */
+function search(connector, query) {
+ let canceled = false;
+
+ // Instantiate an `ongoingSearch` function/object. It's responsible
+ // for triggering set of asynchronous steps like fetching
+ // data from the backend and performing search over it.
+ // This `ongoingSearch` is stored in the Search reducer, so it can
+ // be canceled if needed (e.g. when new search is executed).
+ const newOngoingSearch = async ({ dispatch, getState }) => {
+ const state = getState();
+
+ dispatch(stopOngoingSearch());
+
+ await dispatch(addOngoingSearch(newOngoingSearch));
+ await dispatch(clearSearchResults());
+ await dispatch(addSearchQuery(query));
+
+ dispatch(updateSearchStatus(SEARCH_STATUS.FETCHING));
+
+ // Loop over all displayed resources (in the sorted order),
+ // fetch all the details data and run search worker that
+ // search through the resource structure.
+ const requests = getDisplayedRequests(state);
+ for (const request of requests) {
+ if (canceled) {
+ return;
+ }
+
+ // Fetch all data for the resource.
+ await loadResource(connector, request);
+ if (canceled) {
+ return;
+ }
+
+ // The state changed, so make sure to get fresh new reference
+ // to the updated resource object.
+ const updatedResource = getRequestById(getState(), request.id);
+ await dispatch(searchResource(updatedResource, query));
+ }
+
+ dispatch(updateSearchStatus(SEARCH_STATUS.DONE));
+ };
+
+ // Implement support for canceling (used e.g. when a new search
+ // is executed or the user stops the searching manually).
+ newOngoingSearch.cancel = () => {
+ canceled = true;
+ };
+
+ newOngoingSearch.isCanceled = () => {
+ return canceled;
+ };
+
+ return newOngoingSearch;
+}
+
+/**
+ * Fetch all data related to the specified resource from the backend.
+ */
+async function loadResource(connector, resource) {
+ const updateTypes = [
+ "responseHeaders",
+ "requestHeaders",
+ "responseCookies",
+ "requestCookies",
+ "requestPostData",
+ "responseContent",
+ "responseCache",
+ "stackTrace",
+ "securityInfo",
+ ];
+
+ return fetchNetworkUpdatePacket(connector.requestData, resource, updateTypes);
+}
+
+/**
+ * Search through all data within the specified resource.
+ */
+function searchResource(resource, query) {
+ return async ({ dispatch, getState }) => {
+ const state = getState();
+ const ongoingSearch = getOngoingSearch(state);
+
+ const modifiers = {
+ caseSensitive: state.search.caseSensitive,
+ };
+
+ // Run search in a worker and wait for the results. The return
+ // value is an array with search occurrences.
+ const result = await searchInResource(resource, query, modifiers);
+
+ if (!result.length || ongoingSearch.isCanceled()) {
+ return;
+ }
+
+ dispatch(addSearchResult(resource, result));
+ };
+}
+
+/**
+ * Add search query to the reducer.
+ */
+function addSearchResult(resource, result) {
+ return {
+ type: ADD_SEARCH_RESULT,
+ resource,
+ result,
+ };
+}
+
+/**
+ * Add search query to the reducer.
+ */
+function addSearchQuery(query) {
+ return {
+ type: ADD_SEARCH_QUERY,
+ query,
+ };
+}
+
+/**
+ * Clear all search results.
+ */
+function clearSearchResults() {
+ return {
+ type: CLEAR_SEARCH_RESULTS,
+ };
+}
+
+/**
+ * Used to clear and cancel an ongoing search.
+ * @returns {Function}
+ */
+function clearSearchResultAndCancel() {
+ return ({ dispatch, getState }) => {
+ dispatch(stopOngoingSearch());
+ dispatch(clearSearchResults());
+ };
+}
+
+/**
+ * Update status of the current search.
+ */
+function updateSearchStatus(status) {
+ return {
+ type: UPDATE_SEARCH_STATUS,
+ status,
+ };
+}
+
+/**
+ * Close the entire search panel.
+ */
+function closeSearch() {
+ return ({ dispatch, getState }) => {
+ dispatch(stopOngoingSearch());
+ dispatch({ type: OPEN_ACTION_BAR, open: false });
+ };
+}
+
+/**
+ * Open the entire search panel
+ * @returns {Function}
+ */
+function openSearch() {
+ return ({ dispatch, getState }) => {
+ dispatch({ type: OPEN_ACTION_BAR, open: true });
+
+ dispatch({
+ type: SELECT_ACTION_BAR_TAB,
+ id: PANELS.SEARCH,
+ });
+ };
+}
+
+/**
+ * Toggles case sensitive search
+ * @returns {Function}
+ */
+function toggleCaseSensitiveSearch() {
+ return ({ dispatch, getState }) => {
+ dispatch({ type: TOGGLE_SEARCH_CASE_SENSITIVE_SEARCH });
+ };
+}
+
+/**
+ * Toggle visibility of search panel in network panel
+ */
+function toggleSearchPanel() {
+ return ({ dispatch, getState }) => {
+ const state = getState();
+
+ state.ui.networkActionOpen &&
+ state.ui.selectedActionBarTabId === PANELS.SEARCH
+ ? dispatch({ type: OPEN_ACTION_BAR, open: false })
+ : dispatch({ type: OPEN_ACTION_BAR, open: true });
+
+ dispatch({
+ type: SELECT_ACTION_BAR_TAB,
+ id: PANELS.SEARCH,
+ });
+ };
+}
+
+/**
+ * Append new search object into the reducer. The search object
+ * is cancellable and so, it implements `cancel` method.
+ */
+function addOngoingSearch(ongoingSearch) {
+ return {
+ type: ADD_ONGOING_SEARCH,
+ ongoingSearch,
+ };
+}
+
+/**
+ * Cancel the current ongoing search.
+ */
+function stopOngoingSearch() {
+ return ({ dispatch, getState }) => {
+ const state = getState();
+ const ongoingSearch = getOngoingSearch(state);
+ const status = getSearchStatus(state);
+
+ if (ongoingSearch && status !== SEARCH_STATUS.DONE) {
+ ongoingSearch.cancel();
+ dispatch(updateSearchStatus(SEARCH_STATUS.CANCELED));
+ }
+ };
+}
+
+/**
+ * This action is fired when the user selects a search result
+ * within the Search panel. It opens the details side bar and
+ * selects the right side panel to show the context of the
+ * clicked search result.
+ */
+function navigate(searchResult) {
+ return ({ dispatch, getState }) => {
+ // Store target search result in Search reducer. It's used
+ // for search result navigation within the side panels.
+ dispatch(setTargetSearchResult(searchResult));
+
+ // Preselect the right side panel.
+ dispatch(selectDetailsPanelTab(searchResult.panel));
+
+ // Select related request in the UI (it also opens the
+ // right side bar automatically).
+ dispatch(selectRequest(searchResult.parentResource.id));
+ };
+}
+
+function setTargetSearchResult(searchResult) {
+ return {
+ type: SET_TARGET_SEARCH_RESULT,
+ searchResult,
+ };
+}
+
+module.exports = {
+ search,
+ closeSearch,
+ openSearch,
+ clearSearchResults,
+ addSearchQuery,
+ toggleSearchPanel,
+ navigate,
+ setTargetSearchResult,
+ toggleCaseSensitiveSearch,
+ clearSearchResultAndCancel,
+ stopOngoingSearch,
+};
diff --git a/devtools/client/netmonitor/src/actions/selection.js b/devtools/client/netmonitor/src/actions/selection.js
new file mode 100644
index 0000000000..4603fcb61c
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/selection.js
@@ -0,0 +1,80 @@
+/* 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 {
+ SELECT_REQUEST,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ getDisplayedRequests,
+ getSortedRequests,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+const PAGE_SIZE_ITEM_COUNT_RATIO = 5;
+
+/**
+ * Select request with a given id.
+ */
+function selectRequest(id, request) {
+ return {
+ type: SELECT_REQUEST,
+ id,
+ request,
+ };
+}
+
+/**
+ * Select request with a given index (sorted order)
+ */
+function selectRequestByIndex(index) {
+ return ({ dispatch, getState }) => {
+ const requests = getSortedRequests(getState());
+ let itemId;
+ if (index >= 0 && index < requests.length) {
+ itemId = requests[index].id;
+ }
+ dispatch(selectRequest(itemId));
+ };
+}
+
+/**
+ * Move the selection up to down according to the "delta" parameter. Possible values:
+ * - Number: positive or negative, move up or down by specified distance
+ * - "PAGE_UP" | "PAGE_DOWN" (String): page up or page down
+ * - +Infinity | -Infinity: move to the start or end of the list
+ */
+function selectDelta(delta) {
+ return ({ dispatch, getState }) => {
+ const state = getState();
+ const requests = getDisplayedRequests(state);
+
+ if (!requests.length) {
+ return;
+ }
+
+ const selIndex = requests.findIndex(
+ r => r.id === state.requests.selectedId
+ );
+
+ if (delta === "PAGE_DOWN") {
+ delta = Math.ceil(requests.length / PAGE_SIZE_ITEM_COUNT_RATIO);
+ } else if (delta === "PAGE_UP") {
+ delta = -Math.ceil(requests.length / PAGE_SIZE_ITEM_COUNT_RATIO);
+ }
+
+ const newIndex = Math.min(
+ Math.max(0, selIndex + delta),
+ requests.length - 1
+ );
+ const newItem = requests[newIndex];
+ dispatch(selectRequest(newItem.id, newItem));
+ };
+}
+
+module.exports = {
+ selectRequest,
+ selectRequestByIndex,
+ selectDelta,
+};
diff --git a/devtools/client/netmonitor/src/actions/sort.js b/devtools/client/netmonitor/src/actions/sort.js
new file mode 100644
index 0000000000..06c3f92c54
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/sort.js
@@ -0,0 +1,20 @@
+/* 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 {
+ SORT_BY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+function sortBy(sortType) {
+ return {
+ type: SORT_BY,
+ sortType,
+ };
+}
+
+module.exports = {
+ sortBy,
+};
diff --git a/devtools/client/netmonitor/src/actions/timing-markers.js b/devtools/client/netmonitor/src/actions/timing-markers.js
new file mode 100644
index 0000000000..cce53e8100
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/timing-markers.js
@@ -0,0 +1,22 @@
+/* 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 {
+ ADD_TIMING_MARKER,
+ CLEAR_TIMING_MARKERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+exports.addTimingMarker = marker => {
+ return {
+ type: ADD_TIMING_MARKER,
+ marker,
+ };
+};
+
+exports.clearTimingMarkers = () => {
+ return {
+ type: CLEAR_TIMING_MARKERS,
+ };
+};
diff --git a/devtools/client/netmonitor/src/actions/ui.js b/devtools/client/netmonitor/src/actions/ui.js
new file mode 100644
index 0000000000..4be087c5df
--- /dev/null
+++ b/devtools/client/netmonitor/src/actions/ui.js
@@ -0,0 +1,257 @@
+/* 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 {
+ ACTIVITY_TYPE,
+ OPEN_NETWORK_DETAILS,
+ RESIZE_NETWORK_DETAILS,
+ ENABLE_PERSISTENT_LOGS,
+ DISABLE_BROWSER_CACHE,
+ OPEN_STATISTICS,
+ RESET_COLUMNS,
+ SELECT_DETAILS_PANEL_TAB,
+ SELECT_ACTION_BAR_TAB,
+ TOGGLE_COLUMN,
+ WATERFALL_RESIZE,
+ SET_COLUMNS_WIDTH,
+ SET_HEADERS_URL_PREVIEW_EXPANDED,
+ OPEN_ACTION_BAR,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const {
+ getDisplayedRequests,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+const DEVTOOLS_DISABLE_CACHE_PREF = "devtools.cache.disabled";
+
+/**
+ * Change network details panel.
+ *
+ * @param {boolean} open - expected network details panel open state
+ */
+function openNetworkDetails(open) {
+ return ({ dispatch, getState }) => {
+ const visibleRequestItems = getDisplayedRequests(getState());
+ const defaultSelectedId = visibleRequestItems.length
+ ? visibleRequestItems[0].id
+ : null;
+
+ return dispatch({
+ type: OPEN_NETWORK_DETAILS,
+ open,
+ defaultSelectedId,
+ });
+ };
+}
+
+/**
+ * Change network action bar open state.
+ *
+ * @param {boolean} open - expected network action bar open state
+ */
+function openNetworkActionBar(open) {
+ return {
+ type: OPEN_ACTION_BAR,
+ open,
+ };
+}
+
+/**
+ * Change network details panel size.
+ *
+ * @param {integer} width
+ * @param {integer} height
+ */
+function resizeNetworkDetails(width, height) {
+ return {
+ type: RESIZE_NETWORK_DETAILS,
+ width,
+ height,
+ };
+}
+
+/**
+ * Change persistent logs state.
+ *
+ * @param {boolean} enabled - expected persistent logs enabled state
+ */
+function enablePersistentLogs(enabled, skipTelemetry = false) {
+ return {
+ type: ENABLE_PERSISTENT_LOGS,
+ enabled,
+ skipTelemetry,
+ };
+}
+
+/**
+ * Change browser cache state.
+ *
+ * @param {boolean} disabled - expected browser cache in disable state
+ */
+function disableBrowserCache(disabled) {
+ return {
+ type: DISABLE_BROWSER_CACHE,
+ disabled,
+ };
+}
+
+/**
+ * Change performance statistics panel open state.
+ *
+ * @param {Object} connector - connector object to the backend
+ * @param {boolean} visible - expected performance statistics panel open state
+ */
+function openStatistics(connector, open) {
+ if (open) {
+ connector.triggerActivity(ACTIVITY_TYPE.RELOAD.WITH_CACHE_ENABLED);
+ } else if (Services.prefs.getBoolPref(DEVTOOLS_DISABLE_CACHE_PREF)) {
+ // Opening the Statistics panel reconfigures the page and enables
+ // the browser cache (using ACTIVITY_TYPE.RELOAD.WITH_CACHE_ENABLED).
+ // So, make sure to disable the cache again when the user returns back
+ // from the Statistics panel (if DEVTOOLS_DISABLE_CACHE_PREF == true).
+ // See also bug 1430359.
+ connector.triggerActivity(ACTIVITY_TYPE.DISABLE_CACHE);
+ }
+ return {
+ type: OPEN_STATISTICS,
+ open,
+ };
+}
+
+/**
+ * Resets all columns to their default state.
+ *
+ */
+function resetColumns() {
+ return {
+ type: RESET_COLUMNS,
+ };
+}
+
+/**
+ * Waterfall width has changed (likely on window resize). Update the UI.
+ */
+function resizeWaterfall(width) {
+ return {
+ type: WATERFALL_RESIZE,
+ width,
+ };
+}
+
+/**
+ * Change the selected tab for network details panel.
+ *
+ * @param {string} id - tab id to be selected
+ */
+function selectDetailsPanelTab(id) {
+ return {
+ type: SELECT_DETAILS_PANEL_TAB,
+ id,
+ };
+}
+
+/**
+ * Change the selected tab for network action bar.
+ *
+ * @param {string} id - tab id to be selected
+ */
+function selectActionBarTab(id) {
+ return {
+ type: SELECT_ACTION_BAR_TAB,
+ id,
+ };
+}
+
+/**
+ * Toggles a column
+ *
+ * @param {string} column - The column that is going to be toggled
+ */
+function toggleColumn(column) {
+ return {
+ type: TOGGLE_COLUMN,
+ column,
+ };
+}
+
+/**
+ * Set width of multiple columns
+ *
+ * @param {array} widths - array of pairs {name, width}
+ */
+function setColumnsWidth(widths) {
+ return {
+ type: SET_COLUMNS_WIDTH,
+ widths,
+ };
+}
+
+/**
+ * Toggle network details panel.
+ */
+function toggleNetworkDetails() {
+ return ({ dispatch, getState }) =>
+ dispatch(openNetworkDetails(!getState().ui.networkDetailsOpen));
+}
+
+/**
+ * Toggle network action panel.
+ */
+function toggleNetworkActionBar() {
+ return ({ dispatch, getState }) =>
+ dispatch(openNetworkActionBar(!getState().ui.networkActionOpen));
+}
+
+/**
+ * Toggle persistent logs status.
+ */
+function togglePersistentLogs() {
+ return ({ dispatch, getState }) =>
+ dispatch(enablePersistentLogs(!getState().ui.persistentLogsEnabled));
+}
+
+/**
+ * Toggle browser cache status.
+ */
+function toggleBrowserCache() {
+ return ({ dispatch, getState }) =>
+ dispatch(disableBrowserCache(!getState().ui.browserCacheDisabled));
+}
+
+/**
+ * Toggle performance statistics panel.
+ */
+function toggleStatistics(connector) {
+ return ({ dispatch, getState }) =>
+ dispatch(openStatistics(connector, !getState().ui.statisticsOpen));
+}
+
+function setHeadersUrlPreviewExpanded(expanded) {
+ return {
+ type: SET_HEADERS_URL_PREVIEW_EXPANDED,
+ expanded,
+ };
+}
+
+module.exports = {
+ openNetworkDetails,
+ openNetworkActionBar,
+ resizeNetworkDetails,
+ enablePersistentLogs,
+ disableBrowserCache,
+ openStatistics,
+ resetColumns,
+ resizeWaterfall,
+ selectDetailsPanelTab,
+ selectActionBarTab,
+ toggleColumn,
+ setColumnsWidth,
+ toggleNetworkDetails,
+ toggleNetworkActionBar,
+ togglePersistentLogs,
+ toggleBrowserCache,
+ toggleStatistics,
+ setHeadersUrlPreviewExpanded,
+};
diff --git a/devtools/client/netmonitor/src/api.js b/devtools/client/netmonitor/src/api.js
new file mode 100644
index 0000000000..8d760de788
--- /dev/null
+++ b/devtools/client/netmonitor/src/api.js
@@ -0,0 +1,216 @@
+/* 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 EventEmitter = require("resource://devtools/shared/event-emitter.js");
+
+const {
+ bindActionCreators,
+} = require("resource://devtools/client/shared/vendor/redux.js");
+const {
+ Connector,
+} = require("resource://devtools/client/netmonitor/src/connector/index.js");
+const {
+ configureStore,
+} = require("resource://devtools/client/netmonitor/src/create-store.js");
+const {
+ EVENTS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+
+const {
+ getDisplayedRequestById,
+ getSortedRequests,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+/**
+ * API object for NetMonitor panel (like a facade). This object can be
+ * consumed by other panels, WebExtension API, etc.
+ *
+ * This object doesn't depend on the panel UI and can be created
+ * and used even if the Network panel UI doesn't exist.
+ */
+function NetMonitorAPI() {
+ EventEmitter.decorate(this);
+
+ // Connector to the backend.
+ this.connector = new Connector();
+
+ // List of listeners for `devtools.network.onRequestFinished` WebExt API
+ this._requestFinishedListeners = new Set();
+
+ // Bind event handlers
+ this.onPayloadReady = this.onPayloadReady.bind(this);
+}
+
+NetMonitorAPI.prototype = {
+ async connect(toolbox) {
+ // Bail out if already connected.
+ if (this.toolbox) {
+ return;
+ }
+
+ this.toolbox = toolbox;
+
+ // Configure store/state object.
+ this.store = configureStore(
+ this.connector,
+ this.toolbox.commands,
+ this.toolbox.telemetry
+ );
+ this.actions = bindActionCreators(Actions, this.store.dispatch);
+
+ // Register listener for new requests (utilized by WebExtension API).
+ this.on(EVENTS.PAYLOAD_READY, this.onPayloadReady);
+
+ // Initialize connection to the backend. Pass `this` as the owner,
+ // so this object can receive all emitted events.
+ const connection = {
+ toolbox,
+ owner: this,
+ };
+
+ await this.connector.connect(connection, this.actions, this.store.getState);
+ },
+
+ /**
+ * Clean up (unmount from DOM, remove listeners, disconnect).
+ */
+ destroy() {
+ this.off(EVENTS.PAYLOAD_READY, this.onPayloadReady);
+
+ this.connector.disconnect();
+
+ if (this.harExportConnector) {
+ this.harExportConnector.disconnect();
+ }
+ },
+
+ // HAR
+
+ /**
+ * Support for `devtools.network.getHAR` (get collected data as HAR)
+ */
+ async getHar() {
+ const {
+ HarExporter,
+ } = require("resource://devtools/client/netmonitor/src/har/har-exporter.js");
+ const state = this.store.getState();
+
+ const options = {
+ connector: this.connector,
+ items: getSortedRequests(state),
+ };
+
+ return HarExporter.getHar(options);
+ },
+
+ /**
+ * Support for `devtools.network.onRequestFinished`. A hook for
+ * every finished HTTP request used by WebExtensions API.
+ */
+ async onPayloadReady(resource) {
+ if (!this._requestFinishedListeners.size) {
+ return;
+ }
+
+ const {
+ HarExporter,
+ } = require("resource://devtools/client/netmonitor/src/har/har-exporter.js");
+
+ const connector = await this.getHarExportConnector();
+ const request = getDisplayedRequestById(
+ this.store.getState(),
+ resource.actor
+ );
+ if (!request) {
+ console.error("HAR: request not found " + resource.actor);
+ return;
+ }
+
+ const options = {
+ connector,
+ includeResponseBodies: false,
+ items: [request],
+ };
+
+ const har = await HarExporter.getHar(options);
+
+ // There is page so remove the page reference.
+ const harEntry = har.log.entries[0];
+ delete harEntry.pageref;
+
+ this._requestFinishedListeners.forEach(listener =>
+ listener({
+ harEntry,
+ requestId: resource.actor,
+ })
+ );
+ },
+
+ /**
+ * Support for `Request.getContent` WebExt API (lazy loading response body)
+ */
+ async fetchResponseContent(requestId) {
+ return this.connector.requestData(requestId, "responseContent");
+ },
+
+ /**
+ * Add listener for `onRequestFinished` events.
+ *
+ * @param {Object} listener
+ * The listener to be called it's expected to be
+ * a function that takes ({harEntry, requestId})
+ * as first argument.
+ */
+ addRequestFinishedListener(listener) {
+ this._requestFinishedListeners.add(listener);
+ },
+
+ removeRequestFinishedListener(listener) {
+ this._requestFinishedListeners.delete(listener);
+ },
+
+ hasRequestFinishedListeners() {
+ return this._requestFinishedListeners.size > 0;
+ },
+
+ /**
+ * Separate connector for HAR export.
+ */
+ async getHarExportConnector() {
+ if (this.harExportConnector) {
+ // Wait for the connector to be ready to avoid exceptions if this method is called
+ // twice during its initialization.
+ await this.harExportConnectorReady;
+ return this.harExportConnector;
+ }
+
+ const connection = {
+ toolbox: this.toolbox,
+ };
+
+ this.harExportConnector = new Connector();
+ this.harExportConnectorReady = this.harExportConnector.connect(connection);
+
+ await this.harExportConnectorReady;
+ return this.harExportConnector;
+ },
+
+ /**
+ * Resends a given network request
+ * @param {String} requestId
+ * Id of the network request
+ */
+ resendRequest(requestId) {
+ // Flush queued requests.
+ this.store.dispatch(Actions.batchFlush());
+ // Send custom request with same url, headers and body as the request
+ // with the given requestId.
+ this.store.dispatch(Actions.sendCustomRequest(requestId));
+ },
+};
+
+exports.NetMonitorAPI = NetMonitorAPI;
diff --git a/devtools/client/netmonitor/src/app.js b/devtools/client/netmonitor/src/app.js
new file mode 100644
index 0000000000..d7cf642d48
--- /dev/null
+++ b/devtools/client/netmonitor/src/app.js
@@ -0,0 +1,135 @@
+/* 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 {
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const {
+ render,
+ unmountComponentAtNode,
+} = require("resource://devtools/client/shared/vendor/react-dom.js");
+const Provider = createFactory(
+ require("resource://devtools/client/shared/vendor/react-redux.js").Provider
+);
+const App = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/App.js")
+);
+const {
+ EVENTS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const {
+ getDisplayedRequestById,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+const SearchDispatcher = require("resource://devtools/client/netmonitor/src/workers/search/index.js");
+
+/**
+ * Global App object for Network panel. This object depends
+ * on the UI and can't be created independently.
+ *
+ * This object can be consumed by other panels (e.g. Console
+ * is using inspectRequest), by the Launchpad (bootstrap), etc.
+ *
+ * @param {Object} api An existing API object to be reused.
+ */
+function NetMonitorApp(api) {
+ this.api = api;
+}
+
+NetMonitorApp.prototype = {
+ async bootstrap({ toolbox, document, win }) {
+ // Get the root element for mounting.
+ this.mount = document.querySelector("#mount");
+
+ const openLink = link => {
+ const parentDoc = toolbox.doc;
+ const iframe = parentDoc.getElementById(
+ "toolbox-panel-iframe-netmonitor"
+ );
+ const { top } = iframe.ownerDocument.defaultView;
+ top.openWebLinkIn(link, "tab");
+ };
+
+ const openSplitConsole = err => {
+ toolbox.openSplitConsole().then(() => {
+ toolbox.target.logErrorInPage(err, "har");
+ });
+ };
+
+ const { actions, connector, store } = this.api;
+
+ const sourceMapURLService = toolbox.sourceMapURLService;
+ const app = App({
+ actions,
+ connector,
+ openLink,
+ openSplitConsole,
+ sourceMapURLService,
+ toolboxDoc: toolbox.doc,
+ });
+
+ // Render the root Application component.
+ render(Provider({ store }, app), this.mount);
+ },
+
+ /**
+ * Clean up (unmount from DOM, remove listeners, disconnect).
+ */
+ destroy() {
+ unmountComponentAtNode(this.mount);
+
+ SearchDispatcher.stop();
+
+ // Make sure to destroy the API object. It's usually destroyed
+ // in the Toolbox destroy method, but we need it here for case
+ // where the Network panel is initialized without the toolbox
+ // and running in a tab (see initialize.js for details).
+ this.api.destroy();
+ },
+
+ /**
+ * Selects the specified request in the waterfall and opens the details view.
+ * This is a firefox toolbox specific API, which providing an ability to inspect
+ * a network request directly from other internal toolbox panel.
+ *
+ * @param {string} requestId The actor ID of the request to inspect.
+ * @return {object} A promise resolved once the task finishes.
+ */
+ async inspectRequest(requestId) {
+ const { actions, store } = this.api;
+
+ // Look for the request in the existing ones or wait for it to appear,
+ // if the network monitor is still loading.
+ return new Promise(resolve => {
+ let request = null;
+ const inspector = () => {
+ request = getDisplayedRequestById(store.getState(), requestId);
+ if (!request) {
+ // Reset filters so that the request is visible.
+ actions.toggleRequestFilterType("all");
+ request = getDisplayedRequestById(store.getState(), requestId);
+ }
+
+ // If the request was found, select it. Otherwise this function will be
+ // called again once new requests arrive.
+ if (request) {
+ this.api.off(EVENTS.REQUEST_ADDED, inspector);
+ actions.selectRequest(request.id);
+ resolve();
+ }
+ };
+
+ inspector();
+
+ if (!request) {
+ this.api.on(EVENTS.REQUEST_ADDED, inspector);
+ }
+ });
+ },
+};
+
+exports.NetMonitorApp = NetMonitorApp;
diff --git a/devtools/client/netmonitor/src/assets/icons/arrow-up.svg b/devtools/client/netmonitor/src/assets/icons/arrow-up.svg
new file mode 100644
index 0000000000..ed45876011
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/icons/arrow-up.svg
@@ -0,0 +1,6 @@
+<!-- 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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">
+ <path fill="context-fill" d="M8 2C8.2336 2 8.45387 2.10885 8.59577 2.29441L11.8458 6.54441C12.0784 6.84863 12.0445 7.27924 11.7671 7.54327C11.4897 7.8073 11.0579 7.81991 10.7655 7.57254L9 6V13C9 13.5523 8.55228 14 8 14C7.44772 14 7 13.5523 7 13V6L5.23446 7.57254C4.9421 7.81991 4.51034 7.8073 4.23293 7.54327C3.95553 7.27924 3.9216 6.84863 4.15423 6.54441L7.40423 2.29441C7.54613 2.10885 7.7664 2 8 2Z" />
+</svg>
diff --git a/devtools/client/netmonitor/src/assets/icons/play.svg b/devtools/client/netmonitor/src/assets/icons/play.svg
new file mode 100644
index 0000000000..a47acd4613
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/icons/play.svg
@@ -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/. -->
+<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="context-fill #0b0b0b">
+ <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <polygon id="Triangle-2" fill="#0A84FF" points="14 8 4 14 4 2"></polygon>
+ </g>
+</svg>
diff --git a/devtools/client/netmonitor/src/assets/icons/shield.svg b/devtools/client/netmonitor/src/assets/icons/shield.svg
new file mode 100644
index 0000000000..dd7676d59f
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/icons/shield.svg
@@ -0,0 +1,6 @@
+<!-- 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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">
+ <path fill="context-fill" fill-rule="evenodd" d="M13 5.049l-1 1V6.5c0 2.877-.954 4.49-1.905 5.386a4.66 4.66 0 0 1-1.375.903c-.384.162-.703.21-.72.21a3.104 3.104 0 0 1-.72-.21 4.63 4.63 0 0 1-1.24-.78l-.708.708c.545.487 1.099.8 1.56.994.476.2.89.289 1.108.289.218 0 .632-.089 1.108-.29a5.66 5.66 0 0 0 1.672-1.096C11.954 11.51 13 9.623 13 6.5V5.049zM8 10.049l-1.1 1.099c.31.29.672.515 1.1.652v-1.752z M8 1.993l4.08.68c.126.021.243.062.349.12l.582-.582a.55.55 0 1 1 .778.778l-10.8 10.8a.55.55 0 1 1-.778-.778l1.863-1.863C3.442 10.038 3 8.53 3 6.5V3.758a1.1 1.1 0 0 1 .92-1.085L8 1.993zM4 6.5V3.758a.1.1 0 0 1 .084-.098L8 3.007l3.613.602L8 7.222V4.2l-2.8.5c0 1.409.095 3.231.626 4.696L4.812 10.41C4.338 9.478 4 8.213 4 6.5z"/>
+</svg>
diff --git a/devtools/client/netmonitor/src/assets/icons/turtle.svg b/devtools/client/netmonitor/src/assets/icons/turtle.svg
new file mode 100644
index 0000000000..1f308649f3
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/icons/turtle.svg
@@ -0,0 +1,6 @@
+<!-- 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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 7.5" width="12" height="12" fill="context-fill">
+ <path d="M1.5,4.5c.75,0,1.31.75,1.68,1.49A4.47,4.47,0,0,1,7.5,2.25C10.5,2.25,12,5,12,7.5h-.75V9.38a.37.37,0,0,1-.37.38H9.38A.38.38,0,0,1,9,9.38V8.25H5.25V9.38a.37.37,0,0,1-.37.38H3.38A.37.37,0,0,1,3,9.38V7.5H1.5a1.5,1.5,0,0,1,0-3Z" transform="translate(0 -2.25)"/>
+</svg>
diff --git a/devtools/client/netmonitor/src/assets/styles/CustomRequestPanel.css b/devtools/client/netmonitor/src/assets/styles/CustomRequestPanel.css
new file mode 100644
index 0000000000..9549985326
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/CustomRequestPanel.css
@@ -0,0 +1,181 @@
+/* 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/. */
+
+.network-monitor .custom-method-and-url .custom-method-value-label {
+ grid-column: 1 / 1;
+ grid-row: 1 / 1;
+}
+
+.network-monitor .custom-method-and-url .custom-url-value {
+ grid-column: 2 / 2;
+ grid-row: 2 / 2;
+ margin-inline-start: 12px;
+}
+
+.network-monitor .custom-method-and-url .custom-method-value {
+ grid-column: 1 / 1;
+ grid-row: 2 / 2;
+}
+
+.network-monitor .custom-method-and-url .custom-url-value-label {
+ grid-column: 2 / 2;
+ grid-row: 1 / 1 ;
+ margin-inline-start: 12px;
+}
+
+.network-monitor .tabpanel-summary-container.custom-method-and-url {
+ display: grid;
+ grid-template-columns: auto 1fr;
+}
+
+.network-monitor .custom-method-and-url input {
+ font-weight: 400;
+ margin-top: 4px;
+ min-width: 9ch;
+ padding: 2px 3px;
+}
+
+.network-monitor .custom-request-panel textarea {
+ font-weight: 400;
+ margin-top: 4px;
+ padding: 8px;
+ direction: ltr;
+}
+
+.network-monitor .custom-request-panel {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.network-monitor .custom-request-panel .custom-request-panel-content {
+ flex: 1 1 auto;
+ height: auto;
+ overflow: auto;
+}
+
+.network-monitor .custom-request-panel-content > div:not(.custom-request) {
+ margin-bottom: 12px;
+ padding-inline: 16px;
+}
+
+.network-monitor .custom-request {
+ display: block;
+ padding: 0;
+}
+
+.network-monitor .custom-request .custom-request-button-container {
+ display: flex;
+ flex-wrap: wrap-reverse;
+ gap: 8px;
+ margin-block: 16px 12px;
+ margin-inline: 16px;
+}
+
+.network-monitor .custom-request-panel .custom-request-label {
+ font-weight: 400;
+ white-space: nowrap;
+}
+
+.network-monitor .custom-request button {
+ height: 24px;
+ margin-bottom: 4px;
+ padding-inline: 8px;
+ width: auto;
+}
+
+.network-monitor .custom-request button:focus {
+ box-shadow: 0 0 0 1px #0a84ff inset, 0 0 0 1px #0a84ff,
+ 0 0 0 4px rgba(10,132,255,0.3)
+}
+
+.network-monitor .custom-request #custom-request-send-button {
+ background-color: var(--blue-60);
+ color: white;
+}
+
+.network-monitor .custom-request #custom-request-send-button:active {
+ background-color: var(--blue-80);
+}
+
+.network-monitor .custom-request #custom-request-send-button:hover {
+ background-color: var(--blue-70);
+}
+
+.network-monitor .custom-request #custom-request-close-button {
+ margin-inline-end: 4px;
+}
+
+.network-monitor .custom-header {
+ border-style: solid;
+ border-width: 0;
+ flex: none;
+ height: calc(var(--theme-toolbar-height) + 1px);
+ padding: 4px 16px;
+}
+
+:root.theme-dark .network-details-bar .custom-request-panel {
+ background-color: var(--grey-85);
+}
+
+:root.theme-dark .network-monitor #custom-request-close-button {
+ background-color: var(--toolbarbutton-background);
+ border: 1px solid var(--theme-splitter-color);
+}
+
+:root.theme-dark .network-monitor #custom-request-close-button:hover:active {
+ background-color: var(--theme-selection-background-hover);
+}
+
+:root.theme-dark .network-monitor #custom-request-close-button:focus {
+ background-color: var(--theme-selection-focus-background);
+}
+
+:root.theme-dark .network-monitor .custom-request-label.custom-header {
+ background-color: var(--grey-80);
+ border-bottom: 1px solid var(--theme-splitter-color);
+}
+
+:root.theme-dark .network-details-bar .custom-request-panel input,
+:root.theme-dark .network-details-bar .custom-request-panel textarea {
+ background-color: var(--grey-70);
+ border: 1px solid var(--grey-85);
+ color: white;
+}
+
+:root.theme-dark .network-monitor .custom-request-label {
+ color: var(--grey-40);
+}
+
+:root.theme-light .network-details-bar .custom-request-label.custom-header {
+ background-color: var(--grey-10);
+ border-bottom: 1px solid var(--grey-25);
+}
+
+:root.theme-light .network-monitor #custom-request-close-button {
+ background-color: var(--grey-20);
+ border: var(--theme-splitter-color);
+}
+
+:root.theme-light .network-monitor #custom-request-close-button:hover:active {
+ background-color: var(--theme-selection-background-hover);
+}
+
+:root.theme-light .network-monitor #custom-request-close-button:focus {
+ outline: 2px solid var(--blue-50);
+ outline-offset: -2px;
+ box-shadow: 0 0 0 2px rgba(10, 132, 255, 0.3);
+ border-radius: 2px;
+}
+
+:root.theme-light .network-details-bar .custom-request-panel input,
+:root.theme-light .network-details-bar .custom-request-panel textarea {
+ background-color: white;
+ border: 1px solid var(--grey-25);
+ color: var(--grey-90);
+}
+
+:root.theme-light .network-monitor .custom-request-label {
+ color: var(--grey-60);
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/HTTPCustomRequestPanel.css b/devtools/client/netmonitor/src/assets/styles/HTTPCustomRequestPanel.css
new file mode 100644
index 0000000000..cd0f269bc6
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/HTTPCustomRequestPanel.css
@@ -0,0 +1,379 @@
+/* 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/. */
+
+.network-monitor .tabpanel-summary-container:is(.http-custom-section, .http-custom-method-and-url, .http-custom-input ) {
+ padding-inline-start: 0;
+ margin: 0;
+}
+
+.network-monitor .tabpanel-summary-container.http-custom-method-and-url {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ width: 100%;
+}
+
+.network-monitor .http-custom-method-and-url .http-custom-method-value {
+ grid-column: 1 / 1;
+ grid-row: 1 / 1;
+ align-self: start;
+ margin-inline-start: 10px;
+ padding-top: 4px;
+ font-size: 11px;
+ line-height: 13px;
+}
+
+.auto-growing-textarea {
+ display: grid;
+ width: 100%;
+}
+
+.auto-growing-textarea:focus-within::after {
+ content: attr(data-replicated-value) " ";
+ white-space: pre-wrap;
+ visibility: hidden;
+ word-wrap: break-word;
+}
+
+.auto-growing-textarea > textarea {
+ resize: none;
+ overflow: hidden;
+ /* Force the content in a single line */
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* When editing a textarea, restore the multiline display */
+.auto-growing-textarea > textarea:focus {
+ text-overflow: unset;
+ white-space: unset;
+}
+
+.auto-growing-textarea > textarea,
+.auto-growing-textarea:focus-within::after {
+ grid-area: 1 / 1 / 2 / 2;
+ border: 0;
+ font-weight: normal;
+ min-width: 9ch;
+ padding: 4px;
+ padding-inline-start: 7px;
+ /* Adding this to have maximo 5 lines */
+ max-height: 70px;
+ overflow-y: auto;
+}
+
+.network-monitor .http-custom-method-and-url .http-custom-method-value,
+.tabpanel-summary-container.http-custom-section .tabpanel-summary-input {
+ border: 0;
+}
+
+.tabpanel-summary-container .http-custom-section .tabpanel-summary-input-value {
+ font-weight: normal;
+ min-width: 9ch;
+ padding: 4px;
+ padding-inline-start: 7px;
+}
+
+.network-monitor .http-custom-method-and-url input ::placeholder {
+ color: var(--grey-50);
+ font-size: 11px;
+ line-height: 13px;
+ margin-inline-end: 8px;
+}
+
+.network-monitor .tabpanel-summary-container .http-custom-request-label {
+ padding: 6px 13px;
+ font-size: 12px;
+ line-height: 14px;
+}
+
+.network-monitor .http-custom-request-panel textarea {
+ color: var(--grey-50);
+ font-weight: normal;
+ font-size: 11px;
+ line-height: 13px;
+ direction: ltr;
+}
+
+.network-monitor .http-custom-request-panel {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.network-monitor .http-custom-request-panel .http-custom-request-panel-content {
+ flex: 1 1 auto;
+ height: auto;
+ overflow: auto;
+}
+
+.network-monitor .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) {
+ position: relative;
+ display: flex;
+ flex-wrap: nowrap;
+ align-items: flex-start;
+ width: 100%;
+ overflow: hidden;
+ padding: 0px 13px;
+ padding-inline-end: 0;
+}
+
+.network-monitor .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .tabpanel-summary-input-name {
+ width: 25%;
+ align-self: stretch;
+ min-width: min-content;
+}
+
+.network-monitor .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .tabpanel-summary-input-value {
+ width: 75%;
+ align-self: stretch;
+}
+
+.map-add-new-inputs {
+ padding-bottom: 2px;
+}
+
+#http-custom-postdata-value.tabpanel-summary-input {
+ padding-inline-start: 14px;
+}
+
+.http-custom-delete-button {
+ opacity: 0;
+ flex: none;
+ width: 20px;
+ height: 20px;
+ margin: 0;
+ padding: 2px;
+ border: none;
+ outline: none;
+ background-color: transparent;
+ position: absolute;
+ right: 0;
+}
+
+.tabpanel-summary-container.http-custom-input .http-custom-delete-button::-moz-focus-inner {
+ border: none;
+}
+
+.tabpanel-summary-container.http-custom-input:hover .http-custom-delete-button {
+ opacity: 1;
+}
+
+.tabpanel-summary-container.http-custom-input .http-custom-delete-button::before {
+ content: "";
+ display: block;
+ width: 16px;
+ height: 16px;
+ border-radius: 2px;
+ background: url("chrome://devtools/skin/images/close.svg") no-repeat center;
+ background-size: 12px;
+ -moz-context-properties: fill;
+ fill: var(--theme-icon-color);
+}
+
+.tabpanel-summary-container.http-custom-input .http-custom-delete-button:hover::before {
+ fill: var(--theme-selection-color);
+ background-color: var(--theme-selection-background);
+}
+
+.network-monitor .http-custom-request-button-container {
+ display: flex;
+ justify-content: end;
+ flex-wrap: wrap-reverse;
+ gap: 8px;
+ padding: 10px 16px;
+ border-block-start: 1px solid var(--theme-splitter-color);
+}
+
+.network-monitor .http-custom-request-panel .http-custom-request-label {
+ font-weight: 400;
+ white-space: nowrap;
+}
+
+.network-monitor .http-custom-request-button-container button {
+ height: 24px;
+ padding-inline: 8px;
+ width: auto;
+}
+
+.network-monitor .http-custom-request-button-container button:focus {
+ box-shadow: 0 0 0 1px #0a84ff inset, 0 0 0 1px #0a84ff,
+ 0 0 0 4px rgba(10,132,255,0.3)
+}
+
+.network-monitor .http-custom-request-button-container #http-custom-request-send-button {
+ background-color: var(--blue-60);
+ color: white;
+}
+
+.network-monitor .http-custom-request-button-container #http-custom-request-send-button:active {
+ background-color: var(--blue-80);
+}
+
+.network-monitor .http-custom-request-button-container #http-custom-request-send-button:hover {
+ background-color: var(--blue-70);
+}
+
+.network-monitor .http-custom-header {
+ border-style: solid;
+ border-width: 0;
+ flex: none;
+ height: calc(var(--theme-toolbar-height) + 1px);
+ padding: 4px 16px;
+}
+
+/* Dark theme */
+:root.theme-dark .network-details-bar .http-custom-request-panel {
+ background-color: var(--grey-85);
+}
+
+:root.theme-dark .network-monitor .tabpanel-summary-container:is(.http-custom-method-and-url, .http-custom-section),
+:root.theme-dark .network-monitor .tabpanel-summary-container .http-custom-request-label {
+ border-bottom: 1px solid var(--grey-60);
+}
+
+:root.theme-dark .network-monitor .http-custom-method-and-url :is(.http-custom-method-value, .http-custom-url-value),
+:root.theme-dark .network-monitor .tabpanel-summary-container .tabpanel-summary-input,
+:root.theme-dark .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-name,
+:root.theme-dark .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-value {
+ background-color: var(--grey-85);
+ color: white;
+}
+
+:root.theme-dark .network-monitor .http-custom-method-and-url .http-custom-url-value,
+:root.theme-dark .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) #http-custom-input-value {
+ border-inline-start: 1px solid var(--grey-60);
+}
+
+:root.theme-dark .network-monitor .http-custom-method-and-url .http-custom-url-value:focus {
+ outline: 2px solid var(--blue-50);
+ width: calc(100% - 8px);
+}
+
+:root.theme-dark .network-monitor .tabpanel-summary-container .tabpanel-summary-input:focus {
+ outline: 2px solid var(--blue-50);
+ margin-inline-start: 2px;
+ width: calc(100% - 5px);
+}
+
+:root.theme-dark .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-name:focus {
+ outline: 2px solid var(--blue-50);
+ margin-inline-end: 1px;
+}
+
+:root.theme-dark .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-value:focus {
+ outline: 2px solid var(--blue-50);
+ width: calc(100% - 20px);
+}
+
+:root.theme-dark .http-custom-input-and-map-form .map-add-new-inputs .tabpanel-summary-input-value,
+:root.theme-dark #http-custom-query .http-custom-input-and-map-form .tabpanel-summary-input-value:focus {
+ margin-inline-end: 1px;
+}
+
+:root.theme-dark .network-monitor #http-custom-request-clear-button {
+ background-color: var(--toolbarbutton-background);
+ border: 1px solid var(--theme-splitter-color);
+}
+
+:root.theme-dark .network-monitor #http-custom-request-clear-button:hover:active {
+ background-color: var(--theme-selection-background-hover);
+}
+
+:root.theme-dark .network-monitor #http-custom-request-clear-button:focus {
+ background-color: var(--theme-selection-focus-background);
+}
+
+:root.theme-dark .network-monitor .http-custom-request-label.http-custom-header {
+ background-color: var(--grey-80);
+ border-bottom: 1px solid var(--theme-splitter-color);
+}
+
+:root.theme-dark .network-details-bar .http-custom-request-panel input,
+:root.theme-dark .network-details-bar .http-custom-request-panel textarea {
+ background-color: var(--grey-70);
+ border: 1px solid var(--grey-85);
+ color: white;
+}
+
+:root.theme-dark .network-monitor .http-custom-request-label {
+ color: var(--grey-40);
+}
+
+/* Light theme */
+:root.theme-light .network-monitor .tabpanel-summary-container:is(.http-custom-method-and-url, .http-custom-section),
+:root.theme-light .network-monitor .tabpanel-summary-container .http-custom-request-label {
+ border-bottom: 1px solid var(--grey-30);
+}
+
+:root.theme-light .network-monitor .http-custom-method-and-url .http-custom-method-value {
+ background-color: white;
+}
+
+:root.theme-light .network-monitor .http-custom-method-and-url .http-custom-url-value,
+:root.theme-light .tabpanel-summary-container .tabpanel-summary-input-value {
+ border-inline-start: 1px solid var(--grey-30);
+}
+
+:root.theme-light .network-monitor .http-custom-method-and-url .http-custom-url-value:focus {
+ outline: 2px solid var(--blue-50);
+ width: calc(100% - 8px);
+}
+
+:root.theme-light .network-monitor .tabpanel-summary-container .tabpanel-summary-input:focus {
+ outline: 2px solid var(--blue-50);
+ margin-inline-start: 2px;
+ width: calc(100% - 5px);
+}
+
+:root.theme-light .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-name:focus {
+ outline: 2px solid var(--blue-50);
+ margin-inline-end: 1px;
+}
+
+:root.theme-light .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-value:focus {
+ outline: 2px solid var(--blue-50);
+ width: calc(100% - 20px);
+}
+
+:root.theme-light .http-custom-input-and-map-form .map-add-new-inputs .tabpanel-summary-input-value:focus,
+:root.theme-light #http-custom-query .http-custom-input-and-map-form .tabpanel-summary-input-value:focus {
+ margin-inline-end: 3px;
+}
+
+:root.theme-light .network-monitor .tabpanel-summary-container .http-custom-request-label {
+ background-color: var(--grey-10);
+ color: var(--grey-90);
+}
+
+:root.theme-light .network-details-bar .http-custom-request-label.http-custom-header {
+ background-color: var(--grey-10);
+ border-bottom: 1px solid var(--grey-25);
+}
+
+:root.theme-light .network-monitor #http-custom-request-clear-button {
+ background-color: var(--grey-25);
+ border: var(--theme-splitter-color);
+}
+
+:root.theme-light .network-monitor #http-custom-request-clear-button:hover:active {
+ background-color: var(--theme-selection-background-hover);
+}
+
+:root.theme-light .network-monitor #http-custom-request-clear-button:focus {
+ outline: 2px solid var(--blue-50);
+ outline-offset: -2px;
+ box-shadow: 0 0 0 2px rgba(10, 132, 255, 0.3);
+ border-radius: 2px;
+}
+
+:root.theme-light .network-details-bar .http-custom-request-panel input,
+:root.theme-light .network-details-bar .http-custom-request-panel textarea {
+ background-color: white;
+ border: 1px solid var(--grey-25);
+ color: var(--grey-90);
+}
+
+:root.theme-light .network-monitor .http-custom-request-label {
+ color: var(--grey-60);
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/HeadersPanel.css b/devtools/client/netmonitor/src/assets/styles/HeadersPanel.css
new file mode 100644
index 0000000000..f62ec166e1
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/HeadersPanel.css
@@ -0,0 +1,210 @@
+/* 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/. */
+
+/* Headers tabpanel */
+
+.network-monitor .headers-panel-container {
+ height: 100%;
+ overflow: hidden;
+ position: relative;
+}
+
+.network-monitor .headers-panel-container .treeTable {
+ overflow: hidden;
+}
+
+.network-monitor .headers-panel-container .panel-container {
+ position: absolute;
+ top: calc(var(--theme-toolbar-height) + 1px);
+ bottom: 0;
+ right: 0;
+ left: 0;
+ height: auto;
+}
+
+.network-monitor .headers-panel-container .devtools-button {
+ padding: 0;
+}
+.network-monitor .headers-panel-container .devtools-dropdown-button {
+ padding: 0;
+}
+
+.network-monitor .headers-panel-container .devtools-button:is(#block-button, #edit-resend-button) {
+ height: 19px;
+ padding: 0 2px;
+}
+
+.network-monitor .headers-panel-container .devtools-button:not(:hover) {
+ background-color: transparent;
+}
+
+.network-monitor .headers-overview {
+ border-bottom: 1px solid var(--theme-splitter-color);
+}
+
+.network-monitor .headers-overview .summary {
+ padding: 6px 16px 2px;
+}
+
+.network-monitor .headers-summary,
+.network-monitor .response-summary {
+ display: flex;
+ align-items: center;
+}
+
+.network-monitor .raw-headers-toggle {
+ display: flex;
+ flex-direction: row;
+ flex-wrap: nowrap;
+ justify-content: flex-end;
+ align-items: center;
+ cursor: pointer;
+}
+
+.network-monitor .raw-headers-toggle .headers-summary-label {
+ color: var(--theme-toolbar-color);
+}
+
+.network-monitor .raw-headers-toggle-input > input {
+ display: inline-block;
+ width: 2em;
+ vertical-align: bottom;
+ font-size: 12px;
+}
+
+.network-monitor .properties-view .tree-container .treeTable .treeValueCell .devtools-checkbox-toggle {
+ margin-block: 2px;
+}
+
+.network-monitor .properties-view .raw-headers-container .raw-headers {
+ display: block;
+ overflow: hidden;
+ width: 100%;
+ padding: 2px 12px;
+ white-space: pre;
+ overflow-wrap: normal;
+ overflow-x: auto;
+ border: none;
+}
+
+.network-monitor .accordion-item .treeTable .objectBox-string {
+ color: var(--theme-body-color);
+}
+
+.network-monitor .accordion-item .treeTable tr.treeRow.selected .objectBox-string {
+ color: var(--theme-selection-color);
+}
+
+.network-monitor .properties-view .raw-headers-container td {
+ display: block;
+}
+
+.network-monitor .properties-view .raw-headers-container textarea {
+ width: 100%;
+ font-family: var(--monospace-font-family);
+ font-size: var(--theme-body-font-size);
+ resize: none;
+}
+
+.theme-light .network-monitor .properties-view textarea {
+ background-color: white;
+ border: 1px solid var(--grey-25);
+ color: var(--grey-90);
+}
+
+.theme-dark .network-monitor .properties-view textarea {
+ background-color: var(--grey-70);
+ border: 1px solid var(--grey-85);
+ color: white;
+}
+
+.network-monitor .properties-view .raw-headers .tabpanel-summary-label {
+ padding: 0 0 4px;
+}
+
+.headers-summary .textbox-input {
+ margin-inline-end: 2px;
+}
+
+.network-monitor .headers-summary .status-text {
+ width: auto !important;
+ margin-inline-start: 4px;
+}
+
+.network-monitor .headers-panel-container .accordion .properties-view tr.treeRow {
+ padding: 1px 0 2px;
+}
+.network-monitor .headers-panel-container .accordion .properties-view tr.treeRow .treeLabelCell {
+ float: left;
+ margin-right: -33px;
+ margin-left: 5px;
+ padding: 0;
+
+}
+.network-monitor .headers-panel-container .accordion .properties-view tr.treeRow .treeValueCell {
+ display: inline;
+ word-break: break-all;
+ box-decoration-break: clone;
+ padding-left: 39px;
+ padding-right: 20px;
+}
+
+.network-monitor .headers-panel-container .accordion .properties-view tr.treeRow .treeValueCell div {
+ display: inline;
+}
+
+/* Cookies */
+
+.network-monitor .cookies-panel-container .accordion .properties-view tr.treeRow .treeLabelCell {
+ padding-inline-start: 0;
+}
+
+/* Summary tabpanel */
+
+.network-monitor .tabpanel-summary-container {
+ flex-wrap: wrap;
+ padding-inline-start: 4px;
+ margin-bottom: 5px;
+}
+
+.network-monitor .tabpanel-summary-container .tracking-resource {
+ margin-inline: -2px 2px;
+ vertical-align: text-bottom;
+ fill: var(--theme-icon-color);
+}
+
+.network-monitor .tabpanel-summary-label {
+ display: inline-block;
+ padding-inline-end: 3px;
+ min-width: 90px;
+ color: var(--theme-icon-dimmed-color);
+}
+
+.network-monitor .tabpanel-summary-value {
+ color: inherit;
+ padding-inline-start: 3px;
+ unicode-bidi: plaintext;
+}
+
+.network-monitor .tabpanel-summary-value strong {
+ margin-right: 3px;
+}
+
+.theme-dark .network-monitor .tabpanel-summary-value {
+ color: var(--theme-selection-color);
+}
+
+.network-monitor .tracking-protection {
+ color: var(--theme-icon-dimmed-color);
+ max-width: 200px;
+}
+
+.network-monitor .tracking-protection .learn-more-link:not(:hover)::before {
+ color: var(--theme-icon-dimmed-color);
+}
+
+.network-monitor .headers-summary-label,
+.network-monitor .tree-container .objectBox {
+ white-space: nowrap;
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/NetworkActionBar.css b/devtools/client/netmonitor/src/assets/styles/NetworkActionBar.css
new file mode 100644
index 0000000000..a2d46ed522
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/NetworkActionBar.css
@@ -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/. */
+
+ .network-monitor .network-action-bar {
+ width: 100%;
+ }
+
+ .network-monitor .network-action-bar .tabs-menu-item {
+ width: 50%;
+ }
diff --git a/devtools/client/netmonitor/src/assets/styles/NetworkDetailsBar.css b/devtools/client/netmonitor/src/assets/styles/NetworkDetailsBar.css
new file mode 100644
index 0000000000..0f17d4cc64
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/NetworkDetailsBar.css
@@ -0,0 +1,574 @@
+/* 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/. */
+
+/* Network details panel */
+
+.network-monitor .network-details-bar {
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+}
+
+.network-monitor .panel-container {
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ overflow-x: hidden;
+ overflow-y: auto;
+}
+
+.network-monitor .panel-container .tree-container .objectBox {
+ white-space: normal;
+ word-wrap: break-word;
+ unicode-bidi: plaintext;
+}
+
+.network-monitor .properties-view {
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ height: 100%;
+ overflow: auto;
+}
+
+.network-monitor .properties-view .searchbox-section {
+ flex: 0 1 auto;
+}
+
+.network-monitor .properties-view .devtools-searchbox {
+ padding: 0;
+}
+
+.network-monitor .properties-view .devtools-searchbox input {
+ margin: 1px 3px;
+}
+
+/* Empty notices in tab panels */
+
+.network-monitor .empty-notice {
+ color: var(--theme-text-color-inactive);
+ padding: 3px 8px;
+ text-align: center;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ font-size: 24px;
+}
+
+/* Accordions in the tab panels */
+
+.network-monitor .accordion-content .treeIcon {
+ margin-left: 16px;
+}
+
+.network-monitor .accordion {
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+}
+
+.network-monitor .accordion-item:last-child {
+ position: relative;
+ height: 100%;
+}
+
+.network-monitor .accordion-item:last-child .accordion-header {
+ position: relative;
+}
+
+.network-monitor .accordion-item:last-child .accordion-content {
+ position: relative;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ overflow: inherit;
+}
+
+
+/* Text inputs in tab panels */
+
+.network-monitor .textbox-input {
+ text-overflow: ellipsis;
+ border: none;
+ background: none;
+ color: inherit;
+ width: 100%;
+}
+
+.network-monitor .textbox-input:focus {
+ outline: 0;
+ box-shadow: var(--theme-focus-box-shadow-textbox);
+}
+
+/* Tree table in tab panels */
+
+.network-monitor .tree-container, .tree-container .treeTable {
+ position: relative;
+ height: 100%;
+ width: 100%;
+ overflow: auto;
+ flex: 1;
+}
+
+.network-monitor .tree-container .treeTable,
+.network-monitor .tree-container .treeTable tbody {
+ display: flex;
+ flex-direction: column;
+}
+
+.network-monitor .tree-container .treeTable tbody {
+ height: 100%;
+}
+
+.network-monitor .tree-container .treeTable tr {
+ display: block;
+ position: relative;
+}
+
+/* Make right td fill available horizontal space */
+.network-monitor .tree-container .treeTable td:last-child {
+ width: 100%;
+}
+
+.network-monitor .tree-container .treeTable .tree-section,
+.network-monitor .properties-view .raw-headers-container {
+ width: 100%;
+ background-color: var(--theme-toolbar-background);
+}
+
+.network-monitor .tree-container .treeTable tr.tree-section:not(:first-child) td:not([class=""]) {
+ border-top: 1px solid var(--theme-splitter-color);
+}
+
+.network-monitor .tree-container .treeTable tr.tree-section:not(:last-child) td:not([class=""]) {
+ border-bottom: 1px solid var(--theme-splitter-color);
+}
+
+.network-monitor .tree-container .treeTable .tree-section > * {
+ vertical-align: middle;
+}
+
+.network-monitor .tree-container .treeTable .treeRow.tree-section > .treeLabelCell > .treeLabel,
+.network-monitor .tree-container .treeTable .treeRow.tree-section > .treeLabelCell > .treeLabel:hover,
+.network-monitor .tree-container .treeTable .treeRow.tree-section > .treeValueCell:not(:hover) * {
+ color: var(--theme-toolbar-color);
+}
+
+/* Force the twisty icon to gray even if the treeRow has the selected class */
+.network-monitor .tree-container .treeTable .treeRow.tree-section .theme-twisty {
+ fill: var(--theme-icon-dimmed-color);
+}
+
+/* Make the twisties rotate to the right in code-only sections on RTL. */
+.network-monitor .tab-panel.panel-with-code tr:not(.tree-section).hasChildren .theme-twisty:not(.open):dir(rtl) {
+ transform: rotate(-90deg);
+}
+
+.network-monitor .tree-container .treeTable .treeValueCell {
+ /* FIXME: Make value cell can be reduced to shorter width */
+ max-width: 0;
+ padding-inline-end: 5px;
+}
+
+.network-monitor .tree-container .treeTable .treeRow.hasChildren > .treeLabelCell > .treeLabel:hover {
+ text-decoration: none;
+}
+
+.network-monitor .tab-panel.panel-with-code .tree-container .treeTable tr:not(.tree-section):dir(rtl) {
+ direction: ltr;
+ text-align: left;
+}
+
+/* Source editor in tab panels */
+
+/* If there is a source editor shows up in the last row of TreeView,
+ * it should occupy the available vertical space.
+ */
+.network-monitor .editor-row-container,
+.network-monitor .tree-container .treeTable tr:last-child td[colspan="2"] {
+ display: block;
+ height: 100%;
+ flex: 1;
+ overflow-x: auto;
+}
+
+.network-monitor .responseTextContainer {
+ overflow-x: auto;
+ width: 100%;
+ height: 100%;
+ padding-left: 5px;
+}
+
+/* If there is a source editor shows up in the last row of TreeView,
+ * its height should not collapse into zero
+ */
+.network-monitor .tree-container .treeTable tr:last-child.editor-row-container {
+ overflow: visible;
+}
+
+.network-monitor .source-editor-mount {
+ width: 100%;
+ height: 100%;
+}
+
+.network-monitor .headers-summary-label,
+.network-monitor .tree-container .objectBox {
+ white-space: nowrap;
+}
+
+/* Params and Response error messages */
+
+.network-monitor .request-error-header,
+.network-monitor .response-error-header {
+ margin: 0;
+ padding: 4px 8px;
+ border-bottom: 1px solid var(--theme-splitter-color);
+ background-color: var(--red-60);
+ color: white;
+ line-height: 16px;
+}
+
+.theme-dark .network-monitor .request-error-header,
+.theme-dark .network-monitor .response-error-header {
+ background-color: var(--red-70);
+}
+
+/* Response tabpanel */
+
+.network-monitor .response-image-box {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ overflow-y: auto;
+ padding: 10px;
+}
+
+.network-monitor .response-image {
+ background: #fff;
+ border: 1px dashed GrayText;
+ margin-bottom: 10px;
+ max-width: 300px;
+ max-height: 100px;
+}
+
+.network-monitor #response-panel .response-font-box {
+ overflow-y: auto;
+ padding: 10px;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+}
+
+.network-monitor .response-font {
+ margin-bottom: 10px;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+}
+
+.network-monitor .tree-container .treeTable tr.response-preview-container {
+ flex: 1;
+ min-height: 0;
+}
+
+.network-monitor .tree-container .treeTable tr.response-preview-container td {
+ display: block;
+ height: 100%;
+}
+
+.network-monitor .html-preview {
+ height: 100%;
+}
+
+.network-monitor .html-preview iframe {
+ background-color: #fff;
+ border: none;
+ height: 100%;
+ width: 100%;
+}
+
+/* The editor container should only become a flex item when inside a container
+ * with other flex items. In this case, the HTML preview is a flex item and we
+ * can grow the editor. Otherwise, there may be overflow and
+ * .editor-row-container will become 0px tall. */
+.network-monitor .contains-html-preview .editor-row-container {
+ flex: 1;
+ min-height: 0;
+}
+
+/* Request and response data */
+
+.network-monitor #response-panel .panel-container {
+ overflow-y: hidden;
+}
+
+.network-monitor .data-header {
+ background: var(--theme-toolbar-background);
+ border-bottom: 1px solid var(--theme-splitter-color);
+ color: var(--theme-toolbar-color);
+ font-size: inherit;
+ font-weight: normal;
+ line-height: 16px;
+ margin: 0;
+ padding: 2px 4px;
+ width: 100%;
+ align-items: center;
+ display: flex;
+ user-select: none;
+}
+
+.network-monitor .data-label {
+ display: block;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-size: inherit;
+ line-height: 20px;
+ color: var(--theme-toolbar-color);
+}
+
+.network-monitor .raw-data-toggle {
+ flex: none;
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ max-width: 50%;
+ margin-inline-start: auto;
+ padding-inline-start: 4px;
+}
+
+.network-monitor .raw-data-toggle-label {
+ white-space: nowrap;
+ color: var(--theme-toolbar-color);
+}
+
+.network-monitor .raw-data-toggle-input > input {
+ display: inline-block;
+ width: 2em;
+ vertical-align: bottom;
+ font-size: 12px;
+}
+
+.network-monitor #response-panel .notificationbox .notification[data-key="CORS-error"].notification[data-type="info"] {
+ background-color: var(--theme-body-alternate-emphasized-background);
+}
+
+.network-monitor #response-panel .notification[data-key="CORS-error"] .notificationInner .messageText {
+ white-space: normal;
+ padding-top: 8px;
+ padding-bottom: 8px;
+}
+
+/* Timings tabpanel */
+
+.network-monitor .timings-container {
+ display: flex;
+}
+
+.network-monitor .timings-overview {
+ display: flex;
+ border-bottom: 1px solid var(--theme-splitter-color);
+ padding: 4px;
+}
+
+.network-monitor .timings-overview-item {
+ display: inline-flex;
+}
+
+.network-monitor .timings-overview-item:not(:first-of-type)::before {
+ content: "";
+ display: inline-flex;
+ margin-inline: 10px;
+ width: 1px;
+ background: var(--theme-splitter-color);
+}
+
+.network-monitor .timings-label {
+ width: 10em;
+}
+
+.network-monitor .requests-list-timings-container {
+ display: flex;
+ flex: 1;
+ align-items: center;
+}
+
+.network-monitor .requests-list-timings-offset {
+ transition: width 0.2s ease-out;
+}
+
+.network-monitor .requests-list-timings-box {
+ border: none;
+ min-width: 1px;
+ transition: width 0.2s ease-out;
+}
+
+.network-monitor .label-separator {
+ margin-block: 5px;
+ margin-inline-start: 4px;
+ font-weight: 600;
+ color: var(--theme-comment);
+}
+
+.theme-light .network-monitor .requests-list-timings-box {
+ --timing-server-color-1: rgba(104, 195, 179, 0.8); /* teal */
+ --timing-server-color-2: rgba(123, 102, 167, 0.8); /* purple */
+ --timing-server-color-3: rgba(233, 236, 130, 0.8); /* yellow */
+ --timing-server-color-total: rgba(186, 90, 140, 0.8); /* pink */
+}
+
+.theme-dark .network-monitor .requests-list-timings-box {
+ --timing-server-color-1: rgba(74, 228, 201, 0.8); /* teal */
+ --timing-server-color-2: rgba(156, 119, 233, 0.8); /* purple */
+ --timing-server-color-3: rgba(234, 239, 73, 0.8); /* yellow */
+ --timing-server-color-total: rgba(186, 74, 133, 0.8); /* pink */
+}
+
+.network-monitor .server-timings-color-1 {
+ background: var(--timing-server-color-1);
+}
+
+.network-monitor .server-timings-color-2 {
+ background: var(--timing-server-color-2);
+}
+
+.network-monitor .server-timings-color-3 {
+ background: var(--timing-server-color-3);
+}
+
+.network-monitor .server-timings-color-total {
+ background: var(--timing-server-color-total);
+}
+
+
+/* Stack trace panel */
+
+.network-monitor .stack-trace {
+ font-family: var(--monospace-font-family);
+ /* The markup contains extra whitespace to improve formatting of clipboard text.
+ Make sure this whitespace doesn't affect the HTML rendering */
+ white-space: normal;
+ padding: 5px;
+ direction: ltr;
+}
+
+.network-monitor .stack-trace .frame-link-source {
+ /* Makes the file name truncated (and ellipsis shown) on the left side */
+ direction: rtl;
+ unicode-bidi: embed;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ text-align: end;
+}
+
+.network-monitor .stack-trace .frame-link-function-display-name {
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ margin-inline-end: 1ch;
+}
+
+/* Security tabpanel */
+
+/* Overwrite tree-view cell colon `:` for security panel and tree section */
+.network-monitor .security-panel .treeTable .treeLabelCell::after,
+.network-monitor .treeTable .tree-section .treeLabelCell::after {
+ content: "";
+}
+
+/* Layout additional warning icon in tree value cell */
+.network-monitor .security-info-value {
+ display: flex;
+}
+
+.network-monitor .security-warning-icon {
+ width: 12px;
+ height: 12px;
+ vertical-align: -1px;
+ margin-inline-start: 5px;
+ background-image: url(chrome://devtools/skin/images/alert-small.svg);
+ background-size: cover;
+ -moz-context-properties: fill;
+ fill: var(--yellow-60);
+}
+
+/* Custom request panel */
+
+.network-monitor .custom-request-panel, .http-custom-request-panel {
+ height: 100%;
+ background-color: var(--theme-sidebar-background);
+}
+
+.theme-dark .network-monitor .custom-request-panel, .http-custom-request-panel {
+ color: var(--theme-selection-color);
+}
+
+.network-monitor .custom-request-label {
+ font-weight: 600;
+}
+
+.network-monitor .custom-request-panel, .http-custom-request-panel textarea {
+ resize: none;
+ font: message-box;
+ font-size: var(--theme-body-font-size);
+}
+
+.network-monitor .custom-header,
+.network-monitor .custom-method-and-url,
+.network-monitor .custom-request,
+.network-monitor .custom-section,
+.network-monitor .http-custom-header,
+.network-monitor .http-custom-method-and-url,
+.network-monitor .http-custom-request,
+.network-monitor .http-custom-section {
+ display: flex;
+}
+
+.network-monitor .custom-header,
+.network-monitor .http-custom-header {
+ flex-grow: 1;
+ font-size: 1.1em;
+ padding-top: 4px;
+}
+
+.network-monitor .custom-section {
+ flex-direction: column;
+ margin-top: 0.5em;
+}
+
+.network-monitor .http-custom-section {
+ flex-direction: column;
+}
+
+.network-monitor .custom-method-value {
+ width: 4.5em;
+}
+
+.network-monitor .http-custom-method-value{
+ width: 6.0em;
+}
+
+.network-monitor .custom-url-value,
+.network-monitor .http-custom-url-value {
+ flex-grow: 1;
+ margin-inline-start: 6px;
+}
+
+.network-monitor #response-panel .notification[data-key="xssi-string-removed-info-box"] {
+ background-color: var(--theme-body-alternate-emphasized-background);
+}
+
+.network-monitor #response-panel .notification[data-key="xssi-string-removed-info-box"] .notificationInner .messageText {
+ white-space: normal;
+ padding-top: 8px;
+ padding-bottom: 8px;
+}
+
+#timings-panel .learn-more-link {
+ width: -moz-max-content;
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/RequestBlockingPanel.css b/devtools/client/netmonitor/src/assets/styles/RequestBlockingPanel.css
new file mode 100644
index 0000000000..3675dd5f22
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/RequestBlockingPanel.css
@@ -0,0 +1,184 @@
+/* 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/. */
+
+.request-blocking-panel {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ overflow: hidden;
+}
+
+/* Override the devtools-checkbox style to improve hit area and alignment */
+.request-blocking-panel .devtools-checkbox-label {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ margin: 0;
+ padding: 2px 4px;
+ /* checkbox can be 13px, 14px or 16px depending on the platform */
+ line-height: 16px;
+ user-select: none;
+ cursor: default;
+}
+
+.request-blocking-panel .devtools-checkbox-label > input {
+ flex: none;
+ margin: 0;
+}
+
+.request-blocking-label {
+ flex: 1 1 auto;
+ display: block;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.request-blocking-editable-label {
+ cursor: text
+}
+
+/* The "Enable Blocking Requests" bar */
+.request-blocking-enable-bar {
+ flex: none;
+ background: var(--theme-tab-toolbar-background);
+ height: calc(var(--theme-toolbar-height) + 1px);
+ padding-block: 2px;
+ padding-inline: 16px 4px;
+ align-items: center;
+ overflow: hidden;
+ white-space: nowrap;
+ border-bottom: 1px solid var(--theme-splitter-color);
+}
+
+.request-blocking-enable-form {
+ flex-grow: 1;
+}
+
+.request-blocking-contents {
+ flex: 0 1 auto;
+ overflow-y: auto;
+ border-bottom: 1px solid var(--theme-splitter-color);
+}
+
+/* Blocked request list */
+.request-blocking-list {
+ margin: 0;
+ padding: 4px 0;
+}
+
+.request-blocking-list.disabled {
+ background-color: var(--theme-toolbar-hover);
+ opacity: 0.6;
+}
+
+.request-blocking-list li {
+ display: flex;
+ align-items: center;
+ min-height: 20px;
+ padding-inline: 16px 8px;
+}
+
+.request-blocking-list li.request-blocking-edit-item {
+ padding: 0;
+ /* Text input is 24px but we want it to occupy the same space as our 20px rows */
+ margin-block: -2px;
+}
+
+.request-blocking-list li.request-blocking-edit-item form {
+ width: 100%;
+}
+
+.request-blocking-list .devtools-checkbox-label {
+ flex: 1 1 auto;
+ /* Can't seem to make the flex-shrink reduce the element's width when the
+ content is a long URL, even if the URL container has text-overflow: ellipsis.
+ DevTools shows that "the item was clamped to its minimum size" and the shrink
+ part is thus ignored. So we're reserving 20px for the delete button. */
+ max-width: calc(100% - 20px);
+}
+
+.request-blocking-remove-button {
+ /* Visually hide but stay focusable in keyboard navigation */
+ opacity: 0;
+ flex: none;
+ width: 20px;
+ height: 20px;
+ margin: 0;
+ padding: 2px;
+ border: none;
+ outline: none;
+ background-color: transparent;
+}
+
+.request-blocking-remove-button::-moz-focus-inner {
+ border: none;
+}
+
+.request-blocking-list li:hover .request-blocking-remove-button {
+ opacity: 1;
+}
+
+.request-blocking-remove-button::before {
+ content: "";
+ display: block;
+ width: 16px;
+ height: 16px;
+ border-radius: 2px;
+ background: url("chrome://devtools/skin/images/close.svg") no-repeat center;
+ background-size: 12px;
+ -moz-context-properties: fill;
+ fill: var(--theme-icon-color);
+}
+
+.request-blocking-remove-button:hover::before {
+ fill: var(--theme-selection-color);
+ background-color: var(--theme-selection-background);
+}
+
+/* Footer content, progressively pushed by pattern rows in the main list and
+ * remaining "fixed" at the bottom when there is enough content to scroll,
+ * thanks to the magic of flexbox */
+.request-blocking-footer {
+ position: relative;
+ flex: none;
+}
+
+/* Draw a border 1px below the form, so that it disappears out of view when
+ * there are many pattern rows in the main container and the footer is pushed
+ * to the bottom */
+.request-blocking-footer::after {
+ content: "";
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: 100%;
+ border-bottom: 1px solid var(--theme-splitter-color);
+}
+
+/* Text input for the addition and edition forms */
+.request-blocking-add-form input,
+.request-blocking-edit-item input {
+ width: calc(100% - 1px);
+ height: 24px;
+ padding-block: 4px;
+ padding-inline: 20px 8px;
+ background: none;
+}
+
+.request-blocking-list-empty-notice {
+ margin: 0;
+ flex: 1;
+ overflow-x: hidden;
+}
+
+.request-blocking-notice-element {
+ padding-top: 12px;
+ padding-inline: 12px;
+}
+
+.request-blocking-notice-element::before {
+ content:"• ";
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/RequestList.css b/devtools/client/netmonitor/src/assets/styles/RequestList.css
new file mode 100644
index 0000000000..3d1b77fdef
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/RequestList.css
@@ -0,0 +1,653 @@
+/* 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/. */
+
+/* Request list empty panel */
+
+.request-list-empty-notice {
+ margin: 0;
+ flex: 1;
+ overflow-x: hidden;
+}
+
+.empty-notice-element {
+ padding-top: 12px;
+ padding-inline: 12px;
+ font-size: 1.2rem;
+}
+
+.notice-perf-message {
+ margin-top: 2px;
+ align-items: center;
+}
+
+.requests-list-perf-notice-button {
+ min-width: 30px;
+ min-height: 26px;
+ margin: 0 5px;
+ vertical-align: middle;
+}
+
+.requests-list-perf-notice-button::before {
+ background-image: url(chrome://devtools/skin/images/profiler-stopwatch.svg);
+}
+
+.requests-list-slow-button {
+ width: 12px;
+ height: 12px;
+ position: absolute;
+ right: 0;
+ transform: translateY(-50%);
+ top: 50%;
+ cursor: pointer;
+ background-image: linear-gradient(to right,transparent, var(--theme-body-background) 43%);
+ padding-inline-end: 30px;
+ padding-inline-start: 5px;
+}
+
+.request-list-item:not(.selected).odd .requests-list-slow-button {
+ background-image: linear-gradient(to right,transparent, var(--table-zebra-inline-icons-background) 43%);
+}
+
+.request-list-item:not(.selected):hover .requests-list-slow-button,
+.request-list-item:not(.selected).odd:hover .requests-list-slow-button {
+ background-image: linear-gradient(to right,transparent, var(--table-selection-inline-icons-background-hover) 43%);
+}
+
+.request-list-item.selected .requests-list-slow-button {
+ background-image: linear-gradient(to right,transparent, var(--theme-selection-background) 43%);
+}
+
+.requests-list-slow-button::before {
+ content: "";
+ width: 12px;
+ height: 16px;
+ display: inline-block;
+ background-image: url(chrome://devtools/content/netmonitor/src/assets/icons/turtle.svg);
+ background-repeat: no-repeat;
+ background-position-x: right;
+ padding-inline-end: 14px;
+ fill: var(--grey-40);
+ -moz-context-properties: fill;
+}
+
+.request-list-item.selected .requests-list-slow-button::before {
+ fill: currentColor;
+}
+
+.requests-list-reload-notice-button {
+ font-size: inherit;
+ min-height: 26px;
+ margin: 0 5px;
+}
+
+/* Requests list table */
+
+.request-list-container {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ color: var(--theme-body-color);
+}
+
+.requests-list-scroll {
+ overflow-x: hidden;
+ overflow-y: auto;
+ width: 100% !important;
+}
+
+.requests-list-scroll table {
+ /* Disable overflow-anchor for only child in the scrollable element */
+ overflow-anchor: none;
+}
+
+.requests-list-anchor {
+ overflow-anchor: auto;
+ opacity: 0;
+ height: 1px;
+}
+
+.requests-list-table,
+.message-list-table {
+ /* Reset default browser style of <table> */
+ border-spacing: 0;
+ width: 100%;
+ /* The layout must be fixed for resizing of columns to work.
+ The layout is based on the first row.
+ Set the width of those cells, and the rest of the table follows. */
+ table-layout: fixed;
+}
+
+.requests-list-table {
+ /* Clip column resizers when they are higher than the table. */
+ overflow: hidden;
+}
+
+.requests-list-column,
+.message-list-column {
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ vertical-align: middle;
+ /* Reset default browser style of <td> */
+ padding: 0;
+ /* Prevent text selection because it's often invisible (blue on blue),
+ * it conflicts easily with existing click and double-click actions,
+ * and we already have several Copy and Export options. */
+ user-select: none;
+}
+
+.requests-list-column {
+ position: relative;
+}
+
+.requests-list-column > * {
+ display: inline-block;
+}
+
+/* Requests list headers */
+
+.requests-list-headers-group,
+.message-list-headers-group {
+ position: sticky;
+ top: 0;
+ left: 0;
+ width: 100%;
+ z-index: 1;
+}
+
+.requests-list-headers,
+.message-list-headers {
+ padding: 0;
+ color: var(--theme-body-color);
+ background-color: var(--theme-toolbar-background);
+}
+
+.requests-list-headers th,
+.message-list-headers th {
+ height: calc(var(--theme-toolbar-height) + 1px);
+ border-bottom: 1px solid var(--theme-splitter-color);
+}
+
+.requests-list-headers th {
+ /* Allow column-resizers to be visible beyond the headers. */
+ overflow: visible;
+}
+
+.requests-list-headers th:not(:first-child),
+.message-list-headers th:not(:first-child) {
+ border-inline-start: 1px solid var(--theme-splitter-color);
+}
+
+.requests-list-header-button,
+.message-list-header-button {
+ width: 100%;
+ min-height: var(--theme-toolbar-height);
+ border-width: 0;
+ padding-block: 1px;
+ padding-inline-start: 5px;
+ padding-inline-end: 4px;
+ text-align: start;
+ color: inherit;
+ background-color: transparent;
+}
+
+.requests-list-header-button::-moz-focus-inner,
+.message-list-header-button::-moz-focus-inner {
+ border: 0;
+ padding: 0;
+}
+
+.requests-list-header-button:hover {
+ background-color: rgba(0, 0, 0, 0.1);
+}
+
+.requests-list-header-button > .button-text,
+.message-list-header-button > .button-text {
+ display: inline-block;
+ vertical-align: middle;
+ width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.requests-list-header-button > .button-icon,
+.message-list-header-button > .button-icon {
+ /* display icon only when column sorted otherwise display:none */
+ display: none;
+ width: 7px;
+ height: 4px;
+ margin-inline: 3px 6px;
+ vertical-align: middle;
+}
+
+.requests-list-header-button[data-sorted] > .button-icon {
+ /* display icon only when column sorted */
+ display: inline-block;
+}
+
+.requests-list-header-button[data-sorted] > .button-text {
+ /* when sorted - adjust width to fit the icon inside the button */
+ width: calc(100% - 11px);
+}
+
+.requests-list-header-button[data-sorted=ascending] > .button-icon {
+ background-image: url("chrome://devtools/skin/images/sort-ascending-arrow.svg");
+}
+
+.requests-list-header-button[data-sorted=descending] > .button-icon {
+ background-image: url("chrome://devtools/skin/images/sort-descending-arrow.svg");
+}
+
+.requests-list-header-button[data-sorted],
+.requests-list-header-button[data-sorted]:hover {
+ background-color: var(--theme-selection-background);
+ color: var(--theme-selection-color);
+}
+
+.requests-list-header-button[data-sorted],
+.requests-list-column[data-active] + .requests-list-column .requests-list-header-button {
+ border-image: linear-gradient(var(--theme-splitter-color), var(--theme-splitter-color)) 1 1;
+}
+
+/* Requests list headers column-resizer */
+
+.requests-list-headers .column-resizer {
+ z-index: 1000;
+ cursor: ew-resize;
+ margin-inline-start: -3px;
+ width: 7px;
+ min-height: 23px;
+ position: absolute;
+ background-color: transparent;
+ /* Extend column-resizers beyond table header to allow resizing on
+ * column borders as well.*/
+ height: 100vh;
+}
+
+/**
+ * Make sure headers are not processing any mouse
+ * events. This is good for performance during dragging.
+ */
+.requests-list-headers.dragging {
+ pointer-events: none;
+}
+
+/* Requests list column */
+
+/* Status column */
+
+.requests-list-status {
+ /* Don't ellipsize status codes */
+ text-overflow: initial;
+}
+
+.requests-list-status-code.status-code-blocked {
+ /* Improve the icon's vertical alignment by matching the row height. */
+ display: inline-flex;
+ vertical-align: top;
+ align-items: center;
+ justify-content: center;
+ height: 24px;
+}
+
+.requests-security-icon-group {
+ display: inline-flex;
+ vertical-align: top;
+ align-items: center;
+ height: 24px;
+ /* Icons are drawn as backgrounds on a 16x16 element but are often smaller
+ * (e.g. 12x12). Shift them a few pixels to align with the header text. */
+ margin-inline-start: -3px;
+ margin-inline-end: 2px;
+}
+
+.requests-security-state-icon {
+ display: inline-block;
+ height: 16px;
+ background-position: center;
+ background-repeat: no-repeat;
+ -moz-context-properties: fill, stroke;
+ fill: var(--theme-icon-dimmed-color);
+ stroke: var(--theme-icon-color);
+}
+
+.security-state-secure {
+ background-image: url(chrome://devtools/skin/images/security-state-secure.svg);
+ width: 16px;
+}
+
+.security-state-weak {
+ /* Shift icon to the right (in both LTR and RTL directions) to align the
+ * padlock shape with other padlock icons. */
+ position: relative;
+ width: 16px;
+ left: 2px;
+ background-image: url(chrome://devtools/skin/images/security-state-weak.svg);
+ stroke: var(--theme-icon-warning-color);
+}
+
+.security-state-insecure {
+ background-image: url(chrome://devtools/skin/images/security-state-insecure.svg);
+ width: 16px;
+ stroke: var(--theme-icon-error-color);
+}
+
+.security-state-broken {
+ background-image: url(chrome://devtools/skin/images/error-small.svg);
+ width: 16px;
+ fill: var(--theme-icon-error-color);
+}
+
+.tracking-resource {
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ background-image: url(chrome://devtools/content/netmonitor/src/assets/icons/shield.svg);
+ background-repeat: no-repeat;
+ -moz-context-properties: fill;
+ fill: var(--theme-icon-dimmed-color);
+}
+
+.request-list-item.selected .status-code-blocked,
+.request-list-item.selected .requests-security-state-icon,
+.request-list-item.selected .tracking-resource {
+ fill: currentColor;
+ stroke: currentColor;
+ color: var(--theme-selection-color);
+}
+
+.theme-dark .request-list-item.selected .status-code-blocked,
+.theme-dark .request-list-item.selected .requests-security-state-icon,
+.theme-dark .request-list-item.selected .tracking-resource {
+ color: rgba(255, 255, 255, 0.75);
+}
+
+.request-list-item .requests-list-column,
+.message-list-item .message-list-column {
+ padding-inline-start: 5px;
+ /* Column text should not touch the next column's border.
+ We could use a 5px space to be symmetrical, but we're using
+ text-overflow:ellipsis which makes that padding look wider in most cases,
+ and a smaller padding saves space for content. */
+ padding-inline-end: 4px;
+}
+
+.request-list-item .requests-list-column:not(:first-child),
+.message-list-item .message-list-column:not(:first-child) {
+ border-inline-start: 1px solid var(--table-splitter-color);
+}
+
+.request-list-item:hover .requests-list-column,
+.request-list-item.selected .requests-list-column,
+.message-list-item:hover .message-list-column,
+.message-list-item.selected .message-list-column {
+ border-inline-start-color: transparent;
+}
+
+.request-list-item .requests-list-waterfall {
+ padding-inline-start: 0;
+}
+
+.requests-list-cause-stack {
+ display: inline-block;
+ background-color: var(--theme-text-color-alt);
+ color: var(--theme-body-background);
+ font-size: 8px;
+ font-weight: bold;
+ line-height: 10px;
+ border-radius: 3px;
+ padding: 0 2px;
+ margin: 0;
+ margin-inline-end: 3px;
+}
+
+/* Waterfall column */
+
+.requests-list-waterfall {
+ background-repeat: repeat-y;
+ background-position: left center;
+ overflow: visible;
+ /* Background created on a <canvas> in js. */
+ /* @see devtools/client/netmonitor/src/widgets/WaterfallBackground.js */
+ background-image: -moz-element(#waterfall-background);
+}
+
+.requests-list-waterfall:dir(rtl) {
+ background-position: right center;
+}
+
+.requests-list-waterfall > .requests-list-header-button {
+ padding: 0;
+}
+
+.requests-list-waterfall > .requests-list-header-button > .button-text {
+ width: auto;
+}
+
+.requests-list-waterfall-label-wrapper:not(.requests-list-waterfall-visible) {
+ padding-inline-start: 16px;
+}
+
+.requests-list-timings-division {
+ display: inline-block;
+ padding-inline-start: 4px;
+ font-size: 75%;
+ pointer-events: none;
+ text-align: start;
+}
+
+:root[platform="win"] .requests-list-timings-division {
+ padding-top: 1px;
+ font-size: 90%;
+}
+
+.requests-list-timings-division:not(:first-child) {
+ border-inline-start: 1px dashed;
+}
+
+.requests-list-timings-division:dir(ltr) {
+ transform-origin: left center;
+}
+
+.requests-list-timings-division:dir(rtl) {
+ transform-origin: right center;
+}
+
+.theme-dark .requests-list-timings-division {
+ border-inline-start-color: #5a6169 !important;
+}
+
+.theme-light .requests-list-timings-division {
+ border-inline-start-color: #585959 !important;
+}
+
+.requests-list-timings-division[data-division-scale=second],
+.requests-list-timings-division[data-division-scale=minute] {
+ font-weight: 600;
+}
+
+.requests-list-timings {
+ display: flex;
+ align-items: center;
+}
+
+.requests-list-timings:dir(ltr) {
+ transform-origin: left center;
+}
+
+.requests-list-timings:dir(rtl) {
+ transform-origin: right center;
+}
+
+.requests-list-timings-box {
+ display: inline-block;
+ height: 12px;
+}
+
+.requests-list-timings-box.filler {
+ background-color: var(--theme-splitter-color);
+}
+
+.requests-list-timings-box.blocked {
+ background-color: var(--timing-blocked-color);
+}
+
+.requests-list-timings-box.dns {
+ background-color: var(--timing-dns-color);
+}
+
+.requests-list-timings-box.connect {
+ background-color: var(--timing-connect-color);
+}
+
+.requests-list-timings-box.ssl {
+ background-color: var(--timing-ssl-color);
+}
+
+.requests-list-timings-box.send {
+ background-color: var(--timing-send-color);
+}
+
+.requests-list-timings-box.wait {
+ background-color: var(--timing-wait-color);
+}
+
+.requests-list-timings-box.receive {
+ background-color: var(--timing-receive-color);
+}
+
+.requests-list-timings-total {
+ display: inline-block;
+ padding-inline-start: 4px;
+ font-size: 80%;
+ font-weight: 600;
+ white-space: nowrap;
+ text-align: left;
+}
+
+.requests-list-timings-total:dir(ltr) {
+ transform-origin: left center;
+}
+
+.requests-list-timings-total:dir(rtl) {
+ transform-origin: right center;
+}
+
+/* Request list item */
+
+.request-list-item,
+.message-list-item {
+ height: 24px;
+ line-height: 24px;
+}
+
+.request-list-item:not(.selected).odd,
+.message-list-item:not(.selected).odd {
+ background-color: var(--table-zebra-background);
+}
+
+.request-list-item:not(.selected):hover,
+.message-list-item:not(.selected):hover {
+ background-color: var(--table-selection-background-hover);
+}
+
+/*
+ * Dim requests served from cache
+ */
+.request-list-item:not(.selected, :hover).fromCache {
+ --table-icon-opacity: 0.7;
+ color: var(--theme-text-color-alt);
+}
+
+/*
+ * Apply partial opacity to specific icons and icon-like elements
+ * (e.g. for cached requests)
+ */
+.requests-security-icon-group,
+.requests-list-status-code:not([data-code^="3"]) {
+ opacity: var(--table-icon-opacity, 1);
+}
+
+/*
+ * Showing blocked requests in red should always have priority
+ * except when the request is selected.
+ */
+.request-list-item:not(.selected).blocked {
+ color: var(--timing-blocked-color) !important;
+}
+
+/*
+ * Put after .request-list-item.blocked to avoid specificity conflict.
+ * Bug 1530914 - Highlighted Security Value is difficult to read.
+ */
+.request-list-item.selected,
+.message-list-item.selected {
+ background-color: var(--theme-selection-background);
+ color: var(--theme-selection-color);
+ /* Rows have tabindex=0 and get a default outline when clicked, but we already
+ * have a visible selection style so hiding the outline should be okay. */
+ outline: none;
+}
+
+.theme-light {
+ --network-initiator-line-color: var(--theme-highlight-blue);
+ --network-initiator-color: var(--theme-highlight-purple);
+}
+
+.theme-dark {
+ --network-initiator-line-color: hsl(210, 40%, 60%);
+ --network-initiator-color: var(--blue-40);
+}
+
+.requests-list-initiator .requests-list-initiator-lastframe {
+ text-decoration: underline;
+ text-decoration-skip-ink: none;
+}
+
+.requests-list-initiator-lastframe {
+ display: unset;
+}
+
+.request-list-item .requests-list-initiator-filename,
+.request-list-item .requests-list-initiator-line {
+ cursor: pointer;
+ text-decoration: inherit;
+}
+
+.request-list-item:not(.selected) .requests-list-initiator-filename {
+ color: var(--network-initiator-color);
+}
+
+.request-list-item:not(selected) .requests-list-initiator-line {
+ color: var(--network-initiator-line-color);
+}
+
+.request-list-item.selected .requests-list-initiator-filename,
+.request-list-item.selected .requests-list-initiator-line {
+ color: inherit;
+}
+
+.request-list-item .requests-list-initiator-cause {
+ display: unset;
+ white-space: pre;
+}
+
+/* Responsive web design support */
+
+@media (max-width: 700px) {
+ .requests-list-status-code {
+ width: auto;
+ }
+
+ .requests-list-size {
+ /* Given a fix max-width to display all columns in RWD mode */
+ max-width: 7%;
+ }
+
+ .requests-list-waterfall {
+ display: none;
+ }
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/StatisticsPanel.css b/devtools/client/netmonitor/src/assets/styles/StatisticsPanel.css
new file mode 100644
index 0000000000..a0767097c3
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/StatisticsPanel.css
@@ -0,0 +1,171 @@
+/* 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/. */
+
+/* Statistics panel */
+
+@import "chrome://devtools/skin/chart.css";
+
+.statistics-panel {
+ display: flex;
+ height: 100vh;
+ overflow: auto;
+}
+
+.statistics-panel .back-button {
+ height: -moz-fit-content;
+ position: absolute;
+ padding: 7px 5px;
+ margin: 0px;
+ top: 8px;
+ inset-inline-start: 8px;
+}
+
+.theme-light .statistics-panel .back-button {
+ background-color: var(--grey-20);
+}
+
+.statistics-panel .splitter {
+ border-color: var(--theme-splitter-color);
+ cursor: default;
+ pointer-events: none;
+ height: 100%;
+}
+
+.statistics-panel .charts-container {
+ display: flex;
+ width: 100%;
+}
+
+.statistics-panel .charts,
+.statistics-panel .pie-table-chart-container {
+ width: 100%;
+ height: 100%;
+ margin-bottom: 1rem;
+}
+
+.statistics-panel .learn-more-link {
+ font-weight: 400;
+}
+
+.statistics-panel .table-chart-title {
+ display: flex;
+ align-items: center;
+}
+
+.pie-table-chart-container {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+}
+
+.statistics-panel .pie-chart-container {
+ margin-inline-start: 3vw;
+ margin-inline-end: 1vw;
+}
+
+.statistics-panel .table-chart-container {
+ min-width: 240px;
+ margin-inline-start: 1vw;
+ margin-inline-end: 3vw;
+}
+
+tr[data-statistic-name] td:first-of-type {
+ border-inline-start: 15px solid var(--stat-color);
+}
+
+path[data-statistic-name] {
+ fill: var(--stat-color);
+}
+
+[data-statistic-name=html] {
+ --stat-color: var(--theme-highlight-bluegrey);
+}
+
+[data-statistic-name=css] {
+ --stat-color: var(--theme-highlight-blue);
+}
+
+[data-statistic-name=js] {
+ --stat-color: var(--theme-highlight-lightorange);
+}
+
+[data-statistic-name=xhr] {
+ --stat-color: var(--theme-highlight-orange);
+}
+
+[data-statistic-name=fonts] {
+ --stat-color: var(--theme-highlight-purple);
+}
+
+[data-statistic-name=images] {
+ --stat-color: var(--theme-highlight-pink);
+}
+
+[data-statistic-name=media] {
+ --stat-color: var(--theme-highlight-green);
+}
+
+/*
+ * Align cell text to the center by default.
+ */
+.table-chart-row-label {
+ text-align: center;
+}
+
+.table-chart-row-label[name=count] {
+ width: 3em;
+ text-align: end;
+}
+
+.table-chart-row-label[name=label] {
+ width: 7em;
+ text-align: start;
+}
+
+.table-chart-row-label[name=size] {
+ width: 7em;
+ text-align: start;
+}
+
+.table-chart-row-label[name=time] {
+ width: 7em;
+ text-align: start;
+}
+
+.table-chart-totals {
+ display: flex;
+ flex-direction: column;
+}
+
+/* Responsive web design support */
+
+@media (max-width: 700px) {
+ .statistics-panel .charts-container {
+ flex-direction: column;
+ /* Minus 4em for statistics back button width */
+ width: calc(100% - 4em);
+ }
+
+ .statistics-panel .splitter {
+ width: 100%;
+ height: 1px;
+ }
+
+ .statistics-panel .table-chart-title {
+ margin-top: 3rem;
+ }
+
+ .statistics-panel .charts,
+ .statistics-panel .pie-table-chart-container{
+ margin-bottom: 2rem;
+ }
+}
+
+.offscreen{
+ position: absolute!important;
+ font-size: 0px;
+ overflow: hidden;
+ clip: rect(1px,1px,1px,1px);
+ clip-path: polygon(0 0,0 0,0 0,0 0);
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/StatusBar.css b/devtools/client/netmonitor/src/assets/styles/StatusBar.css
new file mode 100644
index 0000000000..ff53a0d866
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/StatusBar.css
@@ -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/. */
+
+/* Status bar */
+
+.devtools-status-bar-label {
+ flex: 0;
+}
+
+.status-bar-label {
+ display: inline-flex;
+ margin-inline-end: 10px;
+ /* Status bar has just one line so, don't wrap labels */
+ white-space: nowrap;
+ font-variant-numeric: tabular-nums;
+}
+
+.status-bar-label:not(:first-of-type)::before {
+ content: "";
+ display: inline-block;
+ margin-inline-end: 10px;
+ margin-top: 4px;
+ margin-bottom: 4px;
+ width: 1px;
+ background: var(--theme-splitter-color);
+}
+
+.status-bar-label.dom-content-loaded {
+ color: var(--theme-highlight-blue);
+}
+
+.status-bar-label.load {
+ color: var(--theme-highlight-red);
+}
+
+.requests-list-network-summary-button {
+ display: inline-flex;
+ align-items: center;
+ cursor: pointer;
+ height: 20px;
+ background: none;
+ box-shadow: none;
+ border-color: transparent;
+ padding-inline-end: 0;
+ margin-top: 3px;
+ margin-bottom: 3px;
+ margin-inline-end: 1em;
+}
+
+.requests-list-network-summary-button > .summary-info-icon {
+ background: url(chrome://devtools/skin/images/profiler-stopwatch.svg) no-repeat;
+ -moz-context-properties: fill;
+ fill: var(--theme-toolbar-color);
+ width: 16px;
+ height: 16px;
+ opacity: 0.8;
+}
+
+.requests-list-network-summary-button:hover > .summary-info-icon {
+ opacity: 1;
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/StatusCode.css b/devtools/client/netmonitor/src/assets/styles/StatusCode.css
new file mode 100644
index 0000000000..5b69d6f72b
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/StatusCode.css
@@ -0,0 +1,100 @@
+/* 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/. */
+
+.status-code {
+ /* non-standard codes may be shorter than 3 characters but should match
+ width of standard codes */
+ min-width: calc(3ch + 4px);
+ padding: 0 2px;
+ border-radius: 3px;
+ text-align: center;
+ font-family: var(--monospace-font-family);
+ /* prevent status code from having full line height width from .request-list-item */
+ line-height: normal;
+}
+
+.status-code[data-code^="1"] {
+ background-color: var(--status-code-color-1xx);
+}
+
+.status-code[data-code^="2"] {
+ background-color: var(--status-code-color-2xx);
+}
+
+.status-code[data-code^="3"] {
+ background-color: var(--status-code-color-3xx);
+}
+
+.status-code[data-code^="4"] {
+ background-color: var(--status-code-color-4xx);
+}
+
+.status-code[data-code^="5"] {
+ background-color: var(--status-code-color-5xx);
+}
+
+/* Non-standard status codes are styled like 5XX */
+.status-code[data-code^="0"],
+.status-code[data-code^="6"],
+.status-code[data-code^="7"],
+.status-code[data-code^="8"],
+.status-code[data-code^="9"] {
+ background-color: var(--status-code-color-5xx);
+}
+
+.status-code:not([data-code^="3"], .status-code-blocked) {
+ color: var(--theme-body-background);
+}
+
+.status-code-blocked {
+ color: var(--theme-icon-error-color);
+}
+
+.status-code-blocked-icon {
+ height: 12px;
+ width: 12px;
+ background-image: url("chrome://devtools/skin/images/blocked.svg");
+ -moz-context-properties: fill;
+ fill: currentColor;
+}
+
+
+/* Status codes for the headers side panel */
+
+.headers-overview .summary .status .status-code {
+ display: inline;
+ background-color: transparent;
+ color: inherit;
+ padding: 0 2px 0 0;
+ font-weight: bold;
+}
+
+.headers-overview .summary .status[data-code^="1"] {
+ color: var(--status-code-color-1xx);
+}
+
+.headers-overview .summary .status[data-code^="2"] {
+ color: var(--status-code-color-2xx);
+}
+
+.headers-overview .summary .status[data-code^="3"] {
+ color: inherit;
+}
+
+.headers-overview .summary .status[data-code^="4"] {
+ color: var(--status-code-color-4xx);
+}
+
+.headers-overview .summary .status[data-code^="5"] {
+ color: var(--status-code-color-5xx);
+}
+
+/* Non-standard status codes are styled like 5XX */
+.headers-overview .summary .status[data-code^="0"],
+.headers-overview .summary .status[data-code^="6"],
+.headers-overview .summary .status[data-code^="7"],
+.headers-overview .summary .status[data-code^="8"],
+.headers-overview .summary .status[data-code^="9"] {
+ color: var(--status-code-color-5xx);
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/Toolbar.css b/devtools/client/netmonitor/src/assets/styles/Toolbar.css
new file mode 100644
index 0000000000..ed37aa4046
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/Toolbar.css
@@ -0,0 +1,102 @@
+/* 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/. */
+
+/* Toolbar */
+
+.devtools-toolbar {
+ display: flex;
+ align-items: center;
+}
+
+#netmonitor-toolbar-container > .devtools-toolbar {
+ /* @TODO: Remove this in bug 1535956 */
+ min-height: var(--primary-toolbar-height);
+}
+
+.requests-list-filter-buttons {
+ white-space: nowrap;
+ margin: 0 7px;
+}
+
+.devtools-button.devtools-pause-icon::before,
+.devtools-button.devtools-play-icon::before {
+ margin-bottom: 1px;
+}
+
+.devtools-button.devtools-pause-icon::before {
+ background-image: url("chrome://devtools/skin/images/pause.svg");
+}
+
+.devtools-button.devtools-play-icon::before {
+ background-image: url("chrome://devtools/content/netmonitor/src/assets/icons/play.svg");
+}
+
+/* New HTTP Custom Request button */
+.devtools-button.devtools-http-custom-request-icon::before {
+ background-image: url("chrome://devtools/skin/images/add.svg");
+ background-size: 13px;
+}
+
+/* Search button */
+.devtools-button.devtools-search-icon::before {
+ background-image: url("chrome://devtools/skin/images/search.svg");
+ background-size: 13px;
+}
+
+/* Request blocking button */
+.devtools-button.requests-list-blocking-button::before {
+ background-image: url("chrome://devtools/skin/images/blocked.svg");
+}
+
+.devtools-button.netmonitor-settings-menu-button::before {
+ background-image: url("chrome://devtools/skin/images/settings.svg");
+}
+
+.devtools-button.requests-list-blocking-button:empty::before {
+ fill: var(--theme-body-color);
+}
+
+.devtools-button.requests-list-blocking-button.checked:empty::before {
+ fill: var(--theme-icon-checked-color);
+}
+
+.devtools-button.requests-list-blocking-button.requests-list-blocking-button-enabled:empty::before {
+ fill: var(--timing-blocked-color);
+}
+
+/* Throttling Button */
+
+#network-throttling-menu {
+ margin-inline-start: 10px;
+ margin-inline-end: 10px;
+}
+
+.devtools-toolbar .devtools-checkbox {
+ position: relative;
+ vertical-align: middle;
+ bottom: 1px;
+}
+
+#devtools-cache-checkbox {
+ vertical-align: unset;
+ bottom: -1px;
+}
+
+.devtools-toolbar .devtools-checkbox-label {
+ margin-inline-start: 2px;
+ margin-inline-end: 2px;
+ white-space: nowrap;
+}
+
+.devtools-toolbar .devtools-checkbox-label.devtools-cache-checkbox {
+ margin-inline-end: 7px;
+}
+
+/* Hide filter input learn more link if there is not enough
+ horizontal space. */
+@media (max-width: 590px) {
+ .network-monitor .devtools-searchbox .learn-more-link {
+ display: none;
+ }
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/UrlPreview.css b/devtools/client/netmonitor/src/assets/styles/UrlPreview.css
new file mode 100644
index 0000000000..9cf41fb7c9
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/UrlPreview.css
@@ -0,0 +1,100 @@
+/* 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/. */
+
+/* Url Preview */
+
+.url-preview {
+ border-bottom: 1px solid var(--theme-splitter-color);
+ padding: 6px 3px;
+}
+
+.url-preview .properties-view,
+.url-preview .tree-container,
+.url-preview .treeTable {
+ overflow: hidden;
+ outline: none;
+}
+
+.url-preview .properties-view {
+ margin-right: 10px;
+}
+
+.url-preview tbody:focus {
+ outline: none;
+}
+.url-preview td.splitter {
+ /* This makes sure that the column spans the width of the
+ side bar so the contained horizontal splitter is visible */
+ width: 100vw !important;
+}
+
+.url-preview .horizontal-splitter {
+ border-bottom: 1px solid var(--theme-splitter-color);
+ margin: 6px 0 6px 16px;
+}
+
+.url-preview .treeValueCell .url {
+ display: inline;
+ white-space: normal;
+}
+
+.url-preview .treeTable .treeRow .treeIcon {
+ margin-inline: 0 1px;
+}
+
+.url-preview .tree-container .treeTable tr {
+ margin-bottom: 3px;
+}
+
+.url-preview .treeTable .treeRow:not(.selected):hover {
+ background-color: transparent !important;
+}
+
+.url-preview .treeTable tr.treeRow:first-child .treeLabelCell::after {
+ content: "";
+}
+.url-preview .treeTable .treeLabelCell {
+ --tree-label-cell-indent: 0 !important;
+}
+/* Indent the array params */
+.url-preview .treeTable .treeRow[aria-level="4"] .treeLabelCell {
+ text-indent: 15px;
+}
+
+.url-preview .treeTable .treeLabel[data-level="1"] {
+ text-transform: capitalize;
+}
+
+/* Collapsed url */
+.url-preview tr.treeRow:first-child .treeLabelCell {
+ font-weight: bold;
+ color: var(--theme-icon-dimmed-color);
+}
+
+.url-preview tr.treeRow .treeLabelCell {
+ float: left;
+ margin-right: -15px;
+ padding: 0 2px 0 0;
+
+}
+.url-preview tr.treeRow .treeValueCell {
+ display: inline;
+ word-break: break-all;
+ max-width: none;
+ box-decoration-break: clone;
+ margin-left: 14px;
+}
+
+.url-preview .treeTable .treeValueCell {
+ color: var(--theme-body-color);
+}
+
+.url-preview .url-scheme,
+.url-preview .url-chars {
+ color: var(--theme-icon-dimmed-color);
+}
+
+.url-preview .url-params-name {
+ color: var(--theme-highlight-blue);
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/messages.css b/devtools/client/netmonitor/src/assets/styles/messages.css
new file mode 100644
index 0000000000..b115d7cf34
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/messages.css
@@ -0,0 +1,165 @@
+/* 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/. */
+
+/* Scroll to bottom */
+
+#messages-view .uncontrolled {
+ flex-direction: column;
+}
+
+#messages-view .message-list-scroll-anchor {
+ /* anchor nodes are required to have non-zero area */
+ min-height: 1px;
+ margin: 0;
+ padding: 0;
+ border: none;
+}
+
+/* Empty notice */
+
+#messages-view .message-list-empty-notice {
+ width: 100%;
+}
+
+/* Frame type icon in the Time column */
+
+#messages-view .message-list-type-icon {
+ display: inline-block;
+ /* align bottom of image 4px below the text baseline
+ this tends to give a better result than "middle" */
+ vertical-align: -4px;
+ -moz-context-properties: fill;
+ fill: currentColor;
+}
+
+#messages-view .message-list-type-icon-sent {
+ color: var(--green-70);
+}
+
+#messages-view .theme-dark .message-list-type-icon-sent {
+ color: var(--green-50);
+}
+
+#messages-view .message-list-type-icon-received {
+ color: var(--red-60);
+ transform: scaleY(-1);
+}
+
+#messages-view .theme-dark .message-list-type-icon-received {
+ color: var(--red-40);
+}
+
+#messages-view .message-list-item.selected .message-list-type-icon {
+ color: inherit;
+}
+
+#messages-view .msg-connection-closed-message {
+ text-align: center;
+}
+
+/* Use lining numbers so that seconds and milliseconds align */
+
+#messages-view .message-list-time {
+ font-variant-numeric: tabular-nums;
+}
+
+/* Styles related to the data items in the MessagePayload component */
+
+#messages-view .message-payload {
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+}
+
+#messages-view .message-rawData-payload {
+ display: block;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ white-space: pre;
+ padding: 4px 8px;
+ padding-inline-start: 20px;
+ border: none;
+ font-family: var(--monospace-font-family);
+ font-size: var(--theme-code-font-size);
+ line-height: calc(15/11);
+ direction: ltr;
+ text-align: left;
+ resize: none;
+ color: var(--theme-body-color);
+ background-color: var(--theme-sidebar-background);
+}
+
+/* Styles related to JSONPreview */
+
+#messages-view .treeTable .objectBox {
+ white-space: normal;
+ overflow-wrap: break-word;
+}
+
+/* Styles related to truncated data */
+
+.theme-light #messages-view .truncated-data-message {
+ background: var(--grey-20);
+}
+
+.theme-dark #messages-view .truncated-data-message {
+ background: var(--grey-70);
+}
+
+.truncated-data-message {
+ border-bottom: 1px solid var(--theme-splitter-color);
+ padding: 4px 8px;
+ font-size: 12px;
+}
+
+/* Styles related to truncated messages */
+
+.theme-light #messages-view .truncated-messages-header {
+ background: var(--grey-20);
+}
+
+.theme-dark #messages-view .truncated-messages-header {
+ background: var(--grey-70);
+}
+
+.theme-dark #messages-view .truncated-messages-warning-icon {
+ fill: var(--grey-40);
+}
+
+#messages-view .truncated-messages-cell {
+ padding: 0; /* reset td default padding */
+}
+
+#messages-view .truncated-messages-header {
+ border-bottom: 1px solid var(--theme-splitter-color);
+ padding: 2px 8px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+#messages-view .truncated-messages-container,
+#messages-view .truncated-messages-checkbox-label {
+ display: flex;
+ align-items: center;
+}
+
+#messages-view .truncated-messages-warning-icon {
+ width: 16px;
+ height: 16px;
+ margin-inline-end: 5px;
+ background-image: url(chrome://devtools/skin/images/info.svg);
+ background-repeat: no-repeat;
+ -moz-context-properties: fill;
+ fill: inherit;
+}
+
+#messages-view .truncation-checkbox {
+ margin-inline-end: 5px;
+}
+
+#messages-view .truncated-message {
+ font-variant-numeric: tabular-nums;
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/netmonitor.css b/devtools/client/netmonitor/src/assets/styles/netmonitor.css
new file mode 100644
index 0000000000..6b821065ed
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/netmonitor.css
@@ -0,0 +1,84 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+@import "chrome://devtools/content/shared/components/SidebarToggle.css";
+@import "chrome://devtools/content/shared/components/splitter/SplitBox.css";
+@import "chrome://devtools/content/shared/components/tree/TreeView.css";
+@import "chrome://devtools/content/shared/components/Accordion.css";
+@import "chrome://devtools/content/shared/components/tabs/Tabs.css";
+@import "chrome://devtools/skin/components-frame.css";
+@import "chrome://devtools/content/shared/sourceeditor/codemirror/lib/codemirror.css";
+@import "chrome://devtools/content/shared/sourceeditor/codemirror/addon/dialog/dialog.css";
+@import "chrome://devtools/content/shared/sourceeditor/codemirror/mozilla.css";
+@import "chrome://devtools/content/shared/components/MdnLink.css";
+@import "chrome://devtools/content/shared/components/NotificationBox.css";
+@import "chrome://devtools/content/shared/components/AppErrorBoundary.css";
+
+/* Network panel components & styles */
+@import "chrome://devtools/content/netmonitor/src/assets/styles/variables.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/Toolbar.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/StatusBar.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/RequestList.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/NetworkActionBar.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/RequestBlockingPanel.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/NetworkDetailsBar.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/StatisticsPanel.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/CustomRequestPanel.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/HTTPCustomRequestPanel.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/StatusCode.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/messages.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/search.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/UrlPreview.css";
+@import "chrome://devtools/content/netmonitor/src/assets/styles/HeadersPanel.css";
+
+/* General */
+
+* {
+ box-sizing: border-box;
+}
+
+html,
+body,
+#mount,
+.launchpad-root,
+.network-monitor,
+.monitor-panel {
+ flex: initial;
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ overflow: hidden;
+}
+
+.split-box {
+ overflow: hidden;
+}
+
+/* Drag and drop HAR files */
+
+.network-monitor > div {
+ height: 100%;
+}
+
+.network-monitor .dropHarFiles {
+ display: none;
+ align-items: center;
+ justify-content: center;
+ position: absolute;
+ text-align: center;
+ inset: 25px;
+ z-index: 100;
+ font-size: 3.5rem;
+ color: gray;
+ border: 4px dashed gray;
+ pointer-events: none;
+}
+
+.network-monitor > div[dragging="true"] .dropHarFiles {
+ display: flex;
+}
+
+.network-monitor > div[dragging="true"] {
+ filter: opacity(50%);
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/search.css b/devtools/client/netmonitor/src/assets/styles/search.css
new file mode 100644
index 0000000000..cc80183eb4
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/search.css
@@ -0,0 +1,155 @@
+/* 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/. */
+
+.search-panel {
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ height: 100%;
+}
+
+.search-panel .search-panel-content {
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ outline: 0 !important;
+}
+
+.search-panel .treeTable {
+ width: 100%;
+ color: var(--theme-body-color);
+ outline: 0 !important;
+}
+
+/* Custom tree styles for the Search results panel*/
+.search-panel .treeTable .treeLabelCell::after {
+ content: "";
+}
+
+/* Color for resource label */
+.search-panel .resourceCell {
+ color: var(--theme-text-color-inactive);
+}
+
+.search-panel .treeTable tbody {
+ outline: 0 !important;
+}
+
+.search-panel .treeTable .resultLabel {
+ font-weight: bold;
+}
+
+.search-panel .treeTable .treeLabelCell {
+ text-overflow: ellipsis;
+ max-width: 0;
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+/* Icon for close button */
+#devtools-network-search-close::before {
+ background-image: url("chrome://devtools/skin/images/close.svg");
+}
+
+/* Case Sensitive button */
+#devtools-network-search-caseSensitive::before {
+ background-image: url("chrome://devtools/skin/images/case-match.svg");
+}
+
+
+#devtools-network-search-close > button {
+ margin: 0 !important;
+ border-radius: 0 !important;
+ position: relative;
+ min-width: 26px;
+}
+
+button.case-sensitive-btn {
+ padding: 2px;
+ margin: 0 3px;
+ border: none;
+ background: none;
+ width: 20px;
+ height: 20px;
+ border-radius: 2px;
+}
+
+/* Color for query matches */
+.search-panel .resultCell .query-match {
+ background-color: var(--theme-contrast-background);
+ color: var(--theme-contrast-color);
+ border-bottom: 1px solid var(--theme-contrast-border);
+}
+
+.search-modifiers {
+ display: flex;
+ align-items: center;
+}
+
+.search-modifiers * {
+ user-select: none;
+}
+
+.pipe-divider {
+ flex: none;
+ align-self: stretch;
+ width: 1px;
+ vertical-align: middle;
+ margin: 4px;
+ background-color: var(--theme-splitter-color);
+}
+
+.search-type-name {
+ margin: 0 4px;
+ border: none;
+ background: transparent;
+ color: var(--theme-comment);
+}
+
+.search-modifiers button {
+ margin: 0 3px;
+ border: none;
+ background: none;
+ width: 25px;
+ height: 20px;
+ border-radius: 2px;
+}
+
+.search-panel .devtools-toolbar {
+ max-height: 26px;
+}
+
+.search-panel .status-bar-label {
+ min-height: 24px;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ display: block;
+ overflow: hidden;
+ min-width: 150px;
+}
+
+.search-panel .img.loader {
+ background-image: url(chrome://devtools/content/debugger/images/loader.svg);
+ background-repeat: no-repeat;
+ background-position: center;
+ background-size: contain;
+ width: 16px;
+ height: 16px;
+ margin-inline-start: 10px;
+ animation: search-loader-rotate 0.5s linear infinite;
+ -moz-context-properties: fill;
+ fill: var(--theme-selection-background);
+ display: inline-block;
+ top: 4px;
+ position: relative;
+}
+
+@keyframes search-loader-rotate {
+ from {
+ transform: rotate(0deg);
+ }
+ to {
+ transform: rotate(360deg);
+ }
+}
diff --git a/devtools/client/netmonitor/src/assets/styles/variables.css b/devtools/client/netmonitor/src/assets/styles/variables.css
new file mode 100644
index 0000000000..cad71e267c
--- /dev/null
+++ b/devtools/client/netmonitor/src/assets/styles/variables.css
@@ -0,0 +1,45 @@
+/* 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/. */
+
+:root {
+ --primary-toolbar-height: 29px;
+ /* HTTP status codes */
+ --status-code-color-1xx: var(--theme-highlight-blue);
+ --status-code-color-2xx: var(--theme-highlight-green);
+ --status-code-color-3xx: transparent;
+ --status-code-color-4xx: var(--theme-highlight-pink);
+ --status-code-color-5xx: var(--theme-highlight-red);
+}
+
+:root.theme-dark {
+ --table-splitter-color: var(--grey-70);
+ --table-zebra-background: rgba(255,255,255,0.05);
+ --table-zebra-inline-icons-background: rgb(49, 47, 47);
+ --table-selection-background-hover: rgba(53, 59, 72, 1);
+ --table-selection-inline-icons-background-hover: rgba(53, 59, 72, 1);
+
+ --timing-blocked-color: var(--red-20);
+ --timing-dns-color: rgba(223, 128, 255, 0.8); /* pink */
+ --timing-ssl-color: rgba(217, 102, 41, 0.8); /* orange */
+ --timing-connect-color: rgba(217, 102, 41, 0.8); /* orange */
+ --timing-send-color: rgba(70, 175, 227, 0.8); /* light blue */
+ --timing-wait-color: rgba(94, 136, 176, 0.8); /* blue grey */
+ --timing-receive-color: rgba(112, 191, 83, 0.8); /* green */
+}
+
+:root.theme-light {
+ --table-splitter-color: var(--grey-20);
+ --table-zebra-background: rgba(247, 247, 247, 0.8);
+ --table-zebra-inline-icons-background: rgba(247, 247, 247);
+ --table-selection-background-hover: rgba(209, 232, 255, 0.8);
+ --table-selection-inline-icons-background-hover: rgba(209, 232, 255);
+
+ --timing-blocked-color: var(--red-70);
+ --timing-dns-color: rgba(223, 128, 255, 0.8); /* pink */
+ --timing-ssl-color: rgba(217, 102, 41, 0.8); /* orange */
+ --timing-connect-color: rgba(217, 102, 41, 0.8); /* orange */
+ --timing-send-color: rgba(0, 136, 204, 0.8); /* blue */
+ --timing-wait-color: rgba(95, 136, 176, 0.8); /* blue grey */
+ --timing-receive-color: rgba(44, 187, 15, 0.8); /* green */
+}
diff --git a/devtools/client/netmonitor/src/components/App.js b/devtools/client/netmonitor/src/components/App.js
new file mode 100644
index 0000000000..4f25f2d89d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/App.js
@@ -0,0 +1,119 @@
+/* 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 dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+
+// Components
+loader.lazyGetter(this, "AppErrorBoundary", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/AppErrorBoundary.js")
+ );
+});
+loader.lazyGetter(this, "MonitorPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/MonitorPanel.js")
+ );
+});
+loader.lazyGetter(this, "StatisticsPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/StatisticsPanel.js")
+ );
+});
+loader.lazyGetter(this, "DropHarHandler", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/DropHarHandler.js")
+ );
+});
+
+// Localized strings for (devtools/client/locales/en-US/startup.properties)
+loader.lazyGetter(this, "L10N", function () {
+ const { LocalizationHelper } = require("resource://devtools/shared/l10n.js");
+ return new LocalizationHelper("devtools/client/locales/startup.properties");
+});
+
+const { div } = dom;
+
+/**
+ * App component
+ * The top level component for representing main panel
+ */
+class App extends Component {
+ static get propTypes() {
+ return {
+ // List of actions passed to HAR importer.
+ actions: PropTypes.object.isRequired,
+ // The backend connector object.
+ connector: PropTypes.object.isRequired,
+ // Callback for opening links in the UI
+ openLink: PropTypes.func,
+ // Callback for opening split console.
+ openSplitConsole: PropTypes.func,
+ // Service to enable the source map feature.
+ sourceMapURLService: PropTypes.object,
+ // True if the stats panel is opened.
+ statisticsOpen: PropTypes.bool.isRequired,
+ // Document which settings menu will be injected to
+ toolboxDoc: PropTypes.object.isRequired,
+ // Syncing blocked requests
+ addBlockedUrl: PropTypes.func,
+ };
+ }
+ // Rendering
+
+ render() {
+ const {
+ actions,
+ connector,
+ openLink,
+ openSplitConsole,
+ sourceMapURLService,
+ statisticsOpen,
+ toolboxDoc,
+ } = this.props;
+
+ return div(
+ { className: "network-monitor" },
+ AppErrorBoundary(
+ {
+ componentName: "Netmonitor",
+ panel: L10N.getStr("netmonitor.label"),
+ },
+ !statisticsOpen
+ ? DropHarHandler(
+ {
+ actions,
+ openSplitConsole,
+ },
+ MonitorPanel({
+ actions,
+ connector,
+ openSplitConsole,
+ sourceMapURLService,
+ openLink,
+ toolboxDoc,
+ })
+ )
+ : StatisticsPanel({
+ connector,
+ })
+ )
+ );
+ }
+}
+
+// Exports
+
+module.exports = connect(state => ({
+ statisticsOpen: state.ui.statisticsOpen,
+}))(App);
diff --git a/devtools/client/netmonitor/src/components/CustomRequestPanel.js b/devtools/client/netmonitor/src/components/CustomRequestPanel.js
new file mode 100644
index 0000000000..66f63b7d8d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/CustomRequestPanel.js
@@ -0,0 +1,371 @@
+/* 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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ getSelectedRequest,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ getUrlQuery,
+ parseQueryString,
+ writeHeaderText,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { button, div, input, label, textarea } = dom;
+
+const CUSTOM_CANCEL = L10N.getStr("netmonitor.custom.cancel");
+const CUSTOM_HEADERS = L10N.getStr("netmonitor.custom.headers");
+const CUSTOM_NEW_REQUEST = L10N.getStr("netmonitor.custom.newRequest");
+const CUSTOM_NEW_REQUEST_METHOD_LABEL = L10N.getStr(
+ "netmonitor.custom.newRequestMethodLabel"
+);
+const CUSTOM_NEW_REQUEST_URL_LABEL = L10N.getStr(
+ "netmonitor.custom.newRequestUrlLabel"
+);
+const CUSTOM_POSTDATA = L10N.getStr("netmonitor.custom.postData");
+const CUSTOM_QUERY = L10N.getStr("netmonitor.custom.query");
+const CUSTOM_SEND = L10N.getStr("netmonitor.custom.send");
+
+/*
+ * Custom request panel component
+ * A network request editor which simply provide edit and resend interface
+ * for network development.
+ */
+class CustomRequestPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ removeSelectedCustomRequest: PropTypes.func.isRequired,
+ request: PropTypes.object.isRequired,
+ sendCustomRequest: PropTypes.func.isRequired,
+ updateRequest: PropTypes.func.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { request, connector } = this.props;
+ this.initialRequestMethod = request.method;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestHeaders",
+ "responseHeaders",
+ "requestPostData",
+ ]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestHeaders",
+ "responseHeaders",
+ "requestPostData",
+ ]);
+ }
+
+ /**
+ * Parse a text representation of a name[divider]value list with
+ * the given name regex and divider character.
+ *
+ * @param {string} text - Text of list
+ * @return {array} array of headers info {name, value}
+ */
+ parseRequestText(text, namereg, divider) {
+ const regex = new RegExp(`(${namereg})\\${divider}\\s*(\\S.*)`);
+ const pairs = [];
+
+ for (const line of text.split("\n")) {
+ const matches = regex.exec(line);
+ if (matches) {
+ const [, name, value] = matches;
+ pairs.push({ name, value });
+ }
+ }
+ return pairs;
+ }
+
+ /**
+ * Update Custom Request Fields
+ *
+ * @param {Object} evt click event
+ * @param {Object} request current request
+ * @param {updateRequest} updateRequest action
+ */
+ updateCustomRequestFields(evt, request, updateRequest) {
+ const val = evt.target.value;
+ let data;
+
+ switch (evt.target.id) {
+ case "custom-headers-value":
+ data = {
+ requestHeaders: {
+ customHeadersValue: val || "",
+ // Parse text representation of multiple HTTP headers
+ headers: this.parseRequestText(val, "\\S+?", ":"),
+ },
+ };
+ break;
+ case "custom-method-value":
+ // If val is empty when leaving the "method" field, set the method to
+ // its original value
+ data =
+ evt.type === "blur" && val === ""
+ ? { method: this.initialRequestMethod }
+ : { method: val.trim() };
+ break;
+ case "custom-postdata-value":
+ // Update "content-length" header value to reflect change
+ // in post data field.
+ const { requestHeaders } = request;
+ const newHeaders = requestHeaders.headers.map(header => {
+ if (header.name.toLowerCase() == "content-length") {
+ return {
+ name: header.name,
+ value: val.length,
+ };
+ }
+ return header;
+ });
+
+ data = {
+ requestPostData: {
+ postData: { text: val },
+ },
+ requestHeaders: {
+ headers: newHeaders,
+ },
+ };
+ break;
+ case "custom-query-value":
+ let customQueryValue = val || "";
+ // Parse readable text list of a query string
+ const queryArray = customQueryValue
+ ? this.parseRequestText(customQueryValue, ".+?", "=")
+ : [];
+ // Write out a list of query params into a query string
+ const queryString = queryArray
+ .map(({ name, value }) => name + "=" + value)
+ .join("&");
+ const url = queryString
+ ? [request.url.split("?")[0], queryString].join("?")
+ : request.url.split("?")[0];
+ // Remove temp customQueryValue while query string is parsable
+ if (
+ customQueryValue === "" ||
+ queryArray.length === customQueryValue.split("\n").length
+ ) {
+ customQueryValue = null;
+ }
+ data = {
+ customQueryValue,
+ url,
+ };
+ break;
+ case "custom-url-value":
+ data = {
+ customQueryValue: null,
+ url: val,
+ };
+ break;
+ default:
+ break;
+ }
+ if (data) {
+ // All updateRequest batch mode should be disabled to make UI editing in sync
+ updateRequest(request.id, data, false);
+ }
+ }
+
+ render() {
+ const {
+ removeSelectedCustomRequest,
+ request = {},
+ sendCustomRequest,
+ updateRequest,
+ } = this.props;
+ const { method, customQueryValue, requestHeaders, requestPostData, url } =
+ request;
+
+ let headers = "";
+ if (requestHeaders) {
+ headers = requestHeaders.customHeadersValue
+ ? requestHeaders.customHeadersValue
+ : writeHeaderText(requestHeaders.headers).trim();
+ }
+ const queryArray = url ? parseQueryString(getUrlQuery(url)) : [];
+ let params = customQueryValue;
+ if (!params) {
+ params = queryArray
+ ? queryArray.map(({ name, value }) => name + "=" + value).join("\n")
+ : "";
+ }
+ const postData = requestPostData?.postData.text
+ ? requestPostData.postData.text
+ : "";
+
+ return div(
+ { className: "custom-request-panel" },
+ div(
+ { className: "custom-request-label custom-header" },
+ CUSTOM_NEW_REQUEST
+ ),
+ div(
+ { className: "custom-request-panel-content" },
+ div(
+ { className: "tabpanel-summary-container custom-request" },
+ div(
+ { className: "custom-request-button-container" },
+ button(
+ {
+ className: "devtools-button",
+ id: "custom-request-close-button",
+ onClick: removeSelectedCustomRequest,
+ },
+ CUSTOM_CANCEL
+ ),
+ button(
+ {
+ className: "devtools-button",
+ id: "custom-request-send-button",
+ onClick: sendCustomRequest,
+ },
+ CUSTOM_SEND
+ )
+ )
+ ),
+ div(
+ {
+ className: "tabpanel-summary-container custom-method-and-url",
+ id: "custom-method-and-url",
+ },
+ label(
+ {
+ className: "custom-method-value-label custom-request-label",
+ htmlFor: "custom-method-value",
+ },
+ CUSTOM_NEW_REQUEST_METHOD_LABEL
+ ),
+ input({
+ className: "custom-method-value",
+ id: "custom-method-value",
+ onChange: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ onBlur: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ value: method,
+ }),
+ label(
+ {
+ className: "custom-url-value-label custom-request-label",
+ htmlFor: "custom-url-value",
+ },
+ CUSTOM_NEW_REQUEST_URL_LABEL
+ ),
+ input({
+ className: "custom-url-value",
+ id: "custom-url-value",
+ onChange: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ value: url || "http://",
+ })
+ ),
+ // Hide query field when there is no params
+ params
+ ? div(
+ {
+ className: "tabpanel-summary-container custom-section",
+ id: "custom-query",
+ },
+ label(
+ {
+ className: "custom-request-label",
+ htmlFor: "custom-query-value",
+ },
+ CUSTOM_QUERY
+ ),
+ textarea({
+ className: "tabpanel-summary-input",
+ id: "custom-query-value",
+ onChange: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ rows: 4,
+ value: params,
+ wrap: "off",
+ })
+ )
+ : null,
+ div(
+ {
+ id: "custom-headers",
+ className: "tabpanel-summary-container custom-section",
+ },
+ label(
+ {
+ className: "custom-request-label",
+ htmlFor: "custom-headers-value",
+ },
+ CUSTOM_HEADERS
+ ),
+ textarea({
+ className: "tabpanel-summary-input",
+ id: "custom-headers-value",
+ onChange: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ rows: 8,
+ value: headers,
+ wrap: "off",
+ })
+ ),
+ div(
+ {
+ id: "custom-postdata",
+ className: "tabpanel-summary-container custom-section",
+ },
+ label(
+ {
+ className: "custom-request-label",
+ htmlFor: "custom-postdata-value",
+ },
+ CUSTOM_POSTDATA
+ ),
+ textarea({
+ className: "tabpanel-summary-input",
+ id: "custom-postdata-value",
+ onChange: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ rows: 6,
+ value: postData,
+ wrap: "off",
+ })
+ )
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({ request: getSelectedRequest(state) }),
+ (dispatch, props) => ({
+ removeSelectedCustomRequest: () =>
+ dispatch(Actions.removeSelectedCustomRequest()),
+ sendCustomRequest: () => dispatch(Actions.sendCustomRequest()),
+ updateRequest: (id, data, batch) =>
+ dispatch(Actions.updateRequest(id, data, batch)),
+ })
+)(CustomRequestPanel);
diff --git a/devtools/client/netmonitor/src/components/DropHarHandler.js b/devtools/client/netmonitor/src/components/DropHarHandler.js
new file mode 100644
index 0000000000..6c51a6b80e
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/DropHarHandler.js
@@ -0,0 +1,141 @@
+/* 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 {
+ findDOMNode,
+} = require("resource://devtools/client/shared/vendor/react-dom.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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+loader.lazyRequireGetter(
+ this,
+ "HarMenuUtils",
+ "resource://devtools/client/netmonitor/src/har/har-menu-utils.js",
+ true
+);
+
+const { div } = dom;
+
+const DROP_HAR_FILES = L10N.getStr("netmonitor.label.dropHarFiles");
+
+/**
+ * Helper component responsible for handling and importing
+ * dropped *.har files.
+ */
+class DropHarHandler extends Component {
+ static get propTypes() {
+ return {
+ // List of actions passed to HAR importer.
+ actions: PropTypes.object.isRequired,
+ // Child component.
+ children: PropTypes.element.isRequired,
+ // Callback for opening split console.
+ openSplitConsole: PropTypes.func,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ // Drag and drop event handlers.
+ this.onDragEnter = this.onDragEnter.bind(this);
+ this.onDragOver = this.onDragOver.bind(this);
+ this.onDragLeave = this.onDragLeave.bind(this);
+ this.onDrop = this.onDrop.bind(this);
+ }
+
+ // Drag Events
+
+ onDragEnter(event) {
+ event.preventDefault();
+ if (event.dataTransfer.files.length === 0) {
+ return;
+ }
+
+ startDragging(findDOMNode(this));
+ }
+
+ onDragLeave(event) {
+ const node = findDOMNode(this);
+ if (!node.contains(event.relatedTarget)) {
+ stopDragging(node);
+ }
+ }
+
+ onDragOver(event) {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ }
+
+ onDrop(event) {
+ event.preventDefault();
+ stopDragging(findDOMNode(this));
+
+ const { files } = event.dataTransfer;
+ if (!files) {
+ return;
+ }
+
+ const { actions, openSplitConsole } = this.props;
+
+ // Import only the first dragged file for now
+ // See also:
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1438792
+ if (files.length) {
+ const file = files[0];
+ readFile(file).then(har => {
+ if (har) {
+ HarMenuUtils.appendPreview(har, actions, openSplitConsole);
+ }
+ });
+ }
+ }
+
+ // Rendering
+
+ render() {
+ return div(
+ {
+ onDragEnter: this.onDragEnter,
+ onDragOver: this.onDragOver,
+ onDragLeave: this.onDragLeave,
+ onDrop: this.onDrop,
+ },
+ this.props.children,
+ div({ className: "dropHarFiles" }, div({}, DROP_HAR_FILES))
+ );
+ }
+}
+
+// Helpers
+
+function readFile(file) {
+ return new Promise(resolve => {
+ const fileReader = new FileReader();
+ fileReader.onloadend = () => {
+ resolve(fileReader.result);
+ };
+ fileReader.readAsText(file);
+ });
+}
+
+function startDragging(node) {
+ node.setAttribute("dragging", "true");
+}
+
+function stopDragging(node) {
+ node.removeAttribute("dragging");
+}
+
+// Exports
+
+module.exports = DropHarHandler;
diff --git a/devtools/client/netmonitor/src/components/MonitorPanel.js b/devtools/client/netmonitor/src/components/MonitorPanel.js
new file mode 100644
index 0000000000..47b3758efe
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/MonitorPanel.js
@@ -0,0 +1,271 @@
+/* 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 } = 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 {
+ findDOMNode,
+} = require("resource://devtools/client/shared/vendor/react-dom.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ updateFormDataSections,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getSelectedRequest,
+ isSelectedRequestVisible,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+// Components
+const SplitBox = createFactory(
+ require("resource://devtools/client/shared/components/splitter/SplitBox.js")
+);
+const RequestList = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestList.js")
+);
+const Toolbar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/Toolbar.js")
+);
+
+loader.lazyGetter(this, "NetworkDetailsBar", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js")
+ );
+});
+
+loader.lazyGetter(this, "NetworkActionBar", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/NetworkActionBar.js")
+ );
+});
+
+// MediaQueryList object responsible for switching sidebar splitter
+// between landscape and portrait mode (depending on browser window size).
+const MediaQueryVert = window.matchMedia("(min-width: 700px)");
+
+// MediaQueryList object responsible for switching the toolbar
+// between single and 2-rows layout (depending on browser window size).
+const MediaQuerySingleRow = window.matchMedia("(min-width: 1020px)");
+
+/**
+ * Monitor panel component
+ * The main panel for displaying various network request information
+ */
+class MonitorPanel extends Component {
+ static get propTypes() {
+ return {
+ actions: PropTypes.object.isRequired,
+ connector: PropTypes.object.isRequired,
+ isEmpty: PropTypes.bool.isRequired,
+ networkDetailsOpen: PropTypes.bool.isRequired,
+ openNetworkDetails: PropTypes.func.isRequired,
+ toolboxDoc: PropTypes.object.isRequired,
+ // Callback for opening split console.
+ openSplitConsole: PropTypes.func,
+ onNetworkDetailsResized: PropTypes.func.isRequired,
+ request: PropTypes.object,
+ selectedRequestVisible: PropTypes.bool.isRequired,
+ sourceMapURLService: PropTypes.object,
+ openLink: PropTypes.func,
+ updateRequest: PropTypes.func.isRequired,
+ networkActionOpen: PropTypes.bool.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ isSingleRow: MediaQuerySingleRow.matches,
+ isVerticalSpliter: MediaQueryVert.matches,
+ };
+
+ this.onLayoutChange = this.onLayoutChange.bind(this);
+ this.onNetworkDetailsResized = this.onNetworkDetailsResized.bind(this);
+ }
+
+ componentDidMount() {
+ MediaQuerySingleRow.addListener(this.onLayoutChange);
+ MediaQueryVert.addListener(this.onLayoutChange);
+ this.persistDetailsPanelSize();
+ this.persistActionBarSize();
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ updateFormDataSections(nextProps);
+ }
+
+ componentDidUpdate() {
+ const { selectedRequestVisible, openNetworkDetails } = this.props;
+ if (!selectedRequestVisible) {
+ openNetworkDetails(false);
+ }
+ }
+
+ componentWillUnmount() {
+ MediaQuerySingleRow.removeListener(this.onLayoutChange);
+ MediaQueryVert.removeListener(this.onLayoutChange);
+ this.persistDetailsPanelSize();
+ this.persistActionBarSize();
+ }
+
+ persistDetailsPanelSize() {
+ const { clientWidth, clientHeight } = findDOMNode(this.refs.endPanel) || {};
+
+ if (this.state.isVerticalSpliter && clientWidth) {
+ Services.prefs.setIntPref(
+ "devtools.netmonitor.panes-network-details-width",
+ clientWidth
+ );
+ }
+ if (!this.state.isVerticalSpliter && clientHeight) {
+ Services.prefs.setIntPref(
+ "devtools.netmonitor.panes-network-details-height",
+ clientHeight
+ );
+ }
+ }
+
+ persistActionBarSize() {
+ const { clientWidth, clientHeight } =
+ findDOMNode(this.refs.actionBar) || {};
+ if (clientWidth) {
+ Services.prefs.setIntPref(
+ "devtools.netmonitor.panes-search-width",
+ clientWidth
+ );
+ }
+ if (clientHeight) {
+ Services.prefs.setIntPref(
+ "devtools.netmonitor.panes-search-height",
+ clientHeight
+ );
+ }
+ }
+
+ onLayoutChange() {
+ this.setState({
+ isSingleRow: MediaQuerySingleRow.matches,
+ isVerticalSpliter: MediaQueryVert.matches,
+ });
+ }
+
+ onNetworkDetailsResized(width, height) {
+ // Cleaning width and height parameters, because SplitBox passes ALWAYS two values,
+ // while depending on orientation ONLY ONE dimension is managed by it at a time.
+ const { isVerticalSpliter } = this.state;
+ return this.props.onNetworkDetailsResized(
+ isVerticalSpliter ? width : null,
+ isVerticalSpliter ? null : height
+ );
+ }
+
+ renderActionBar() {
+ const { connector, isEmpty, networkActionOpen } = this.props;
+
+ const initialWidth = Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-search-width"
+ );
+ const initialHeight = Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-search-height"
+ );
+
+ return SplitBox({
+ className: "devtools-responsive-container",
+ initialWidth,
+ initialHeight,
+ minSize: "250px",
+ maxSize: "80%",
+ splitterSize: networkActionOpen ? 1 : 0,
+ startPanel:
+ networkActionOpen &&
+ NetworkActionBar({
+ ref: "actionBar",
+ connector,
+ }),
+ endPanel: RequestList({ isEmpty, connector }),
+ endPanelControl: false,
+ vert: true,
+ });
+ }
+
+ render() {
+ const {
+ actions,
+ connector,
+ networkDetailsOpen,
+ openLink,
+ openSplitConsole,
+ sourceMapURLService,
+ toolboxDoc,
+ } = this.props;
+
+ const initialWidth = Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-network-details-width"
+ );
+
+ const initialHeight = Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-network-details-height"
+ );
+
+ return div(
+ { className: "monitor-panel" },
+ Toolbar({
+ actions,
+ connector,
+ openSplitConsole,
+ singleRow: this.state.isSingleRow,
+ toolboxDoc,
+ }),
+ SplitBox({
+ className: "devtools-responsive-container",
+ initialWidth,
+ initialHeight,
+ minSize: "50px",
+ maxSize: "80%",
+ splitterSize: networkDetailsOpen ? 1 : 0,
+ startPanel: this.renderActionBar(),
+ endPanel:
+ networkDetailsOpen &&
+ NetworkDetailsBar({
+ ref: "endPanel",
+ connector,
+ openLink,
+ sourceMapURLService,
+ }),
+ endPanelCollapsed: !networkDetailsOpen,
+ endPanelControl: true,
+ vert: this.state.isVerticalSpliter,
+ onControlledPanelResized: this.onNetworkDetailsResized,
+ })
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ isEmpty: !state.requests.requests.length,
+ networkDetailsOpen: state.ui.networkDetailsOpen,
+ networkActionOpen: state.ui.networkActionOpen,
+ request: getSelectedRequest(state),
+ selectedRequestVisible: isSelectedRequestVisible(state),
+ }),
+ dispatch => ({
+ openNetworkDetails: open => dispatch(Actions.openNetworkDetails(open)),
+ onNetworkDetailsResized: (width, height) =>
+ dispatch(Actions.resizeNetworkDetails(width, height)),
+ updateRequest: (id, data, batch) =>
+ dispatch(Actions.updateRequest(id, data, batch)),
+ })
+)(MonitorPanel);
diff --git a/devtools/client/netmonitor/src/components/NetworkActionBar.js b/devtools/client/netmonitor/src/components/NetworkActionBar.js
new file mode 100644
index 0000000000..92110e9ec5
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/NetworkActionBar.js
@@ -0,0 +1,136 @@
+/* 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 {
+ div,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+const Tabbar = createFactory(
+ require("resource://devtools/client/shared/components/tabs/TabBar.js")
+);
+const TabPanel = createFactory(
+ require("resource://devtools/client/shared/components/tabs/Tabs.js").TabPanel
+);
+
+loader.lazyGetter(this, "SearchPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/search/SearchPanel.js")
+ );
+});
+
+loader.lazyGetter(this, "RequestBlockingPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js")
+ );
+});
+
+loader.lazyGetter(this, "HTTPCustomRequestPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js")
+ );
+});
+
+class NetworkActionBar extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ selectedActionBarTabId: PropTypes.string,
+ selectActionBarTab: PropTypes.func.isRequired,
+ toggleNetworkActionBar: PropTypes.func.isRequired,
+ };
+ }
+
+ render() {
+ const {
+ connector,
+ selectedActionBarTabId,
+ selectActionBarTab,
+ toggleNetworkActionBar,
+ } = this.props;
+
+ // The request blocking and search panels are available behind a pref
+ const showBlockingPanel = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.requestBlocking"
+ );
+ const showSearchPanel = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.search"
+ );
+ const showNewCustomRequestPanel = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend"
+ );
+
+ return div(
+ { className: "network-action-bar" },
+ Tabbar(
+ {
+ activeTabId: selectedActionBarTabId,
+ onSelect: id => selectActionBarTab(id),
+ sidebarToggleButton: {
+ collapsed: false,
+ collapsePaneTitle: L10N.getStr("collapseActionPane"),
+ expandPaneTitle: "",
+ onClick: toggleNetworkActionBar,
+ alignRight: true,
+ canVerticalSplit: false,
+ },
+ },
+ showNewCustomRequestPanel &&
+ TabPanel(
+ {
+ id: PANELS.HTTP_CUSTOM_REQUEST,
+ title: L10N.getStr("netmonitor.actionbar.HTTPCustomRequest"),
+ className: "network-action-bar-HTTP-custom-request",
+ },
+ HTTPCustomRequestPanel({ connector })
+ ),
+ showSearchPanel &&
+ TabPanel(
+ {
+ id: PANELS.SEARCH,
+ title: L10N.getStr("netmonitor.actionbar.search"),
+ className: "network-action-bar-search",
+ },
+ SearchPanel({ connector })
+ ),
+ showBlockingPanel &&
+ TabPanel(
+ {
+ id: PANELS.BLOCKING,
+ title: L10N.getStr("netmonitor.actionbar.requestBlocking2"),
+ className: "network-action-bar-blocked",
+ },
+ RequestBlockingPanel()
+ )
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ selectedActionBarTabId: state.ui.selectedActionBarTabId,
+ }),
+ dispatch => ({
+ selectActionBarTab: id => dispatch(Actions.selectActionBarTab(id)),
+ toggleNetworkActionBar: () => dispatch(Actions.toggleNetworkActionBar()),
+ })
+)(NetworkActionBar);
diff --git a/devtools/client/netmonitor/src/components/SecurityState.js b/devtools/client/netmonitor/src/components/SecurityState.js
new file mode 100644
index 0000000000..74e098d290
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/SecurityState.js
@@ -0,0 +1,78 @@
+/* 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 {
+ div,
+} = 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 {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const UPDATED_DOMAIN_PROPS = ["remoteAddress", "securityState", "urlDetails"];
+
+class SecurityState extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ onSecurityIconMouseDown: PropTypes.func.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_DOMAIN_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const { item, onSecurityIconMouseDown } = this.props;
+
+ const {
+ securityState,
+ urlDetails: { isLocal },
+ } = item;
+ const iconClassList = ["requests-security-state-icon"];
+
+ let iconTitle;
+ let realSecurityState = securityState;
+
+ // Locally delivered files such as http://localhost and file:// paths
+ // are considered to have been delivered securely.
+ if (isLocal) {
+ realSecurityState = "secure";
+ }
+
+ if (realSecurityState) {
+ iconClassList.push(`security-state-${realSecurityState}`);
+ iconTitle = L10N.getStr(`netmonitor.security.state.${realSecurityState}`);
+ }
+
+ return div(
+ { className: "requests-security-icon-group" },
+ div({
+ className: iconClassList.join(" "),
+ onMouseDown: onSecurityIconMouseDown,
+ title: iconTitle,
+ }),
+ item.isThirdPartyTrackingResource &&
+ div({
+ className: "tracking-resource",
+ title: L10N.getStr("netmonitor.trackingResource.tooltip"),
+ })
+ );
+ }
+}
+
+module.exports = SecurityState;
diff --git a/devtools/client/netmonitor/src/components/SourceEditor.js b/devtools/client/netmonitor/src/components/SourceEditor.js
new file mode 100644
index 0000000000..89165e8a77
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/SourceEditor.js
@@ -0,0 +1,137 @@
+/* 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const Editor = require("resource://devtools/client/shared/sourceeditor/editor.js");
+const {
+ setTargetSearchResult,
+} = require("resource://devtools/client/netmonitor/src/actions/search.js");
+const { div } = dom;
+
+/**
+ * CodeMirror editor as a React component
+ */
+class SourceEditor extends Component {
+ static get propTypes() {
+ return {
+ // Source editor syntax highlight mode, which is a mime type defined in CodeMirror
+ mode: PropTypes.string,
+ // Source editor content
+ text: PropTypes.string,
+ // Auto scroll to specific line
+ scrollToLine: PropTypes.number,
+ // Reset target search result that has been used for navigation in this panel.
+ // This is done to avoid second navigation the next time.
+ resetTargetSearchResult: PropTypes.func,
+ };
+ }
+
+ componentDidMount() {
+ const { mode, text } = this.props;
+
+ this.editor = new Editor({
+ lineNumbers: true,
+ lineWrapping: false,
+ mode: null, // Disable auto syntax detection, but then we set mode asynchronously
+ readOnly: true,
+ theme: "mozilla",
+ value: text,
+ });
+
+ // Delay to CodeMirror initialization content to prevent UI freezing
+ this.editorTimeout = setTimeout(() => {
+ this.editorTimeout = null;
+ this.editor.appendToLocalElement(this.refs.editorElement);
+
+ // CodeMirror's setMode() (syntax highlight) is the performance bottleneck when
+ // processing large content, so we enable it asynchronously within the setTimeout
+ // to avoid UI blocking. (rendering source code -> drawing syntax highlight)
+ this.editorSetModeTimeout = setTimeout(() => {
+ this.editorSetModeTimeout = null;
+ this.editor.setMode(mode);
+ this.scrollToLine();
+ });
+ });
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ nextProps.mode !== this.props.mode ||
+ nextProps.text !== this.props.text ||
+ nextProps.scrollToLine !== this.props.scrollToLine
+ );
+ }
+
+ componentDidUpdate(prevProps) {
+ const { mode, scrollToLine, text } = this.props;
+
+ // Bail out if the editor has been destroyed in the meantime.
+ if (this.editor.isDestroyed()) {
+ return;
+ }
+
+ if (prevProps.text !== text) {
+ // Reset the existed 'mode' attribute in order to make setText() process faster
+ // to prevent drawing unnecessary syntax highlight.
+ this.editor.setMode(null);
+ this.editor.setText(text);
+
+ if (this.editorSetModeTimeout) {
+ clearTimeout(this.editorSetModeTimeout);
+ }
+
+ // CodeMirror's setMode() (syntax highlight) is the performance bottleneck when
+ // processing large content, so we enable it asynchronously within the setTimeout
+ // to avoid UI blocking. (rendering source code -> drawing syntax highlight)
+ this.editorSetModeTimeout = setTimeout(() => {
+ this.editorSetModeTimeout = null;
+ this.editor.setMode(mode);
+ this.scrollToLine();
+ });
+ } else if (prevProps.scrollToLine !== scrollToLine) {
+ this.scrollToLine();
+ }
+ }
+
+ componentWillUnmount() {
+ clearTimeout(this.editorTimeout);
+ clearTimeout(this.editorSetModeTimeout);
+ this.editor.destroy();
+ }
+
+ scrollToLine() {
+ const { scrollToLine, resetTargetSearchResult } = this.props;
+
+ if (scrollToLine) {
+ this.editor.setCursor(
+ {
+ line: scrollToLine - 1,
+ },
+ "center"
+ );
+ }
+
+ resetTargetSearchResult();
+ }
+
+ render() {
+ return div({
+ ref: "editorElement",
+ className: "source-editor-mount devtools-monospace",
+ });
+ }
+}
+
+module.exports = connect(null, dispatch => ({
+ resetTargetSearchResult: () => dispatch(setTargetSearchResult(null)),
+}))(SourceEditor);
diff --git a/devtools/client/netmonitor/src/components/StatisticsPanel.js b/devtools/client/netmonitor/src/components/StatisticsPanel.js
new file mode 100644
index 0000000000..e3d6787819
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/StatisticsPanel.js
@@ -0,0 +1,413 @@
+/* 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 ReactDOM = require("resource://devtools/client/shared/vendor/react-dom.js");
+const {
+ FILTER_TAGS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+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");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const { Chart } = require("resource://devtools/client/shared/widgets/Chart.js");
+const { PluralForm } = require("resource://devtools/shared/plural-form.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ Filters,
+} = require("resource://devtools/client/netmonitor/src/utils/filter-predicates.js");
+const {
+ getSizeWithDecimals,
+ getTimeWithDecimals,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getPerformanceAnalysisURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+// Components
+const MDNLink = createFactory(
+ require("resource://devtools/client/shared/components/MdnLink.js")
+);
+
+const { button, div } = dom;
+const MediaQueryList = window.matchMedia("(min-width: 700px)");
+
+const NETWORK_ANALYSIS_PIE_CHART_DIAMETER = 200;
+const BACK_BUTTON = L10N.getStr("netmonitor.backButton");
+const CHARTS_CACHE_ENABLED = L10N.getStr("charts.cacheEnabled");
+const CHARTS_CACHE_DISABLED = L10N.getStr("charts.cacheDisabled");
+const CHARTS_LEARN_MORE = L10N.getStr("charts.learnMore");
+
+/*
+ * Statistics panel component
+ * Performance analysis tool which shows you how long the browser takes to
+ * download the different parts of your site.
+ */
+class StatisticsPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ closeStatistics: PropTypes.func.isRequired,
+ enableRequestFilterTypeOnly: PropTypes.func.isRequired,
+ hasLoad: PropTypes.bool,
+ requests: PropTypes.array,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ isVerticalSpliter: MediaQueryList.matches,
+ };
+
+ this.createMDNLink = this.createMDNLink.bind(this);
+ this.unmountMDNLinkContainers = this.unmountMDNLinkContainers.bind(this);
+ this.createChart = this.createChart.bind(this);
+ this.sanitizeChartDataSource = this.sanitizeChartDataSource.bind(this);
+ this.responseIsFresh = this.responseIsFresh.bind(this);
+ this.onLayoutChange = this.onLayoutChange.bind(this);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillMount() {
+ this.mdnLinkContainerNodes = new Map();
+ }
+
+ componentDidMount() {
+ const { requests, connector } = this.props;
+ requests.forEach(request => {
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "eventTimings",
+ "responseHeaders",
+ ]);
+ });
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { requests, connector } = nextProps;
+ requests.forEach(request => {
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "eventTimings",
+ "responseHeaders",
+ ]);
+ });
+ }
+
+ componentDidUpdate(prevProps) {
+ MediaQueryList.addListener(this.onLayoutChange);
+
+ const { hasLoad, requests } = this.props;
+
+ // Display statistics about all requests for which we received enough data,
+ // as soon as the page is considered to be loaded
+ const ready = requests.length && hasLoad;
+
+ // Ignore requests which are missing data expected by this component:
+ // - pending/incomplete requests
+ // - blocked/errored requests
+ const validRequests = requests.filter(
+ req =>
+ req.contentSize !== undefined &&
+ req.mimeType &&
+ req.responseHeaders &&
+ req.status !== undefined &&
+ req.totalTime !== undefined
+ );
+
+ this.createChart({
+ id: "primedCacheChart",
+ title: CHARTS_CACHE_ENABLED,
+ data: ready ? this.sanitizeChartDataSource(validRequests, false) : null,
+ });
+
+ this.createChart({
+ id: "emptyCacheChart",
+ title: CHARTS_CACHE_DISABLED,
+ data: ready ? this.sanitizeChartDataSource(validRequests, true) : null,
+ });
+
+ this.createMDNLink("primedCacheChart", getPerformanceAnalysisURL());
+ this.createMDNLink("emptyCacheChart", getPerformanceAnalysisURL());
+ }
+
+ componentWillUnmount() {
+ MediaQueryList.removeListener(this.onLayoutChange);
+ this.unmountMDNLinkContainers();
+ }
+
+ createMDNLink(chartId, url) {
+ if (this.mdnLinkContainerNodes.has(chartId)) {
+ ReactDOM.unmountComponentAtNode(this.mdnLinkContainerNodes.get(chartId));
+ }
+
+ // MDNLink is a React component but Chart isn't. To get the link
+ // into the chart we mount a new ReactDOM at the appropriate
+ // location after the chart has been created.
+ const title = this.refs[chartId].querySelector(".table-chart-title");
+ const containerNode = document.createElement("span");
+ title.appendChild(containerNode);
+
+ ReactDOM.render(
+ MDNLink({
+ url,
+ title: CHARTS_LEARN_MORE,
+ }),
+ containerNode
+ );
+ this.mdnLinkContainerNodes.set(chartId, containerNode);
+ }
+
+ unmountMDNLinkContainers() {
+ for (const [, node] of this.mdnLinkContainerNodes) {
+ ReactDOM.unmountComponentAtNode(node);
+ }
+ }
+
+ createChart({ id, title, data }) {
+ // Create a new chart.
+ const chart = Chart.PieTable(document, {
+ diameter: NETWORK_ANALYSIS_PIE_CHART_DIAMETER,
+ title,
+ header: {
+ count: L10N.getStr("charts.requestsNumber"),
+ label: L10N.getStr("charts.type"),
+ size: L10N.getStr("charts.size"),
+ transferredSize: L10N.getStr("charts.transferred"),
+ time: L10N.getStr("charts.time"),
+ nonBlockingTime: L10N.getStr("charts.nonBlockingTime"),
+ },
+ data,
+ strings: {
+ size: value =>
+ L10N.getFormatStr(
+ "charts.size.kB",
+ getSizeWithDecimals(value / 1000)
+ ),
+ transferredSize: value =>
+ L10N.getFormatStr(
+ "charts.transferredSize.kB",
+ getSizeWithDecimals(value / 1000)
+ ),
+ time: value =>
+ L10N.getFormatStr("charts.totalS", getTimeWithDecimals(value / 1000)),
+ nonBlockingTime: value =>
+ L10N.getFormatStr("charts.totalS", getTimeWithDecimals(value / 1000)),
+ },
+ totals: {
+ cached: total => L10N.getFormatStr("charts.totalCached", total),
+ count: total => L10N.getFormatStr("charts.totalCount", total),
+ size: total =>
+ L10N.getFormatStr(
+ "charts.totalSize.kB",
+ getSizeWithDecimals(total / 1000)
+ ),
+ transferredSize: total =>
+ L10N.getFormatStr(
+ "charts.totalTransferredSize.kB",
+ getSizeWithDecimals(total / 1000)
+ ),
+ time: total => {
+ const seconds = total / 1000;
+ const string = getTimeWithDecimals(seconds);
+ return PluralForm.get(
+ seconds,
+ L10N.getStr("charts.totalSeconds")
+ ).replace("#1", string);
+ },
+ nonBlockingTime: total => {
+ const seconds = total / 1000;
+ const string = getTimeWithDecimals(seconds);
+ return PluralForm.get(
+ seconds,
+ L10N.getStr("charts.totalSecondsNonBlocking")
+ ).replace("#1", string);
+ },
+ },
+ sorted: true,
+ });
+
+ chart.on("click", ({ label }) => {
+ // Reset FilterButtons and enable one filter exclusively
+ this.props.closeStatistics();
+ this.props.enableRequestFilterTypeOnly(label);
+ });
+
+ const container = this.refs[id];
+
+ // Nuke all existing charts of the specified type.
+ while (container.hasChildNodes()) {
+ container.firstChild.remove();
+ }
+
+ container.appendChild(chart.node);
+ }
+
+ sanitizeChartDataSource(requests, emptyCache) {
+ const data = FILTER_TAGS.map(type => ({
+ cached: 0,
+ count: 0,
+ label: type,
+ size: 0,
+ transferredSize: 0,
+ time: 0,
+ nonBlockingTime: 0,
+ }));
+
+ for (const request of requests) {
+ let type;
+
+ if (Filters.html(request)) {
+ // "html"
+ type = 0;
+ } else if (Filters.css(request)) {
+ // "css"
+ type = 1;
+ } else if (Filters.js(request)) {
+ // "js"
+ type = 2;
+ } else if (Filters.fonts(request)) {
+ // "fonts"
+ type = 4;
+ } else if (Filters.images(request)) {
+ // "images"
+ type = 5;
+ } else if (Filters.media(request)) {
+ // "media"
+ type = 6;
+ } else if (Filters.ws(request)) {
+ // "ws"
+ type = 7;
+ } else if (Filters.xhr(request)) {
+ // Verify XHR last, to categorize other mime types in their own blobs.
+ // "xhr"
+ type = 3;
+ } else {
+ // "other"
+ type = 8;
+ }
+
+ if (emptyCache || !this.responseIsFresh(request)) {
+ data[type].time += request.totalTime || 0;
+ data[type].size += request.contentSize || 0;
+ data[type].transferredSize += request.transferredSize || 0;
+ const nonBlockingTime =
+ request.eventTimings.totalTime - request.eventTimings.timings.blocked;
+ data[type].nonBlockingTime += nonBlockingTime || 0;
+ } else {
+ data[type].cached++;
+ }
+ data[type].count++;
+ }
+
+ return data.filter(e => e.count > 0);
+ }
+
+ /**
+ * Checks if the "Expiration Calculations" defined in section 13.2.4 of the
+ * "HTTP/1.1: Caching in HTTP" spec holds true for a collection of headers.
+ *
+ * @param object
+ * An object containing the { responseHeaders, status } properties.
+ * @return boolean
+ * True if the response is fresh and loaded from cache.
+ */
+ responseIsFresh({ responseHeaders, status }) {
+ // Check for a "304 Not Modified" status and response headers availability.
+ if (status != 304 || !responseHeaders) {
+ return false;
+ }
+
+ const list = responseHeaders.headers;
+ const cacheControl = list.find(
+ e => e.name.toLowerCase() === "cache-control"
+ );
+ const expires = list.find(e => e.name.toLowerCase() === "expires");
+
+ // Check the "Cache-Control" header for a maximum age value.
+ if (cacheControl) {
+ const maxAgeMatch =
+ cacheControl.value.match(/s-maxage\s*=\s*(\d+)/) ||
+ cacheControl.value.match(/max-age\s*=\s*(\d+)/);
+
+ if (maxAgeMatch && maxAgeMatch.pop() > 0) {
+ return true;
+ }
+ }
+
+ // Check the "Expires" header for a valid date.
+ if (expires && Date.parse(expires.value)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ onLayoutChange() {
+ this.setState({
+ isVerticalSpliter: MediaQueryList.matches,
+ });
+ }
+
+ render() {
+ const { closeStatistics } = this.props;
+ const splitterClassName = ["splitter"];
+
+ if (this.state.isVerticalSpliter) {
+ splitterClassName.push("devtools-side-splitter");
+ } else {
+ splitterClassName.push("devtools-horizontal-splitter");
+ }
+
+ return div(
+ { className: "statistics-panel" },
+ button(
+ {
+ className: "back-button devtools-button",
+ "data-text-only": "true",
+ title: BACK_BUTTON,
+ onClick: closeStatistics,
+ },
+ BACK_BUTTON
+ ),
+ div(
+ { className: "charts-container" },
+ div({
+ ref: "primedCacheChart",
+ className: "charts primed-cache-chart",
+ }),
+ div({ className: splitterClassName.join(" ") }),
+ div({ ref: "emptyCacheChart", className: "charts empty-cache-chart" })
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ // `firstDocumentLoadTimestamp` is set on timing markers when we receive
+ // DOCUMENT_EVENT's dom-complete, which is equivalent to page `load` event.
+ hasLoad: state.timingMarkers.firstDocumentLoadTimestamp != -1,
+ requests: [...state.requests.requests],
+ }),
+ (dispatch, props) => ({
+ closeStatistics: () =>
+ dispatch(Actions.openStatistics(props.connector, false)),
+ enableRequestFilterTypeOnly: label =>
+ dispatch(Actions.enableRequestFilterTypeOnly(label)),
+ })
+)(StatisticsPanel);
diff --git a/devtools/client/netmonitor/src/components/StatusBar.js b/devtools/client/netmonitor/src/components/StatusBar.js
new file mode 100644
index 0000000000..3a6c73e0db
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/StatusBar.js
@@ -0,0 +1,175 @@
+/* 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 Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ getDisplayedRequestsSummary,
+ getDisplayedTimingMarker,
+} = 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 { button, div } = dom;
+
+const REQUESTS_COUNT_EMPTY = L10N.getStr(
+ "networkMenu.summary.requestsCountEmpty"
+);
+const TOOLTIP_PERF = L10N.getStr("networkMenu.summary.tooltip.perf");
+const TOOLTIP_REQUESTS_COUNT = L10N.getStr(
+ "networkMenu.summary.tooltip.requestsCount"
+);
+const TOOLTIP_TRANSFERRED = L10N.getStr(
+ "networkMenu.summary.tooltip.transferred"
+);
+const TOOLTIP_FINISH = L10N.getStr("networkMenu.summary.tooltip.finish");
+const TOOLTIP_DOM_CONTENT_LOADED = L10N.getStr(
+ "networkMenu.summary.tooltip.domContentLoaded"
+);
+const TOOLTIP_LOAD = L10N.getStr("networkMenu.summary.tooltip.load");
+
+const UPDATED_SUMMARY_PROPS = ["count", "contentSize", "transferredSize", "ms"];
+
+const UPDATED_TIMING_PROPS = ["DOMContentLoaded", "load"];
+
+/**
+ * Status Bar component
+ * Displays the summary of total size and transferred size by all requests
+ * Also displays different timing markers
+ */
+class StatusBar extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ openStatistics: PropTypes.func.isRequired,
+ summary: PropTypes.object.isRequired,
+ timingMarkers: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ const { summary, timingMarkers } = this.props;
+ return (
+ !propertiesEqual(UPDATED_SUMMARY_PROPS, summary, nextProps.summary) ||
+ !propertiesEqual(
+ UPDATED_TIMING_PROPS,
+ timingMarkers,
+ nextProps.timingMarkers
+ )
+ );
+ }
+
+ render() {
+ const { openStatistics, summary, timingMarkers, connector } = this.props;
+ const { count, contentSize, transferredSize, ms } = summary;
+ const { DOMContentLoaded, load } = timingMarkers;
+
+ const toolbox = connector.getToolbox();
+ const countText =
+ count === 0
+ ? REQUESTS_COUNT_EMPTY
+ : PluralForm.get(
+ count,
+ L10N.getStr("networkMenu.summary.requestsCount2")
+ ).replace("#1", count);
+ const transferText = L10N.getFormatStrWithNumbers(
+ "networkMenu.summary.transferred",
+ getFormattedSize(contentSize),
+ getFormattedSize(transferredSize)
+ );
+ const finishText = L10N.getFormatStrWithNumbers(
+ "networkMenu.summary.finish",
+ getFormattedTime(ms)
+ );
+
+ return div(
+ { className: "devtools-toolbar devtools-toolbar-bottom" },
+ !toolbox.isBrowserToolbox
+ ? button(
+ {
+ className: "devtools-button requests-list-network-summary-button",
+ title: TOOLTIP_PERF,
+ onClick: openStatistics,
+ },
+ div({ className: "summary-info-icon" })
+ )
+ : null,
+ div(
+ {
+ className: "status-bar-label requests-list-network-summary-count",
+ title: TOOLTIP_REQUESTS_COUNT,
+ },
+ countText
+ ),
+ count !== 0 &&
+ div(
+ {
+ className:
+ "status-bar-label requests-list-network-summary-transfer",
+ title: TOOLTIP_TRANSFERRED,
+ },
+ transferText
+ ),
+ count !== 0 &&
+ div(
+ {
+ className: "status-bar-label requests-list-network-summary-finish",
+ title: TOOLTIP_FINISH,
+ },
+ finishText
+ ),
+ DOMContentLoaded > -1 &&
+ div(
+ {
+ className: "status-bar-label dom-content-loaded",
+ title: TOOLTIP_DOM_CONTENT_LOADED,
+ },
+ `DOMContentLoaded: ${getFormattedTime(DOMContentLoaded)}`
+ ),
+ load > -1 &&
+ div(
+ {
+ className: "status-bar-label load",
+ title: TOOLTIP_LOAD,
+ },
+ `load: ${getFormattedTime(load)}`
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ summary: getDisplayedRequestsSummary(state),
+ timingMarkers: {
+ DOMContentLoaded: getDisplayedTimingMarker(
+ state,
+ "firstDocumentDOMContentLoadedTimestamp"
+ ),
+ load: getDisplayedTimingMarker(state, "firstDocumentLoadTimestamp"),
+ },
+ }),
+ (dispatch, props) => ({
+ openStatistics: () =>
+ dispatch(Actions.openStatistics(props.connector, true)),
+ })
+)(StatusBar);
diff --git a/devtools/client/netmonitor/src/components/StatusCode.js b/devtools/client/netmonitor/src/components/StatusCode.js
new file mode 100644
index 0000000000..7f4f082636
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/StatusCode.js
@@ -0,0 +1,129 @@
+/* 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 {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { div } = dom;
+
+const UPDATED_STATUS_PROPS = [
+ "fromCache",
+ "fromServiceWorker",
+ "status",
+ "statusText",
+];
+
+/**
+ * Status code component
+ * Displays HTTP status code icon
+ * Used in RequestListColumnStatus and HeadersPanel
+ */
+class StatusCode extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_STATUS_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const { item } = this.props;
+ const { fromCache, fromServiceWorker, status, statusText, blockedReason } =
+ item;
+ let code;
+
+ if (status) {
+ if (fromCache) {
+ code = "cached";
+ } else if (fromServiceWorker) {
+ code = "service worker";
+ } else {
+ code = status;
+ }
+ }
+
+ if (blockedReason) {
+ return div(
+ {
+ className:
+ "requests-list-status-code status-code status-code-blocked",
+ title: L10N.getStr("networkMenu.blockedTooltip"),
+ },
+ div({
+ className: "status-code-blocked-icon",
+ })
+ );
+ }
+
+ // `data-code` refers to the status-code
+ // `data-status-code` can be one of "cached", "service worker"
+ // or the status-code itself
+ // For example - if a resource is cached, `data-code` would be 200
+ // and the `data-status-code` would be "cached"
+ return div(
+ {
+ className: "requests-list-status-code status-code",
+ onMouseOver({ target }) {
+ if (status && statusText && !target.title) {
+ target.title = getStatusTooltip(item);
+ }
+ },
+ "data-status-code": code,
+ "data-code": status,
+ },
+ status
+ );
+ }
+}
+
+function getStatusTooltip(item) {
+ const { fromCache, fromServiceWorker, status, statusText } = item;
+ let title;
+ if (fromCache && fromServiceWorker) {
+ title = L10N.getFormatStr(
+ "netmonitor.status.tooltip.cachedworker",
+ status,
+ statusText
+ );
+ } else if (fromCache) {
+ title = L10N.getFormatStr(
+ "netmonitor.status.tooltip.cached",
+ status,
+ statusText
+ );
+ } else if (fromServiceWorker) {
+ title = L10N.getFormatStr(
+ "netmonitor.status.tooltip.worker",
+ status,
+ statusText
+ );
+ } else {
+ title = L10N.getFormatStr(
+ "netmonitor.status.tooltip.simple",
+ status,
+ statusText
+ );
+ }
+ return title;
+}
+
+module.exports = StatusCode;
diff --git a/devtools/client/netmonitor/src/components/TabboxPanel.js b/devtools/client/netmonitor/src/components/TabboxPanel.js
new file mode 100644
index 0000000000..9395b53307
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/TabboxPanel.js
@@ -0,0 +1,242 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Components
+const Tabbar = createFactory(
+ require("resource://devtools/client/shared/components/tabs/TabBar.js")
+);
+const TabPanel = createFactory(
+ require("resource://devtools/client/shared/components/tabs/Tabs.js").TabPanel
+);
+const CookiesPanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/CookiesPanel.js")
+);
+const HeadersPanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/HeadersPanel.js")
+);
+const RequestPanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/RequestPanel.js")
+);
+const CachePanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/CachePanel.js")
+);
+const ResponsePanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/ResponsePanel.js")
+);
+const SecurityPanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/SecurityPanel.js")
+);
+const StackTracePanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/StackTracePanel.js")
+);
+const TimingsPanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/TimingsPanel.js")
+);
+
+const COLLAPSE_DETAILS_PANE = L10N.getStr("collapseDetailsPane");
+const ALL_TABS_MENU_BUTTON_TOOLTIP = L10N.getStr("allTabsMenuButton.tooltip");
+const CACHE_TITLE = L10N.getStr("netmonitor.tab.cache");
+const COOKIES_TITLE = L10N.getStr("netmonitor.tab.cookies");
+const HEADERS_TITLE = L10N.getStr("netmonitor.tab.headers");
+const REQUEST_TITLE = L10N.getStr("netmonitor.tab.request");
+const RESPONSE_TITLE = L10N.getStr("netmonitor.tab.response");
+const SECURITY_TITLE = L10N.getStr("netmonitor.tab.security");
+const STACK_TRACE_TITLE = L10N.getStr("netmonitor.tab.stackTrace");
+const TIMINGS_TITLE = L10N.getStr("netmonitor.tab.timings");
+
+/**
+ * Tabbox panel component
+ * Display the network request details
+ */
+class TabboxPanel extends Component {
+ static get propTypes() {
+ return {
+ activeTabId: PropTypes.string,
+ cloneSelectedRequest: PropTypes.func,
+ connector: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ request: PropTypes.object,
+ selectTab: PropTypes.func.isRequired,
+ sourceMapURLService: PropTypes.object,
+ hideToggleButton: PropTypes.bool,
+ toggleNetworkDetails: PropTypes.func,
+ openNetworkDetails: PropTypes.func.isRequired,
+ showMessagesView: PropTypes.bool,
+ targetSearchResult: PropTypes.object,
+ };
+ }
+ static get defaultProps() {
+ return {
+ showMessagesView: true,
+ };
+ }
+ componentDidMount() {
+ this.closeOnEscRef = this.closeOnEsc.bind(this);
+ window.addEventListener("keydown", this.closeOnEscRef);
+ }
+
+ componentWillUnmount() {
+ window.removeEventListener("keydown", this.closeOnEscRef);
+ }
+
+ closeOnEsc(event) {
+ if (event.key == "Escape") {
+ event.preventDefault();
+ this.props.openNetworkDetails(false);
+ }
+ }
+
+ render() {
+ const {
+ activeTabId,
+ cloneSelectedRequest = () => {},
+ connector,
+ hideToggleButton,
+ openLink,
+ request,
+ selectTab,
+ sourceMapURLService,
+ toggleNetworkDetails,
+ targetSearchResult,
+ } = this.props;
+
+ if (!request) {
+ return null;
+ }
+
+ const isWs = request.cause.type === "websocket";
+ const isSse = request.isEventStream;
+
+ const showMessagesView = (isWs || isSse) && this.props.showMessagesView;
+
+ return Tabbar(
+ {
+ activeTabId,
+ menuDocument: window.parent.document,
+ onSelect: selectTab,
+ renderOnlySelected: true,
+ showAllTabsMenu: true,
+ allTabsMenuButtonTooltip: ALL_TABS_MENU_BUTTON_TOOLTIP,
+ sidebarToggleButton: hideToggleButton
+ ? null
+ : {
+ collapsed: false,
+ collapsePaneTitle: COLLAPSE_DETAILS_PANE,
+ expandPaneTitle: "",
+ onClick: toggleNetworkDetails,
+ },
+ },
+ TabPanel(
+ {
+ id: PANELS.HEADERS,
+ title: HEADERS_TITLE,
+ className: "panel-with-code",
+ },
+ HeadersPanel({
+ cloneSelectedRequest,
+ connector,
+ openLink,
+ request,
+ targetSearchResult,
+ })
+ ),
+ TabPanel(
+ {
+ id: PANELS.COOKIES,
+ title: COOKIES_TITLE,
+ className: "panel-with-code",
+ },
+ CookiesPanel({
+ connector,
+ openLink,
+ request,
+ targetSearchResult,
+ })
+ ),
+ TabPanel(
+ {
+ id: PANELS.REQUEST,
+ title: REQUEST_TITLE,
+ className: "panel-with-code",
+ },
+ RequestPanel({
+ connector,
+ openLink,
+ request,
+ targetSearchResult,
+ })
+ ),
+ TabPanel(
+ {
+ id: PANELS.RESPONSE,
+ title: RESPONSE_TITLE,
+ className: "panel-with-code",
+ },
+ ResponsePanel({
+ request,
+ openLink,
+ connector,
+ showMessagesView,
+ targetSearchResult,
+ })
+ ),
+ (request.fromCache || request.status == "304") &&
+ TabPanel(
+ {
+ id: PANELS.CACHE,
+ title: CACHE_TITLE,
+ },
+ CachePanel({ request, openLink, connector })
+ ),
+ TabPanel(
+ {
+ id: PANELS.TIMINGS,
+ title: TIMINGS_TITLE,
+ },
+ TimingsPanel({
+ connector,
+ request,
+ })
+ ),
+ request.cause?.stacktraceAvailable &&
+ TabPanel(
+ {
+ id: PANELS.STACK_TRACE,
+ title: STACK_TRACE_TITLE,
+ className: "panel-with-code",
+ },
+ StackTracePanel({ connector, openLink, request, sourceMapURLService })
+ ),
+ request.securityState &&
+ request.securityState !== "insecure" &&
+ TabPanel(
+ {
+ id: PANELS.SECURITY,
+ title: SECURITY_TITLE,
+ },
+ SecurityPanel({
+ connector,
+ openLink,
+ request,
+ })
+ )
+ );
+ }
+}
+
+module.exports = TabboxPanel;
diff --git a/devtools/client/netmonitor/src/components/Toolbar.js b/devtools/client/netmonitor/src/components/Toolbar.js
new file mode 100644
index 0000000000..0da3d826c2
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/Toolbar.js
@@ -0,0 +1,688 @@
+/* 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");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ FILTER_SEARCH_DELAY,
+ FILTER_TAGS,
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ getDisplayedRequests,
+ getRecordingState,
+ getTypeFilteredRequests,
+ getSelectedRequest,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ autocompleteProvider,
+} = require("resource://devtools/client/netmonitor/src/utils/filter-autocomplete-provider.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+loader.lazyRequireGetter(
+ this,
+ "KeyShortcuts",
+ "resource://devtools/client/shared/key-shortcuts.js"
+);
+
+// MDN
+const {
+ getFilterBoxURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+const LEARN_MORE_URL = getFilterBoxURL();
+
+// Components
+const NetworkThrottlingMenu = createFactory(
+ require("resource://devtools/client/shared/components/throttling/NetworkThrottlingMenu.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+
+const { button, div, input, label, span, hr } = dom;
+
+// Localization
+const FILTER_KEY_SHORTCUT = L10N.getStr(
+ "netmonitor.toolbar.filterFreetext.key"
+);
+const SEARCH_KEY_SHORTCUT = L10N.getStr("netmonitor.toolbar.search.key");
+const SEARCH_PLACE_HOLDER = L10N.getStr(
+ "netmonitor.toolbar.filterFreetext.label"
+);
+const COPY_KEY_SHORTCUT = L10N.getStr("netmonitor.toolbar.copy.key");
+const TOOLBAR_CLEAR = L10N.getStr("netmonitor.toolbar.clear");
+const TOOLBAR_TOGGLE_RECORDING = L10N.getStr(
+ "netmonitor.toolbar.toggleRecording"
+);
+const TOOLBAR_HTTP_CUSTOM_REQUEST = L10N.getStr(
+ "netmonitor.toolbar.HTTPCustomRequest"
+);
+const TOOLBAR_SEARCH = L10N.getStr("netmonitor.toolbar.search");
+const TOOLBAR_BLOCKING = L10N.getStr("netmonitor.toolbar.requestBlocking");
+const LEARN_MORE_TITLE = L10N.getStr(
+ "netmonitor.toolbar.filterFreetext.learnMore"
+);
+
+// Preferences
+const DEVTOOLS_DISABLE_CACHE_PREF = "devtools.cache.disabled";
+const DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF = "devtools.netmonitor.persistlog";
+const TOOLBAR_FILTER_LABELS = FILTER_TAGS.concat("all").reduce(
+ (o, tag) =>
+ Object.assign(o, {
+ [tag]: L10N.getStr(`netmonitor.toolbar.filter.${tag}`),
+ }),
+ {}
+);
+const DISABLE_CACHE_TOOLTIP = L10N.getStr(
+ "netmonitor.toolbar.disableCache.tooltip"
+);
+const DISABLE_CACHE_LABEL = L10N.getStr(
+ "netmonitor.toolbar.disableCache.label"
+);
+
+const MenuButton = createFactory(
+ require("resource://devtools/client/shared/components/menu/MenuButton.js")
+);
+
+loader.lazyGetter(this, "MenuItem", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/menu/MenuItem.js")
+ );
+});
+
+loader.lazyGetter(this, "MenuList", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/menu/MenuList.js")
+ );
+});
+
+// Menu
+loader.lazyRequireGetter(
+ this,
+ "HarMenuUtils",
+ "resource://devtools/client/netmonitor/src/har/har-menu-utils.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "copyString",
+ "resource://devtools/shared/platform/clipboard.js",
+ true
+);
+
+// Throttling
+const Types = require("resource://devtools/client/shared/components/throttling/types.js");
+const {
+ changeNetworkThrottling,
+} = require("resource://devtools/client/shared/components/throttling/actions.js");
+
+/**
+ * Network monitor toolbar component.
+ *
+ * Toolbar contains a set of useful tools to control network requests
+ * as well as set of filters for filtering the content.
+ */
+class Toolbar extends Component {
+ static get propTypes() {
+ return {
+ actions: PropTypes.object.isRequired,
+ connector: PropTypes.object.isRequired,
+ toggleRecording: PropTypes.func.isRequired,
+ recording: PropTypes.bool.isRequired,
+ clearRequests: PropTypes.func.isRequired,
+ // List of currently displayed requests (i.e. filtered & sorted).
+ displayedRequests: PropTypes.array.isRequired,
+ requestFilterTypes: PropTypes.object.isRequired,
+ setRequestFilterText: PropTypes.func.isRequired,
+ enablePersistentLogs: PropTypes.func.isRequired,
+ togglePersistentLogs: PropTypes.func.isRequired,
+ persistentLogsEnabled: PropTypes.bool.isRequired,
+ disableBrowserCache: PropTypes.func.isRequired,
+ toggleBrowserCache: PropTypes.func.isRequired,
+ browserCacheDisabled: PropTypes.bool.isRequired,
+ toggleRequestFilterType: PropTypes.func.isRequired,
+ filteredRequests: PropTypes.array.isRequired,
+ // Set to true if there is enough horizontal space
+ // and the toolbar needs just one row.
+ singleRow: PropTypes.bool.isRequired,
+ // Callback for opening split console.
+ openSplitConsole: PropTypes.func,
+ networkThrottling: PropTypes.shape(Types.networkThrottling).isRequired,
+ // Executed when throttling changes (through toolbar button).
+ onChangeNetworkThrottling: PropTypes.func.isRequired,
+ toggleSearchPanel: PropTypes.func.isRequired,
+ toggleHTTPCustomRequestPanel: PropTypes.func.isRequired,
+ networkActionBarOpen: PropTypes.bool,
+ toggleRequestBlockingPanel: PropTypes.func.isRequired,
+ networkActionBarSelectedPanel: PropTypes.string.isRequired,
+ hasBlockedRequests: PropTypes.bool.isRequired,
+ selectedRequest: PropTypes.object,
+ toolboxDoc: PropTypes.object.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.autocompleteProvider = this.autocompleteProvider.bind(this);
+ this.onSearchBoxFocusKeyboardShortcut =
+ this.onSearchBoxFocusKeyboardShortcut.bind(this);
+ this.onSearchBoxFocus = this.onSearchBoxFocus.bind(this);
+ this.toggleRequestFilterType = this.toggleRequestFilterType.bind(this);
+ this.updatePersistentLogsEnabled =
+ this.updatePersistentLogsEnabled.bind(this);
+ this.updateBrowserCacheDisabled =
+ this.updateBrowserCacheDisabled.bind(this);
+ }
+
+ componentDidMount() {
+ Services.prefs.addObserver(
+ DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF,
+ this.updatePersistentLogsEnabled
+ );
+ Services.prefs.addObserver(
+ DEVTOOLS_DISABLE_CACHE_PREF,
+ this.updateBrowserCacheDisabled
+ );
+
+ this.shortcuts = new KeyShortcuts({
+ window,
+ });
+
+ this.shortcuts.on(SEARCH_KEY_SHORTCUT, event => {
+ event.preventDefault();
+ this.props.toggleSearchPanel();
+ });
+
+ this.shortcuts.on(COPY_KEY_SHORTCUT, () => {
+ if (this.props.selectedRequest && this.props.selectedRequest.url) {
+ copyString(this.props.selectedRequest.url);
+ }
+ });
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ this.props.persistentLogsEnabled !== nextProps.persistentLogsEnabled ||
+ this.props.browserCacheDisabled !== nextProps.browserCacheDisabled ||
+ this.props.recording !== nextProps.recording ||
+ this.props.networkActionBarOpen !== nextProps.networkActionBarOpen ||
+ this.props.singleRow !== nextProps.singleRow ||
+ !Object.is(this.props.requestFilterTypes, nextProps.requestFilterTypes) ||
+ this.props.networkThrottling !== nextProps.networkThrottling ||
+ // Filtered requests are useful only when searchbox is focused
+ !!(this.refs.searchbox && this.refs.searchbox.focused) ||
+ this.props.networkActionBarSelectedPanel !==
+ nextProps.networkActionBarSelectedPanel ||
+ this.props.hasBlockedRequests !== nextProps.hasBlockedRequests
+ );
+ }
+
+ componentWillUnmount() {
+ Services.prefs.removeObserver(
+ DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF,
+ this.updatePersistentLogsEnabled
+ );
+ Services.prefs.removeObserver(
+ DEVTOOLS_DISABLE_CACHE_PREF,
+ this.updateBrowserCacheDisabled
+ );
+
+ if (this.shortcuts) {
+ this.shortcuts.destroy();
+ }
+ }
+
+ toggleRequestFilterType(evt) {
+ if (evt.type === "keydown" && (evt.key !== "" || evt.key !== "Enter")) {
+ return;
+ }
+ this.props.toggleRequestFilterType(evt.target.dataset.key);
+ }
+
+ updatePersistentLogsEnabled() {
+ // Make sure the UI is updated when the pref changes.
+ // It might happen when the user changed it through about:config or
+ // through another Toolbox instance (opened in another browser tab).
+ // In such case, skip telemetry recordings.
+ this.props.enablePersistentLogs(
+ Services.prefs.getBoolPref(DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF),
+ true
+ );
+ }
+
+ updateBrowserCacheDisabled() {
+ this.props.disableBrowserCache(
+ Services.prefs.getBoolPref(DEVTOOLS_DISABLE_CACHE_PREF)
+ );
+ }
+
+ autocompleteProvider(filter) {
+ return autocompleteProvider(filter, this.props.filteredRequests);
+ }
+
+ onSearchBoxFocusKeyboardShortcut(event) {
+ // Don't take focus when the keyboard shortcut is triggered in a CodeMirror instance,
+ // so the CodeMirror search UI is displayed.
+ return !!event.target.closest(".CodeMirror");
+ }
+
+ onSearchBoxFocus() {
+ const { connector, filteredRequests } = this.props;
+
+ // Fetch responseCookies & responseHeaders for building autocomplete list
+ filteredRequests.forEach(request => {
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "responseCookies",
+ "responseHeaders",
+ ]);
+ });
+ }
+
+ /**
+ * Render a separator.
+ */
+ renderSeparator() {
+ return span({ className: "devtools-separator" });
+ }
+
+ /**
+ * Render a clear button.
+ */
+ renderClearButton(clearRequests) {
+ return button({
+ className:
+ "devtools-button devtools-clear-icon requests-list-clear-button",
+ title: TOOLBAR_CLEAR,
+ onClick: clearRequests,
+ });
+ }
+
+ /**
+ * Render a ToggleRecording button.
+ */
+ renderToggleRecordingButton(recording, toggleRecording) {
+ // Calculate class-list for toggle recording button.
+ // The button has two states: pause/play.
+ const toggleRecordingButtonClass = [
+ "devtools-button",
+ "requests-list-pause-button",
+ recording ? "devtools-pause-icon" : "devtools-play-icon",
+ ].join(" ");
+
+ return button({
+ className: toggleRecordingButtonClass,
+ title: TOOLBAR_TOGGLE_RECORDING,
+ onClick: toggleRecording,
+ });
+ }
+
+ /**
+ * Render a blocking button.
+ */
+ renderBlockingButton(toggleSearchPanel) {
+ const {
+ networkActionBarOpen,
+ toggleRequestBlockingPanel,
+ networkActionBarSelectedPanel,
+ hasBlockedRequests,
+ } = this.props;
+
+ // The blocking feature is available behind a pref.
+ if (
+ !Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.requestBlocking"
+ )
+ ) {
+ return null;
+ }
+
+ const className = ["devtools-button", "requests-list-blocking-button"];
+ if (
+ networkActionBarOpen &&
+ networkActionBarSelectedPanel === PANELS.BLOCKING
+ ) {
+ className.push("checked");
+ }
+
+ if (hasBlockedRequests) {
+ className.push("requests-list-blocking-button-enabled");
+ }
+
+ return button({
+ className: className.join(" "),
+ title: TOOLBAR_BLOCKING,
+ "aria-pressed": networkActionBarOpen,
+ onClick: toggleRequestBlockingPanel,
+ });
+ }
+
+ /**
+ * Render a search button.
+ */
+ renderSearchButton(toggleSearchPanel) {
+ const { networkActionBarOpen, networkActionBarSelectedPanel } = this.props;
+
+ // The search feature is available behind a pref.
+ if (!Services.prefs.getBoolPref("devtools.netmonitor.features.search")) {
+ return null;
+ }
+
+ const className = [
+ "devtools-button",
+ "devtools-search-icon",
+ "requests-list-search-button",
+ ];
+
+ if (
+ networkActionBarOpen &&
+ networkActionBarSelectedPanel === PANELS.SEARCH
+ ) {
+ className.push("checked");
+ }
+
+ return button({
+ className: className.join(" "),
+ title: TOOLBAR_SEARCH,
+ "aria-pressed": networkActionBarOpen,
+ onClick: toggleSearchPanel,
+ });
+ }
+
+ /**
+ * Render a new HTTP Custom Request button.
+ */
+ renderHTTPCustomRequestButton() {
+ const {
+ networkActionBarOpen,
+ networkActionBarSelectedPanel,
+ toggleHTTPCustomRequestPanel,
+ } = this.props;
+
+ // The new HTTP Custom Request feature is available behind a pref.
+ if (
+ !Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend"
+ )
+ ) {
+ return null;
+ }
+
+ const className = [
+ "devtools-button",
+ "devtools-http-custom-request-icon",
+ "requests-list-http-custom-request-button",
+ ];
+
+ if (
+ networkActionBarOpen &&
+ networkActionBarSelectedPanel === PANELS.HTTP_CUSTOM_REQUEST
+ ) {
+ className.push("checked");
+ }
+
+ return button({
+ className: className.join(" "),
+ title: TOOLBAR_HTTP_CUSTOM_REQUEST,
+ "aria-pressed": networkActionBarOpen,
+ onClick: toggleHTTPCustomRequestPanel,
+ });
+ }
+
+ /**
+ * Render filter buttons.
+ */
+ renderFilterButtons(requestFilterTypes) {
+ // Render list of filter-buttons.
+ const buttons = Object.entries(requestFilterTypes).map(([type, checked]) =>
+ button(
+ {
+ className: `devtools-togglebutton requests-list-filter-${type}-button`,
+ key: type,
+ onClick: this.toggleRequestFilterType,
+ onKeyDown: this.toggleRequestFilterType,
+ "aria-pressed": checked,
+ "data-key": type,
+ },
+ TOOLBAR_FILTER_LABELS[type]
+ )
+ );
+ return div({ className: "requests-list-filter-buttons" }, buttons);
+ }
+
+ /**
+ * Render a Cache checkbox.
+ */
+ renderCacheCheckbox(browserCacheDisabled, toggleBrowserCache) {
+ return label(
+ {
+ className: "devtools-checkbox-label devtools-cache-checkbox",
+ title: DISABLE_CACHE_TOOLTIP,
+ },
+ input({
+ id: "devtools-cache-checkbox",
+ className: "devtools-checkbox",
+ type: "checkbox",
+ checked: browserCacheDisabled,
+ onChange: toggleBrowserCache,
+ }),
+ DISABLE_CACHE_LABEL
+ );
+ }
+
+ /**
+ * Render network throttling menu button.
+ */
+ renderThrottlingMenu() {
+ const { networkThrottling, onChangeNetworkThrottling } = this.props;
+
+ return NetworkThrottlingMenu({
+ networkThrottling,
+ onChangeNetworkThrottling,
+ });
+ }
+
+ /**
+ * Render filter Searchbox.
+ */
+ renderFilterBox(setRequestFilterText) {
+ return SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ keyShortcut: FILTER_KEY_SHORTCUT,
+ placeholder: SEARCH_PLACE_HOLDER,
+ type: "filter",
+ ref: "searchbox",
+ onChange: setRequestFilterText,
+ onFocusKeyboardShortcut: this.onSearchBoxFocusKeyboardShortcut,
+ onFocus: this.onSearchBoxFocus,
+ autocompleteProvider: this.autocompleteProvider,
+ learnMoreUrl: LEARN_MORE_URL,
+ learnMoreTitle: LEARN_MORE_TITLE,
+ });
+ }
+
+ renderSettingsMenuButton() {
+ const { toolboxDoc } = this.props;
+ return MenuButton(
+ {
+ menuId: "netmonitor-settings-menu-button",
+ toolboxDoc,
+ className: "devtools-button netmonitor-settings-menu-button",
+ title: L10N.getStr("netmonitor.settings.menuTooltip"),
+ },
+ // We pass the children in a function so we don't require the MenuItem and MenuList
+ // components until we need to display them (i.e. when the button is clicked).
+ () => this.renderSettingsMenuItems()
+ );
+ }
+
+ renderSettingsMenuItems() {
+ const {
+ actions,
+ connector,
+ displayedRequests,
+ openSplitConsole,
+ persistentLogsEnabled,
+ togglePersistentLogs,
+ } = this.props;
+
+ const menuItems = [
+ MenuItem({
+ key: "netmonitor-settings-persist-item",
+ className: "menu-item netmonitor-settings-persist-item",
+ type: "checkbox",
+ checked: persistentLogsEnabled,
+ label: L10N.getStr("netmonitor.toolbar.enablePersistentLogs.label"),
+ tooltip: L10N.getStr("netmonitor.toolbar.enablePersistentLogs.tooltip"),
+ onClick: () => togglePersistentLogs(),
+ }),
+ hr({ key: "netmonitor-settings-har-divider" }),
+ MenuItem({
+ key: "request-list-context-import-har",
+ className: "menu-item netmonitor-settings-import-har-item",
+ label: L10N.getStr("netmonitor.har.importHarDialogTitle"),
+ tooltip: L10N.getStr("netmonitor.settings.importHarTooltip"),
+ accesskey: L10N.getStr("netmonitor.context.importHar.accesskey"),
+ onClick: () => HarMenuUtils.openHarFile(actions, openSplitConsole),
+ }),
+ MenuItem({
+ key: "request-list-context-save-all-as-har",
+ className: "menu-item netmonitor-settings-save-har-item",
+ label: L10N.getStr("netmonitor.context.saveAllAsHar"),
+ accesskey: L10N.getStr("netmonitor.context.saveAllAsHar.accesskey"),
+ tooltip: L10N.getStr("netmonitor.settings.saveHarTooltip"),
+ disabled: !displayedRequests.length,
+ onClick: () => HarMenuUtils.saveAllAsHar(displayedRequests, connector),
+ }),
+ MenuItem({
+ key: "request-list-context-copy-all-as-har",
+ className: "menu-item netmonitor-settings-copy-har-item",
+ label: L10N.getStr("netmonitor.context.copyAllAsHar"),
+ accesskey: L10N.getStr("netmonitor.context.copyAllAsHar.accesskey"),
+ tooltip: L10N.getStr("netmonitor.settings.copyHarTooltip"),
+ disabled: !displayedRequests.length,
+ onClick: () => HarMenuUtils.copyAllAsHar(displayedRequests, connector),
+ }),
+ ];
+
+ return MenuList({ id: "netmonitor-settings-menu-list" }, menuItems);
+ }
+
+ render() {
+ const {
+ toggleRecording,
+ clearRequests,
+ requestFilterTypes,
+ setRequestFilterText,
+ toggleBrowserCache,
+ browserCacheDisabled,
+ recording,
+ singleRow,
+ toggleSearchPanel,
+ } = this.props;
+
+ // Render the entire toolbar.
+ // dock at bottom or dock at side has different layout
+ return singleRow
+ ? span(
+ { id: "netmonitor-toolbar-container" },
+ span(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ this.renderClearButton(clearRequests),
+ this.renderSeparator(),
+ this.renderFilterBox(setRequestFilterText),
+ this.renderSeparator(),
+ this.renderToggleRecordingButton(recording, toggleRecording),
+ this.renderHTTPCustomRequestButton(),
+ this.renderSearchButton(toggleSearchPanel),
+ this.renderBlockingButton(toggleSearchPanel),
+ this.renderSeparator(),
+ this.renderFilterButtons(requestFilterTypes),
+ this.renderSeparator(),
+ this.renderCacheCheckbox(browserCacheDisabled, toggleBrowserCache),
+ this.renderSeparator(),
+ this.renderThrottlingMenu(),
+ this.renderSeparator(),
+ this.renderSettingsMenuButton()
+ )
+ )
+ : span(
+ { id: "netmonitor-toolbar-container" },
+ span(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ this.renderClearButton(clearRequests),
+ this.renderSeparator(),
+ this.renderFilterBox(setRequestFilterText),
+ this.renderSeparator(),
+ this.renderToggleRecordingButton(recording, toggleRecording),
+ this.renderHTTPCustomRequestButton(),
+ this.renderSearchButton(toggleSearchPanel),
+ this.renderBlockingButton(toggleSearchPanel),
+ this.renderSeparator(),
+ this.renderCacheCheckbox(browserCacheDisabled, toggleBrowserCache),
+ this.renderSeparator(),
+ this.renderThrottlingMenu(),
+ this.renderSeparator(),
+ this.renderSettingsMenuButton()
+ ),
+ span(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ this.renderFilterButtons(requestFilterTypes)
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ browserCacheDisabled: state.ui.browserCacheDisabled,
+ displayedRequests: getDisplayedRequests(state),
+ hasBlockedRequests:
+ state.requestBlocking.blockingEnabled &&
+ state.requestBlocking.blockedUrls.some(({ enabled }) => enabled),
+ filteredRequests: getTypeFilteredRequests(state),
+ persistentLogsEnabled: state.ui.persistentLogsEnabled,
+ recording: getRecordingState(state),
+ requestFilterTypes: state.filters.requestFilterTypes,
+ networkThrottling: state.networkThrottling,
+ networkActionBarOpen: state.ui.networkActionOpen,
+ networkActionBarSelectedPanel: state.ui.selectedActionBarTabId || "",
+ selectedRequest: getSelectedRequest(state),
+ }),
+ dispatch => ({
+ clearRequests: () => dispatch(Actions.clearRequests()),
+ disableBrowserCache: disabled =>
+ dispatch(Actions.disableBrowserCache(disabled)),
+ enablePersistentLogs: (enabled, skipTelemetry) =>
+ dispatch(Actions.enablePersistentLogs(enabled, skipTelemetry)),
+ setRequestFilterText: text => dispatch(Actions.setRequestFilterText(text)),
+ toggleBrowserCache: () => dispatch(Actions.toggleBrowserCache()),
+ toggleRecording: () => dispatch(Actions.toggleRecording()),
+ togglePersistentLogs: () => dispatch(Actions.togglePersistentLogs()),
+ toggleRequestFilterType: type =>
+ dispatch(Actions.toggleRequestFilterType(type)),
+ onChangeNetworkThrottling: (enabled, profile) =>
+ dispatch(changeNetworkThrottling(enabled, profile)),
+ toggleHTTPCustomRequestPanel: () =>
+ dispatch(Actions.toggleHTTPCustomRequestPanel()),
+ toggleSearchPanel: () => dispatch(Actions.toggleSearchPanel()),
+ toggleRequestBlockingPanel: () =>
+ dispatch(Actions.toggleRequestBlockingPanel()),
+ })
+)(Toolbar);
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 };
diff --git a/devtools/client/netmonitor/src/components/moz.build b/devtools/client/netmonitor/src/components/moz.build
new file mode 100644
index 0000000000..98d821338f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/moz.build
@@ -0,0 +1,28 @@
+# 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 += [
+ "messages",
+ "new-request",
+ "previews",
+ "request-blocking",
+ "request-details",
+ "request-list",
+ "search",
+]
+
+DevToolsModules(
+ "App.js",
+ "CustomRequestPanel.js",
+ "DropHarHandler.js",
+ "MonitorPanel.js",
+ "NetworkActionBar.js",
+ "SecurityState.js",
+ "SourceEditor.js",
+ "StatisticsPanel.js",
+ "StatusBar.js",
+ "StatusCode.js",
+ "TabboxPanel.js",
+ "Toolbar.js",
+)
diff --git a/devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js b/devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js
new file mode 100644
index 0000000000..826f0317ba
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js
@@ -0,0 +1,511 @@
+/* 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 asyncStorage = require("resource://devtools/shared/async-storage.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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ getClickedRequest,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ getUrlQuery,
+ parseQueryString,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const InputMap = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/new-request/InputMap.js")
+);
+const { button, div, footer, label, textarea, select, option } = dom;
+
+const CUSTOM_HEADERS = L10N.getStr("netmonitor.custom.newRequestHeaders");
+const CUSTOM_NEW_REQUEST_URL_LABEL = L10N.getStr(
+ "netmonitor.custom.newRequestUrlLabel"
+);
+const CUSTOM_POSTDATA = L10N.getStr("netmonitor.custom.postBody");
+const CUSTOM_POSTDATA_PLACEHOLDER = L10N.getStr(
+ "netmonitor.custom.postBody.placeholder"
+);
+const CUSTOM_QUERY = L10N.getStr("netmonitor.custom.urlParameters");
+const CUSTOM_SEND = L10N.getStr("netmonitor.custom.send");
+const CUSTOM_CLEAR = L10N.getStr("netmonitor.custom.clear");
+
+const FIREFOX_DEFAULT_HEADERS = [
+ "Accept-Charset",
+ "Accept-Encoding",
+ "Access-Control-Request-Headers",
+ "Access-Control-Request-Method",
+ "Connection",
+ "Content-Length",
+ "Cookie",
+ "Cookie2",
+ "Date",
+ "DNT",
+ "Expect",
+ "Feature-Policy",
+ "Host",
+ "Keep-Alive",
+ "Origin",
+ "Proxy-",
+ "Sec-",
+ "Referer",
+ "TE",
+ "Trailer",
+ "Transfer-Encoding",
+ "Upgrade",
+ "Via",
+];
+// This does not include the CONNECT method as it is restricted and special.
+// See https://bugzilla.mozilla.org/show_bug.cgi?id=1769572#c2 for details
+const HTTP_METHODS = [
+ "GET",
+ "HEAD",
+ "POST",
+ "DELETE",
+ "PUT",
+ "OPTIONS",
+ "TRACE",
+ "PATCH",
+];
+
+/*
+ * HTTP Custom request panel component
+ * A network request panel which enables creating and sending new requests
+ * or selecting, editing and re-sending current requests.
+ */
+class HTTPCustomRequestPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ request: PropTypes.object,
+ sendCustomRequest: PropTypes.func.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ method: HTTP_METHODS[0],
+ url: "",
+ urlQueryParams: [],
+ headers: [],
+ postBody: "",
+ // Flag to know the data from either the request or the async storage has
+ // been loaded in componentDidMount
+ _isStateDataReady: false,
+ };
+
+ this.handleInputChange = this.handleInputChange.bind(this);
+ this.handleChangeURL = this.handleChangeURL.bind(this);
+ this.updateInputMapItem = this.updateInputMapItem.bind(this);
+ this.addInputMapItem = this.addInputMapItem.bind(this);
+ this.deleteInputMapItem = this.deleteInputMapItem.bind(this);
+ this.checkInputMapItem = this.checkInputMapItem.bind(this);
+ this.handleClear = this.handleClear.bind(this);
+ this.createQueryParamsListFromURL =
+ this.createQueryParamsListFromURL.bind(this);
+ this.onUpdateQueryParams = this.onUpdateQueryParams.bind(this);
+ }
+
+ async componentDidMount() {
+ let { connector, request } = this.props;
+ const persistedCustomRequest = await asyncStorage.getItem(
+ "devtools.netmonitor.customRequest"
+ );
+ request = request || persistedCustomRequest;
+
+ if (!request) {
+ this.setState({ _isStateDataReady: true });
+ return;
+ }
+
+ // We need this part because in the asyncStorage we are saving the request in one format
+ // and from the edit and resend it comes in a different form with different properties,
+ // so we need this to nomalize the request.
+ if (request.requestHeaders) {
+ request.headers = request.requestHeaders.headers;
+ }
+
+ if (request.requestPostData?.postData?.text) {
+ request.postBody = request.requestPostData.postData.text;
+ }
+
+ const headers = request.headers
+ .map(({ name, value }) => {
+ return {
+ name,
+ value,
+ checked: true,
+ disabled: FIREFOX_DEFAULT_HEADERS.some(i => name.startsWith(i)),
+ };
+ })
+ .sort((a, b) => {
+ if (a.disabled && !b.disabled) {
+ return -1;
+ }
+ if (!a.disabled && b.disabled) {
+ return 1;
+ }
+ return 0;
+ });
+
+ if (request.requestPostDataAvailable && !request.postBody) {
+ const requestData = await connector.requestData(
+ request.id,
+ "requestPostData"
+ );
+ request.postBody = requestData.postData.text;
+ }
+
+ this.setState({
+ method: request.method,
+ url: request.url,
+ urlQueryParams: this.createQueryParamsListFromURL(request.url),
+ headers,
+ postBody: request.postBody,
+ _isStateDataReady: true,
+ });
+ }
+
+ componentDidUpdate(prevProps, prevState) {
+ // This is when the query params change in the url params input map
+ if (
+ prevState.urlQueryParams !== this.state.urlQueryParams &&
+ prevState.url === this.state.url
+ ) {
+ this.onUpdateQueryParams();
+ }
+ }
+
+ componentWillUnmount() {
+ asyncStorage.setItem("devtools.netmonitor.customRequest", this.state);
+ }
+
+ handleChangeURL(event) {
+ const { value } = event.target;
+
+ this.setState({
+ url: value,
+ urlQueryParams: this.createQueryParamsListFromURL(value),
+ });
+ }
+
+ handleInputChange(event) {
+ const { name, value } = event.target;
+ const newState = {
+ [name]: value,
+ };
+
+ // If the message body changes lets make sure we
+ // keep the content-length up to date.
+ if (name == "postBody") {
+ newState.headers = this.state.headers.map(header => {
+ if (header.name == "Content-Length") {
+ header.value = value.length;
+ }
+ return header;
+ });
+ }
+
+ this.setState(newState);
+ }
+
+ updateInputMapItem(stateName, event) {
+ const { name, value } = event.target;
+ const [prop, index] = name.split("-");
+ const updatedList = [...this.state[stateName]];
+ updatedList[Number(index)][prop] = value;
+
+ this.setState({
+ [stateName]: updatedList,
+ });
+ }
+
+ addInputMapItem(stateName, name, value) {
+ this.setState({
+ [stateName]: [
+ ...this.state[stateName],
+ { name, value, checked: true, disabled: false },
+ ],
+ });
+ }
+
+ deleteInputMapItem(stateName, index) {
+ this.setState({
+ [stateName]: this.state[stateName].filter((_, i) => i !== index),
+ });
+ }
+
+ checkInputMapItem(stateName, index, checked) {
+ this.setState({
+ [stateName]: this.state[stateName].map((item, i) => {
+ if (index === i) {
+ return {
+ ...item,
+ checked,
+ };
+ }
+ return item;
+ }),
+ });
+ }
+
+ onUpdateQueryParams() {
+ const { urlQueryParams, url } = this.state;
+ let queryString = "";
+ for (const { name, value, checked } of urlQueryParams) {
+ if (checked) {
+ queryString += `${encodeURIComponent(name)}=${encodeURIComponent(
+ value
+ )}&`;
+ }
+ }
+
+ let finalURL = url.split("?")[0];
+
+ if (queryString.length) {
+ finalURL += `?${queryString.substring(0, queryString.length - 1)}`;
+ }
+ this.setState({
+ url: finalURL,
+ });
+ }
+
+ createQueryParamsListFromURL(url = "") {
+ const parsedQuery = parseQueryString(getUrlQuery(url) || url.split("?")[1]);
+ const queryArray = parsedQuery || [];
+ return queryArray.map(({ name, value }) => {
+ return {
+ checked: true,
+ name,
+ value,
+ };
+ });
+ }
+
+ handleClear() {
+ this.setState({
+ method: HTTP_METHODS[0],
+ url: "",
+ urlQueryParams: [],
+ headers: [],
+ postBody: "",
+ });
+ }
+
+ render() {
+ return div(
+ { className: "http-custom-request-panel" },
+ div(
+ { className: "http-custom-request-panel-content" },
+ div(
+ {
+ className: "tabpanel-summary-container http-custom-method-and-url",
+ id: "http-custom-method-and-url",
+ },
+ select(
+ {
+ className: "http-custom-method-value",
+ id: "http-custom-method-value",
+ name: "method",
+ onChange: this.handleInputChange,
+ onBlur: this.handleInputChange,
+ value: this.state.method,
+ },
+
+ HTTP_METHODS.map(item =>
+ option(
+ {
+ value: item,
+ key: item,
+ },
+ item
+ )
+ )
+ ),
+ div(
+ {
+ className: "auto-growing-textarea",
+ "data-replicated-value": this.state.url,
+ title: this.state.url,
+ },
+ textarea({
+ className: "http-custom-url-value",
+ id: "http-custom-url-value",
+ name: "url",
+ placeholder: CUSTOM_NEW_REQUEST_URL_LABEL,
+ onChange: event => {
+ this.handleChangeURL(event);
+ },
+ onBlur: this.handleTextareaChange,
+ value: this.state.url,
+ rows: 1,
+ })
+ )
+ ),
+ div(
+ {
+ className: "tabpanel-summary-container http-custom-section",
+ id: "http-custom-query",
+ },
+ label(
+ {
+ className: "http-custom-request-label",
+ htmlFor: "http-custom-query-value",
+ },
+ CUSTOM_QUERY
+ ),
+ // This is the input map for the Url Parameters Component
+ InputMap({
+ list: this.state.urlQueryParams,
+ onUpdate: event => {
+ this.updateInputMapItem(
+ "urlQueryParams",
+ event,
+ this.onUpdateQueryParams
+ );
+ },
+ onAdd: (name, value) =>
+ this.addInputMapItem(
+ "urlQueryParams",
+ name,
+ value,
+ this.onUpdateQueryParams
+ ),
+ onDelete: index =>
+ this.deleteInputMapItem(
+ "urlQueryParams",
+ index,
+ this.onUpdateQueryParams
+ ),
+ onChecked: (index, checked) => {
+ this.checkInputMapItem(
+ "urlQueryParams",
+ index,
+ checked,
+ this.onUpdateQueryParams
+ );
+ },
+ })
+ ),
+ div(
+ {
+ id: "http-custom-headers",
+ className: "tabpanel-summary-container http-custom-section",
+ },
+ label(
+ {
+ className: "http-custom-request-label",
+ htmlFor: "custom-headers-value",
+ },
+ CUSTOM_HEADERS
+ ),
+ // This is the input map for the Headers Component
+ InputMap({
+ ref: this.headersListRef,
+ list: this.state.headers,
+ onUpdate: event => {
+ this.updateInputMapItem("headers", event);
+ },
+ onAdd: (name, value) =>
+ this.addInputMapItem("headers", name, value),
+ onDelete: index => this.deleteInputMapItem("headers", index),
+ onChecked: (index, checked) => {
+ this.checkInputMapItem("headers", index, checked);
+ },
+ })
+ ),
+ div(
+ {
+ id: "http-custom-postdata",
+ className: "tabpanel-summary-container http-custom-section",
+ },
+ label(
+ {
+ className: "http-custom-request-label",
+ htmlFor: "http-custom-postdata-value",
+ },
+ CUSTOM_POSTDATA
+ ),
+ textarea({
+ className: "tabpanel-summary-input",
+ id: "http-custom-postdata-value",
+ name: "postBody",
+ placeholder: CUSTOM_POSTDATA_PLACEHOLDER,
+ onChange: this.handleInputChange,
+ rows: 6,
+ value: this.state.postBody,
+ wrap: "off",
+ })
+ )
+ ),
+ footer(
+ { className: "http-custom-request-button-container" },
+ button(
+ {
+ className: "devtools-button",
+ id: "http-custom-request-clear-button",
+ onClick: this.handleClear,
+ },
+ CUSTOM_CLEAR
+ ),
+ button(
+ {
+ className: "devtools-button",
+ id: "http-custom-request-send-button",
+ disabled:
+ !this.state._isStateDataReady ||
+ !this.state.url ||
+ !this.state.method,
+ onClick: () => {
+ const newRequest = {
+ method: this.state.method,
+ url: this.state.url,
+ cause: this.props.request?.cause,
+ urlQueryParams: this.state.urlQueryParams.map(
+ ({ checked, ...params }) => params
+ ),
+ requestHeaders: {
+ headers: this.state.headers
+ .filter(({ checked }) => checked)
+ .map(({ checked, ...headersValues }) => headersValues),
+ },
+ };
+
+ if (this.state.postBody) {
+ newRequest.requestPostData = {
+ postData: {
+ text: this.state.postBody,
+ },
+ };
+ }
+ this.props.sendCustomRequest(newRequest);
+ },
+ },
+ CUSTOM_SEND
+ )
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({ request: getClickedRequest(state) }),
+ (dispatch, props) => ({
+ sendCustomRequest: request =>
+ dispatch(Actions.sendHTTPCustomRequest(request)),
+ })
+)(HTTPCustomRequestPanel);
diff --git a/devtools/client/netmonitor/src/components/new-request/InputMap.js b/devtools/client/netmonitor/src/components/new-request/InputMap.js
new file mode 100644
index 0000000000..6e9eff2845
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/new-request/InputMap.js
@@ -0,0 +1,211 @@
+/* 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,
+} = require("resource://devtools/client/shared/vendor/react.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 dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { div, input, textarea, button } = dom;
+
+const CUSTOM_NEW_REQUEST_INPUT_NAME = L10N.getStr(
+ "netmonitor.custom.placeholder.name"
+);
+
+const CUSTOM_NEW_REQUEST_INPUT_VALUE = L10N.getStr(
+ "netmonitor.custom.placeholder.value"
+);
+
+const REMOVE_ITEM = L10N.getStr("netmonitor.custom.removeItem");
+
+/**
+ * Editable name and value list component with optional form to add new items
+ **/
+class InputMap extends Component {
+ static get propTypes() {
+ return {
+ list: PropTypes.arrayOf(
+ PropTypes.shape({
+ name: PropTypes.string.isRequired,
+ value: PropTypes.string.isRequired,
+ disabled: PropTypes.bool,
+ })
+ ).isRequired,
+ onUpdate: PropTypes.func,
+ onAdd: PropTypes.func,
+ onDelete: PropTypes.func,
+ onChange: PropTypes.func,
+ onChecked: PropTypes.func,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.listRef = createRef();
+
+ this.state = {
+ name: "",
+ value: "",
+ };
+ }
+
+ render() {
+ const { list, onUpdate, onAdd, onDelete, onChecked } = this.props;
+ const { name, value } = this.state;
+
+ // Adds a new item with name and value when the user starts typing on the form
+ const onKeyDown = event => {
+ const { target } = event;
+ onAdd(name, value);
+ this.setState({ name: "", value: "" }, () => {
+ // Get next to last child on the list,
+ // because that was the item that was just added and
+ // we need to focous on it, so the user can keep editing it.
+ const targetParentNode =
+ this.listRef.current.childNodes?.[
+ this.listRef.current.childElementCount - 2
+ ];
+ targetParentNode?.querySelector(`.${target.className}`).focus();
+ });
+ };
+
+ return div(
+ {
+ ref: this.listRef,
+ className: "http-custom-input-and-map-form",
+ },
+ list.map((item, index) => {
+ return div(
+ {
+ className: "tabpanel-summary-container http-custom-input",
+ id: `http-custom-${item.name.toLowerCase()}`,
+ key: index,
+ },
+ input({
+ className: "tabpanel-summary-input-checkbox",
+ name: `checked-${index}`,
+ type: "checkbox",
+ onChange: event => {
+ onChecked(index, event.target.checked);
+ },
+ checked: item.checked,
+ disabled: !!item.disabled,
+ wrap: "off",
+ }),
+ div(
+ { className: "tabpanel-summary-input-name" },
+ div(
+ {
+ className: "auto-growing-textarea",
+ "data-replicated-value": item.name,
+ title: item.name,
+ },
+ textarea({
+ className: "http-custom-input-name",
+ name: `name-${index}`,
+ value: item.name,
+ disabled: !!item.disabled,
+ onChange: event => {
+ onUpdate(event);
+ },
+ rows: 1,
+ })
+ )
+ ),
+ div(
+ { className: "tabpanel-summary-input-value" },
+ div(
+ {
+ className: "auto-growing-textarea",
+ "data-replicated-value": item.value,
+ title: item.value,
+ },
+ textarea({
+ className: "http-custom-input-value",
+ name: `value-${index}`,
+ placeholder: "value",
+ disabled: !!item.disabled,
+ onChange: event => {
+ onUpdate(event);
+ },
+ value: item.value,
+ rows: 1,
+ })
+ )
+ ),
+ !item.disabled &&
+ onDelete &&
+ button({
+ className: "http-custom-delete-button",
+ title: REMOVE_ITEM,
+ "aria-label": REMOVE_ITEM,
+ onClick: () => onDelete(index),
+ })
+ );
+ }),
+ onAdd &&
+ div(
+ {
+ className: "map-add-new-inputs",
+ },
+ input({
+ className: "tabpanel-summary-input-checkbox",
+ onChange: () => {},
+ checked: true,
+ type: "checkbox",
+ }),
+ div(
+ { className: "tabpanel-summary-input-name" },
+ div(
+ {
+ className: "auto-growing-textarea",
+ "data-replicated-value": name,
+ title: value,
+ },
+ textarea({
+ className: "http-custom-input-name",
+ type: "text",
+ ref: "addInputName",
+ checked: true,
+ value: name,
+ rows: 1,
+ placeholder: CUSTOM_NEW_REQUEST_INPUT_NAME,
+ onChange: e => this.setState({ name: e.target.value }),
+ onKeyDown,
+ })
+ )
+ ),
+ div(
+ { className: "tabpanel-summary-input-value" },
+ div(
+ {
+ className: "auto-growing-textarea",
+ "data-replicated-value": value,
+ title: value,
+ },
+ textarea({
+ className: "http-custom-input-value",
+ type: "text",
+ ref: "addInputValue",
+ value,
+ onChange: e => this.setState({ value: e.target.value }),
+ rows: 1,
+ placeholder: CUSTOM_NEW_REQUEST_INPUT_VALUE,
+ onKeyDown,
+ })
+ )
+ )
+ )
+ );
+ }
+}
+
+module.exports = InputMap;
diff --git a/devtools/client/netmonitor/src/components/new-request/moz.build b/devtools/client/netmonitor/src/components/new-request/moz.build
new file mode 100644
index 0000000000..7e47799a22
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/new-request/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(
+ "HTTPCustomRequestPanel.js",
+ "InputMap.js",
+)
diff --git a/devtools/client/netmonitor/src/components/previews/FontPreview.js b/devtools/client/netmonitor/src/components/previews/FontPreview.js
new file mode 100644
index 0000000000..2692fdefa0
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/FontPreview.js
@@ -0,0 +1,135 @@
+/* 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 {
+ gDevTools,
+} = require("resource://devtools/client/framework/devtools.js");
+const {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.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 {
+ div,
+ img,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+
+const { getColor } = require("resource://devtools/client/shared/theme.js");
+
+const FONT_NAME = L10N.getStr("netmonitor.response.name");
+const FONT_MIME_TYPE = L10N.getStr("netmonitor.response.mime");
+const FONT_PREVIEW_FAILED = L10N.getStr(
+ "netmonitor.response.fontPreviewFailed"
+);
+
+const FONT_PREVIEW_TEXT =
+ "ABCDEFGHIJKLM\nNOPQRSTUVWXYZ\nabcdefghijklm\nnopqrstuvwxyz\n0123456789";
+
+class FontPreview extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ mimeType: PropTypes.string,
+ url: PropTypes.string,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ name: "",
+ dataURL: "",
+ };
+
+ this.onThemeChanged = this.onThemeChanged.bind(this);
+ }
+
+ componentDidMount() {
+ this.getPreview();
+
+ // Listen for theme changes as the color of the preview depends on the theme
+ gDevTools.on("theme-switched", this.onThemeChanged);
+ }
+
+ componentDidUpdate(prevProps) {
+ const { url } = this.props;
+ if (prevProps.url !== url) {
+ this.getPreview();
+ }
+ }
+
+ componentWillUnmount() {
+ gDevTools.off("theme-switched", this.onThemeChanged);
+ }
+
+ /**
+ * Handler for the "theme-switched" event.
+ */
+ onThemeChanged(frame) {
+ if (frame === window) {
+ this.getPreview();
+ }
+ }
+
+ /**
+ * Generate the font preview and receives information about the font.
+ */
+ async getPreview() {
+ const { connector } = this.props;
+
+ const toolbox = connector.getToolbox();
+ const inspectorFront = await toolbox.target.getFront("inspector");
+ const { pageStyle } = inspectorFront;
+ const pageFontFaces = await pageStyle.getAllUsedFontFaces({
+ includePreviews: true,
+ includeVariations: false,
+ previewText: FONT_PREVIEW_TEXT,
+ previewFillStyle: getColor("body-color"),
+ });
+
+ const fontFace = pageFontFaces.find(
+ pageFontFace => pageFontFace.URI === this.props.url
+ );
+
+ this.setState({
+ name: fontFace?.name ?? "",
+ dataURL: (await fontFace?.preview.data.string()) ?? "",
+ });
+ }
+
+ render() {
+ const { mimeType } = this.props;
+ const { name, dataURL } = this.state;
+
+ if (dataURL === "") {
+ return div({ className: "empty-notice" }, FONT_PREVIEW_FAILED);
+ }
+
+ return div(
+ { className: "panel-container response-font-box devtools-monospace" },
+ img({
+ className: "response-font",
+ src: dataURL,
+ alt: "",
+ }),
+ div(
+ { className: "response-summary" },
+ div({ className: "tabpanel-summary-label" }, FONT_NAME),
+ div({ className: "tabpanel-summary-value" }, name)
+ ),
+ div(
+ { className: "response-summary" },
+ div({ className: "tabpanel-summary-label" }, FONT_MIME_TYPE),
+ div({ className: "tabpanel-summary-value" }, mimeType)
+ )
+ );
+ }
+}
+
+module.exports = FontPreview;
diff --git a/devtools/client/netmonitor/src/components/previews/HtmlPreview.js b/devtools/client/netmonitor/src/components/previews/HtmlPreview.js
new file mode 100644
index 0000000000..ab8c24fac0
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/HtmlPreview.js
@@ -0,0 +1,75 @@
+/* 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");
+
+/*
+ * Response preview component
+ * Display HTML content within a sandbox enabled iframe
+ */
+class HTMLPreview extends Component {
+ static get propTypes() {
+ return {
+ responseContent: PropTypes.object.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { container } = this.refs;
+ const iframe = container.ownerDocument.createXULElement("iframe");
+ this.iframe = iframe;
+ iframe.setAttribute("type", "content");
+ iframe.setAttribute("remote", "true");
+
+ // For some reason, when we try to select some text,
+ // a drag of the whole page is initiated.
+ // Workaround this by canceling any start of drag.
+ iframe.addEventListener("dragstart", e => e.preventDefault(), {
+ capture: true,
+ });
+
+ // Bug 1800916 allow interaction with the preview page until
+ // we find a way to prevent navigation without preventing copy paste from it.
+ //
+ // iframe.addEventListener("mousedown", e => e.preventDefault(), {
+ // capture: true,
+ // });
+ container.appendChild(iframe);
+
+ // browsingContext attribute is only available after the iframe
+ // is attached to the DOM Tree.
+ iframe.browsingContext.allowJavascript = false;
+
+ this.#updatePreview();
+ }
+
+ componentDidUpdate() {
+ this.#updatePreview();
+ }
+
+ componentWillUnmount() {
+ this.iframe.remove();
+ }
+
+ #updatePreview() {
+ const { responseContent } = this.props;
+ const htmlBody = responseContent ? responseContent.content.text : "";
+ this.iframe.setAttribute(
+ "src",
+ "data:text/html;charset=UTF-8," + encodeURIComponent(htmlBody)
+ );
+ }
+
+ render() {
+ return dom.div({ className: "html-preview", ref: "container" });
+ }
+}
+
+module.exports = HTMLPreview;
diff --git a/devtools/client/netmonitor/src/components/previews/ImagePreview.js b/devtools/client/netmonitor/src/components/previews/ImagePreview.js
new file mode 100644
index 0000000000..003a7ec38e
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/ImagePreview.js
@@ -0,0 +1,91 @@
+/* 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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+const {
+ div,
+ img,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+
+const {
+ formDataURI,
+ getUrlBaseName,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const RESPONSE_IMG_NAME = L10N.getStr("netmonitor.response.name");
+const RESPONSE_IMG_DIMENSIONS = L10N.getStr("netmonitor.response.dimensions");
+const RESPONSE_IMG_MIMETYPE = L10N.getStr("netmonitor.response.mime");
+
+class ImagePreview extends Component {
+ static get propTypes() {
+ return {
+ mimeType: PropTypes.string,
+ encoding: PropTypes.string,
+ text: PropTypes.string,
+ url: PropTypes.string,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ dimensions: {
+ width: 0,
+ height: 0,
+ },
+ };
+
+ this.updateDimensions = this.updateDimensions.bind(this);
+ }
+
+ updateDimensions({ target }) {
+ this.setState({
+ dimensions: {
+ width: target.naturalWidth,
+ height: target.naturalHeight,
+ },
+ });
+ }
+
+ render() {
+ const { mimeType, encoding, text, url } = this.props;
+ const { width, height } = this.state.dimensions;
+
+ return div(
+ { className: "panel-container response-image-box devtools-monospace" },
+ img({
+ className: "response-image",
+ src: formDataURI(mimeType, encoding, text),
+ onLoad: this.updateDimensions,
+ }),
+ div(
+ { className: "response-summary" },
+ div({ className: "tabpanel-summary-label" }, RESPONSE_IMG_NAME),
+ div({ className: "tabpanel-summary-value" }, getUrlBaseName(url))
+ ),
+ div(
+ { className: "response-summary" },
+ div({ className: "tabpanel-summary-label" }, RESPONSE_IMG_DIMENSIONS),
+ div({ className: "tabpanel-summary-value" }, `${width} × ${height}`)
+ ),
+ div(
+ { className: "response-summary" },
+ div({ className: "tabpanel-summary-label" }, RESPONSE_IMG_MIMETYPE),
+ div({ className: "tabpanel-summary-value" }, mimeType)
+ )
+ );
+ }
+}
+
+module.exports = ImagePreview;
diff --git a/devtools/client/netmonitor/src/components/previews/SourcePreview.js b/devtools/client/netmonitor/src/components/previews/SourcePreview.js
new file mode 100644
index 0000000000..7e9d011bad
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/SourcePreview.js
@@ -0,0 +1,178 @@
+/* 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const Editor = require("resource://devtools/client/shared/sourceeditor/editor.js");
+const {
+ setTargetSearchResult,
+} = require("resource://devtools/client/netmonitor/src/actions/search.js");
+const { div } = dom;
+/**
+ * CodeMirror editor as a React component
+ */
+class SourcePreview extends Component {
+ static get propTypes() {
+ return {
+ // Source editor syntax highlight mode, which is a mime type defined in CodeMirror
+ mode: PropTypes.string,
+ // Source editor content
+ text: PropTypes.string,
+ // Search result text to select
+ targetSearchResult: PropTypes.object,
+ // Reset target search result that has been used for navigation in this panel.
+ // This is done to avoid second navigation the next time.
+ resetTargetSearchResult: PropTypes.func,
+ };
+ }
+
+ componentDidMount() {
+ const { mode, text } = this.props;
+ this.loadEditor(mode, text);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ nextProps.mode !== this.props.mode ||
+ nextProps.text !== this.props.text ||
+ nextProps.targetSearchResult !== this.props.targetSearchResult
+ );
+ }
+
+ componentDidUpdate(prevProps) {
+ const { mode, targetSearchResult, text } = this.props;
+
+ if (prevProps.text !== text) {
+ // When updating from editor to editor
+ this.updateEditor(mode, text);
+ } else if (prevProps.targetSearchResult !== targetSearchResult) {
+ this.findSearchResult();
+ }
+ }
+
+ componentWillUnmount() {
+ this.unloadEditor();
+ }
+
+ loadEditor(mode, text) {
+ this.editor = new Editor({
+ lineNumbers: true,
+ lineWrapping: false,
+ mode: null, // Disable auto syntax detection, but then we set mode asynchronously
+ readOnly: true,
+ theme: "mozilla",
+ value: text,
+ });
+
+ // Delay to CodeMirror initialization content to prevent UI freezing
+ this.editorTimeout = setTimeout(() => {
+ this.editorTimeout = null;
+ this.editor.appendToLocalElement(this.refs.editorElement);
+
+ // CodeMirror's setMode() (syntax highlight) is the performance bottleneck when
+ // processing large content, so we enable it asynchronously within the setTimeout
+ // to avoid UI blocking. (rendering source code -> drawing syntax highlight)
+ this.editorSetModeTimeout = setTimeout(() => {
+ this.editorSetModeTimeout = null;
+ this.editor.setMode(mode);
+ this.findSearchResult();
+ });
+ });
+ }
+
+ updateEditor(mode, text) {
+ // Reset the existed 'mode' attribute in order to make setText() process faster
+ // to prevent drawing unnecessary syntax highlight.
+ if (this?.editor?.hasCodeMirror) {
+ this.editor.setMode(null);
+ this.editor.setText(text);
+ }
+
+ if (this.editorSetModeTimeout) {
+ clearTimeout(this.editorSetModeTimeout);
+ }
+
+ // CodeMirror's setMode() (syntax highlight) is the performance bottleneck when
+ // processing large content, so we enable it asynchronously within the setTimeout
+ // to avoid UI blocking. (rendering source code -> drawing syntax highlight)
+ this.editorSetModeTimeout = setTimeout(() => {
+ this.editorSetModeTimeout = null;
+ this.editor.setMode(mode);
+ this.findSearchResult();
+ });
+ }
+
+ unloadEditor() {
+ clearTimeout(this.editorTimeout);
+ clearTimeout(this.editorSetModeTimeout);
+ if (this.editor) {
+ this.editor.destroy();
+ this.editor = null;
+ }
+ }
+
+ findSearchResult() {
+ const { targetSearchResult, resetTargetSearchResult } = this.props;
+
+ if (targetSearchResult?.line) {
+ const { line } = targetSearchResult;
+ // scroll the editor to center the line
+ // with the target search result
+ if (this.editor) {
+ this.editor.setCursor({ line: line - 1 }, "center");
+ }
+ }
+
+ resetTargetSearchResult();
+ }
+
+ // Scroll to specified line if the user clicks on search results.
+ scrollToLine(element) {
+ const { targetSearchResult, resetTargetSearchResult } = this.props;
+
+ // The following code is responsible for scrolling given line
+ // to visible view-port.
+ // It gets the <div> child element representing the target
+ // line (by index) and uses `scrollIntoView` API to make sure
+ // it's visible to the user.
+ if (element && targetSearchResult && targetSearchResult.line) {
+ const child = element.children[targetSearchResult.line - 1];
+ if (child) {
+ const range = document.createRange();
+ range.selectNode(child);
+ document.getSelection().addRange(range);
+ child.scrollIntoView({ block: "center" });
+ }
+ resetTargetSearchResult();
+ }
+ }
+
+ renderEditor() {
+ return div(
+ { className: "editor-row-container" },
+ div({
+ ref: "editorElement",
+ className: "source-editor-mount devtools-monospace",
+ })
+ );
+ }
+
+ render() {
+ return div(
+ { key: "EDITOR_CONFIG", className: "editor-row-container" },
+ this.renderEditor()
+ );
+ }
+}
+
+module.exports = connect(null, dispatch => ({
+ resetTargetSearchResult: () => dispatch(setTargetSearchResult(null)),
+}))(SourcePreview);
diff --git a/devtools/client/netmonitor/src/components/previews/UrlPreview.js b/devtools/client/netmonitor/src/components/previews/UrlPreview.js
new file mode 100644
index 0000000000..c20762912f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/UrlPreview.js
@@ -0,0 +1,290 @@
+/* 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 PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ parseQueryString,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const TreeRow = createFactory(
+ require("resource://devtools/client/shared/components/tree/TreeRow.js")
+);
+
+loader.lazyGetter(this, "MODE", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .MODE;
+});
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+
+const { div, span, tr, td } = dom;
+
+/**
+ * Url Preview Component
+ * This component is used to render urls. Its show both compact and destructured views
+ * of the url. Its takes a url and the http method as properties.
+ *
+ * Example Url:
+ * https://foo.com/bla?x=123&y=456&z=789&a=foo&a=bar
+ *
+ * Structure:
+ * {
+ * GET : {
+ * "scheme" : "https",
+ * "host" : "foo.com",
+ * "filename" : "bla",
+ * "query" : {
+ * "x": "123",
+ * "y": "456",
+ * "z": "789",
+ * "a": {
+ * "0": foo,
+ * "1": bar
+ * }
+ * },
+ * "remote" : {
+ * "address" : "127.0.0.1:8080"
+ * }
+ * }
+ * }
+ */
+class UrlPreview extends Component {
+ static get propTypes() {
+ return {
+ url: PropTypes.string,
+ method: PropTypes.string,
+ address: PropTypes.string,
+ shouldExpandPreview: PropTypes.bool,
+ onTogglePreview: PropTypes.func,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.parseUrl = this.parseUrl.bind(this);
+ this.renderValue = this.renderValue.bind(this);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ nextProps.url !== this.props.url ||
+ nextProps.method !== this.props.method ||
+ nextProps.address !== this.props.address
+ );
+ }
+
+ renderRow(props) {
+ const {
+ member: { name, level },
+ } = props;
+ if ((name == "query" || name == "remote") && level == 1) {
+ return tr(
+ { key: name, className: "treeRow stringRow" },
+ td(
+ { colSpan: 2, className: "splitter" },
+ div({ className: "horizontal-splitter" })
+ )
+ );
+ }
+
+ const customProps = { ...props };
+ customProps.member.selected = false;
+ return TreeRow(customProps);
+ }
+
+ renderValue(props) {
+ const {
+ member: { level, open },
+ value,
+ } = props;
+ if (level == 0) {
+ if (open) {
+ return "";
+ }
+ const { scheme, host, filename, query } = value;
+ const queryParamNames = query ? Object.keys(query) : [];
+ // render collapsed url
+ return div(
+ { key: "url", className: "url" },
+ span({ key: "url-scheme", className: "url-scheme" }, `${scheme}://`),
+ span({ key: "url-host", className: "url-host" }, `${host}`),
+ span({ key: "url-filename", className: "url-filename" }, `${filename}`),
+ !!queryParamNames.length &&
+ span({ key: "url-ques", className: "url-chars" }, "?"),
+
+ queryParamNames.map((name, index) => {
+ if (Array.isArray(query[name])) {
+ return query[name].map((item, queryIndex) => {
+ return span(
+ {
+ key: `url-params-${name}${queryIndex}`,
+ className: "url-params",
+ },
+ span(
+ {
+ key: `url-params${name}${queryIndex}-name`,
+ className: "url-params-name",
+ },
+ `${name}`
+ ),
+ span(
+ {
+ key: `url-chars-${name}${queryIndex}-equals`,
+ className: "url-chars",
+ },
+ "="
+ ),
+ span(
+ {
+ key: `url-params-${name}${queryIndex}-value`,
+ className: "url-params-value",
+ },
+ `${item}`
+ ),
+ (query[name].length - 1 !== queryIndex ||
+ queryParamNames.length - 1 !== index) &&
+ span({ key: "url-amp", className: "url-chars" }, "&")
+ );
+ });
+ }
+
+ return span(
+ { key: `url-params-${name}`, className: "url-params" },
+ span(
+ { key: "url-params-name", className: "url-params-name" },
+ `${name}`
+ ),
+ span({ key: "url-chars-equals", className: "url-chars" }, "="),
+ span(
+ { key: "url-params-value", className: "url-params-value" },
+ `${query[name]}`
+ ),
+ queryParamNames.length - 1 !== index &&
+ span({ key: "url-amp", className: "url-chars" }, "&")
+ );
+ })
+ );
+ }
+ if (typeof value !== "string") {
+ // the query node would be an object
+ if (level == 0) {
+ return "";
+ }
+ // for arrays (multival)
+ return "[...]";
+ }
+
+ return value;
+ }
+
+ parseUrl(url) {
+ const { method, address } = this.props;
+ const { host, protocol, pathname, search } = new URL(url);
+
+ const urlObject = {
+ [method]: {
+ scheme: protocol.replace(":", ""),
+ host,
+ filename: pathname,
+ },
+ };
+
+ const expandedNodes = new Set();
+
+ // check and add query parameters
+ if (search.length) {
+ const params = parseQueryString(search);
+ // make sure the query node is always expanded
+ expandedNodes.add(`/${method}/query`);
+ urlObject[method].query = params.reduce((map, obj) => {
+ const value = map[obj.name];
+ if (value || value === "") {
+ if (typeof value !== "object") {
+ expandedNodes.add(`/${method}/query/${obj.name}`);
+ map[obj.name] = [value];
+ }
+ map[obj.name].push(obj.value);
+ } else {
+ map[obj.name] = obj.value;
+ }
+ return map;
+ }, Object.create(null));
+ }
+
+ if (address) {
+ // makes sure the remote adress section is expanded
+ expandedNodes.add(`/${method}/remote`);
+ urlObject[method].remote = {
+ [L10N.getStr("netmonitor.headers.address")]: address,
+ };
+ }
+
+ return {
+ urlObject,
+ expandedNodes,
+ };
+ }
+
+ render() {
+ const {
+ url,
+ method,
+ shouldExpandPreview = false,
+ onTogglePreview,
+ } = this.props;
+
+ const { urlObject, expandedNodes } = this.parseUrl(url);
+
+ if (shouldExpandPreview) {
+ expandedNodes.add(`/${method}`);
+ }
+
+ return div(
+ { className: "url-preview" },
+ PropertiesView({
+ object: urlObject,
+ useQuotes: true,
+ defaultSelectFirstNode: false,
+ mode: MODE.TINY,
+ expandedNodes,
+ renderRow: this.renderRow,
+ renderValue: this.renderValue,
+ enableInput: false,
+ onClickRow: (path, evt, member) => {
+ // Only track when the root is toggled
+ // as all the others are always expanded by
+ // default.
+ if (path == `/${method}`) {
+ onTogglePreview(!member.open);
+ }
+ },
+ contextMenuFormatters: {
+ copyFormatter: (member, baseCopyFormatter) => {
+ const { value, level, hasChildren } = member;
+ if (hasChildren && level == 0) {
+ const { scheme, filename, host, query } = value;
+ return `${scheme}://${host}${filename}${
+ query ? "?" + new URLSearchParams(query).toString() : ""
+ }`;
+ }
+ return baseCopyFormatter(member);
+ },
+ },
+ })
+ );
+ }
+}
+
+module.exports = UrlPreview;
diff --git a/devtools/client/netmonitor/src/components/previews/moz.build b/devtools/client/netmonitor/src/components/previews/moz.build
new file mode 100644
index 0000000000..0252ec3246
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/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/.
+
+DevToolsModules(
+ "FontPreview.js",
+ "HtmlPreview.js",
+ "ImagePreview.js",
+ "SourcePreview.js",
+ "UrlPreview.js",
+)
diff --git a/devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js b/devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js
new file mode 100644
index 0000000000..4d209e788d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js
@@ -0,0 +1,350 @@
+/* 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 {
+ button,
+ div,
+ form,
+ input,
+ label,
+ li,
+ span,
+ ul,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.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");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const RequestBlockingContextMenu = require("resource://devtools/client/netmonitor/src/widgets/RequestBlockingContextMenu.js");
+
+const ENABLE_BLOCKING_LABEL = L10N.getStr(
+ "netmonitor.actionbar.enableBlocking"
+);
+const ADD_URL_PLACEHOLDER = L10N.getStr(
+ "netmonitor.actionbar.blockSearchPlaceholder"
+);
+const REQUEST_BLOCKING_USAGE_NOTICE = L10N.getStr(
+ "netmonitor.actionbar.requestBlockingUsageNotice"
+);
+const REQUEST_BLOCKING_ADD_NOTICE = L10N.getStr(
+ "netmonitor.actionbar.requestBlockingAddNotice"
+);
+const REMOVE_URL_TOOLTIP = L10N.getStr("netmonitor.actionbar.removeBlockedUrl");
+
+class RequestBlockingPanel extends Component {
+ static get propTypes() {
+ return {
+ blockedUrls: PropTypes.array.isRequired,
+ addBlockedUrl: PropTypes.func.isRequired,
+ isDisplaying: PropTypes.bool.isRequired,
+ removeBlockedUrl: PropTypes.func.isRequired,
+ toggleBlockingEnabled: PropTypes.func.isRequired,
+ toggleBlockedUrl: PropTypes.func.isRequired,
+ updateBlockedUrl: PropTypes.func.isRequired,
+ removeAllBlockedUrls: PropTypes.func.isRequired,
+ disableAllBlockedUrls: PropTypes.func.isRequired,
+ enableAllBlockedUrls: PropTypes.func.isRequired,
+ blockingEnabled: PropTypes.bool.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ editingUrl: null,
+ };
+ }
+
+ componentDidMount() {
+ this.refs.addInput.focus();
+ }
+
+ componentDidUpdate(prevProps) {
+ if (this.state.editingUrl) {
+ this.refs.editInput.focus();
+ this.refs.editInput.select();
+ } else if (this.props.isDisplaying && !prevProps.isDisplaying) {
+ this.refs.addInput.focus();
+ }
+ }
+
+ componentWillUnmount() {
+ if (this.scrollToBottomTimeout) {
+ clearTimeout(this.scrollToBottomTimeout);
+ }
+ }
+
+ scrollToBottom() {
+ if (this.scrollToBottomTimeout) {
+ clearTimeout(this.scrollToBottomTimeout);
+ }
+ this.scrollToBottomTimeout = setTimeout(() => {
+ const { contents } = this.refs;
+ if (contents.scrollHeight > contents.offsetHeight) {
+ contents.scrollTo({ top: contents.scrollHeight });
+ }
+ }, 40);
+ }
+
+ renderEnableBar() {
+ return div(
+ { className: "request-blocking-enable-bar" },
+ div(
+ { className: "request-blocking-enable-form" },
+ label(
+ { className: "devtools-checkbox-label" },
+ input({
+ type: "checkbox",
+ className: "devtools-checkbox",
+ checked: this.props.blockingEnabled,
+ ref: "enabledCheckbox",
+ onChange: () =>
+ this.props.toggleBlockingEnabled(
+ this.refs.enabledCheckbox.checked
+ ),
+ }),
+ span({ className: "request-blocking-label" }, ENABLE_BLOCKING_LABEL)
+ )
+ )
+ );
+ }
+
+ renderItemContent({ url, enabled }) {
+ const { toggleBlockedUrl, removeBlockedUrl } = this.props;
+
+ return li(
+ { key: url },
+ label(
+ {
+ className: "devtools-checkbox-label",
+ onDoubleClick: () => this.setState({ editingUrl: url }),
+ },
+ input({
+ type: "checkbox",
+ className: "devtools-checkbox",
+ checked: enabled,
+ onChange: () => toggleBlockedUrl(url),
+ }),
+ span(
+ {
+ className: "request-blocking-label request-blocking-editable-label",
+ title: url,
+ },
+ url
+ )
+ ),
+ button({
+ className: "request-blocking-remove-button",
+ title: REMOVE_URL_TOOLTIP,
+ "aria-label": REMOVE_URL_TOOLTIP,
+ onClick: () => removeBlockedUrl(url),
+ })
+ );
+ }
+
+ renderEditForm(url) {
+ const { updateBlockedUrl, removeBlockedUrl } = this.props;
+ return li(
+ { key: url, className: "request-blocking-edit-item" },
+ form(
+ {
+ onSubmit: e => {
+ const { editInput } = this.refs;
+ const newValue = editInput.value;
+ e.preventDefault();
+
+ if (url != newValue) {
+ if (editInput.value.trim() === "") {
+ removeBlockedUrl(url, newValue);
+ } else {
+ updateBlockedUrl(url, newValue);
+ }
+ }
+ this.setState({ editingUrl: null });
+ },
+ },
+ input({
+ type: "text",
+ defaultValue: url,
+ ref: "editInput",
+ className: "devtools-searchinput",
+ placeholder: ADD_URL_PLACEHOLDER,
+ onBlur: () => this.setState({ editingUrl: null }),
+ onKeyDown: e => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ e.preventDefault();
+ this.setState({ editingUrl: null });
+ }
+ },
+ }),
+
+ input({ type: "submit", style: { display: "none" } })
+ )
+ );
+ }
+
+ renderBlockedList() {
+ const {
+ blockedUrls,
+ blockingEnabled,
+ removeAllBlockedUrls,
+ disableAllBlockedUrls,
+ enableAllBlockedUrls,
+ } = this.props;
+
+ if (blockedUrls.length === 0) {
+ return null;
+ }
+
+ const listItems = blockedUrls.map(item =>
+ this.state.editingUrl === item.url
+ ? this.renderEditForm(item.url)
+ : this.renderItemContent(item)
+ );
+
+ return div(
+ {
+ className: "request-blocking-contents",
+ ref: "contents",
+ onContextMenu: event => {
+ if (!this.contextMenu) {
+ this.contextMenu = new RequestBlockingContextMenu({
+ removeAllBlockedUrls,
+ disableAllBlockedUrls,
+ enableAllBlockedUrls,
+ });
+ }
+
+ const contextMenuOptions = {
+ disableDisableAllBlockedUrls: blockedUrls.every(
+ ({ enabled }) => enabled === false
+ ),
+ disableEnableAllBlockedUrls: blockedUrls.every(
+ ({ enabled }) => enabled === true
+ ),
+ };
+
+ this.contextMenu.open(event, contextMenuOptions);
+ },
+ },
+ ul(
+ {
+ className: `request-blocking-list ${
+ blockingEnabled ? "" : "disabled"
+ }`,
+ },
+ ...listItems
+ )
+ );
+ }
+
+ renderAddForm() {
+ const { addBlockedUrl } = this.props;
+ return div(
+ { className: "request-blocking-footer" },
+ form(
+ {
+ className: "request-blocking-add-form",
+ onSubmit: e => {
+ const { addInput } = this.refs;
+ e.preventDefault();
+ addBlockedUrl(addInput.value);
+ addInput.value = "";
+ addInput.focus();
+ this.scrollToBottom();
+ },
+ },
+ input({
+ type: "text",
+ ref: "addInput",
+ className: "devtools-searchinput",
+ placeholder: ADD_URL_PLACEHOLDER,
+ onKeyDown: e => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ e.preventDefault();
+
+ const { addInput } = this.refs;
+ addInput.value = "";
+ addInput.focus();
+ }
+ },
+ }),
+ input({ type: "submit", style: { display: "none" } })
+ )
+ );
+ }
+
+ renderEmptyListNotice() {
+ return div(
+ { className: "request-blocking-list-empty-notice" },
+ div(
+ { className: "request-blocking-notice-element" },
+ REQUEST_BLOCKING_USAGE_NOTICE
+ ),
+ div(
+ { className: "request-blocking-notice-element" },
+ REQUEST_BLOCKING_ADD_NOTICE
+ )
+ );
+ }
+
+ render() {
+ const { blockedUrls, addBlockedUrl } = this.props;
+
+ return div(
+ {
+ className: "request-blocking-panel",
+ onDragOver: e => {
+ e.preventDefault();
+ },
+ onDrop: e => {
+ e.preventDefault();
+ const url = e.dataTransfer.getData("text/plain");
+ addBlockedUrl(url);
+ this.scrollToBottom();
+ },
+ },
+ this.renderEnableBar(),
+ this.renderBlockedList(),
+ this.renderAddForm(),
+ !blockedUrls.length && this.renderEmptyListNotice()
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ blockedUrls: state.requestBlocking.blockedUrls,
+ blockingEnabled: state.requestBlocking.blockingEnabled,
+ isDisplaying: state.ui.selectedActionBarTabId === PANELS.BLOCKING,
+ }),
+ dispatch => ({
+ toggleBlockingEnabled: checked =>
+ dispatch(Actions.toggleBlockingEnabled(checked)),
+ addBlockedUrl: url => dispatch(Actions.addBlockedUrl(url)),
+ removeBlockedUrl: url => dispatch(Actions.removeBlockedUrl(url)),
+ toggleBlockedUrl: url => dispatch(Actions.toggleBlockedUrl(url)),
+ removeAllBlockedUrls: () => dispatch(Actions.removeAllBlockedUrls()),
+ enableAllBlockedUrls: () => dispatch(Actions.enableAllBlockedUrls()),
+ disableAllBlockedUrls: () => dispatch(Actions.disableAllBlockedUrls()),
+ updateBlockedUrl: (oldUrl, newUrl) =>
+ dispatch(Actions.updateBlockedUrl(oldUrl, newUrl)),
+ })
+)(RequestBlockingPanel);
diff --git a/devtools/client/netmonitor/src/components/request-blocking/moz.build b/devtools/client/netmonitor/src/components/request-blocking/moz.build
new file mode 100644
index 0000000000..7ce0f7ecc6
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-blocking/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(
+ "RequestBlockingPanel.js",
+)
diff --git a/devtools/client/netmonitor/src/components/request-details/CachePanel.js b/devtools/client/netmonitor/src/components/request-details/CachePanel.js
new file mode 100644
index 0000000000..5f3db6c501
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/CachePanel.js
@@ -0,0 +1,144 @@
+/* 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 dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+// Components
+const TreeViewClass = require("resource://devtools/client/shared/components/tree/TreeView.js");
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+
+const { div, input } = dom;
+
+const CACHE = L10N.getStr("netmonitor.cache.cache");
+const DATA_SIZE = L10N.getStr("netmonitor.cache.dataSize");
+const EXPIRES = L10N.getStr("netmonitor.cache.expires");
+const FETCH_COUNT = L10N.getStr("netmonitor.cache.fetchCount");
+const LAST_FETCHED = L10N.getStr("netmonitor.cache.lastFetched");
+const LAST_MODIFIED = L10N.getStr("netmonitor.cache.lastModified");
+const DEVICE = L10N.getStr("netmonitor.cache.device");
+const NOT_AVAILABLE = L10N.getStr("netmonitor.cache.notAvailable");
+const EMPTY = L10N.getStr("netmonitor.cache.empty");
+
+/**
+ * Cache panel component
+ * This tab lists full details of any cache information of the response.
+ */
+class CachePanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ request: PropTypes.object.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { connector, request } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["responseCache"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { connector, request } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["responseCache"]);
+ }
+
+ renderSummary(label, value) {
+ return div(
+ { className: "tabpanel-summary-container cache-summary" },
+ div(
+ {
+ className: "tabpanel-summary-label cache-summary-label",
+ },
+ label + ":"
+ ),
+ input({
+ className: "tabpanel-summary-value textbox-input devtools-monospace",
+ readOnly: true,
+ value,
+ })
+ );
+ }
+
+ getProperties(responseCache) {
+ let responseCacheObj;
+ let cacheObj;
+ try {
+ responseCacheObj = Object.assign({}, responseCache);
+ responseCacheObj = responseCacheObj.cache;
+ } catch (e) {
+ return null;
+ }
+ try {
+ cacheObj = Object.assign({}, responseCacheObj);
+ } catch (e) {
+ return null;
+ }
+ return cacheObj;
+ }
+
+ getDate(timestamp) {
+ if (!timestamp) {
+ return null;
+ }
+ const d = new Date(parseInt(timestamp, 10) * 1000);
+ return d.toLocaleDateString() + " " + d.toLocaleTimeString();
+ }
+
+ render() {
+ const { request } = this.props;
+ const { responseCache } = request;
+
+ let object;
+ const cache = this.getProperties(responseCache);
+
+ if (
+ cache.lastFetched ||
+ cache.fetchCount ||
+ cache.storageDataSize ||
+ cache.lastModified ||
+ cache.expirationTime ||
+ cache.deviceID
+ ) {
+ object = {
+ [CACHE]: {
+ [LAST_FETCHED]: this.getDate(cache.lastFetched) || NOT_AVAILABLE,
+ [FETCH_COUNT]: cache.fetchCount || NOT_AVAILABLE,
+ [DATA_SIZE]: cache.storageDataSize || NOT_AVAILABLE,
+ [LAST_MODIFIED]: this.getDate(cache.lastModified) || NOT_AVAILABLE,
+ [EXPIRES]: this.getDate(cache.expirationTime) || NOT_AVAILABLE,
+ [DEVICE]: cache.deviceID || NOT_AVAILABLE,
+ },
+ };
+ } else {
+ return div({ className: "empty-notice" }, EMPTY);
+ }
+
+ return div(
+ { className: "panel-container security-panel" },
+ PropertiesView({
+ object,
+ enableFilter: false,
+ expandedNodes: TreeViewClass.getExpandedNodes(object),
+ })
+ );
+ }
+}
+
+module.exports = CachePanel;
diff --git a/devtools/client/netmonitor/src/components/request-details/CookiesPanel.js b/devtools/client/netmonitor/src/components/request-details/CookiesPanel.js
new file mode 100644
index 0000000000..466c0379cd
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/CookiesPanel.js
@@ -0,0 +1,225 @@
+/* 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 dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ sortObjectKeys,
+} = require("resource://devtools/client/netmonitor/src/utils/sort-utils.js");
+const {
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Component
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+const Accordion = createFactory(
+ require("resource://devtools/client/shared/components/Accordion.js")
+);
+
+loader.lazyGetter(this, "TreeRow", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/tree/TreeRow.js")
+ );
+});
+
+const { div } = dom;
+
+const COOKIES_EMPTY_TEXT = L10N.getStr("cookiesEmptyText");
+const COOKIES_FILTER_TEXT = L10N.getStr("cookiesFilterText");
+const REQUEST_COOKIES = L10N.getStr("requestCookies");
+const RESPONSE_COOKIES = L10N.getStr("responseCookies");
+
+/*
+ * Cookies panel component
+ * This tab lists full details of any cookies sent with the request or response
+ */
+class CookiesPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ request: PropTypes.object.isRequired,
+ targetSearchResult: PropTypes.object,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.state = {
+ filterText: "",
+ };
+ }
+
+ componentDidMount() {
+ const { connector, request } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestCookies",
+ "responseCookies",
+ ]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { connector, request } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestCookies",
+ "responseCookies",
+ ]);
+ }
+
+ /**
+ * Mapping array to dict for TreeView usage.
+ * Since TreeView only support Object(dict) format.
+ *
+ * @param {Object[]} arr - key-value pair array like cookies or params
+ * @returns {Object}
+ */
+ getProperties(arr, title) {
+ const cookies = arr.reduce((map, obj) => {
+ // Generally cookies object contains only name and value properties and can
+ // be rendered as name: value pair.
+ // When there are more properties in cookies object such as extra or path,
+ // We will pass the object to display these extra information
+ if (Object.keys(obj).length > 2) {
+ map[obj.name] = Object.assign({}, obj);
+ delete map[obj.name].name;
+ } else {
+ map[obj.name] = obj.value;
+ }
+ return map;
+ }, Object.create(null));
+
+ // To have different roots for Request and Response cookies
+ return { [title]: cookies };
+ }
+
+ /**
+ * Custom rendering method passed to PropertiesView. It's
+ * responsible to filter out level 0 node in the tree
+ *
+ * @param {Object} props
+ */
+ renderRow(props) {
+ const { level } = props.member;
+
+ if (level === 0) {
+ return null;
+ }
+
+ return TreeRow(props);
+ }
+
+ /**
+ * Get the selected cookies path
+ * @param {Object} searchResult
+ * @returns {string}
+ */
+ getTargetCookiePath(searchResult) {
+ if (!searchResult) {
+ return null;
+ }
+
+ switch (searchResult.type) {
+ case "requestCookies": {
+ return `/${REQUEST_COOKIES}/${searchResult.label}`;
+ }
+ case "responseCookies":
+ return `/${RESPONSE_COOKIES}/${searchResult.label}`;
+ }
+
+ return null;
+ }
+
+ render() {
+ let {
+ request: {
+ requestCookies = { cookies: [] },
+ responseCookies = { cookies: [] },
+ },
+ targetSearchResult,
+ } = this.props;
+
+ const { filterText } = this.state;
+
+ requestCookies = requestCookies.cookies || requestCookies;
+ responseCookies = responseCookies.cookies || responseCookies;
+
+ if (!requestCookies.length && !responseCookies.length) {
+ return div({ className: "empty-notice" }, COOKIES_EMPTY_TEXT);
+ }
+
+ const items = [];
+
+ if (responseCookies.length) {
+ items.push({
+ component: PropertiesView,
+ componentProps: {
+ object: sortObjectKeys(
+ this.getProperties(responseCookies, RESPONSE_COOKIES)
+ ),
+ filterText,
+ targetSearchResult,
+ defaultSelectFirstNode: false,
+ selectPath: this.getTargetCookiePath,
+ renderRow: this.renderRow,
+ },
+ header: RESPONSE_COOKIES,
+ id: "responseCookies",
+ opened: true,
+ });
+ }
+
+ if (requestCookies.length) {
+ items.push({
+ component: PropertiesView,
+ componentProps: {
+ object: sortObjectKeys(
+ this.getProperties(requestCookies, REQUEST_COOKIES)
+ ),
+ filterText,
+ targetSearchResult,
+ defaultSelectFirstNode: false,
+ selectPath: this.getTargetCookiePath,
+ renderRow: this.renderRow,
+ },
+ header: REQUEST_COOKIES,
+ id: "requestCookies",
+ opened: true,
+ });
+ }
+
+ return div(
+ { className: "panel-container cookies-panel-container" },
+ div(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ type: "filter",
+ onChange: text => this.setState({ filterText: text }),
+ placeholder: COOKIES_FILTER_TEXT,
+ })
+ ),
+ Accordion({ items })
+ );
+ }
+}
+
+module.exports = CookiesPanel;
diff --git a/devtools/client/netmonitor/src/components/request-details/HeadersPanel.js b/devtools/client/netmonitor/src/components/request-details/HeadersPanel.js
new file mode 100644
index 0000000000..80b9aed27d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/HeadersPanel.js
@@ -0,0 +1,850 @@
+/* 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 Actions = require("resource://devtools/client/netmonitor/src/actions/index.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 {
+ getFormattedIPAndPort,
+ getFormattedSize,
+ getRequestPriorityAsText,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getHeadersURL,
+ getTrackingProtectionURL,
+ getHTTPStatusCodeURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+const {
+ fetchNetworkUpdatePacket,
+ writeHeaderText,
+ getRequestHeadersRawText,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ HeadersProvider,
+ HeaderList,
+} = require("resource://devtools/client/netmonitor/src/utils/headers-provider.js");
+const {
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+// Components
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+const Accordion = createFactory(
+ require("resource://devtools/client/shared/components/Accordion.js")
+);
+const UrlPreview = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/UrlPreview.js")
+);
+const HeadersPanelContextMenu = require("resource://devtools/client/netmonitor/src/widgets/HeadersPanelContextMenu.js");
+const StatusCode = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/StatusCode.js")
+);
+
+loader.lazyGetter(this, "MDNLink", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/MdnLink.js")
+ );
+});
+loader.lazyGetter(this, "Rep", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .REPS.Rep;
+});
+loader.lazyGetter(this, "MODE", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .MODE;
+});
+loader.lazyGetter(this, "TreeRow", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/tree/TreeRow.js")
+ );
+});
+loader.lazyRequireGetter(
+ this,
+ "showMenu",
+ "resource://devtools/client/shared/components/menu/utils.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "openContentLink",
+ "resource://devtools/client/shared/link.js",
+ true
+);
+
+const { div, input, label, span, textarea, tr, td, button } = dom;
+
+const RESEND = L10N.getStr("netmonitor.context.resend.label");
+const EDIT_AND_RESEND = L10N.getStr("netmonitor.summary.editAndResend");
+const RAW_HEADERS = L10N.getStr("netmonitor.headers.raw");
+const HEADERS_EMPTY_TEXT = L10N.getStr("headersEmptyText");
+const HEADERS_FILTER_TEXT = L10N.getStr("headersFilterText");
+const REQUEST_HEADERS = L10N.getStr("requestHeaders");
+const REQUEST_HEADERS_FROM_UPLOAD = L10N.getStr("requestHeadersFromUpload");
+const RESPONSE_HEADERS = L10N.getStr("responseHeaders");
+const HEADERS_STATUS = L10N.getStr("netmonitor.headers.status");
+const HEADERS_VERSION = L10N.getStr("netmonitor.headers.version");
+const HEADERS_TRANSFERRED = L10N.getStr("netmonitor.toolbar.transferred");
+const SUMMARY_STATUS_LEARN_MORE = L10N.getStr("netmonitor.summary.learnMore");
+const SUMMARY_ETP_LEARN_MORE = L10N.getStr(
+ "netmonitor.enhancedTrackingProtection.learnMore"
+);
+const HEADERS_REFERRER = L10N.getStr("netmonitor.headers.referrerPolicy");
+const HEADERS_CONTENT_BLOCKING = L10N.getStr(
+ "netmonitor.headers.contentBlocking"
+);
+const HEADERS_ETP = L10N.getStr(
+ "netmonitor.trackingResource.enhancedTrackingProtection"
+);
+const HEADERS_PRIORITY = L10N.getStr("netmonitor.headers.requestPriority");
+
+/**
+ * Headers panel component
+ * Lists basic information about the request
+ *
+ * In http/2 all response headers are in small case.
+ * See: https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/request_details/index.html#response-headers
+ * RFC: https://tools.ietf.org/html/rfc7540#section-8.1.2
+ */
+class HeadersPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ cloneSelectedRequest: PropTypes.func.isRequired,
+ member: PropTypes.object,
+ request: PropTypes.object.isRequired,
+ renderValue: PropTypes.func,
+ openLink: PropTypes.func,
+ targetSearchResult: PropTypes.object,
+ openRequestBlockingAndAddUrl: PropTypes.func.isRequired,
+ openHTTPCustomRequestTab: PropTypes.func.isRequired,
+ cloneRequest: PropTypes.func,
+ sendCustomRequest: PropTypes.func,
+ shouldExpandPreview: PropTypes.bool,
+ setHeadersUrlPreviewExpanded: PropTypes.func,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ rawRequestHeadersOpened: false,
+ rawResponseHeadersOpened: false,
+ rawUploadHeadersOpened: false,
+ lastToggledRawHeader: "",
+ filterText: null,
+ };
+
+ this.getProperties = this.getProperties.bind(this);
+ this.getTargetHeaderPath = this.getTargetHeaderPath.bind(this);
+ this.toggleRawResponseHeaders = this.toggleRawResponseHeaders.bind(this);
+ this.toggleRawRequestHeaders = this.toggleRawRequestHeaders.bind(this);
+ this.toggleRawUploadHeaders = this.toggleRawUploadHeaders.bind(this);
+ this.renderSummary = this.renderSummary.bind(this);
+ this.renderRow = this.renderRow.bind(this);
+ this.renderValue = this.renderValue.bind(this);
+ this.renderRawHeadersBtn = this.renderRawHeadersBtn.bind(this);
+ this.onShowResendMenu = this.onShowResendMenu.bind(this);
+ this.onShowHeadersContextMenu = this.onShowHeadersContextMenu.bind(this);
+ }
+
+ componentDidMount() {
+ const { request, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestHeaders",
+ "responseHeaders",
+ "requestPostData",
+ ]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestHeaders",
+ "responseHeaders",
+ "requestPostData",
+ ]);
+ }
+
+ getHeadersTitle(headers, title) {
+ let result = "";
+ let preHeaderText = "";
+ const {
+ responseHeaders,
+ requestHeaders,
+ httpVersion,
+ status,
+ statusText,
+ method,
+ urlDetails,
+ } = this.props.request;
+ if (headers?.headers.length) {
+ if (!headers.headersSize) {
+ if (title == RESPONSE_HEADERS) {
+ preHeaderText = `${httpVersion} ${status} ${statusText}`;
+ result = `${title} (${getFormattedSize(
+ writeHeaderText(responseHeaders.headers, preHeaderText).length,
+ 3
+ )})`;
+ } else {
+ const hostHeader = requestHeaders.headers.find(
+ ele => ele.name === "Host"
+ );
+ if (hostHeader) {
+ preHeaderText = `${method} ${
+ urlDetails.url.split(hostHeader.value)[1]
+ } ${httpVersion}`;
+ }
+ result = `${title} (${getFormattedSize(
+ writeHeaderText(requestHeaders.headers, preHeaderText).length,
+ 3
+ )})`;
+ }
+ } else {
+ result = `${title} (${getFormattedSize(headers.headersSize, 3)})`;
+ }
+ }
+
+ return result;
+ }
+
+ getProperties(headers, title) {
+ let propertiesResult;
+
+ if (headers?.headers.length) {
+ const headerKey = this.getHeadersTitle(headers, title);
+ propertiesResult = {
+ [headerKey]: new HeaderList(headers.headers),
+ };
+ if (
+ (title === RESPONSE_HEADERS && this.state.rawResponseHeadersOpened) ||
+ (title === REQUEST_HEADERS && this.state.rawRequestHeadersOpened) ||
+ (title === REQUEST_HEADERS_FROM_UPLOAD &&
+ this.state.rawUploadHeadersOpened)
+ ) {
+ propertiesResult = {
+ [headerKey]: { RAW_HEADERS_ID: headers.rawHeaders },
+ };
+ }
+ }
+ return propertiesResult;
+ }
+
+ toggleRawResponseHeaders() {
+ this.setState({
+ rawResponseHeadersOpened: !this.state.rawResponseHeadersOpened,
+ lastToggledRawHeader: "response",
+ });
+ }
+
+ toggleRawRequestHeaders() {
+ this.setState({
+ rawRequestHeadersOpened: !this.state.rawRequestHeadersOpened,
+ lastToggledRawHeader: "request",
+ });
+ }
+
+ toggleRawUploadHeaders() {
+ this.setState({
+ rawUploadHeadersOpened: !this.state.rawUploadHeadersOpened,
+ lastToggledRawHeader: "upload",
+ });
+ }
+
+ /**
+ * Helper method to identify what kind of raw header this is.
+ * Information is in the path variable
+ */
+ getRawHeaderType(path) {
+ if (path.includes(RESPONSE_HEADERS)) {
+ return "RESPONSE";
+ }
+ if (path.includes(REQUEST_HEADERS_FROM_UPLOAD)) {
+ return "UPLOAD";
+ }
+ return "REQUEST";
+ }
+
+ /**
+ * Renders the top part of the headers detail panel - Summary.
+ */
+ renderSummary(summaryLabel, value) {
+ return div(
+ {
+ key: summaryLabel,
+ className: "tabpanel-summary-container headers-summary",
+ },
+ span(
+ { className: "tabpanel-summary-label headers-summary-label" },
+ summaryLabel
+ ),
+ span({ className: "tabpanel-summary-value" }, value)
+ );
+ }
+
+ /**
+ * Get path for target header if it's set. It's used to select
+ * the header automatically within the tree of headers.
+ * Note that the target header is set by the Search panel.
+ */
+ getTargetHeaderPath(searchResult) {
+ if (!searchResult) {
+ return null;
+ }
+ if (
+ searchResult.type !== "requestHeaders" &&
+ searchResult.type !== "responseHeaders" &&
+ searchResult.type !== "requestHeadersFromUploadStream"
+ ) {
+ return null;
+ }
+ const {
+ request: {
+ requestHeaders,
+ requestHeadersFromUploadStream: uploadHeaders,
+ responseHeaders,
+ },
+ } = this.props;
+ // Using `HeaderList` ensures that we'll get the same
+ // header index as it's used in the tree.
+ const getPath = (headers, title) => {
+ return (
+ "/" +
+ this.getHeadersTitle(headers, title) +
+ "/" +
+ new HeaderList(headers.headers).headers.findIndex(
+ header => header.name == searchResult.label
+ )
+ );
+ };
+ // Calculate target header path according to the header type.
+ switch (searchResult.type) {
+ case "requestHeaders":
+ return getPath(requestHeaders, REQUEST_HEADERS);
+ case "responseHeaders":
+ return getPath(responseHeaders, RESPONSE_HEADERS);
+ case "requestHeadersFromUploadStream":
+ return getPath(uploadHeaders, REQUEST_HEADERS_FROM_UPLOAD);
+ }
+ return null;
+ }
+
+ /**
+ * Custom rendering method passed to PropertiesView. It's responsible
+ * for rendering <textarea> element with raw headers data.
+ */
+ renderRow(props) {
+ const { level, path } = props.member;
+
+ const {
+ request: {
+ method,
+ httpVersion,
+ requestHeaders,
+ requestHeadersFromUploadStream: uploadHeaders,
+ responseHeaders,
+ status,
+ statusText,
+ urlDetails,
+ },
+ } = this.props;
+
+ let value;
+ let preHeaderText = "";
+ if (path.includes("RAW_HEADERS_ID")) {
+ const rawHeaderType = this.getRawHeaderType(path);
+ switch (rawHeaderType) {
+ case "REQUEST":
+ value = getRequestHeadersRawText(
+ method,
+ httpVersion,
+ requestHeaders,
+ urlDetails
+ );
+ break;
+ case "RESPONSE":
+ preHeaderText = `${httpVersion} ${status} ${statusText}`;
+ value = writeHeaderText(
+ responseHeaders.headers,
+ preHeaderText
+ ).trim();
+ break;
+ case "UPLOAD":
+ value = writeHeaderText(uploadHeaders.headers, preHeaderText).trim();
+ break;
+ }
+
+ let rows;
+ if (value) {
+ const match = value.match(/\n/g);
+ rows = match !== null ? match.length : 0;
+ // Need to add 1 for the horizontal scrollbar
+ // not to cover the last row of raw data
+ rows = rows + 1;
+ }
+
+ return tr(
+ {
+ key: path,
+ role: "treeitem",
+ className: "raw-headers-container",
+ onClick: event => {
+ event.stopPropagation();
+ },
+ },
+ td(
+ {
+ colSpan: 2,
+ },
+ textarea({
+ className: "raw-headers",
+ rows,
+ value,
+ readOnly: true,
+ })
+ )
+ );
+ }
+
+ if (level !== 1) {
+ return null;
+ }
+
+ return TreeRow(props);
+ }
+
+ renderRawHeadersBtn(key, checked, onChange) {
+ return [
+ label(
+ {
+ key: `${key}RawHeadersBtn`,
+ className: "raw-headers-toggle",
+ htmlFor: `raw-${key}-checkbox`,
+ onClick: event => {
+ // stop the header click event
+ event.stopPropagation();
+ },
+ },
+ span({ className: "headers-summary-label" }, RAW_HEADERS),
+ span(
+ { className: "raw-headers-toggle-input" },
+ input({
+ id: `raw-${key}-checkbox`,
+ checked,
+ className: "devtools-checkbox-toggle",
+ onChange,
+ type: "checkbox",
+ })
+ )
+ ),
+ ];
+ }
+
+ renderValue(props) {
+ const { member, value } = props;
+
+ if (typeof value !== "string") {
+ return null;
+ }
+
+ const headerDocURL = getHeadersURL(member.name);
+
+ return div(
+ { className: "treeValueCellDivider" },
+ Rep(
+ Object.assign(props, {
+ // FIXME: A workaround for the issue in StringRep
+ // Force StringRep to crop the text everytime
+ member: Object.assign({}, member, { open: false }),
+ mode: MODE.TINY,
+ noGrip: true,
+ openLink: openContentLink,
+ })
+ ),
+ headerDocURL ? MDNLink({ url: headerDocURL }) : null
+ );
+ }
+
+ getShouldOpen(rawHeader, filterText, targetSearchResult) {
+ return (item, opened) => {
+ // If closed, open panel for these reasons
+ // 1.The raw header is switched on or off
+ // 2.The filter text is set
+ // 3.The search text is set
+ if (
+ (!opened && this.state.lastToggledRawHeader === rawHeader) ||
+ (!opened && filterText) ||
+ (!opened && targetSearchResult)
+ ) {
+ return true;
+ }
+ return !!opened;
+ };
+ }
+
+ onShowResendMenu(event) {
+ const {
+ request: { id },
+ cloneSelectedRequest,
+ cloneRequest,
+ sendCustomRequest,
+ } = this.props;
+ const menuItems = [
+ {
+ label: RESEND,
+ type: "button",
+ click: () => {
+ cloneRequest(id);
+ sendCustomRequest();
+ },
+ },
+ {
+ label: EDIT_AND_RESEND,
+ type: "button",
+ click: evt => {
+ cloneSelectedRequest(evt);
+ },
+ },
+ ];
+
+ showMenu(menuItems, { button: event.target });
+ }
+
+ onShowHeadersContextMenu(event) {
+ if (!this.contextMenu) {
+ this.contextMenu = new HeadersPanelContextMenu();
+ }
+ this.contextMenu.open(event, window.getSelection());
+ }
+
+ render() {
+ const {
+ targetSearchResult,
+ request: {
+ fromCache,
+ fromServiceWorker,
+ httpVersion,
+ method,
+ remoteAddress,
+ remotePort,
+ requestHeaders,
+ requestHeadersFromUploadStream: uploadHeaders,
+ responseHeaders,
+ status,
+ statusText,
+ urlDetails,
+ referrerPolicy,
+ priority,
+ isThirdPartyTrackingResource,
+ contentSize,
+ transferredSize,
+ },
+ openRequestBlockingAndAddUrl,
+ openHTTPCustomRequestTab,
+ shouldExpandPreview,
+ setHeadersUrlPreviewExpanded,
+ } = this.props;
+ const {
+ rawResponseHeadersOpened,
+ rawRequestHeadersOpened,
+ rawUploadHeadersOpened,
+ filterText,
+ } = this.state;
+
+ if (
+ (!requestHeaders || !requestHeaders.headers.length) &&
+ (!uploadHeaders || !uploadHeaders.headers.length) &&
+ (!responseHeaders || !responseHeaders.headers.length)
+ ) {
+ return div({ className: "empty-notice" }, HEADERS_EMPTY_TEXT);
+ }
+
+ const items = [];
+
+ if (responseHeaders?.headers.length) {
+ items.push({
+ component: PropertiesView,
+ componentProps: {
+ object: this.getProperties(responseHeaders, RESPONSE_HEADERS),
+ filterText,
+ targetSearchResult,
+ renderRow: this.renderRow,
+ renderValue: this.renderValue,
+ provider: HeadersProvider,
+ selectPath: this.getTargetHeaderPath,
+ defaultSelectFirstNode: false,
+ enableInput: false,
+ useQuotes: false,
+ },
+ header: this.getHeadersTitle(responseHeaders, RESPONSE_HEADERS),
+ buttons: this.renderRawHeadersBtn(
+ "response",
+ rawResponseHeadersOpened,
+ this.toggleRawResponseHeaders
+ ),
+ id: "responseHeaders",
+ opened: true,
+ shouldOpen: this.getShouldOpen(
+ "response",
+ filterText,
+ targetSearchResult
+ ),
+ });
+ }
+
+ if (requestHeaders?.headers.length) {
+ items.push({
+ component: PropertiesView,
+ componentProps: {
+ object: this.getProperties(requestHeaders, REQUEST_HEADERS),
+ filterText,
+ targetSearchResult,
+ renderRow: this.renderRow,
+ renderValue: this.renderValue,
+ provider: HeadersProvider,
+ selectPath: this.getTargetHeaderPath,
+ defaultSelectFirstNode: false,
+ enableInput: false,
+ useQuotes: false,
+ },
+ header: this.getHeadersTitle(requestHeaders, REQUEST_HEADERS),
+ buttons: this.renderRawHeadersBtn(
+ "request",
+ rawRequestHeadersOpened,
+ this.toggleRawRequestHeaders
+ ),
+ id: "requestHeaders",
+ opened: true,
+ shouldOpen: this.getShouldOpen(
+ "request",
+ filterText,
+ targetSearchResult
+ ),
+ });
+ }
+
+ if (uploadHeaders?.headers.length) {
+ items.push({
+ component: PropertiesView,
+ componentProps: {
+ object: this.getProperties(
+ uploadHeaders,
+ REQUEST_HEADERS_FROM_UPLOAD
+ ),
+ filterText,
+ targetSearchResult,
+ renderRow: this.renderRow,
+ renderValue: this.renderValue,
+ provider: HeadersProvider,
+ selectPath: this.getTargetHeaderPath,
+ defaultSelectFirstNode: false,
+ enableInput: false,
+ useQuotes: false,
+ },
+ header: this.getHeadersTitle(
+ uploadHeaders,
+ REQUEST_HEADERS_FROM_UPLOAD
+ ),
+ buttons: this.renderRawHeadersBtn(
+ "upload",
+ rawUploadHeadersOpened,
+ this.toggleRawUploadHeaders
+ ),
+ id: "uploadHeaders",
+ opened: true,
+ shouldOpen: this.getShouldOpen(
+ "upload",
+ filterText,
+ targetSearchResult
+ ),
+ });
+ }
+
+ const sizeText = L10N.getFormatStrWithNumbers(
+ "netmonitor.headers.sizeDetails",
+ getFormattedSize(transferredSize),
+ getFormattedSize(contentSize)
+ );
+
+ const summarySize = this.renderSummary(HEADERS_TRANSFERRED, sizeText);
+
+ let summaryStatus;
+ if (status) {
+ summaryStatus = div(
+ {
+ key: "headers-summary",
+ className: "tabpanel-summary-container headers-summary",
+ },
+ span(
+ {
+ className: "tabpanel-summary-label headers-summary-label",
+ },
+ HEADERS_STATUS
+ ),
+ span(
+ {
+ className: "tabpanel-summary-value status",
+ "data-code": status,
+ },
+ StatusCode({
+ item: { fromCache, fromServiceWorker, status, statusText },
+ }),
+ statusText,
+ MDNLink({
+ url: getHTTPStatusCodeURL(status),
+ title: SUMMARY_STATUS_LEARN_MORE,
+ })
+ )
+ );
+ }
+
+ let trackingProtectionStatus;
+ let trackingProtectionDetails = "";
+ if (isThirdPartyTrackingResource) {
+ const trackingProtectionDocURL = getTrackingProtectionURL();
+
+ trackingProtectionStatus = this.renderSummary(
+ HEADERS_CONTENT_BLOCKING,
+ div(null, span({ className: "tracking-resource" }), HEADERS_ETP)
+ );
+ trackingProtectionDetails = this.renderSummary(
+ "",
+ div(
+ {
+ key: "tracking-protection",
+ className: "tracking-protection",
+ },
+ L10N.getStr("netmonitor.trackingResource.tooltip"),
+ trackingProtectionDocURL
+ ? MDNLink({
+ url: trackingProtectionDocURL,
+ title: SUMMARY_ETP_LEARN_MORE,
+ })
+ : span({ className: "headers-summary learn-more-link" })
+ )
+ );
+ }
+
+ const summaryVersion = httpVersion
+ ? this.renderSummary(HEADERS_VERSION, httpVersion)
+ : null;
+
+ const summaryReferrerPolicy = referrerPolicy
+ ? this.renderSummary(HEADERS_REFERRER, referrerPolicy)
+ : null;
+
+ const summaryPriority = priority
+ ? this.renderSummary(HEADERS_PRIORITY, getRequestPriorityAsText(priority))
+ : null;
+
+ const summaryItems = [
+ summaryStatus,
+ summaryVersion,
+ summarySize,
+ summaryReferrerPolicy,
+ summaryPriority,
+ trackingProtectionStatus,
+ trackingProtectionDetails,
+ ].filter(summaryItem => summaryItem !== null);
+
+ const newEditAndResendPref = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend"
+ );
+
+ return div(
+ { className: "headers-panel-container" },
+ div(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ type: "filter",
+ onChange: text => this.setState({ filterText: text }),
+ placeholder: HEADERS_FILTER_TEXT,
+ }),
+ span({ className: "devtools-separator" }),
+ button(
+ {
+ id: "block-button",
+ className: "devtools-button",
+ title: L10N.getStr("netmonitor.context.blockURL"),
+ onClick: () => openRequestBlockingAndAddUrl(urlDetails.url),
+ },
+ L10N.getStr("netmonitor.headers.toolbar.block")
+ ),
+ span({ className: "devtools-separator" }),
+ button(
+ {
+ id: "edit-resend-button",
+ className: !newEditAndResendPref
+ ? "devtools-button devtools-dropdown-button"
+ : "devtools-button",
+ title: RESEND,
+ onClick: !newEditAndResendPref
+ ? this.onShowResendMenu
+ : () => {
+ openHTTPCustomRequestTab();
+ },
+ },
+ span({ className: "title" }, RESEND)
+ )
+ ),
+ div(
+ { className: "panel-container" },
+ div(
+ { className: "headers-overview" },
+ UrlPreview({
+ url: urlDetails.url,
+ method,
+ address: remoteAddress
+ ? getFormattedIPAndPort(remoteAddress, remotePort)
+ : null,
+ shouldExpandPreview,
+ onTogglePreview: expanded => setHeadersUrlPreviewExpanded(expanded),
+ }),
+ div(
+ {
+ className: "summary",
+ onContextMenu: this.onShowHeadersContextMenu,
+ },
+ summaryItems
+ )
+ ),
+ Accordion({ items })
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ shouldExpandPreview: state.ui.shouldExpandHeadersUrlPreview,
+ }),
+ (dispatch, props) => ({
+ setHeadersUrlPreviewExpanded: expanded =>
+ dispatch(Actions.setHeadersUrlPreviewExpanded(expanded)),
+ openRequestBlockingAndAddUrl: url =>
+ dispatch(Actions.openRequestBlockingAndAddUrl(url)),
+ openHTTPCustomRequestTab: () =>
+ dispatch(Actions.openHTTPCustomRequest(true)),
+ cloneRequest: id => dispatch(Actions.cloneRequest(id)),
+ sendCustomRequest: () => dispatch(Actions.sendCustomRequest()),
+ })
+)(HeadersPanel);
diff --git a/devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js b/devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js
new file mode 100644
index 0000000000..8092eedc87
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js
@@ -0,0 +1,106 @@
+/* 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 {
+ createFactory,
+} = 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 Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ getSelectedRequest,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+// Components
+loader.lazyGetter(this, "CustomRequestPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/CustomRequestPanel.js")
+ );
+});
+loader.lazyGetter(this, "TabboxPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/TabboxPanel.js")
+ );
+});
+
+const { div } = dom;
+
+/**
+ * Network details panel component
+ */
+function NetworkDetailsBar({
+ connector,
+ activeTabId,
+ cloneSelectedRequest,
+ request,
+ selectTab,
+ sourceMapURLService,
+ toggleNetworkDetails,
+ openNetworkDetails,
+ openLink,
+ targetSearchResult,
+}) {
+ if (!request) {
+ return null;
+ }
+
+ const newEditAndResendPref = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend"
+ );
+
+ return div(
+ { className: "network-details-bar" },
+ request.isCustom && !newEditAndResendPref
+ ? CustomRequestPanel({
+ connector,
+ request,
+ })
+ : TabboxPanel({
+ activeTabId,
+ cloneSelectedRequest,
+ connector,
+ openLink,
+ request,
+ selectTab,
+ sourceMapURLService,
+ toggleNetworkDetails,
+ openNetworkDetails,
+ targetSearchResult,
+ })
+ );
+}
+
+NetworkDetailsBar.displayName = "NetworkDetailsBar";
+
+NetworkDetailsBar.propTypes = {
+ connector: PropTypes.object.isRequired,
+ activeTabId: PropTypes.string,
+ cloneSelectedRequest: PropTypes.func.isRequired,
+ open: PropTypes.bool,
+ request: PropTypes.object,
+ selectTab: PropTypes.func.isRequired,
+ sourceMapURLService: PropTypes.object,
+ toggleNetworkDetails: PropTypes.func.isRequired,
+ openLink: PropTypes.func,
+ targetSearchResult: PropTypes.object,
+};
+
+module.exports = connect(
+ state => ({
+ activeTabId: state.ui.detailsPanelSelectedTab,
+ request: getSelectedRequest(state),
+ targetSearchResult: state.search.targetSearchResult,
+ }),
+ dispatch => ({
+ cloneSelectedRequest: () => dispatch(Actions.cloneSelectedRequest()),
+ selectTab: tabId => dispatch(Actions.selectDetailsPanelTab(tabId)),
+ toggleNetworkDetails: () => dispatch(Actions.toggleNetworkDetails()),
+ openNetworkDetails: open => dispatch(Actions.openNetworkDetails(open)),
+ })
+)(NetworkDetailsBar);
diff --git a/devtools/client/netmonitor/src/components/request-details/PropertiesView.js b/devtools/client/netmonitor/src/components/request-details/PropertiesView.js
new file mode 100644
index 0000000000..759653c1aa
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/PropertiesView.js
@@ -0,0 +1,247 @@
+/* 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/. */
+
+/* eslint-disable react/prop-types */
+
+"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");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ setTargetSearchResult,
+} = require("resource://devtools/client/netmonitor/src/actions/search.js");
+
+// Components
+const TreeViewClass = require("resource://devtools/client/shared/components/tree/TreeView.js");
+const TreeView = createFactory(TreeViewClass);
+const PropertiesViewContextMenu = require("resource://devtools/client/netmonitor/src/widgets/PropertiesViewContextMenu.js");
+
+loader.lazyGetter(this, "Rep", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .REPS.Rep;
+});
+loader.lazyGetter(this, "MODE", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .MODE;
+});
+
+// Constants
+const {
+ AUTO_EXPAND_MAX_LEVEL,
+ AUTO_EXPAND_MAX_NODES,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const { div } = dom;
+
+/**
+ * Properties View component
+ * A scrollable tree view component which provides some useful features for
+ * representing object properties.
+ *
+ * Tree view
+ * Rep
+ */
+class PropertiesView extends Component {
+ static get propTypes() {
+ return {
+ object: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
+ provider: PropTypes.object,
+ enableInput: PropTypes.bool,
+ expandableStrings: PropTypes.bool,
+ expandedNodes: PropTypes.object,
+ useBaseTreeViewExpand: PropTypes.bool,
+ filterText: PropTypes.string,
+ cropLimit: PropTypes.number,
+ targetSearchResult: PropTypes.object,
+ resetTargetSearchResult: PropTypes.func,
+ selectPath: PropTypes.func,
+ mode: PropTypes.symbol,
+ defaultSelectFirstNode: PropTypes.bool,
+ useQuotes: PropTypes.bool,
+ onClickRow: PropTypes.func,
+ contextMenuFormatters: PropTypes.object,
+ };
+ }
+
+ static get defaultProps() {
+ return {
+ enableInput: true,
+ enableFilter: true,
+ expandableStrings: false,
+ cropLimit: 1024,
+ useQuotes: true,
+ contextMenuFormatters: {},
+ useBaseTreeViewExpand: false,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.onFilter = this.onFilter.bind(this);
+ this.renderValueWithRep = this.renderValueWithRep.bind(this);
+ this.getSelectedPath = this.getSelectedPath.bind(this);
+ }
+
+ /**
+ * Update only if:
+ * 1) The rendered object has changed
+ * 2) The filter text has changed
+ * 3) The user selected another search result target.
+ */
+ shouldComponentUpdate(nextProps) {
+ return (
+ this.props.object !== nextProps.object ||
+ this.props.filterText !== nextProps.filterText ||
+ (this.props.targetSearchResult !== nextProps.targetSearchResult &&
+ nextProps.targetSearchResult !== null)
+ );
+ }
+
+ onFilter(props) {
+ const { name, value } = props;
+ const { filterText } = this.props;
+
+ if (!filterText) {
+ return true;
+ }
+
+ const jsonString = JSON.stringify({ [name]: value }).toLowerCase();
+ return jsonString.includes(filterText.toLowerCase());
+ }
+
+ getSelectedPath(targetSearchResult) {
+ if (!targetSearchResult) {
+ return null;
+ }
+
+ return `/${targetSearchResult.label}`;
+ }
+
+ /**
+ * If target is selected, let's scroll the content
+ * so the property is visible. This is used for search result navigation,
+ * which happens when the user clicks on a search result.
+ */
+ scrollSelectedIntoView() {
+ const { targetSearchResult, resetTargetSearchResult, selectPath } =
+ this.props;
+ if (!targetSearchResult) {
+ return;
+ }
+
+ const path =
+ typeof selectPath == "function"
+ ? selectPath(targetSearchResult)
+ : this.getSelectedPath(targetSearchResult);
+ const element = document.getElementById(path);
+ if (element) {
+ element.scrollIntoView({ block: "center" });
+ }
+
+ resetTargetSearchResult();
+ }
+
+ onContextMenuRow(member, evt) {
+ evt.preventDefault();
+
+ const { object } = member;
+
+ // Select the right clicked row
+ this.selectRow({ props: { member } });
+
+ // if data exists and can be copied, then show the contextmenu
+ if (typeof object === "object") {
+ if (!this.contextMenu) {
+ this.contextMenu = new PropertiesViewContextMenu({
+ customFormatters: this.props.contextMenuFormatters,
+ });
+ }
+ this.contextMenu.open(evt, window.getSelection(), {
+ member,
+ object: this.props.object,
+ });
+ }
+ }
+
+ renderValueWithRep(props) {
+ const { member } = props;
+
+ /* Hide strings with following conditions
+ * - the `value` object has a `value` property (only happens in Cookies panel)
+ */
+ if (typeof member.value === "object" && member.value?.value) {
+ return null;
+ }
+
+ return Rep(
+ Object.assign(props, {
+ // FIXME: A workaround for the issue in StringRep
+ // Force StringRep to crop the text every time
+ member: Object.assign({}, member, { open: false }),
+ mode: this.props.mode || MODE.TINY,
+ cropLimit: this.props.cropLimit,
+ noGrip: true,
+ })
+ );
+ }
+
+ render() {
+ const {
+ useBaseTreeViewExpand,
+ expandedNodes,
+ object,
+ renderValue,
+ targetSearchResult,
+ selectPath,
+ } = this.props;
+
+ let currentExpandedNodes;
+ // In the TreeView, when the component is re-rendered
+ // the state of `expandedNodes` is persisted by default
+ // e.g. when you open a node and filter the properties list,
+ // the node remains open.
+ // We have the prop `useBaseTreeViewExpand` to flag when we want to use
+ // this functionality or not.
+ if (!useBaseTreeViewExpand) {
+ currentExpandedNodes =
+ expandedNodes ||
+ TreeViewClass.getExpandedNodes(object, {
+ maxLevel: AUTO_EXPAND_MAX_LEVEL,
+ maxNodes: AUTO_EXPAND_MAX_NODES,
+ });
+ }
+ return div(
+ { className: "properties-view" },
+ div(
+ { className: "tree-container" },
+ TreeView({
+ ...this.props,
+ ref: () => this.scrollSelectedIntoView(),
+ columns: [{ id: "value", width: "100%" }],
+
+ expandedNodes: currentExpandedNodes,
+
+ onFilter: props => this.onFilter(props),
+ renderValue: renderValue || this.renderValueWithRep,
+ onContextMenuRow: this.onContextMenuRow,
+ selected:
+ typeof selectPath == "function"
+ ? selectPath(targetSearchResult)
+ : this.getSelectedPath(targetSearchResult),
+ })
+ )
+ );
+ }
+}
+
+module.exports = connect(null, dispatch => ({
+ resetTargetSearchResult: () => dispatch(setTargetSearchResult(null)),
+}))(PropertiesView);
diff --git a/devtools/client/netmonitor/src/components/request-details/RequestPanel.js b/devtools/client/netmonitor/src/components/request-details/RequestPanel.js
new file mode 100644
index 0000000000..5306161d2e
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/RequestPanel.js
@@ -0,0 +1,301 @@
+/* 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");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+ parseFormData,
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ sortObjectKeys,
+} = require("resource://devtools/client/netmonitor/src/utils/sort-utils.js");
+const {
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ updateFormDataSections,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+
+// Components
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+
+loader.lazyGetter(this, "SourcePreview", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/SourcePreview.js")
+ );
+});
+
+const { div, input, label, span, h2 } = dom;
+
+const JSON_SCOPE_NAME = L10N.getStr("jsonScopeName");
+const REQUEST_EMPTY_TEXT = L10N.getStr("paramsNoPayloadText");
+const REQUEST_FILTER_TEXT = L10N.getStr("paramsFilterText");
+const REQUEST_FORM_DATA = L10N.getStr("paramsFormData");
+const REQUEST_POST_PAYLOAD = L10N.getStr("paramsPostPayload");
+const RAW_REQUEST_PAYLOAD = L10N.getStr("netmonitor.request.raw");
+const REQUEST_TRUNCATED = L10N.getStr("requestTruncated");
+
+/**
+ * Params panel component
+ * Displays the GET parameters and POST data of a request
+ */
+class RequestPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ request: PropTypes.object.isRequired,
+ updateRequest: PropTypes.func.isRequired,
+ targetSearchResult: PropTypes.object,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.state = {
+ filterText: "",
+ rawRequestPayloadDisplayed: !!props.targetSearchResult,
+ };
+
+ this.toggleRawRequestPayload = this.toggleRawRequestPayload.bind(this);
+ this.renderRawRequestPayloadBtn =
+ this.renderRawRequestPayloadBtn.bind(this);
+ }
+
+ componentDidMount() {
+ const { request, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestPostData",
+ ]);
+ updateFormDataSections(this.props);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestPostData",
+ ]);
+ updateFormDataSections(nextProps);
+
+ if (nextProps.targetSearchResult !== null) {
+ this.setState({
+ rawRequestPayloadDisplayed: !!nextProps.targetSearchResult,
+ });
+ }
+ }
+
+ /**
+ * Update only if:
+ * 1) The rendered object has changed
+ * 2) The filter text has changed
+ * 2) The display got toggled between formatted and raw data
+ * 3) The user selected another search result target.
+ */
+ shouldComponentUpdate(nextProps, nextState) {
+ return (
+ this.props.request !== nextProps.request ||
+ this.state.filterText !== nextState.filterText ||
+ this.state.rawRequestPayloadDisplayed !==
+ nextState.rawRequestPayloadDisplayed ||
+ this.props.targetSearchResult !== nextProps.targetSearchResult
+ );
+ }
+
+ /**
+ * Mapping array to dict for TreeView usage.
+ * Since TreeView only support Object(dict) format.
+ * This function also deal with duplicate key case
+ * (for multiple selection and query params with same keys)
+ *
+ * This function is not sorting result properties since it can
+ * results in unexpected order of params. See bug 1469533
+ *
+ * @param {Object[]} arr - key-value pair array or form params
+ * @returns {Object} Rep compatible object
+ */
+ getProperties(arr) {
+ return arr.reduce((map, obj) => {
+ const value = map[obj.name];
+ if (value || value === "") {
+ if (typeof value !== "object") {
+ map[obj.name] = [value];
+ }
+ map[obj.name].push(obj.value);
+ } else {
+ map[obj.name] = obj.value;
+ }
+ return map;
+ }, {});
+ }
+
+ toggleRawRequestPayload() {
+ this.setState({
+ rawRequestPayloadDisplayed: !this.state.rawRequestPayloadDisplayed,
+ });
+ }
+
+ renderRawRequestPayloadBtn(key, checked, onChange) {
+ return [
+ label(
+ {
+ key: `${key}RawRequestPayloadBtn`,
+ className: "raw-data-toggle",
+ htmlFor: `raw-${key}-checkbox`,
+ onClick: event => {
+ // stop the header click event
+ event.stopPropagation();
+ },
+ },
+ span({ className: "raw-data-toggle-label" }, RAW_REQUEST_PAYLOAD),
+ span(
+ { className: "raw-data-toggle-input" },
+ input({
+ id: `raw-${key}-checkbox`,
+ checked,
+ className: "devtools-checkbox-toggle",
+ onChange,
+ type: "checkbox",
+ })
+ )
+ ),
+ ];
+ }
+
+ renderRequestPayload(component, componentProps) {
+ return component(componentProps);
+ }
+
+ render() {
+ const { request, targetSearchResult } = this.props;
+ const { filterText, rawRequestPayloadDisplayed } = this.state;
+ const { formDataSections, mimeType, requestPostData } = request;
+ const postData = requestPostData ? requestPostData.postData?.text : null;
+
+ if ((!formDataSections || formDataSections.length === 0) && !postData) {
+ return div({ className: "empty-notice" }, REQUEST_EMPTY_TEXT);
+ }
+
+ let component;
+ let componentProps;
+ let requestPayloadLabel = REQUEST_POST_PAYLOAD;
+ let hasFormattedDisplay = false;
+
+ let error;
+
+ // Form Data section
+ if (formDataSections && formDataSections.length) {
+ const sections = formDataSections.filter(str => /\S/.test(str)).join("&");
+ component = PropertiesView;
+ componentProps = {
+ object: this.getProperties(parseFormData(sections)),
+ filterText,
+ targetSearchResult,
+ defaultSelectFirstNode: false,
+ };
+ requestPayloadLabel = REQUEST_FORM_DATA;
+ hasFormattedDisplay = true;
+ }
+
+ // Request payload section
+ const limit = Services.prefs.getIntPref(
+ "devtools.netmonitor.requestBodyLimit"
+ );
+
+ // Check if the request post data has been truncated from the backend,
+ // in which case no parse should be attempted.
+ if (postData && limit <= postData.length) {
+ error = REQUEST_TRUNCATED;
+ }
+ if (formDataSections && formDataSections.length === 0 && postData) {
+ if (!error) {
+ const jsonParsedPostData = parseJSON(postData);
+ const { json, strippedChars } = jsonParsedPostData;
+ // If XSSI characters were present in the request just display the raw
+ // data because a request should never have XSSI escape characters
+ if (strippedChars) {
+ hasFormattedDisplay = false;
+ } else if (json) {
+ component = PropertiesView;
+ componentProps = {
+ object: sortObjectKeys(json),
+ filterText,
+ targetSearchResult,
+ defaultSelectFirstNode: false,
+ };
+ requestPayloadLabel = JSON_SCOPE_NAME;
+ hasFormattedDisplay = true;
+ }
+ }
+ }
+
+ if (
+ (!hasFormattedDisplay || this.state.rawRequestPayloadDisplayed) &&
+ postData
+ ) {
+ component = SourcePreview;
+ componentProps = {
+ text: postData,
+ mode: mimeType?.replace(/;.+/, ""),
+ targetSearchResult,
+ };
+ requestPayloadLabel = REQUEST_POST_PAYLOAD;
+ }
+
+ return div(
+ { className: "panel-container" },
+ error && div({ className: "request-error-header", title: error }, error),
+ div(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ type: "filter",
+ onChange: text => this.setState({ filterText: text }),
+ placeholder: REQUEST_FILTER_TEXT,
+ })
+ ),
+ h2({ className: "data-header", role: "heading" }, [
+ span(
+ {
+ key: "data-label",
+ className: "data-label",
+ },
+ requestPayloadLabel
+ ),
+ hasFormattedDisplay &&
+ this.renderRawRequestPayloadBtn(
+ "request",
+ rawRequestPayloadDisplayed,
+ this.toggleRawRequestPayload
+ ),
+ ]),
+ this.renderRequestPayload(component, componentProps)
+ );
+ }
+}
+
+module.exports = connect(null, dispatch => ({
+ updateRequest: (id, data, batch) =>
+ dispatch(Actions.updateRequest(id, data, batch)),
+}))(RequestPanel);
diff --git a/devtools/client/netmonitor/src/components/request-details/ResponsePanel.js b/devtools/client/netmonitor/src/components/request-details/ResponsePanel.js
new file mode 100644
index 0000000000..ac4435ea1d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/ResponsePanel.js
@@ -0,0 +1,496 @@
+/* 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");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ decodeUnicodeBase64,
+ fetchNetworkUpdatePacket,
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getCORSErrorURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+const {
+ Filters,
+} = require("resource://devtools/client/netmonitor/src/utils/filter-predicates.js");
+const {
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ BLOCKED_REASON_MESSAGES,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Components
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+const ImagePreview = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/ImagePreview.js")
+);
+const FontPreview = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/FontPreview.js")
+);
+const SourcePreview = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/SourcePreview.js")
+);
+const HtmlPreview = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/HtmlPreview.js")
+);
+let {
+ NotificationBox,
+ PriorityLevels,
+} = require("resource://devtools/client/shared/components/NotificationBox.js");
+NotificationBox = createFactory(NotificationBox);
+const MessagesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessagesView.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+
+loader.lazyGetter(this, "MODE", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .MODE;
+});
+
+const { div, input, label, span, h2 } = dom;
+const JSON_SCOPE_NAME = L10N.getStr("jsonScopeName");
+const JSON_FILTER_TEXT = L10N.getStr("jsonFilterText");
+const RESPONSE_PAYLOAD = L10N.getStr("responsePayload");
+const RAW_RESPONSE_PAYLOAD = L10N.getStr("netmonitor.response.raw");
+const HTML_RESPONSE = L10N.getStr("netmonitor.response.html");
+const RESPONSE_EMPTY_TEXT = L10N.getStr("responseEmptyText");
+const RESPONSE_TRUNCATED = L10N.getStr("responseTruncated");
+
+const JSON_VIEW_MIME_TYPE = "application/vnd.mozilla.json.view";
+
+/**
+ * Response panel component
+ * Displays the GET parameters and POST data of a request
+ */
+class ResponsePanel extends Component {
+ static get propTypes() {
+ return {
+ request: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ targetSearchResult: PropTypes.object,
+ connector: PropTypes.object.isRequired,
+ showMessagesView: PropTypes.bool,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ filterText: "",
+ rawResponsePayloadDisplayed: !!props.targetSearchResult,
+ };
+
+ this.toggleRawResponsePayload = this.toggleRawResponsePayload.bind(this);
+ this.renderCORSBlockedReason = this.renderCORSBlockedReason.bind(this);
+ this.renderRawResponsePayloadBtn =
+ this.renderRawResponsePayloadBtn.bind(this);
+ this.renderJsonHtmlAndSource = this.renderJsonHtmlAndSource.bind(this);
+ this.handleJSONResponse = this.handleJSONResponse.bind(this);
+ }
+
+ componentDidMount() {
+ const { request, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "responseContent",
+ ]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "responseContent",
+ ]);
+
+ // If the response contains XSSI stripped chars default to raw view
+ const text = nextProps.request?.responseContent?.content?.text;
+ const xssiStrippedChars = text && parseJSON(text)?.strippedChars;
+ if (xssiStrippedChars && !this.state.rawResponsePayloadDisplayed) {
+ this.toggleRawResponsePayload();
+ }
+
+ if (nextProps.targetSearchResult !== null) {
+ this.setState({
+ rawResponsePayloadDisplayed: !!nextProps.targetSearchResult,
+ });
+ }
+ }
+
+ /**
+ * Update only if:
+ * 1) The rendered object has changed
+ * 2) The user selected another search result target.
+ * 3) Internal state changes
+ */
+ shouldComponentUpdate(nextProps, nextState) {
+ return (
+ this.state !== nextState ||
+ this.props.request !== nextProps.request ||
+ nextProps.targetSearchResult !== null
+ );
+ }
+
+ /**
+ * Handle json, which we tentatively identify by checking the
+ * MIME type for "json" after any word boundary. This works
+ * for the standard "application/json", and also for custom
+ * types like "x-bigcorp-json". Additionally, we also
+ * directly parse the response text content to verify whether
+ * it's json or not, to handle responses incorrectly labeled
+ * as text/plain instead.
+ */
+ handleJSONResponse(mimeType, response) {
+ const limit = Services.prefs.getIntPref(
+ "devtools.netmonitor.responseBodyLimit"
+ );
+ const { request } = this.props;
+
+ // Check if the response has been truncated, in which case no parse should
+ // be attempted.
+ if (limit > 0 && limit <= request.responseContent.content.size) {
+ const result = {};
+ result.error = RESPONSE_TRUNCATED;
+ return result;
+ }
+
+ const { json, error, jsonpCallback, strippedChars } = parseJSON(response);
+
+ if (/\bjson/.test(mimeType) || json) {
+ const result = {};
+ // Make sure this is a valid JSON object first. If so, nicely display
+ // the parsing results in a tree view.
+
+ // Valid JSON
+ if (json) {
+ result.json = json;
+ }
+ // Valid JSONP
+ if (jsonpCallback) {
+ result.jsonpCallback = jsonpCallback;
+ }
+ // Malformed JSON
+ if (error) {
+ result.error = "" + error;
+ }
+ // XSSI protection sequence
+ if (strippedChars) {
+ result.strippedChars = strippedChars;
+ }
+
+ return result;
+ }
+
+ return null;
+ }
+
+ renderCORSBlockedReason(blockedReason) {
+ // ensure that the blocked reason is in the CORS range
+ if (
+ typeof blockedReason != "number" ||
+ blockedReason < 1000 ||
+ blockedReason > 1015
+ ) {
+ return null;
+ }
+
+ const blockedMessage = BLOCKED_REASON_MESSAGES[blockedReason];
+ const messageText = L10N.getFormatStr(
+ "netmonitor.headers.blockedByCORS",
+ blockedMessage
+ );
+
+ const learnMoreTooltip = L10N.getStr(
+ "netmonitor.headers.blockedByCORSTooltip"
+ );
+
+ // Create a notifications map with the CORS error notification
+ const notifications = new Map();
+ notifications.set("CORS-error", {
+ label: messageText,
+ value: "CORS-error",
+ image: "",
+ priority: PriorityLevels.PRIORITY_INFO_HIGH,
+ type: "info",
+ eventCallback: e => {},
+ buttons: [
+ {
+ mdnUrl: getCORSErrorURL(blockedReason),
+ label: learnMoreTooltip,
+ },
+ ],
+ });
+
+ return NotificationBox({
+ notifications,
+ displayBorderTop: false,
+ displayBorderBottom: true,
+ displayCloseButton: false,
+ });
+ }
+
+ toggleRawResponsePayload() {
+ this.setState({
+ rawResponsePayloadDisplayed: !this.state.rawResponsePayloadDisplayed,
+ });
+ }
+
+ /**
+ * Pick correct component, componentprops, and other needed data to render
+ * the given response
+ *
+ * @returns {Object} shape:
+ * {component}: React component used to render response
+ * {Object} componetProps: Props passed to component
+ * {Error} error: JSON parsing error
+ * {Object} json: parsed JSON payload
+ * {bool} hasFormattedDisplay: whether the given payload has a formatted
+ * display or if it should be rendered raw
+ * {string} responsePayloadLabel: describes type in response panel
+ * {component} xssiStrippedCharsInfoBox: React component to notifiy users
+ * that XSSI characters were stripped from the response
+ */
+ renderJsonHtmlAndSource() {
+ const { request, targetSearchResult } = this.props;
+ const { responseContent } = request;
+ let { encoding, mimeType, text } = responseContent.content;
+ const { filterText, rawResponsePayloadDisplayed } = this.state;
+
+ // Decode response if it's coming from JSONView.
+ if (mimeType?.includes(JSON_VIEW_MIME_TYPE) && encoding === "base64") {
+ text = decodeUnicodeBase64(text);
+ }
+ const { json, jsonpCallback, error, strippedChars } =
+ this.handleJSONResponse(mimeType, text) || {};
+
+ let component;
+ let componentProps;
+ let xssiStrippedCharsInfoBox;
+ let responsePayloadLabel = RESPONSE_PAYLOAD;
+ let hasFormattedDisplay = false;
+
+ if (json) {
+ if (jsonpCallback) {
+ responsePayloadLabel = L10N.getFormatStr(
+ "jsonpScopeName",
+ jsonpCallback
+ );
+ } else {
+ responsePayloadLabel = JSON_SCOPE_NAME;
+ }
+
+ // If raw response payload is not displayed render xssi info box if
+ // there are stripped chars
+ if (!rawResponsePayloadDisplayed) {
+ xssiStrippedCharsInfoBox =
+ this.renderXssiStrippedCharsInfoBox(strippedChars);
+ } else {
+ xssiStrippedCharsInfoBox = null;
+ }
+
+ component = PropertiesView;
+ componentProps = {
+ object: json,
+ useQuotes: true,
+ filterText,
+ targetSearchResult,
+ defaultSelectFirstNode: false,
+ mode: MODE.LONG,
+ useBaseTreeViewExpand: true,
+ };
+ hasFormattedDisplay = true;
+ } else if (Filters.html(this.props.request)) {
+ // Display HTML
+ responsePayloadLabel = HTML_RESPONSE;
+ component = HtmlPreview;
+ componentProps = { responseContent };
+ hasFormattedDisplay = true;
+ }
+ if (!hasFormattedDisplay || rawResponsePayloadDisplayed) {
+ component = SourcePreview;
+ componentProps = {
+ text,
+ mode: json ? "application/json" : mimeType.replace(/;.+/, ""),
+ targetSearchResult,
+ };
+ }
+ return {
+ component,
+ componentProps,
+ error,
+ hasFormattedDisplay,
+ json,
+ responsePayloadLabel,
+ xssiStrippedCharsInfoBox,
+ };
+ }
+
+ renderRawResponsePayloadBtn(key, checked, onChange) {
+ return [
+ label(
+ {
+ key: `${key}RawResponsePayloadBtn`,
+ className: "raw-data-toggle",
+ htmlFor: `raw-${key}-checkbox`,
+ onClick: event => {
+ // stop the header click event
+ event.stopPropagation();
+ },
+ },
+ span({ className: "raw-data-toggle-label" }, RAW_RESPONSE_PAYLOAD),
+ span(
+ { className: "raw-data-toggle-input" },
+ input({
+ id: `raw-${key}-checkbox`,
+ checked,
+ className: "devtools-checkbox-toggle",
+ onChange,
+ type: "checkbox",
+ })
+ )
+ ),
+ ];
+ }
+
+ renderResponsePayload(component, componentProps) {
+ return component(componentProps);
+ }
+
+ /**
+ * This function takes a string of the XSSI protection characters
+ * removed from a JSON payload and produces a notification component
+ * letting the user know that they were removed
+ *
+ * @param {string} strippedChars: string of XSSI protection characters
+ * removed from JSON payload
+ * @returns {component} NotificationBox component
+ */
+ renderXssiStrippedCharsInfoBox(strippedChars) {
+ if (!strippedChars || this.state.rawRequestPayloadDisplayed) {
+ return null;
+ }
+ const message = L10N.getFormatStr("jsonXssiStripped", strippedChars);
+
+ const notifications = new Map();
+ notifications.set("xssi-string-removed-info-box", {
+ label: message,
+ value: "xssi-string-removed-info-box",
+ image: "",
+ priority: PriorityLevels.PRIORITY_INFO_MEDIUM,
+ type: "info",
+ eventCallback: e => {},
+ buttons: [],
+ });
+
+ return NotificationBox({
+ notifications,
+ displayBorderTop: false,
+ displayBorderBottom: true,
+ displayCloseButton: false,
+ });
+ }
+
+ render() {
+ const { connector, showMessagesView, request } = this.props;
+ const { blockedReason, responseContent, url } = request;
+ const { filterText, rawResponsePayloadDisplayed } = this.state;
+
+ // Display CORS blocked Reason info box
+ const CORSBlockedReasonDetails =
+ this.renderCORSBlockedReason(blockedReason);
+
+ if (showMessagesView) {
+ return MessagesView({ connector });
+ }
+
+ if (
+ !responseContent ||
+ typeof responseContent.content.text !== "string" ||
+ !responseContent.content.text
+ ) {
+ return div(
+ { className: "panel-container" },
+ CORSBlockedReasonDetails,
+ div({ className: "empty-notice" }, RESPONSE_EMPTY_TEXT)
+ );
+ }
+
+ const { encoding, mimeType, text } = responseContent.content;
+
+ if (Filters.images({ mimeType })) {
+ return ImagePreview({ encoding, mimeType, text, url });
+ }
+
+ if (Filters.fonts({ url, mimeType })) {
+ return FontPreview({ connector, mimeType, url });
+ }
+
+ // Get Data needed for formatted display
+ const {
+ component,
+ componentProps,
+ error,
+ hasFormattedDisplay,
+ json,
+ responsePayloadLabel,
+ xssiStrippedCharsInfoBox,
+ } = this.renderJsonHtmlAndSource();
+
+ const classList = ["panel-container"];
+ if (Filters.html(this.props.request)) {
+ classList.push("contains-html-preview");
+ }
+
+ return div(
+ { className: classList.join(" ") },
+ error && div({ className: "response-error-header", title: error }, error),
+ json &&
+ div(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ type: "filter",
+ onChange: filter => this.setState({ filterText: filter }),
+ placeholder: JSON_FILTER_TEXT,
+ value: filterText,
+ })
+ ),
+ div({ tabIndex: "0" }, CORSBlockedReasonDetails),
+ h2({ className: "data-header", role: "heading" }, [
+ span(
+ {
+ key: "data-label",
+ className: "data-label",
+ },
+ responsePayloadLabel
+ ),
+ hasFormattedDisplay &&
+ this.renderRawResponsePayloadBtn(
+ "response",
+ rawResponsePayloadDisplayed,
+ this.toggleRawResponsePayload
+ ),
+ ]),
+ xssiStrippedCharsInfoBox,
+ this.renderResponsePayload(component, componentProps)
+ );
+ }
+}
+
+module.exports = ResponsePanel;
diff --git a/devtools/client/netmonitor/src/components/request-details/SecurityPanel.js b/devtools/client/netmonitor/src/components/request-details/SecurityPanel.js
new file mode 100644
index 0000000000..74dca02cc8
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/SecurityPanel.js
@@ -0,0 +1,283 @@
+/* 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 dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+ getUrlHost,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+// Components
+const TreeViewClass = require("resource://devtools/client/shared/components/tree/TreeView.js");
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+
+loader.lazyGetter(this, "Rep", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .REPS.Rep;
+});
+loader.lazyGetter(this, "MODE", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .MODE;
+});
+
+const { div, span } = dom;
+const NOT_AVAILABLE = L10N.getStr("netmonitor.security.notAvailable");
+const ERROR_LABEL = L10N.getStr("netmonitor.security.error");
+const CIPHER_SUITE_LABEL = L10N.getStr("netmonitor.security.cipherSuite");
+const WARNING_CIPHER_LABEL = L10N.getStr("netmonitor.security.warning.cipher");
+const ENABLED_LABEL = L10N.getStr("netmonitor.security.enabled");
+const DISABLED_LABEL = L10N.getStr("netmonitor.security.disabled");
+const CONNECTION_LABEL = L10N.getStr("netmonitor.security.connection");
+const PROTOCOL_VERSION_LABEL = L10N.getStr(
+ "netmonitor.security.protocolVersion"
+);
+const KEA_GROUP_LABEL = L10N.getStr("netmonitor.security.keaGroup");
+const KEA_GROUP_NONE = L10N.getStr("netmonitor.security.keaGroup.none");
+const KEA_GROUP_CUSTOM = L10N.getStr("netmonitor.security.keaGroup.custom");
+const KEA_GROUP_UNKNOWN = L10N.getStr("netmonitor.security.keaGroup.unknown");
+const SIGNATURE_SCHEME_LABEL = L10N.getStr(
+ "netmonitor.security.signatureScheme"
+);
+const SIGNATURE_SCHEME_NONE = L10N.getStr(
+ "netmonitor.security.signatureScheme.none"
+);
+const SIGNATURE_SCHEME_UNKNOWN = L10N.getStr(
+ "netmonitor.security.signatureScheme.unknown"
+);
+const HSTS_LABEL = L10N.getStr("netmonitor.security.hsts");
+const HPKP_LABEL = L10N.getStr("netmonitor.security.hpkp");
+const CERTIFICATE_LABEL = L10N.getStr("netmonitor.security.certificate");
+const CERTIFICATE_TRANSPARENCY_LABEL = L10N.getStr(
+ "certmgr.certificateTransparency.label"
+);
+const CERTIFICATE_TRANSPARENCY_POLICY_COMPLIANT = L10N.getStr(
+ "certmgr.certificateTransparency.status.ok"
+);
+const CERTIFICATE_TRANSPARENCY_POLICY_NOT_ENOUGH_SCTS = L10N.getStr(
+ "certmgr.certificateTransparency.status.notEnoughSCTS"
+);
+const CERTIFICATE_TRANSPARENCY_POLICY_NOT_DIVERSE_SCTS = L10N.getStr(
+ "certmgr.certificateTransparency.status.notDiverseSCTS"
+);
+const SUBJECT_INFO_LABEL = L10N.getStr("certmgr.subjectinfo.label");
+const CERT_DETAIL_COMMON_NAME_LABEL = L10N.getStr("certmgr.certdetail.cn");
+const CERT_DETAIL_ORG_LABEL = L10N.getStr("certmgr.certdetail.o");
+const CERT_DETAIL_ORG_UNIT_LABEL = L10N.getStr("certmgr.certdetail.ou");
+const ISSUER_INFO_LABEL = L10N.getStr("certmgr.issuerinfo.label");
+const PERIOD_OF_VALIDITY_LABEL = L10N.getStr("certmgr.periodofvalidity.label");
+const BEGINS_LABEL = L10N.getStr("certmgr.begins");
+const EXPIRES_LABEL = L10N.getStr("certmgr.expires");
+const FINGERPRINTS_LABEL = L10N.getStr("certmgr.fingerprints.label");
+const SHA256_FINGERPRINT_LABEL = L10N.getStr(
+ "certmgr.certdetail.sha256fingerprint"
+);
+const SHA1_FINGERPRINT_LABEL = L10N.getStr(
+ "certmgr.certdetail.sha1fingerprint"
+);
+
+/*
+ * Localize special values for key exchange group name,
+ * certificate signature scheme, and certificate
+ * transparency status.
+ */
+const formatSecurityInfo = securityInfo => {
+ const formattedSecurityInfo = { ...securityInfo };
+
+ const formatters = {
+ keaGroupName: value => {
+ if (value === "none") {
+ return KEA_GROUP_NONE;
+ }
+ if (value === "custom") {
+ return KEA_GROUP_CUSTOM;
+ }
+ if (value === "unknown group") {
+ return KEA_GROUP_UNKNOWN;
+ }
+ return value;
+ },
+ signatureSchemeName: value => {
+ if (value === "none") {
+ return SIGNATURE_SCHEME_NONE;
+ }
+ if (value === "unknown signature") {
+ return SIGNATURE_SCHEME_UNKNOWN;
+ }
+ return value;
+ },
+ certificateTransparency: value => {
+ if (value === 5) {
+ return CERTIFICATE_TRANSPARENCY_POLICY_COMPLIANT;
+ }
+ if (value === 6) {
+ return CERTIFICATE_TRANSPARENCY_POLICY_NOT_ENOUGH_SCTS;
+ }
+ if (value === 7) {
+ return CERTIFICATE_TRANSPARENCY_POLICY_NOT_DIVERSE_SCTS;
+ }
+ return value;
+ },
+ };
+
+ return Object.keys(formatters).reduce((acc, key) => {
+ const formatter = formatters[key];
+ acc[key] = formatter(acc[key]);
+ return acc;
+ }, formattedSecurityInfo);
+};
+
+const getConnectionLabel = securityInfo => ({
+ [PROTOCOL_VERSION_LABEL]: securityInfo.protocolVersion || NOT_AVAILABLE,
+ [CIPHER_SUITE_LABEL]: securityInfo.cipherSuite || NOT_AVAILABLE,
+ [KEA_GROUP_LABEL]: securityInfo.keaGroupName || NOT_AVAILABLE,
+ [SIGNATURE_SCHEME_LABEL]: securityInfo.signatureSchemeName || NOT_AVAILABLE,
+});
+
+const getHostHeaderLabel = securityInfo => ({
+ [HSTS_LABEL]: securityInfo.hsts ? ENABLED_LABEL : DISABLED_LABEL,
+ [HPKP_LABEL]: securityInfo.hpkp ? ENABLED_LABEL : DISABLED_LABEL,
+});
+
+const getCertificateLabel = securityInfo => {
+ const { fingerprint, issuer, subject, validity } = securityInfo.cert;
+
+ return {
+ [SUBJECT_INFO_LABEL]: {
+ [CERT_DETAIL_COMMON_NAME_LABEL]: subject?.commonName || NOT_AVAILABLE,
+ [CERT_DETAIL_ORG_LABEL]: subject?.organization || NOT_AVAILABLE,
+ [CERT_DETAIL_ORG_UNIT_LABEL]: subject?.organizationUnit || NOT_AVAILABLE,
+ },
+ [ISSUER_INFO_LABEL]: {
+ [CERT_DETAIL_COMMON_NAME_LABEL]: issuer?.commonName || NOT_AVAILABLE,
+ [CERT_DETAIL_ORG_LABEL]: issuer?.organization || NOT_AVAILABLE,
+ [CERT_DETAIL_ORG_UNIT_LABEL]: issuer?.organizationUnit || NOT_AVAILABLE,
+ },
+ [PERIOD_OF_VALIDITY_LABEL]: {
+ [BEGINS_LABEL]: validity?.start || NOT_AVAILABLE,
+ [EXPIRES_LABEL]: validity?.end || NOT_AVAILABLE,
+ },
+ [FINGERPRINTS_LABEL]: {
+ [SHA256_FINGERPRINT_LABEL]: fingerprint?.sha256 || NOT_AVAILABLE,
+ [SHA1_FINGERPRINT_LABEL]: fingerprint?.sha1 || NOT_AVAILABLE,
+ },
+ [CERTIFICATE_TRANSPARENCY_LABEL]:
+ securityInfo.certificateTransparency || NOT_AVAILABLE,
+ };
+};
+
+const getObject = ({ securityInfo, url }) => {
+ if (securityInfo.state !== "secure" && securityInfo.state !== "weak") {
+ return {
+ [ERROR_LABEL]: securityInfo.errorMessage || NOT_AVAILABLE,
+ };
+ }
+
+ const HOST_HEADER_LABEL = L10N.getFormatStr(
+ "netmonitor.security.hostHeader",
+ getUrlHost(url)
+ );
+ const formattedSecurityInfo = formatSecurityInfo(securityInfo);
+
+ return {
+ [CONNECTION_LABEL]: getConnectionLabel(formattedSecurityInfo),
+ [HOST_HEADER_LABEL]: getHostHeaderLabel(formattedSecurityInfo),
+ [CERTIFICATE_LABEL]: getCertificateLabel(formattedSecurityInfo),
+ };
+};
+
+/*
+ * Security panel component
+ * If the site is being served over HTTPS, you get an extra tab labeled "Security".
+ * This contains details about the secure connection used including the protocol,
+ * the cipher suite, and certificate details
+ */
+class SecurityPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ request: PropTypes.object.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { request, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["securityInfo"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["securityInfo"]);
+ }
+
+ renderValue(props, weaknessReasons = []) {
+ const { member, value } = props;
+
+ // Hide object summary
+ if (typeof member.value === "object") {
+ return null;
+ }
+
+ return span(
+ { className: "security-info-value" },
+ member.name === ERROR_LABEL
+ ? // Display multiline text for security error for a label using a rep.
+ value
+ : Rep(
+ Object.assign(props, {
+ // FIXME: A workaround for the issue in StringRep
+ // Force StringRep to crop the text everytime
+ member: Object.assign({}, member, { open: false }),
+ mode: MODE.TINY,
+ cropLimit: 60,
+ noGrip: true,
+ })
+ ),
+ weaknessReasons.includes("cipher") && member.name === CIPHER_SUITE_LABEL
+ ? // Display an extra warning icon after the cipher suite
+ div({
+ id: "security-warning-cipher",
+ className: "security-warning-icon",
+ title: WARNING_CIPHER_LABEL,
+ })
+ : null
+ );
+ }
+
+ render() {
+ const { request } = this.props;
+ const { securityInfo, url } = request;
+
+ if (!securityInfo || !url) {
+ return null;
+ }
+
+ const object = getObject({ securityInfo, url });
+ return div(
+ { className: "panel-container security-panel" },
+ PropertiesView({
+ object,
+ renderValue: props =>
+ this.renderValue(props, securityInfo.weaknessReasons),
+ enableFilter: false,
+ expandedNodes: TreeViewClass.getExpandedNodes(object),
+ })
+ );
+ }
+}
+
+module.exports = SecurityPanel;
diff --git a/devtools/client/netmonitor/src/components/request-details/StackTracePanel.js b/devtools/client/netmonitor/src/components/request-details/StackTracePanel.js
new file mode 100644
index 0000000000..6b01ee27b7
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/StackTracePanel.js
@@ -0,0 +1,81 @@
+/* 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");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { div } = dom;
+
+// Components
+const StackTrace = createFactory(
+ require("resource://devtools/client/shared/components/StackTrace.js")
+);
+
+/**
+ * This component represents a side panel responsible for
+ * rendering stack-trace info for selected request.
+ */
+class StackTracePanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ request: PropTypes.object.isRequired,
+ sourceMapURLService: PropTypes.object,
+ openLink: PropTypes.func,
+ };
+ }
+
+ /**
+ * `componentDidMount` is called when opening the StackTracePanel
+ * for the first time
+ */
+ componentDidMount() {
+ const { request, connector } = this.props;
+ if (!request.stacktrace) {
+ fetchNetworkUpdatePacket(connector.requestData, request, ["stackTrace"]);
+ }
+ }
+
+ /**
+ * `componentWillReceiveProps` is the only method called when
+ * switching between two requests while this panel is displayed.
+ */
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ // Only try to fetch the stacktrace if we don't already have the stacktrace yet
+ if (!request.stacktrace) {
+ fetchNetworkUpdatePacket(connector.requestData, request, ["stackTrace"]);
+ }
+ }
+
+ render() {
+ const { connector, openLink, request, sourceMapURLService } = this.props;
+
+ const { stacktrace } = request;
+
+ return div(
+ { className: "panel-container" },
+ StackTrace({
+ stacktrace: stacktrace || [],
+ onViewSourceInDebugger: ({ url, line, column }) => {
+ return connector.viewSourceInDebugger(url, line, column);
+ },
+ sourceMapURLService,
+ openLink,
+ })
+ );
+ }
+}
+
+module.exports = StackTracePanel;
diff --git a/devtools/client/netmonitor/src/components/request-details/TimingsPanel.js b/devtools/client/netmonitor/src/components/request-details/TimingsPanel.js
new file mode 100644
index 0000000000..30053f09ea
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/TimingsPanel.js
@@ -0,0 +1,229 @@
+/* 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getNetMonitorTimingsURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ TIMING_KEYS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Components
+const MDNLink = require("resource://devtools/client/shared/components/MdnLink.js");
+
+const { div, span } = dom;
+
+const TIMINGS_END_PADDING = "80px";
+
+/**
+ * Timings panel component
+ * Display timeline bars that shows the total wait time for various stages
+ */
+class TimingsPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ request: PropTypes.object.isRequired,
+ firstRequestStartedMs: PropTypes.number.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { connector, request } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["eventTimings"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { connector, request } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["eventTimings"]);
+ }
+
+ renderServerTimings() {
+ const { serverTimings, totalTime } = this.props.request.eventTimings;
+
+ if (!serverTimings?.length) {
+ return null;
+ }
+
+ return div(
+ {},
+ div(
+ { className: "label-separator" },
+ L10N.getStr("netmonitor.timings.serverTiming")
+ ),
+ ...serverTimings.map(({ name, duration, description }, index) => {
+ const color = name === "total" ? "total" : (index % 3) + 1;
+
+ return div(
+ {
+ key: index,
+ className: "tabpanel-summary-container timings-container server",
+ },
+ span(
+ { className: "tabpanel-summary-label timings-label" },
+ description || name
+ ),
+ div(
+ { className: "requests-list-timings-container" },
+ span({
+ className: "requests-list-timings-offset",
+ style: {
+ width: `calc(${
+ (totalTime - duration) / totalTime
+ } * (100% - ${TIMINGS_END_PADDING})`,
+ },
+ }),
+ span({
+ className: `requests-list-timings-box server-timings-color-${color}`,
+ style: {
+ width: `calc(${
+ duration / totalTime
+ } * (100% - ${TIMINGS_END_PADDING}))`,
+ },
+ }),
+ span(
+ { className: "requests-list-timings-total" },
+ getFormattedTime(duration)
+ )
+ )
+ );
+ })
+ );
+ }
+
+ render() {
+ const { eventTimings, totalTime, startedMs } = this.props.request;
+ const { firstRequestStartedMs } = this.props;
+
+ if (!eventTimings) {
+ return div(
+ {
+ className:
+ "tabpanel-summary-container timings-container empty-notice",
+ },
+ L10N.getStr("netmonitor.timings.noTimings")
+ );
+ }
+
+ const { timings, offsets } = eventTimings;
+ let queuedAt, startedAt, downloadedAt;
+ const isFirstRequestStartedAvailable = firstRequestStartedMs !== null;
+
+ if (isFirstRequestStartedAvailable) {
+ queuedAt = startedMs - firstRequestStartedMs;
+ startedAt = queuedAt + timings.blocked;
+ downloadedAt = queuedAt + totalTime;
+ }
+
+ const timelines = TIMING_KEYS.map((type, idx) => {
+ // Determine the relative offset for each timings box. For example, the
+ // offset of third timings box will be 0 + blocked offset + dns offset
+ // If offsets sent from the backend aren't available calculate it
+ // from the timing info.
+ const offset = offsets
+ ? offsets[type]
+ : TIMING_KEYS.slice(0, idx).reduce(
+ (acc, cur) => acc + timings[cur] || 0,
+ 0
+ );
+
+ const offsetScale = offset / totalTime || 0;
+ const timelineScale = timings[type] / totalTime || 0;
+
+ return div(
+ {
+ key: type,
+ id: `timings-summary-${type}`,
+ className: "tabpanel-summary-container timings-container request",
+ },
+ span(
+ { className: "tabpanel-summary-label timings-label" },
+ L10N.getStr(`netmonitor.timings.${type}`)
+ ),
+ div(
+ { className: "requests-list-timings-container" },
+ span({
+ className: "requests-list-timings-offset",
+ style: {
+ width: `calc(${offsetScale} * (100% - ${TIMINGS_END_PADDING})`,
+ },
+ }),
+ span({
+ className: `requests-list-timings-box ${type}`,
+ style: {
+ width: `calc(${timelineScale} * (100% - ${TIMINGS_END_PADDING}))`,
+ },
+ }),
+ span(
+ { className: "requests-list-timings-total" },
+ getFormattedTime(timings[type])
+ )
+ )
+ );
+ });
+
+ return div(
+ { className: "panel-container" },
+ isFirstRequestStartedAvailable &&
+ div(
+ { className: "timings-overview" },
+ span(
+ { className: "timings-overview-item" },
+ L10N.getFormatStr(
+ "netmonitor.timings.queuedAt",
+ getFormattedTime(queuedAt)
+ )
+ ),
+ span(
+ { className: "timings-overview-item" },
+ L10N.getFormatStr(
+ "netmonitor.timings.startedAt",
+ getFormattedTime(startedAt)
+ )
+ ),
+ span(
+ { className: "timings-overview-item" },
+ L10N.getFormatStr(
+ "netmonitor.timings.downloadedAt",
+ getFormattedTime(downloadedAt)
+ )
+ )
+ ),
+ div(
+ { className: "label-separator" },
+ L10N.getStr("netmonitor.timings.requestTiming")
+ ),
+ timelines,
+ this.renderServerTimings(),
+ MDNLink({
+ url: getNetMonitorTimingsURL(),
+ title: L10N.getStr("netmonitor.timings.learnMore"),
+ })
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ firstRequestStartedMs: state.requests ? state.requests.firstStartedMs : null,
+}))(TimingsPanel);
diff --git a/devtools/client/netmonitor/src/components/request-details/moz.build b/devtools/client/netmonitor/src/components/request-details/moz.build
new file mode 100644
index 0000000000..09896f2de3
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/moz.build
@@ -0,0 +1,16 @@
+# 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(
+ "CachePanel.js",
+ "CookiesPanel.js",
+ "HeadersPanel.js",
+ "NetworkDetailsBar.js",
+ "PropertiesView.js",
+ "RequestPanel.js",
+ "ResponsePanel.js",
+ "SecurityPanel.js",
+ "StackTracePanel.js",
+ "TimingsPanel.js",
+)
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestList.js b/devtools/client/netmonitor/src/components/request-list/RequestList.js
new file mode 100644
index 0000000000..63640e389c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestList.js
@@ -0,0 +1,50 @@
+/* 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 {
+ 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");
+
+// Components
+const StatusBar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/StatusBar.js")
+);
+
+loader.lazyGetter(this, "RequestListContent", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListContent.js")
+ );
+});
+loader.lazyGetter(this, "RequestListEmptyNotice", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js")
+ );
+});
+
+/**
+ * Request panel component
+ */
+function RequestList({ connector, isEmpty }) {
+ return div(
+ { className: "request-list-container" },
+ isEmpty
+ ? RequestListEmptyNotice({ connector })
+ : RequestListContent({ connector }),
+ StatusBar({ connector })
+ );
+}
+
+RequestList.displayName = "RequestList";
+
+RequestList.propTypes = {
+ connector: PropTypes.object.isRequired,
+ isEmpty: PropTypes.bool.isRequired,
+};
+
+module.exports = RequestList;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js
new file mode 100644
index 0000000000..4c20d4aebe
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js
@@ -0,0 +1,38 @@
+/* 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");
+
+class RequestListColumnContentSize extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.contentSize !== nextProps.item.contentSize;
+ }
+
+ render() {
+ const { contentSize } = this.props.item;
+ const size =
+ typeof contentSize === "number" ? getFormattedSize(contentSize) : null;
+ return dom.td(
+ { className: "requests-list-column requests-list-size", title: size },
+ size
+ );
+ }
+}
+
+module.exports = RequestListColumnContentSize;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.js
new file mode 100644
index 0000000000..0c1431ed60
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.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 {
+ 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 {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+class RequestListColumnCookies extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { item, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["requestCookies"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { item, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["requestCookies"]);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ let { requestCookies: currRequestCookies = { cookies: [] } } =
+ this.props.item;
+ let { requestCookies: nextRequestCookies = { cookies: [] } } =
+ nextProps.item;
+ currRequestCookies = currRequestCookies.cookies || currRequestCookies;
+ nextRequestCookies = nextRequestCookies.cookies || nextRequestCookies;
+ return currRequestCookies !== nextRequestCookies;
+ }
+
+ render() {
+ let { requestCookies = { cookies: [] } } = this.props.item;
+ requestCookies = requestCookies.cookies || requestCookies;
+ const requestCookiesLength = requestCookies.length
+ ? requestCookies.length
+ : "";
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-cookies",
+ title: requestCookiesLength,
+ },
+ requestCookiesLength
+ );
+ }
+}
+
+module.exports = RequestListColumnCookies;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js
new file mode 100644
index 0000000000..3ca6841da6
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js
@@ -0,0 +1,66 @@
+/* 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 {
+ td,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ getFormattedIPAndPort,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const SecurityState = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/SecurityState.js")
+);
+
+const UPDATED_DOMAIN_PROPS = ["remoteAddress", "securityState", "urlDetails"];
+
+class RequestListColumnDomain extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ onSecurityIconMouseDown: PropTypes.func.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_DOMAIN_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const { item, onSecurityIconMouseDown } = this.props;
+
+ const {
+ remoteAddress,
+ remotePort,
+ urlDetails: { host, isLocal },
+ } = item;
+
+ const title =
+ host +
+ (remoteAddress
+ ? ` (${getFormattedIPAndPort(remoteAddress, remotePort)})`
+ : "");
+
+ return td(
+ { className: "requests-list-column requests-list-domain", title },
+ SecurityState({ item, onSecurityIconMouseDown, isLocal }),
+ host
+ );
+ }
+}
+
+module.exports = RequestListColumnDomain;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js
new file mode 100644
index 0000000000..f824cdb973
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js
@@ -0,0 +1,91 @@
+/* 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 {
+ 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 {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+const UPDATED_FILE_PROPS = ["urlDetails", "waitingTime"];
+
+class RequestListColumnFile extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ slowLimit: PropTypes.number,
+ onWaterfallMouseDown: PropTypes.func,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_FILE_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const {
+ item: { urlDetails, waitingTime },
+ slowLimit,
+ onWaterfallMouseDown,
+ } = this.props;
+
+ const originalFileURL = urlDetails.url;
+ const decodedFileURL = urlDetails.unicodeUrl;
+ const ORIGINAL_FILE_URL = L10N.getFormatStr(
+ "netRequest.originalFileURL.tooltip",
+ originalFileURL
+ );
+ const DECODED_FILE_URL = L10N.getFormatStr(
+ "netRequest.decodedFileURL.tooltip",
+ decodedFileURL
+ );
+ const requestedFile = urlDetails.baseNameWithQuery;
+ const fileToolTip =
+ originalFileURL === decodedFileURL
+ ? originalFileURL
+ : ORIGINAL_FILE_URL + "\n\n" + DECODED_FILE_URL;
+
+ const isSlow = slowLimit > 0 && !!waitingTime && waitingTime > slowLimit;
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-file",
+ title: fileToolTip,
+ },
+ dom.div({}, requestedFile),
+ isSlow &&
+ dom.div({
+ title: L10N.getFormatStr(
+ "netmonitor.audits.slowIconTooltip",
+ getFormattedTime(waitingTime),
+ getFormattedTime(slowLimit)
+ ),
+ onMouseDown: onWaterfallMouseDown,
+ className: "requests-list-slow-button",
+ })
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ slowLimit: state.ui.slowLimit,
+}))(RequestListColumnFile);
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js
new file mode 100644
index 0000000000..0c08387fa1
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js
@@ -0,0 +1,65 @@
+/* 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 {
+ getUrlBaseName,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+class RequestListColumnInitiator extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ onInitiatorBadgeMouseDown: PropTypes.func.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.cause !== nextProps.item.cause;
+ }
+
+ render() {
+ const {
+ item: { cause },
+ onInitiatorBadgeMouseDown,
+ } = this.props;
+
+ let initiator = "";
+ let lineNumber = "";
+
+ const lastFrameExists = cause && cause.lastFrame;
+ if (lastFrameExists) {
+ const { filename, lineNumber: _lineNumber } = cause.lastFrame;
+ initiator = getUrlBaseName(filename);
+ lineNumber = ":" + _lineNumber;
+ }
+
+ // Legacy server might send a numeric value. Display it as "unknown"
+ const causeType = typeof cause.type === "string" ? cause.type : "unknown";
+ const causeStr = lastFrameExists ? " (" + causeType + ")" : causeType;
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-initiator",
+ title: initiator + lineNumber + causeStr,
+ },
+ dom.div(
+ {
+ className: "requests-list-initiator-lastframe",
+ onMouseDown: onInitiatorBadgeMouseDown,
+ },
+ dom.span({ className: "requests-list-initiator-filename" }, initiator),
+ dom.span({ className: "requests-list-initiator-line" }, lineNumber)
+ ),
+ dom.div({ className: "requests-list-initiator-cause" }, causeStr)
+ );
+ }
+}
+
+module.exports = RequestListColumnInitiator;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js
new file mode 100644
index 0000000000..08434a76fe
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js
@@ -0,0 +1,33 @@
+/* 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");
+
+class RequestListColumnMethod extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.method !== nextProps.item.method;
+ }
+
+ render() {
+ const { method } = this.props.item;
+ return dom.td(
+ { className: "requests-list-column requests-list-method" },
+ method
+ );
+ }
+}
+
+module.exports = RequestListColumnMethod;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js
new file mode 100644
index 0000000000..56f33ec3de
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js
@@ -0,0 +1,36 @@
+/* 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 {
+ getRequestPriorityAsText,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+class RequestListColumnPriority extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.method !== nextProps.item.method;
+ }
+
+ render() {
+ const { priority } = this.props.item;
+ return dom.td(
+ { className: "requests-list-column" },
+ getRequestPriorityAsText(priority)
+ );
+ }
+}
+
+module.exports = RequestListColumnPriority;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.js
new file mode 100644
index 0000000000..d77ad43406
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.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 {
+ getFormattedProtocol,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+class RequestListColumnProtocol extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ getFormattedProtocol(this.props.item) !==
+ getFormattedProtocol(nextProps.item)
+ );
+ }
+
+ render() {
+ const protocol = getFormattedProtocol(this.props.item);
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-protocol",
+ title: protocol,
+ },
+ protocol
+ );
+ }
+}
+
+module.exports = RequestListColumnProtocol;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.js
new file mode 100644
index 0000000000..4fa22aa2b2
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.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 {
+ getFormattedIPAndPort,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+class RequestListColumnRemoteIP extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.remoteAddress !== nextProps.item.remoteAddress;
+ }
+
+ render() {
+ const { remoteAddress, remotePort } = this.props.item;
+ const remoteIP = remoteAddress
+ ? getFormattedIPAndPort(remoteAddress, remotePort)
+ : "unknown";
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-remoteip",
+ title: remoteIP,
+ },
+ remoteIP
+ );
+ }
+}
+
+module.exports = RequestListColumnRemoteIP;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js
new file mode 100644
index 0000000000..de02da0bc5
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js
@@ -0,0 +1,59 @@
+/* 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 {
+ getResponseHeader,
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+/**
+ * Renders a response header column in the requests list. The actual
+ * header to show is passed as a prop.
+ */
+class RequestListColumnResponseHeader extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ item: PropTypes.object.isRequired,
+ header: PropTypes.string.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { item, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["responseHeaders"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { item, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["responseHeaders"]);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ const currHeader = getResponseHeader(this.props.item, this.props.header);
+ const nextHeader = getResponseHeader(nextProps.item, nextProps.header);
+ return currHeader !== nextHeader;
+ }
+
+ render() {
+ const header = getResponseHeader(this.props.item, this.props.header);
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-response-header",
+ title: header,
+ },
+ header
+ );
+ }
+}
+
+module.exports = RequestListColumnResponseHeader;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js
new file mode 100644
index 0000000000..7309a17d60
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js
@@ -0,0 +1,38 @@
+/* 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");
+
+class RequestListColumnScheme extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ this.props.item.urlDetails.scheme !== nextProps.item.urlDetails.scheme
+ );
+ }
+
+ render() {
+ const { urlDetails } = this.props.item;
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-scheme",
+ title: urlDetails.scheme,
+ },
+ urlDetails.scheme
+ );
+ }
+}
+
+module.exports = RequestListColumnScheme;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.js
new file mode 100644
index 0000000000..0ee8164411
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.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 {
+ 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 {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+class RequestListColumnSetCookies extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { item, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["responseCookies"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { item, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["responseCookies"]);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ let { responseCookies: currResponseCookies = { cookies: [] } } =
+ this.props.item;
+ let { responseCookies: nextResponseCookies = { cookies: [] } } =
+ nextProps.item;
+ currResponseCookies = currResponseCookies.cookies || currResponseCookies;
+ nextResponseCookies = nextResponseCookies.cookies || nextResponseCookies;
+ return currResponseCookies !== nextResponseCookies;
+ }
+
+ render() {
+ let { responseCookies = { cookies: [] } } = this.props.item;
+ responseCookies = responseCookies.cookies || responseCookies;
+ const responseCookiesLength = responseCookies.length
+ ? responseCookies.length
+ : "";
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-set-cookies",
+ title: responseCookiesLength,
+ },
+ responseCookiesLength
+ );
+ }
+}
+
+module.exports = RequestListColumnSetCookies;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js
new file mode 100644
index 0000000000..180d280b1b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js
@@ -0,0 +1,39 @@
+/* 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");
+
+// Components
+
+const StatusCode = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/StatusCode.js")
+);
+
+class RequestListColumnStatus extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ render() {
+ const { item } = this.props;
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-status",
+ },
+ StatusCode({ item })
+ );
+ }
+}
+
+module.exports = RequestListColumnStatus;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js
new file mode 100644
index 0000000000..4ee35d196f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js
@@ -0,0 +1,91 @@
+/* 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 {
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ fetchNetworkUpdatePacket,
+ getResponseTime,
+ getStartTime,
+ getEndTime,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+/**
+ * This component represents a column displaying selected
+ * timing value. There are following possible values this
+ * column can render:
+ * - Start Time
+ * - End Time
+ * - Response Time
+ * - Duration Time
+ * - Latency Time
+ */
+class RequestListColumnTime extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ firstRequestStartedMs: PropTypes.number.isRequired,
+ item: PropTypes.object.isRequired,
+ type: PropTypes.oneOf(["start", "end", "response", "duration", "latency"])
+ .isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { item, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["eventTimings"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { item, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["eventTimings"]);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.getTime(this.props) !== this.getTime(nextProps);
+ }
+
+ getTime(props) {
+ const { firstRequestStartedMs, item, type } = props;
+
+ switch (type) {
+ case "start":
+ return getStartTime(item, firstRequestStartedMs);
+ case "end":
+ return getEndTime(item, firstRequestStartedMs);
+ case "response":
+ return getResponseTime(item, firstRequestStartedMs);
+ case "duration":
+ return item.totalTime;
+ case "latency":
+ return item.eventTimings ? item.eventTimings.timings.wait : undefined;
+ }
+
+ return 0;
+ }
+
+ render() {
+ const { type } = this.props;
+ const time = getFormattedTime(this.getTime(this.props));
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-" + type + "-time",
+ title: time,
+ },
+ time
+ );
+ }
+}
+
+module.exports = RequestListColumnTime;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js
new file mode 100644
index 0000000000..63cc7a7009
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js
@@ -0,0 +1,99 @@
+/* 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");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ BLOCKED_REASON_MESSAGES,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const SIZE_CACHED = L10N.getStr("networkMenu.sizeCached");
+const SIZE_SERVICE_WORKER = L10N.getStr("networkMenu.sizeServiceWorker");
+const SIZE_UNAVAILABLE = L10N.getStr("networkMenu.sizeUnavailable");
+const SIZE_UNAVAILABLE_TITLE = L10N.getStr("networkMenu.sizeUnavailable.title");
+const UPDATED_TRANSFERRED_PROPS = [
+ "transferredSize",
+ "fromCache",
+ "isRacing",
+ "fromServiceWorker",
+];
+
+class RequestListColumnTransferredSize extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_TRANSFERRED_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const {
+ blockedReason,
+ blockingExtension,
+ fromCache,
+ fromServiceWorker,
+ status,
+ transferredSize,
+ isRacing,
+ } = this.props.item;
+ let text;
+
+ if (blockedReason && blockingExtension) {
+ text = L10N.getFormatStr("networkMenu.blockedby", blockingExtension);
+ } else if (blockedReason) {
+ // If we receive a platform error code, print it as-is
+ if (typeof blockedReason == "string" && blockedReason.startsWith("NS_")) {
+ text = blockedReason;
+ } else {
+ text =
+ BLOCKED_REASON_MESSAGES[blockedReason] ||
+ L10N.getStr("networkMenu.blocked2");
+ }
+ } else if (fromCache || status === "304") {
+ text = SIZE_CACHED;
+ } else if (fromServiceWorker) {
+ text = SIZE_SERVICE_WORKER;
+ } else if (typeof transferredSize == "number") {
+ text = getFormattedSize(transferredSize);
+ if (isRacing && typeof isRacing == "boolean") {
+ text = L10N.getFormatStr("networkMenu.raced", text);
+ }
+ } else if (transferredSize === null) {
+ text = SIZE_UNAVAILABLE;
+ }
+
+ const title = text == SIZE_UNAVAILABLE ? SIZE_UNAVAILABLE_TITLE : text;
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-transferred",
+ title,
+ },
+ text
+ );
+ }
+}
+
+module.exports = RequestListColumnTransferredSize;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js
new file mode 100644
index 0000000000..783245dc19
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js
@@ -0,0 +1,45 @@
+/* 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 {
+ getAbbreviatedMimeType,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+class RequestListColumnType extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.mimeType !== nextProps.item.mimeType;
+ }
+
+ render() {
+ const { mimeType } = this.props.item;
+ let abbrevType;
+
+ if (mimeType) {
+ abbrevType = getAbbreviatedMimeType(mimeType);
+ }
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-type",
+ title: mimeType,
+ },
+ abbrevType
+ );
+ }
+}
+
+module.exports = RequestListColumnType;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js
new file mode 100644
index 0000000000..9782e9e820
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js
@@ -0,0 +1,89 @@
+/* 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 {
+ td,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.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 {
+ getFormattedIPAndPort,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const SecurityState = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/SecurityState.js")
+);
+const UPDATED_FILE_PROPS = ["remoteAddress", "securityState", "urlDetails"];
+
+class RequestListColumnUrl extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ onSecurityIconMouseDown: PropTypes.func.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_FILE_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const {
+ item: { urlDetails },
+ } = this.props;
+
+ const { item, onSecurityIconMouseDown } = this.props;
+
+ const {
+ remoteAddress,
+ remotePort,
+ urlDetails: { isLocal },
+ } = item;
+
+ const title = remoteAddress
+ ? ` (${getFormattedIPAndPort(remoteAddress, remotePort)})`
+ : "";
+
+ // deals with returning whole url
+ const originalURL = urlDetails.url;
+ const decodedFileURL = urlDetails.unicodeUrl;
+ const ORIGINAL_FILE_URL = L10N.getFormatStr(
+ "netRequest.originalFileURL.tooltip",
+ originalURL
+ );
+ const DECODED_FILE_URL = L10N.getFormatStr(
+ "netRequest.decodedFileURL.tooltip",
+ decodedFileURL
+ );
+ const urlToolTip =
+ originalURL === decodedFileURL
+ ? originalURL
+ : ORIGINAL_FILE_URL + "\n\n" + DECODED_FILE_URL;
+
+ return td(
+ {
+ className: "requests-list-column requests-list-url",
+ title: urlToolTip + title,
+ },
+ SecurityState({ item, onSecurityIconMouseDown, isLocal }),
+ originalURL
+ );
+ }
+}
+
+module.exports = RequestListColumnUrl;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js
new file mode 100644
index 0000000000..19523399b6
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js
@@ -0,0 +1,209 @@
+/* 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ getWaterfallScale,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+// List of properties of the timing info we want to create boxes for
+const {
+ TIMING_KEYS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const { div } = dom;
+
+const UPDATED_WATERFALL_ITEM_PROPS = ["eventTimings", "totalTime"];
+const UPDATED_WATERFALL_PROPS = [
+ "item",
+ "firstRequestStartedMs",
+ "scale",
+ "isVisible",
+];
+
+class RequestListColumnWaterfall extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ firstRequestStartedMs: PropTypes.number.isRequired,
+ item: PropTypes.object.isRequired,
+ onWaterfallMouseDown: PropTypes.func.isRequired,
+ scale: PropTypes.number,
+ isVisible: PropTypes.bool.isRequired,
+ };
+ }
+
+ constructor() {
+ super();
+ this.handleMouseOver = this.handleMouseOver.bind(this);
+ }
+
+ componentDidMount() {
+ const { connector, item } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["eventTimings"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ if (nextProps.isVisible && nextProps.item.totalTime) {
+ const { connector, item } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["eventTimings"]);
+ }
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ nextProps.isVisible &&
+ (!propertiesEqual(UPDATED_WATERFALL_PROPS, this.props, nextProps) ||
+ !propertiesEqual(
+ UPDATED_WATERFALL_ITEM_PROPS,
+ this.props.item,
+ nextProps.item
+ ))
+ );
+ }
+
+ handleMouseOver({ target }) {
+ if (!target.title) {
+ target.title = this.timingTooltip();
+ }
+ }
+
+ timingTooltip() {
+ const { eventTimings, totalTime } = this.props.item;
+ const tooltip = [];
+
+ if (eventTimings) {
+ for (const key of TIMING_KEYS) {
+ const width = eventTimings.timings[key];
+
+ if (width > 0) {
+ tooltip.push(
+ L10N.getFormatStr("netmonitor.waterfall.tooltip." + key, width)
+ );
+ }
+ }
+ }
+
+ if (typeof totalTime === "number") {
+ tooltip.push(
+ L10N.getFormatStr("netmonitor.waterfall.tooltip.total", totalTime)
+ );
+ }
+
+ return tooltip.join(L10N.getStr("netmonitor.waterfall.tooltip.separator"));
+ }
+
+ timingBoxes() {
+ const {
+ scale,
+ item: { eventTimings, totalTime },
+ } = this.props;
+ const boxes = [];
+
+ // Physical pixel as minimum size
+ const minPixel = 1 / window.devicePixelRatio;
+
+ if (typeof totalTime === "number") {
+ if (eventTimings) {
+ // Add a set of boxes representing timing information.
+ for (const key of TIMING_KEYS) {
+ if (eventTimings.timings[key] > 0) {
+ boxes.push(
+ div({
+ key,
+ className: `requests-list-timings-box ${key}`,
+ style: {
+ width: Math.max(eventTimings.timings[key] * scale, minPixel),
+ },
+ })
+ );
+ }
+ }
+ }
+ // Minimal box to at least show start and total time
+ if (!boxes.length) {
+ boxes.push(
+ div({
+ className: "requests-list-timings-box filler",
+ key: "filler",
+ style: { width: Math.max(totalTime * scale, minPixel) },
+ })
+ );
+ }
+
+ const title = L10N.getFormatStr("networkMenu.totalMS2", totalTime);
+ boxes.push(
+ div(
+ {
+ key: "total",
+ className: "requests-list-timings-total",
+ title,
+ },
+ title
+ )
+ );
+ } else {
+ // Pending requests are marked for start time
+ boxes.push(
+ div({
+ className: "requests-list-timings-box filler",
+ key: "pending",
+ style: { width: minPixel },
+ })
+ );
+ }
+
+ return boxes;
+ }
+
+ render() {
+ const {
+ firstRequestStartedMs,
+ item: { startedMs },
+ scale,
+ onWaterfallMouseDown,
+ } = this.props;
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-waterfall",
+ onMouseOver: this.handeMouseOver,
+ },
+ div(
+ {
+ className: "requests-list-timings",
+ style: {
+ paddingInlineStart: `${
+ (startedMs - firstRequestStartedMs) * scale
+ }px`,
+ },
+ onMouseDown: onWaterfallMouseDown,
+ },
+ this.timingBoxes()
+ )
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ scale: getWaterfallScale(state),
+}))(RequestListColumnWaterfall);
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListContent.js b/devtools/client/netmonitor/src/components/request-list/RequestListContent.js
new file mode 100644
index 0000000000..0ee91cc48e
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListContent.js
@@ -0,0 +1,524 @@
+/* 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");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ HTMLTooltip,
+} = require("resource://devtools/client/shared/widgets/tooltip/HTMLTooltip.js");
+
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ formDataURI,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getDisplayedRequests,
+ getColumns,
+ getSelectedRequest,
+ getClickedRequest,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+loader.lazyRequireGetter(
+ this,
+ "openRequestInTab",
+ "resource://devtools/client/netmonitor/src/utils/firefox/open-request-in-tab.js",
+ true
+);
+loader.lazyGetter(this, "setImageTooltip", function () {
+ return require("resource://devtools/client/shared/widgets/tooltip/ImageTooltipHelper.js")
+ .setImageTooltip;
+});
+loader.lazyGetter(this, "getImageDimensions", function () {
+ return require("resource://devtools/client/shared/widgets/tooltip/ImageTooltipHelper.js")
+ .getImageDimensions;
+});
+
+// Components
+const RequestListHeader = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListHeader.js")
+);
+const RequestListItem = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListItem.js")
+);
+const RequestListContextMenu = require("resource://devtools/client/netmonitor/src/widgets/RequestListContextMenu.js");
+
+const { div } = dom;
+
+// Tooltip show / hide delay in ms
+const REQUESTS_TOOLTIP_TOGGLE_DELAY = 500;
+// Tooltip image maximum dimension in px
+const REQUESTS_TOOLTIP_IMAGE_MAX_DIM = 400;
+
+const LEFT_MOUSE_BUTTON = 0;
+const MIDDLE_MOUSE_BUTTON = 1;
+const RIGHT_MOUSE_BUTTON = 2;
+
+/**
+ * Renders the actual contents of the request list.
+ */
+class RequestListContent extends Component {
+ static get propTypes() {
+ return {
+ blockedUrls: PropTypes.array.isRequired,
+ connector: PropTypes.object.isRequired,
+ columns: PropTypes.object.isRequired,
+ networkActionOpen: PropTypes.bool,
+ networkDetailsOpen: PropTypes.bool.isRequired,
+ networkDetailsWidth: PropTypes.number,
+ networkDetailsHeight: PropTypes.number,
+ cloneRequest: PropTypes.func.isRequired,
+ clickedRequest: PropTypes.object,
+ openDetailsPanelTab: PropTypes.func.isRequired,
+ openHTTPCustomRequestTab: PropTypes.func.isRequired,
+ closeHTTPCustomRequestTab: PropTypes.func.isRequired,
+ sendCustomRequest: PropTypes.func.isRequired,
+ sendHTTPCustomRequest: PropTypes.func.isRequired,
+ displayedRequests: PropTypes.array.isRequired,
+ firstRequestStartedMs: PropTypes.number.isRequired,
+ fromCache: PropTypes.bool,
+ onInitiatorBadgeMouseDown: PropTypes.func.isRequired,
+ onItemRightMouseButtonDown: PropTypes.func.isRequired,
+ onItemMouseDown: PropTypes.func.isRequired,
+ onSecurityIconMouseDown: PropTypes.func.isRequired,
+ onSelectDelta: PropTypes.func.isRequired,
+ onWaterfallMouseDown: PropTypes.func.isRequired,
+ openStatistics: PropTypes.func.isRequired,
+ openRequestBlockingAndAddUrl: PropTypes.func.isRequired,
+ openRequestBlockingAndDisableUrls: PropTypes.func.isRequired,
+ removeBlockedUrl: PropTypes.func.isRequired,
+ selectedActionBarTabId: PropTypes.string,
+ selectRequest: PropTypes.func.isRequired,
+ selectedRequest: PropTypes.object,
+ requestFilterTypes: PropTypes.object.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.onHover = this.onHover.bind(this);
+ this.onScroll = this.onScroll.bind(this);
+ this.onResize = this.onResize.bind(this);
+ this.onKeyDown = this.onKeyDown.bind(this);
+ this.openRequestInTab = this.openRequestInTab.bind(this);
+ this.onDoubleClick = this.onDoubleClick.bind(this);
+ this.onDragStart = this.onDragStart.bind(this);
+ this.onContextMenu = this.onContextMenu.bind(this);
+ this.onMouseDown = this.onMouseDown.bind(this);
+ this.hasOverflow = false;
+ this.onIntersect = this.onIntersect.bind(this);
+ this.intersectionObserver = null;
+ this.state = {
+ onscreenItems: new Set(),
+ };
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillMount() {
+ this.tooltip = new HTMLTooltip(window.parent.document, { type: "arrow" });
+ window.addEventListener("resize", this.onResize);
+ }
+
+ componentDidMount() {
+ // Install event handler for displaying a tooltip
+ this.tooltip.startTogglingOnHover(this.refs.scrollEl, this.onHover, {
+ toggleDelay: REQUESTS_TOOLTIP_TOGGLE_DELAY,
+ interactive: true,
+ });
+ // Install event handler to hide the tooltip on scroll
+ this.refs.scrollEl.addEventListener("scroll", this.onScroll, true);
+ this.onResize();
+ this.intersectionObserver = new IntersectionObserver(this.onIntersect, {
+ root: this.refs.scrollEl,
+ // Render 10% more columns for a scrolling headstart
+ rootMargin: "10%",
+ });
+ // Prime IntersectionObserver with existing entries
+ for (const item of this.refs.scrollEl.querySelectorAll(
+ ".request-list-item"
+ )) {
+ this.intersectionObserver.observe(item);
+ }
+ }
+
+ componentDidUpdate(prevProps) {
+ const output = this.refs.scrollEl;
+ if (!this.hasOverflow && output.scrollHeight > output.clientHeight) {
+ output.scrollTop = output.scrollHeight;
+ this.hasOverflow = true;
+ }
+ if (
+ prevProps.networkDetailsOpen !== this.props.networkDetailsOpen ||
+ prevProps.networkDetailsWidth !== this.props.networkDetailsWidth ||
+ prevProps.networkDetailsHeight !== this.props.networkDetailsHeight
+ ) {
+ this.onResize();
+ }
+ }
+
+ componentWillUnmount() {
+ this.refs.scrollEl.removeEventListener("scroll", this.onScroll, true);
+
+ // Uninstall the tooltip event handler
+ this.tooltip.stopTogglingOnHover();
+ window.removeEventListener("resize", this.onResize);
+ if (this.intersectionObserver !== null) {
+ this.intersectionObserver.disconnect();
+ this.intersectionObserver = null;
+ }
+ }
+
+ /*
+ * Removing onResize() method causes perf regression - too many repaints of the panel.
+ * So it is needed in ComponentDidMount and ComponentDidUpdate. See Bug 1532914.
+ */
+ onResize() {
+ const parent = this.refs.scrollEl.parentNode;
+ this.refs.scrollEl.style.width = parent.offsetWidth + "px";
+ this.refs.scrollEl.style.height = parent.offsetHeight + "px";
+ }
+
+ onIntersect(entries) {
+ // Track when off screen elements moved on screen to ensure updates
+ let onscreenDidChange = false;
+ const onscreenItems = new Set(this.state.onscreenItems);
+ for (const { target, isIntersecting } of entries) {
+ const { id } = target.dataset;
+ if (isIntersecting) {
+ if (onscreenItems.add(id)) {
+ onscreenDidChange = true;
+ }
+ } else {
+ onscreenItems.delete(id);
+ }
+ }
+ if (onscreenDidChange) {
+ // Remove ids that are no longer displayed
+ const itemIds = new Set(this.props.displayedRequests.map(({ id }) => id));
+ for (const id of onscreenItems) {
+ if (!itemIds.has(id)) {
+ onscreenItems.delete(id);
+ }
+ }
+ this.setState({ onscreenItems });
+ }
+ }
+
+ /**
+ * The predicate used when deciding whether a popup should be shown
+ * over a request item or not.
+ *
+ * @param Node target
+ * The element node currently being hovered.
+ * @param object tooltip
+ * The current tooltip instance.
+ * @return {Promise}
+ */
+ async onHover(target, tooltip) {
+ const itemEl = target.closest(".request-list-item");
+ if (!itemEl) {
+ return false;
+ }
+ const itemId = itemEl.dataset.id;
+ if (!itemId) {
+ return false;
+ }
+ const requestItem = this.props.displayedRequests.find(r => r.id == itemId);
+ if (!requestItem) {
+ return false;
+ }
+
+ if (!target.closest(".requests-list-file")) {
+ return false;
+ }
+
+ const { mimeType } = requestItem;
+ if (!mimeType || !mimeType.includes("image/")) {
+ return false;
+ }
+
+ const responseContent = await this.props.connector.requestData(
+ requestItem.id,
+ "responseContent"
+ );
+ const { encoding, text } = responseContent.content;
+ const src = formDataURI(mimeType, encoding, text);
+ const maxDim = REQUESTS_TOOLTIP_IMAGE_MAX_DIM;
+ const { naturalWidth, naturalHeight } = await getImageDimensions(
+ tooltip.doc,
+ src
+ );
+ const options = { maxDim, naturalWidth, naturalHeight };
+ setImageTooltip(tooltip, tooltip.doc, src, options);
+
+ return itemEl.querySelector(".requests-list-file");
+ }
+
+ /**
+ * Scroll listener for the requests menu view.
+ */
+ onScroll() {
+ this.tooltip.hide();
+ }
+
+ onMouseDown(evt, id, request) {
+ if (evt.button === LEFT_MOUSE_BUTTON) {
+ this.props.selectRequest(id, request);
+ } else if (evt.button === RIGHT_MOUSE_BUTTON) {
+ this.props.onItemRightMouseButtonDown(id);
+ } else if (evt.button === MIDDLE_MOUSE_BUTTON) {
+ this.onMiddleMouseButtonDown(request);
+ }
+ }
+
+ /**
+ * Handler for keyboard events. For arrow up/down, page up/down, home/end,
+ * move the selection up or down.
+ */
+ onKeyDown(evt) {
+ 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) {
+ // Prevent scrolling when pressing navigation keys.
+ evt.preventDefault();
+ evt.stopPropagation();
+ this.props.onSelectDelta(delta);
+ }
+ }
+
+ /**
+ * Opens selected item in a new tab.
+ */
+ async openRequestInTab(id, url, requestHeaders, requestPostData) {
+ requestHeaders =
+ requestHeaders ||
+ (await this.props.connector.requestData(id, "requestHeaders"));
+
+ requestPostData =
+ requestPostData ||
+ (await this.props.connector.requestData(id, "requestPostData"));
+
+ openRequestInTab(url, requestHeaders, requestPostData);
+ }
+
+ onDoubleClick({ id, url, requestHeaders, requestPostData }) {
+ this.openRequestInTab(id, url, requestHeaders, requestPostData);
+ }
+
+ onMiddleMouseButtonDown({ id, url, requestHeaders, requestPostData }) {
+ this.openRequestInTab(id, url, requestHeaders, requestPostData);
+ }
+
+ onDragStart(evt, { url }) {
+ evt.dataTransfer.setData("text/plain", url);
+ }
+
+ onContextMenu(evt) {
+ evt.preventDefault();
+ const { clickedRequest, displayedRequests, blockedUrls } = this.props;
+
+ if (!this.contextMenu) {
+ const {
+ connector,
+ cloneRequest,
+ openDetailsPanelTab,
+ openHTTPCustomRequestTab,
+ closeHTTPCustomRequestTab,
+ sendCustomRequest,
+ sendHTTPCustomRequest,
+ openStatistics,
+ openRequestBlockingAndAddUrl,
+ openRequestBlockingAndDisableUrls,
+ removeBlockedUrl,
+ } = this.props;
+ this.contextMenu = new RequestListContextMenu({
+ connector,
+ cloneRequest,
+ openDetailsPanelTab,
+ openHTTPCustomRequestTab,
+ closeHTTPCustomRequestTab,
+ sendCustomRequest,
+ sendHTTPCustomRequest,
+ openStatistics,
+ openRequestBlockingAndAddUrl,
+ openRequestBlockingAndDisableUrls,
+ removeBlockedUrl,
+ openRequestInTab: this.openRequestInTab,
+ });
+ }
+
+ this.contextMenu.open(evt, clickedRequest, displayedRequests, blockedUrls);
+ }
+
+ render() {
+ const {
+ connector,
+ columns,
+ displayedRequests,
+ firstRequestStartedMs,
+ onInitiatorBadgeMouseDown,
+ onSecurityIconMouseDown,
+ onWaterfallMouseDown,
+ requestFilterTypes,
+ selectedRequest,
+ selectedActionBarTabId,
+ openRequestBlockingAndAddUrl,
+ openRequestBlockingAndDisableUrls,
+ networkActionOpen,
+ networkDetailsOpen,
+ } = this.props;
+
+ return div(
+ {
+ ref: "scrollEl",
+ className: "requests-list-scroll",
+ },
+ [
+ dom.table(
+ {
+ className: "requests-list-table",
+ key: "table",
+ },
+ RequestListHeader(),
+ dom.tbody(
+ {
+ ref: "rowGroupEl",
+ className: "requests-list-row-group",
+ tabIndex: 0,
+ onKeyDown: this.onKeyDown,
+ },
+ displayedRequests.map((item, index) => {
+ return RequestListItem({
+ blocked: !!item.blockedReason,
+ firstRequestStartedMs,
+ fromCache: item.status === "304" || item.fromCache,
+ networkDetailsOpen,
+ networkActionOpen,
+ selectedActionBarTabId,
+ connector,
+ columns,
+ item,
+ index,
+ isSelected: item.id === selectedRequest?.id,
+ isVisible: this.state.onscreenItems.has(item.id),
+ key: item.id,
+ intersectionObserver: this.intersectionObserver,
+ onContextMenu: this.onContextMenu,
+ onDoubleClick: () => this.onDoubleClick(item),
+ onDragStart: evt => this.onDragStart(evt, item),
+ onMouseDown: evt => this.onMouseDown(evt, item.id, item),
+ onInitiatorBadgeMouseDown: () =>
+ onInitiatorBadgeMouseDown(item.cause),
+ onSecurityIconMouseDown: () =>
+ onSecurityIconMouseDown(item.securityState),
+ onWaterfallMouseDown,
+ requestFilterTypes,
+ openRequestBlockingAndAddUrl,
+ openRequestBlockingAndDisableUrls,
+ });
+ })
+ )
+ ), // end of requests-list-row-group">
+ dom.div({
+ className: "requests-list-anchor",
+ key: "anchor",
+ }),
+ ]
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ blockedUrls: state.requestBlocking.blockedUrls
+ .map(({ enabled, url }) => (enabled ? url : null))
+ .filter(Boolean),
+ columns: getColumns(state),
+ networkActionOpen: state.ui.networkActionOpen,
+ networkDetailsOpen: state.ui.networkDetailsOpen,
+ networkDetailsWidth: state.ui.networkDetailsWidth,
+ networkDetailsHeight: state.ui.networkDetailsHeight,
+ clickedRequest: getClickedRequest(state),
+ displayedRequests: getDisplayedRequests(state),
+ firstRequestStartedMs: state.requests.firstStartedMs,
+ selectedActionBarTabId: state.ui.selectedActionBarTabId,
+ selectedRequest: getSelectedRequest(state),
+ requestFilterTypes: state.filters.requestFilterTypes,
+ }),
+ (dispatch, props) => ({
+ cloneRequest: id => dispatch(Actions.cloneRequest(id)),
+ openDetailsPanelTab: () => dispatch(Actions.openNetworkDetails(true)),
+ openHTTPCustomRequestTab: () =>
+ dispatch(Actions.openHTTPCustomRequest(true)),
+ closeHTTPCustomRequestTab: () =>
+ dispatch(Actions.openHTTPCustomRequest(false)),
+ sendCustomRequest: () => dispatch(Actions.sendCustomRequest()),
+ sendHTTPCustomRequest: request =>
+ dispatch(Actions.sendHTTPCustomRequest(request)),
+ openStatistics: open =>
+ dispatch(Actions.openStatistics(props.connector, open)),
+ openRequestBlockingAndAddUrl: url =>
+ dispatch(Actions.openRequestBlockingAndAddUrl(url)),
+ removeBlockedUrl: url => dispatch(Actions.removeBlockedUrl(url)),
+ openRequestBlockingAndDisableUrls: url =>
+ dispatch(Actions.openRequestBlockingAndDisableUrls(url)),
+ /**
+ * A handler that opens the stack trace tab when a stack trace is available
+ */
+ onInitiatorBadgeMouseDown: cause => {
+ if (cause.lastFrame) {
+ dispatch(Actions.selectDetailsPanelTab("stack-trace"));
+ }
+ },
+ selectRequest: (id, request) =>
+ dispatch(Actions.selectRequest(id, request)),
+ onItemRightMouseButtonDown: id => dispatch(Actions.rightClickRequest(id)),
+ onItemMouseDown: id => dispatch(Actions.selectRequest(id)),
+ /**
+ * A handler that opens the security tab in the details view if secure or
+ * broken security indicator is clicked.
+ */
+ onSecurityIconMouseDown: securityState => {
+ if (securityState && securityState !== "insecure") {
+ dispatch(Actions.selectDetailsPanelTab("security"));
+ }
+ },
+ onSelectDelta: delta => dispatch(Actions.selectDelta(delta)),
+ /**
+ * A handler that opens the timing sidebar panel if the waterfall is clicked.
+ */
+ onWaterfallMouseDown: () => {
+ dispatch(Actions.selectDetailsPanelTab("timings"));
+ },
+ })
+)(RequestListContent);
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js b/devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js
new file mode 100644
index 0000000000..318078b782
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js
@@ -0,0 +1,107 @@
+/* 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");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ ACTIVITY_TYPE,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getPerformanceAnalysisURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+
+// Components
+const MDNLink = createFactory(
+ require("resource://devtools/client/shared/components/MdnLink.js")
+);
+
+const { button, div, span } = dom;
+
+const RELOAD_NOTICE_1 = L10N.getStr("netmonitor.reloadNotice1");
+const RELOAD_NOTICE_2 = L10N.getStr("netmonitor.reloadNotice2");
+const RELOAD_NOTICE_3 = L10N.getStr("netmonitor.reloadNotice3");
+const RELOAD_NOTICE_BT = L10N.getStr("netmonitor.emptyBrowserToolbox");
+const PERFORMANCE_NOTICE_1 = L10N.getStr("netmonitor.perfNotice1");
+const PERFORMANCE_NOTICE_2 = L10N.getStr("netmonitor.perfNotice2");
+const PERFORMANCE_NOTICE_3 = L10N.getStr("netmonitor.perfNotice3");
+const PERFORMANCE_LEARN_MORE = L10N.getStr("charts.learnMore");
+
+/**
+ * UI displayed when the request list is empty. Contains instructions on reloading
+ * the page and on triggering performance analysis of the page.
+ */
+class RequestListEmptyNotice extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ onReloadClick: PropTypes.func.isRequired,
+ onPerfClick: PropTypes.func.isRequired,
+ };
+ }
+
+ render() {
+ const { connector } = this.props;
+ const toolbox = connector.getToolbox();
+
+ return div(
+ {
+ className: "request-list-empty-notice",
+ },
+ !toolbox.isBrowserToolbox
+ ? div(
+ { className: "notice-reload-message empty-notice-element" },
+ span(null, RELOAD_NOTICE_1),
+ button(
+ {
+ className: "devtools-button requests-list-reload-notice-button",
+ "data-standalone": true,
+ onClick: this.props.onReloadClick,
+ },
+ RELOAD_NOTICE_2
+ ),
+ span(null, RELOAD_NOTICE_3)
+ )
+ : div(
+ { className: "notice-reload-message empty-notice-element" },
+ span(null, RELOAD_NOTICE_BT)
+ ),
+ !toolbox.isBrowserToolbox
+ ? div(
+ { className: "notice-perf-message empty-notice-element" },
+ span(null, PERFORMANCE_NOTICE_1),
+ button({
+ title: PERFORMANCE_NOTICE_3,
+ className: "devtools-button requests-list-perf-notice-button",
+ "data-standalone": true,
+ onClick: this.props.onPerfClick,
+ }),
+ span(null, PERFORMANCE_NOTICE_2),
+ MDNLink({
+ url: getPerformanceAnalysisURL(),
+ title: PERFORMANCE_LEARN_MORE,
+ })
+ )
+ : null
+ );
+ }
+}
+
+module.exports = connect(undefined, (dispatch, props) => ({
+ onPerfClick: () => dispatch(Actions.openStatistics(props.connector, true)),
+ onReloadClick: () =>
+ props.connector.triggerActivity(ACTIVITY_TYPE.RELOAD.WITH_CACHE_DEFAULT),
+}))(RequestListEmptyNotice);
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListHeader.js b/devtools/client/netmonitor/src/components/request-list/RequestListHeader.js
new file mode 100644
index 0000000000..d02e993b02
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListHeader.js
@@ -0,0 +1,731 @@
+/* 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 {
+ createRef,
+ 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");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ getTheme,
+ addThemeObserver,
+ removeThemeObserver,
+} = require("resource://devtools/client/shared/theme.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ HEADERS,
+ REQUESTS_WATERFALL,
+ MIN_COLUMN_WIDTH,
+ DEFAULT_COLUMN_WIDTH,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ getColumns,
+ getWaterfallScale,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const RequestListHeaderContextMenu = require("resource://devtools/client/netmonitor/src/widgets/RequestListHeaderContextMenu.js");
+const WaterfallBackground = require("resource://devtools/client/netmonitor/src/widgets/WaterfallBackground.js");
+const Draggable = createFactory(
+ require("resource://devtools/client/shared/components/splitter/Draggable.js")
+);
+
+const { div, button } = dom;
+
+/**
+ * Render the request list header with sorting arrows for columns.
+ * Displays tick marks in the waterfall column header.
+ * Also draws the waterfall background canvas and updates it when needed.
+ */
+class RequestListHeader extends Component {
+ static get propTypes() {
+ return {
+ columns: PropTypes.object.isRequired,
+ resetColumns: PropTypes.func.isRequired,
+ resetSorting: PropTypes.func.isRequired,
+ resizeWaterfall: PropTypes.func.isRequired,
+ scale: PropTypes.number,
+ sort: PropTypes.object,
+ sortBy: PropTypes.func.isRequired,
+ toggleColumn: PropTypes.func.isRequired,
+ waterfallWidth: PropTypes.number,
+ columnsData: PropTypes.object.isRequired,
+ setColumnsWidth: PropTypes.func.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.requestListHeader = createRef();
+
+ this.onContextMenu = this.onContextMenu.bind(this);
+ this.drawBackground = this.drawBackground.bind(this);
+ this.resizeWaterfall = this.resizeWaterfall.bind(this);
+ this.waterfallDivisionLabels = this.waterfallDivisionLabels.bind(this);
+ this.waterfallLabel = this.waterfallLabel.bind(this);
+ this.onHeaderClick = this.onHeaderClick.bind(this);
+ this.resizeColumnToFitContent = this.resizeColumnToFitContent.bind(this);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillMount() {
+ const { resetColumns, resetSorting, toggleColumn } = this.props;
+ this.contextMenu = new RequestListHeaderContextMenu({
+ resetColumns,
+ resetSorting,
+ toggleColumn,
+ resizeColumnToFitContent: this.resizeColumnToFitContent,
+ });
+ }
+
+ componentDidMount() {
+ // Create the object that takes care of drawing the waterfall canvas background
+ this.background = new WaterfallBackground(document);
+ this.drawBackground();
+ // When visible columns add up to less or more than 100% => update widths in prefs.
+ if (this.shouldUpdateWidths()) {
+ this.updateColumnsWidth();
+ }
+ this.resizeWaterfall();
+ window.addEventListener("resize", this.resizeWaterfall);
+ addThemeObserver(this.drawBackground);
+ }
+
+ componentDidUpdate() {
+ this.drawBackground();
+ // check if the widths in prefs need to be updated
+ // e.g. after hide/show column
+ if (this.shouldUpdateWidths()) {
+ this.updateColumnsWidth();
+ this.resizeWaterfall();
+ }
+ }
+
+ componentWillUnmount() {
+ this.background.destroy();
+ this.background = null;
+ window.removeEventListener("resize", this.resizeWaterfall);
+ removeThemeObserver(this.drawBackground);
+ }
+
+ /**
+ * Helper method to get the total width of cell's content.
+ * Used for resizing columns to fit their content.
+ */
+ totalCellWidth(cellEl) {
+ return [...cellEl.childNodes]
+ .map(cNode => {
+ if (cNode.nodeType === 3) {
+ // if it's text node
+ return Math.ceil(
+ cNode.getBoxQuads()[0].p2.x - cNode.getBoxQuads()[0].p1.x
+ );
+ }
+ return cNode.getBoundingClientRect().width;
+ })
+ .reduce((a, b) => a + b, 0);
+ }
+
+ /**
+ * Resize column to fit its content.
+ * Additionally, resize other columns (starting from last) to compensate.
+ */
+ resizeColumnToFitContent(name) {
+ const headerRef = this.refs[`${name}Header`];
+ const parentEl = headerRef.closest(".requests-list-table");
+ const width = headerRef.getBoundingClientRect().width;
+ const parentWidth = parentEl.getBoundingClientRect().width;
+ const items = parentEl.querySelectorAll(".request-list-item");
+ const columnIndex = headerRef.cellIndex;
+ const widths = [...items].map(item =>
+ this.totalCellWidth(item.children[columnIndex])
+ );
+
+ const minW = this.getMinWidth(name);
+
+ // Add 11 to account for cell padding (padding-right + padding-left = 9px), not accurate.
+ let maxWidth = 11 + Math.max.apply(null, widths);
+
+ if (maxWidth < minW) {
+ maxWidth = minW;
+ }
+
+ // Pixel value which, if added to this column's width, will fit its content.
+ let change = maxWidth - width;
+
+ // Max change we can do while taking other columns into account.
+ let maxAllowedChange = 0;
+ const visibleColumns = this.getVisibleColumns();
+ const newWidths = [];
+
+ // Calculate new widths for other columns to compensate.
+ // Start from the 2nd last column if last column is waterfall.
+ // This is done to comply with the existing resizing behavior.
+ const delta =
+ visibleColumns[visibleColumns.length - 1].name === "waterfall" ? 2 : 1;
+
+ for (let i = visibleColumns.length - delta; i > 0; i--) {
+ if (i !== columnIndex) {
+ const columnName = visibleColumns[i].name;
+ const columnHeaderRef = this.refs[`${columnName}Header`];
+ const columnWidth = columnHeaderRef.getBoundingClientRect().width;
+ const minWidth = this.getMinWidth(columnName);
+ const newWidth = columnWidth - change;
+
+ // If this column can compensate for all the remaining change.
+ if (newWidth >= minWidth) {
+ maxAllowedChange += change;
+ change = 0;
+ newWidths.push({
+ name: columnName,
+ width: this.px2percent(newWidth, parentWidth),
+ });
+ break;
+ } else {
+ // Max change we can do in this column.
+ let maxColumnChange = columnWidth - minWidth;
+ maxColumnChange = maxColumnChange > change ? change : maxColumnChange;
+ maxAllowedChange += maxColumnChange;
+ change -= maxColumnChange;
+ newWidths.push({
+ name: columnName,
+ width: this.px2percent(columnWidth - maxColumnChange, parentWidth),
+ });
+ }
+ }
+ }
+ newWidths.push({
+ name,
+ width: this.px2percent(width + maxAllowedChange, parentWidth),
+ });
+ this.props.setColumnsWidth(newWidths);
+ }
+
+ onContextMenu(evt) {
+ evt.preventDefault();
+ this.contextMenu.open(evt, this.props.columns);
+ }
+
+ onHeaderClick(evt, headerName) {
+ const { sortBy, resetSorting } = this.props;
+ if (evt.button == 1) {
+ // reset sort state on middle click
+ resetSorting();
+ } else {
+ sortBy(headerName);
+ }
+ }
+
+ drawBackground() {
+ // The background component is theme dependent, so add the current theme to the props.
+ const props = Object.assign({}, this.props, {
+ theme: getTheme(),
+ });
+ this.background.draw(props);
+ }
+
+ resizeWaterfall() {
+ const { waterfallHeader } = this.refs;
+ if (waterfallHeader) {
+ // Measure its width and update the 'waterfallWidth' property in the store.
+ // The 'waterfallWidth' will be further updated on every window resize.
+ window.cancelIdleCallback(this._resizeTimerId);
+ this._resizeTimerId = window.requestIdleCallback(() =>
+ this.props.resizeWaterfall(
+ waterfallHeader.getBoundingClientRect().width
+ )
+ );
+ }
+ }
+
+ /**
+ * Build the waterfall header - timing tick marks with the right spacing
+ */
+ waterfallDivisionLabels(waterfallWidth, scale) {
+ const labels = [];
+
+ // Build new millisecond tick labels...
+ const timingStep = REQUESTS_WATERFALL.HEADER_TICKS_MULTIPLE;
+ let scaledStep = scale * timingStep;
+
+ // Ignore any divisions that would end up being too close to each other.
+ while (scaledStep < REQUESTS_WATERFALL.HEADER_TICKS_SPACING_MIN) {
+ scaledStep *= 2;
+ }
+
+ // Insert one label for each division on the current scale.
+ for (let x = 0; x < waterfallWidth; x += scaledStep) {
+ const millisecondTime = x / scale;
+ let divisionScale = "millisecond";
+
+ // If the division is greater than 1 minute.
+ if (millisecondTime > 60000) {
+ divisionScale = "minute";
+ } else if (millisecondTime > 1000) {
+ // If the division is greater than 1 second.
+ divisionScale = "second";
+ }
+
+ let width = ((x + scaledStep) | 0) - (x | 0);
+ // Adjust the first marker for the borders
+ if (x == 0) {
+ width -= 2;
+ }
+ // Last marker doesn't need a width specified at all
+ if (x + scaledStep >= waterfallWidth) {
+ width = undefined;
+ }
+
+ labels.push(
+ div(
+ {
+ key: labels.length,
+ className: "requests-list-timings-division",
+ "data-division-scale": divisionScale,
+ style: { width },
+ },
+ getFormattedTime(millisecondTime)
+ )
+ );
+ }
+
+ return labels;
+ }
+
+ waterfallLabel(waterfallWidth, scale, label) {
+ let className = "button-text requests-list-waterfall-label-wrapper";
+
+ if (waterfallWidth !== null && scale !== null) {
+ label = this.waterfallDivisionLabels(waterfallWidth, scale);
+ className += " requests-list-waterfall-visible";
+ }
+
+ return div({ className }, label);
+ }
+
+ // Dragging Events
+
+ /**
+ * Set 'resizing' cursor on entire container dragging.
+ * This avoids cursor-flickering when the mouse leaves
+ * the column-resizer area (happens frequently).
+ */
+ onStartMove() {
+ // Set cursor to dragging
+ const container = document.querySelector(".request-list-container");
+ container.style.cursor = "ew-resize";
+ // Class .dragging is used to disable pointer events while dragging - see css.
+ this.requestListHeader.classList.add("dragging");
+ }
+
+ /**
+ * A handler that calculates the new width of the columns
+ * based on mouse position and adjusts the width.
+ */
+ onMove(name, x) {
+ const parentEl = document.querySelector(".requests-list-headers");
+ const parentWidth = parentEl.getBoundingClientRect().width;
+
+ // Get the current column handle and save its old width
+ // before changing so we can compute the adjustment in width
+ const headerRef = this.refs[`${name}Header`];
+ const headerRefRect = headerRef.getBoundingClientRect();
+ const oldWidth = headerRefRect.width;
+
+ // Get the column handle that will compensate the width change.
+ const compensateHeaderName = this.getCompensateHeader();
+
+ if (name === compensateHeaderName) {
+ // this is the case where we are resizing waterfall
+ this.moveWaterfall(x, parentWidth);
+ return;
+ }
+
+ const compensateHeaderRef = this.refs[`${compensateHeaderName}Header`];
+ const compensateHeaderRefRect = compensateHeaderRef.getBoundingClientRect();
+ const oldCompensateWidth = compensateHeaderRefRect.width;
+ const sumOfBothColumns = oldWidth + oldCompensateWidth;
+
+ // Get minimal widths for both changed columns (in px).
+ const minWidth = this.getMinWidth(name);
+ const minCompensateWidth = this.getMinWidth(compensateHeaderName);
+
+ // Calculate new width (according to the mouse x-position) and set to style.
+ // Do not allow to set it below minWidth.
+ let newWidth =
+ document.dir == "ltr" ? x - headerRefRect.left : headerRefRect.right - x;
+ newWidth = Math.max(newWidth, minWidth);
+ headerRef.style.width = `${this.px2percent(newWidth, parentWidth)}%`;
+ const adjustment = oldWidth - newWidth;
+
+ // Calculate new compensate width as the original width + adjustment.
+ // Do not allow to set it below minCompensateWidth.
+ const newCompensateWidth = Math.max(
+ adjustment + oldCompensateWidth,
+ minCompensateWidth
+ );
+ compensateHeaderRef.style.width = `${this.px2percent(
+ newCompensateWidth,
+ parentWidth
+ )}%`;
+
+ // Do not allow to reset size of column when compensate column is at minWidth.
+ if (newCompensateWidth === minCompensateWidth) {
+ headerRef.style.width = `${this.px2percent(
+ sumOfBothColumns - newCompensateWidth,
+ parentWidth
+ )}%`;
+ }
+ }
+
+ /**
+ * After resizing - we get the width for each 'column'
+ * and convert it into % and store it in user prefs.
+ * Also resets the 'resizing' cursor back to initial.
+ */
+ onStopMove() {
+ this.updateColumnsWidth();
+ // If waterfall is visible and width has changed, call resizeWaterfall.
+ const waterfallRef = this.refs.waterfallHeader;
+ if (waterfallRef) {
+ const { waterfallWidth } = this.props;
+ const realWaterfallWidth = waterfallRef.getBoundingClientRect().width;
+ if (Math.round(waterfallWidth) !== Math.round(realWaterfallWidth)) {
+ this.resizeWaterfall();
+ }
+ }
+
+ // Restore cursor back to default.
+ const container = document.querySelector(".request-list-container");
+ container.style.cursor = "initial";
+ this.requestListHeader.classList.remove("dragging");
+ }
+
+ /**
+ * Helper method to get the name of the column that will compensate
+ * the width change. It should be the last column before waterfall,
+ * (if waterfall visible) otherwise it is simply the last visible column.
+ */
+ getCompensateHeader() {
+ const visibleColumns = this.getVisibleColumns();
+ const lastColumn = visibleColumns[visibleColumns.length - 1].name;
+ const delta = lastColumn === "waterfall" ? 2 : 1;
+ return visibleColumns[visibleColumns.length - delta].name;
+ }
+
+ /**
+ * Called from onMove() when resizing waterfall column
+ * because waterfall is a special case, where ALL other
+ * columns are made smaller when waterfall is bigger and vice versa.
+ */
+ moveWaterfall(x, parentWidth) {
+ const visibleColumns = this.getVisibleColumns();
+ const minWaterfall = this.getMinWidth("waterfall");
+ const waterfallRef = this.refs.waterfallHeader;
+
+ // Compute and set style.width for waterfall.
+ const waterfallRefRect = waterfallRef.getBoundingClientRect();
+ const oldWidth = waterfallRefRect.width;
+ const adjustment =
+ document.dir == "ltr"
+ ? waterfallRefRect.left - x
+ : x - waterfallRefRect.right;
+ if (this.allColumnsAtMinWidth() && adjustment > 0) {
+ // When we want to make waterfall wider but all
+ // other columns are already at minWidth => return.
+ return;
+ }
+
+ const newWidth = Math.max(oldWidth + adjustment, minWaterfall);
+
+ // Now distribute evenly the change in width to all other columns except waterfall.
+ const changeInWidth = oldWidth - newWidth;
+ const widths = this.autoSizeWidths(changeInWidth, visibleColumns);
+
+ // Set the new computed width for waterfall into array widths.
+ widths[widths.length - 1] = newWidth;
+
+ // Update style for all columns from array widths.
+ let i = 0;
+ visibleColumns.forEach(col => {
+ const { name } = col;
+ const headerRef = this.refs[`${name}Header`];
+ headerRef.style.width = `${this.px2percent(widths[i], parentWidth)}%`;
+ i++;
+ });
+ }
+
+ /**
+ * Helper method that checks if all columns have reached their minWidth.
+ * This can happen when making waterfall column wider.
+ */
+ allColumnsAtMinWidth() {
+ const visibleColumns = this.getVisibleColumns();
+ // Do not check width for waterfall because
+ // when all are getting smaller, waterfall is getting bigger.
+ for (let i = 0; i < visibleColumns.length - 1; i++) {
+ const { name } = visibleColumns[i];
+ const headerRef = this.refs[`${name}Header`];
+ const minColWidth = this.getMinWidth(name);
+ if (headerRef.getBoundingClientRect().width > minColWidth) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Method takes the total change in width for waterfall column
+ * and distributes it among all other columns. Returns an array
+ * where all visible columns have newly computed width in pixels.
+ */
+ autoSizeWidths(changeInWidth, visibleColumns) {
+ const widths = visibleColumns.map(col => {
+ const headerRef = this.refs[`${col.name}Header`];
+ const colWidth = headerRef.getBoundingClientRect().width;
+ return colWidth;
+ });
+
+ // Divide changeInWidth among all columns but waterfall (that's why -1).
+ const changeInWidthPerColumn = changeInWidth / (widths.length - 1);
+
+ while (changeInWidth) {
+ const lastChangeInWidth = changeInWidth;
+ // In the loop adjust all columns except last one - waterfall
+ for (let i = 0; i < widths.length - 1; i++) {
+ const { name } = visibleColumns[i];
+ const minColWidth = this.getMinWidth(name);
+ const newColWidth = Math.max(
+ widths[i] + changeInWidthPerColumn,
+ minColWidth
+ );
+
+ widths[i] = newColWidth;
+ if (changeInWidth > 0) {
+ changeInWidth -= newColWidth - widths[i];
+ } else {
+ changeInWidth += newColWidth - widths[i];
+ }
+ if (!changeInWidth) {
+ break;
+ }
+ }
+ if (lastChangeInWidth == changeInWidth) {
+ break;
+ }
+ }
+ return widths;
+ }
+
+ /**
+ * Method returns 'true' - if the column widths need to be updated
+ * when the total % is less or more than 100%.
+ * It returns 'false' if they add up to 100% => no need to update.
+ */
+ shouldUpdateWidths() {
+ const visibleColumns = this.getVisibleColumns();
+ let totalPercent = 0;
+
+ visibleColumns.forEach(col => {
+ const { name } = col;
+ const headerRef = this.refs[`${name}Header`];
+ // Get column width from style.
+ let widthFromStyle = 0;
+ // In case the column is in visibleColumns but has display:none
+ // we don't want to count its style.width into totalPercent.
+ if (headerRef.getBoundingClientRect().width > 0) {
+ widthFromStyle = headerRef.style.width.slice(0, -1);
+ }
+ totalPercent += +widthFromStyle; // + converts it to a number
+ });
+
+ // Do not update if total percent is from 99-101% or when it is 0
+ // - it means that no columns are displayed (e.g. other panel is currently selected).
+ return Math.round(totalPercent) !== 100 && totalPercent !== 0;
+ }
+
+ /**
+ * Method reads real width of each column header
+ * and updates the style.width for that header.
+ * It returns updated columnsData.
+ */
+ updateColumnsWidth() {
+ const visibleColumns = this.getVisibleColumns();
+ const parentEl = document.querySelector(".requests-list-headers");
+ const parentElRect = parentEl.getBoundingClientRect();
+ const parentWidth = parentElRect.width;
+ const newWidths = [];
+ visibleColumns.forEach(col => {
+ const { name } = col;
+ const headerRef = this.refs[`${name}Header`];
+ const headerWidth = headerRef.getBoundingClientRect().width;
+
+ // Get actual column width, change into %, update style
+ const width = this.px2percent(headerWidth, parentWidth);
+
+ if (width > 0) {
+ // This prevents saving width 0 for waterfall when it is not showing for
+ // @media (max-width: 700px)
+ newWidths.push({ name, width });
+ }
+ });
+ this.props.setColumnsWidth(newWidths);
+ }
+
+ /**
+ * Helper method to convert pixels into percent based on parent container width
+ */
+ px2percent(pxWidth, parentWidth) {
+ const percent = Math.round(((100 * pxWidth) / parentWidth) * 100) / 100;
+ return percent;
+ }
+
+ /**
+ * Helper method to get visibleColumns;
+ */
+ getVisibleColumns() {
+ const { columns } = this.props;
+ return HEADERS.filter(header => columns[header.name]);
+ }
+
+ /**
+ * Helper method to get minWidth from columnsData;
+ */
+ getMinWidth(colName) {
+ const { columnsData } = this.props;
+ if (columnsData.has(colName)) {
+ return columnsData.get(colName).minWidth;
+ }
+ return MIN_COLUMN_WIDTH;
+ }
+
+ /**
+ * Render one column header from the table headers.
+ */
+ renderColumn(header) {
+ const { columnsData } = this.props;
+ const visibleColumns = this.getVisibleColumns();
+ const lastVisibleColumn = visibleColumns[visibleColumns.length - 1].name;
+ const { name } = header;
+ const boxName = header.boxName || name;
+ const label = header.noLocalization
+ ? name
+ : L10N.getStr(`netmonitor.toolbar.${header.label || name}`);
+
+ const { scale, sort, waterfallWidth } = this.props;
+ let sorted, sortedTitle;
+ const active = sort.type == name ? true : undefined;
+
+ if (active) {
+ sorted = sort.ascending ? "ascending" : "descending";
+ sortedTitle = L10N.getStr(
+ sort.ascending ? "networkMenu.sortedAsc" : "networkMenu.sortedDesc"
+ );
+ }
+
+ // If the pref for this column width exists, set the style
+ // otherwise use default.
+ let colWidth = DEFAULT_COLUMN_WIDTH;
+ if (columnsData.has(name)) {
+ const oneColumnEl = columnsData.get(name);
+ colWidth = oneColumnEl.width;
+ }
+ const columnStyle = {
+ width: colWidth + "%",
+ };
+
+ // Support for columns resizing is currently hidden behind a pref.
+ const draggable = Draggable({
+ className: "column-resizer ",
+ title: L10N.getStr("netmonitor.toolbar.resizeColumnToFitContent.title"),
+ onStart: () => this.onStartMove(),
+ onStop: () => this.onStopMove(),
+ onMove: x => this.onMove(name, x),
+ onDoubleClick: () => this.resizeColumnToFitContent(name),
+ });
+
+ return dom.th(
+ {
+ id: `requests-list-${boxName}-header-box`,
+ className: `requests-list-column requests-list-${boxName}`,
+ scope: "col",
+ style: columnStyle,
+ key: name,
+ ref: `${name}Header`,
+ // Used to style the next column.
+ "data-active": active,
+ },
+ button(
+ {
+ id: `requests-list-${name}-button`,
+ className: `requests-list-header-button`,
+ "data-sorted": sorted,
+ "data-name": name,
+ title: sortedTitle ? `${label} (${sortedTitle})` : label,
+ onClick: evt => this.onHeaderClick(evt, name),
+ },
+ name === "waterfall"
+ ? this.waterfallLabel(waterfallWidth, scale, label)
+ : div({ className: "button-text" }, label),
+ div({ className: "button-icon" })
+ ),
+ name !== lastVisibleColumn && draggable
+ );
+ }
+
+ /**
+ * Render all columns in the table header
+ */
+ renderColumns() {
+ const visibleColumns = this.getVisibleColumns();
+ return visibleColumns.map(header => this.renderColumn(header));
+ }
+
+ render() {
+ return dom.thead(
+ { className: "requests-list-headers-group" },
+ dom.tr(
+ {
+ className: "requests-list-headers",
+ onContextMenu: this.onContextMenu,
+ ref: node => {
+ this.requestListHeader = node;
+ },
+ },
+ this.renderColumns()
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ columns: getColumns(state),
+ columnsData: state.ui.columnsData,
+ firstRequestStartedMs: state.requests.firstStartedMs,
+ scale: getWaterfallScale(state),
+ sort: state.sort,
+ timingMarkers: state.timingMarkers,
+ waterfallWidth: state.ui.waterfallWidth,
+ }),
+ dispatch => ({
+ resetColumns: () => dispatch(Actions.resetColumns()),
+ resetSorting: () => dispatch(Actions.sortBy(null)),
+ resizeWaterfall: width => dispatch(Actions.resizeWaterfall(width)),
+ sortBy: type => dispatch(Actions.sortBy(type)),
+ toggleColumn: column => dispatch(Actions.toggleColumn(column)),
+ setColumnsWidth: widths => dispatch(Actions.setColumnsWidth(widths)),
+ })
+)(RequestListHeader);
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListItem.js b/devtools/client/netmonitor/src/components/request-list/RequestListItem.js
new file mode 100644
index 0000000000..5c70b44e00
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListItem.js
@@ -0,0 +1,412 @@
+/* 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");
+const {
+ fetchNetworkUpdatePacket,
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ PANELS,
+ RESPONSE_HEADERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Components
+/* global
+ RequestListColumnInitiator,
+ RequestListColumnContentSize,
+ RequestListColumnCookies,
+ RequestListColumnDomain,
+ RequestListColumnFile,
+ RequestListColumnMethod,
+ RequestListColumnProtocol,
+ RequestListColumnRemoteIP,
+ RequestListColumnResponseHeader,
+ RequestListColumnScheme,
+ RequestListColumnSetCookies,
+ RequestListColumnStatus,
+ RequestListColumnTime,
+ RequestListColumnTransferredSize,
+ RequestListColumnType,
+ RequestListColumnUrl,
+ RequestListColumnWaterfall,
+ RequestListColumnPriority
+*/
+loader.lazyGetter(this, "RequestListColumnInitiator", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnContentSize", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnCookies", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnDomain", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnFile", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnUrl", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnMethod", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnProtocol", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnRemoteIP", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnResponseHeader", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnTime", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnScheme", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnSetCookies", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnStatus", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnTransferredSize", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnType", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnWaterfall", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnPriority", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js")
+ );
+});
+
+/**
+ * Used by shouldComponentUpdate: compare two items, and compare only properties
+ * relevant for rendering the RequestListItem. Other properties (like request and
+ * response headers, cookies, bodies) are ignored. These are very useful for the
+ * network details, but not here.
+ */
+const UPDATED_REQ_ITEM_PROPS = [
+ "mimeType",
+ "eventTimings",
+ "securityState",
+ "status",
+ "statusText",
+ "fromCache",
+ "isRacing",
+ "fromServiceWorker",
+ "method",
+ "url",
+ "remoteAddress",
+ "cause",
+ "contentSize",
+ "transferredSize",
+ "startedMs",
+ "totalTime",
+ "requestCookies",
+ "requestHeaders",
+ "responseCookies",
+ "responseHeaders",
+ "waitingTime",
+ "isEventStream",
+ "priority",
+];
+
+const UPDATED_REQ_PROPS = [
+ "firstRequestStartedMs",
+ "index",
+ "networkDetailsOpen",
+ "isSelected",
+ "isVisible",
+ "requestFilterTypes",
+];
+
+/**
+ * Used by render: renders the given ColumnComponent if the flag for this column
+ * is set in the columns prop. The list of props are used to determine which of
+ * RequestListItem's need to be passed to the ColumnComponent. Any objects contained
+ * in that list are passed as props verbatim.
+ */
+const COLUMN_COMPONENTS = [
+ { column: "status", ColumnComponent: RequestListColumnStatus },
+ { column: "method", ColumnComponent: RequestListColumnMethod },
+ {
+ column: "domain",
+ ColumnComponent: RequestListColumnDomain,
+ props: ["onSecurityIconMouseDown"],
+ },
+ {
+ column: "file",
+ ColumnComponent: RequestListColumnFile,
+ props: ["onWaterfallMouseDown"],
+ },
+ {
+ column: "url",
+ ColumnComponent: RequestListColumnUrl,
+ props: ["onSecurityIconMouseDown"],
+ },
+ { column: "protocol", ColumnComponent: RequestListColumnProtocol },
+ { column: "scheme", ColumnComponent: RequestListColumnScheme },
+ { column: "remoteip", ColumnComponent: RequestListColumnRemoteIP },
+ {
+ column: "initiator",
+ ColumnComponent: RequestListColumnInitiator,
+ props: ["onInitiatorBadgeMouseDown"],
+ },
+ { column: "type", ColumnComponent: RequestListColumnType },
+ {
+ column: "cookies",
+ ColumnComponent: RequestListColumnCookies,
+ props: ["connector"],
+ },
+ {
+ column: "setCookies",
+ ColumnComponent: RequestListColumnSetCookies,
+ props: ["connector"],
+ },
+ { column: "transferred", ColumnComponent: RequestListColumnTransferredSize },
+ { column: "contentSize", ColumnComponent: RequestListColumnContentSize },
+ { column: "priority", ColumnComponent: RequestListColumnPriority },
+ {
+ column: "startTime",
+ ColumnComponent: RequestListColumnTime,
+ props: ["connector", "firstRequestStartedMs", { type: "start" }],
+ },
+ {
+ column: "endTime",
+ ColumnComponent: RequestListColumnTime,
+ props: ["connector", "firstRequestStartedMs", { type: "end" }],
+ },
+ {
+ column: "responseTime",
+ ColumnComponent: RequestListColumnTime,
+ props: ["connector", "firstRequestStartedMs", { type: "response" }],
+ },
+ {
+ column: "duration",
+ ColumnComponent: RequestListColumnTime,
+ props: ["connector", "firstRequestStartedMs", { type: "duration" }],
+ },
+ {
+ column: "latency",
+ ColumnComponent: RequestListColumnTime,
+ props: ["connector", "firstRequestStartedMs", { type: "latency" }],
+ },
+];
+
+/**
+ * Render one row in the request list.
+ */
+class RequestListItem extends Component {
+ static get propTypes() {
+ return {
+ blocked: PropTypes.bool,
+ connector: PropTypes.object.isRequired,
+ columns: PropTypes.object.isRequired,
+ item: PropTypes.object.isRequired,
+ index: PropTypes.number.isRequired,
+ isSelected: PropTypes.bool.isRequired,
+ isVisible: PropTypes.bool.isRequired,
+ firstRequestStartedMs: PropTypes.number.isRequired,
+ fromCache: PropTypes.bool,
+ networkActionOpen: PropTypes.bool,
+ networkDetailsOpen: PropTypes.bool,
+ onInitiatorBadgeMouseDown: PropTypes.func.isRequired,
+ onDoubleClick: PropTypes.func.isRequired,
+ onDragStart: PropTypes.func.isRequired,
+ onContextMenu: PropTypes.func.isRequired,
+ onFocusedNodeChange: PropTypes.func,
+ onMouseDown: PropTypes.func.isRequired,
+ onSecurityIconMouseDown: PropTypes.func.isRequired,
+ onWaterfallMouseDown: PropTypes.func.isRequired,
+ requestFilterTypes: PropTypes.object.isRequired,
+ selectedActionBarTabId: PropTypes.string,
+ intersectionObserver: PropTypes.object,
+ };
+ }
+
+ componentDidMount() {
+ if (this.props.isSelected) {
+ this.refs.listItem.focus();
+ }
+ if (this.props.intersectionObserver) {
+ this.props.intersectionObserver.observe(this.refs.listItem);
+ }
+
+ const { connector, item, requestFilterTypes } = this.props;
+ // Filtering XHR & WS require to lazily fetch requestHeaders & responseHeaders
+ if (requestFilterTypes.xhr || requestFilterTypes.ws) {
+ fetchNetworkUpdatePacket(connector.requestData, item, [
+ "requestHeaders",
+ "responseHeaders",
+ ]);
+ }
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { connector, item, requestFilterTypes } = nextProps;
+ // Filtering XHR & WS require to lazily fetch requestHeaders & responseHeaders
+ if (requestFilterTypes.xhr || requestFilterTypes.ws) {
+ fetchNetworkUpdatePacket(connector.requestData, item, [
+ "requestHeaders",
+ "responseHeaders",
+ ]);
+ }
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ !propertiesEqual(
+ UPDATED_REQ_ITEM_PROPS,
+ this.props.item,
+ nextProps.item
+ ) ||
+ !propertiesEqual(UPDATED_REQ_PROPS, this.props, nextProps) ||
+ this.props.columns !== nextProps.columns
+ );
+ }
+
+ componentDidUpdate(prevProps) {
+ if (!prevProps.isSelected && this.props.isSelected) {
+ this.refs.listItem.focus();
+ if (this.props.onFocusedNodeChange) {
+ this.props.onFocusedNodeChange();
+ }
+ }
+ }
+
+ componentWillUnmount() {
+ if (this.props.intersectionObserver) {
+ this.props.intersectionObserver.unobserve(this.refs.listItem);
+ }
+ }
+
+ render() {
+ const {
+ blocked,
+ connector,
+ columns,
+ item,
+ index,
+ isSelected,
+ isVisible,
+ firstRequestStartedMs,
+ fromCache,
+ networkActionOpen,
+ onDoubleClick,
+ onDragStart,
+ onContextMenu,
+ onMouseDown,
+ onWaterfallMouseDown,
+ selectedActionBarTabId,
+ } = this.props;
+
+ const classList = ["request-list-item", index % 2 ? "odd" : "even"];
+ isSelected && classList.push("selected");
+ fromCache && classList.push("fromCache");
+ blocked && classList.push("blocked");
+
+ return dom.tr(
+ {
+ ref: "listItem",
+ className: classList.join(" "),
+ "data-id": item.id,
+ draggable:
+ !blocked &&
+ networkActionOpen &&
+ selectedActionBarTabId === PANELS.BLOCKING,
+ tabIndex: 0,
+ onContextMenu,
+ onMouseDown,
+ onDoubleClick,
+ onDragStart,
+ },
+ ...COLUMN_COMPONENTS.filter(({ column }) => columns[column]).map(
+ ({ column, ColumnComponent, props: columnProps }) => {
+ return ColumnComponent({
+ key: column,
+ item,
+ ...(columnProps || []).reduce((acc, keyOrObject) => {
+ if (typeof keyOrObject == "string") {
+ acc[keyOrObject] = this.props[keyOrObject];
+ } else {
+ Object.assign(acc, keyOrObject);
+ }
+ return acc;
+ }, {}),
+ });
+ }
+ ),
+ ...RESPONSE_HEADERS.filter(header => columns[header]).map(header =>
+ RequestListColumnResponseHeader({
+ connector,
+ item,
+ header,
+ })
+ ),
+ // The last column is Waterfall (aka Timeline)
+ columns.waterfall &&
+ RequestListColumnWaterfall({
+ connector,
+ firstRequestStartedMs,
+ item,
+ onWaterfallMouseDown,
+ isVisible,
+ })
+ );
+ }
+}
+
+module.exports = RequestListItem;
diff --git a/devtools/client/netmonitor/src/components/request-list/moz.build b/devtools/client/netmonitor/src/components/request-list/moz.build
new file mode 100644
index 0000000000..22f0602b00
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/moz.build
@@ -0,0 +1,29 @@
+# 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(
+ "RequestList.js",
+ "RequestListColumnContentSize.js",
+ "RequestListColumnCookies.js",
+ "RequestListColumnDomain.js",
+ "RequestListColumnFile.js",
+ "RequestListColumnInitiator.js",
+ "RequestListColumnMethod.js",
+ "RequestListColumnPriority.js",
+ "RequestListColumnProtocol.js",
+ "RequestListColumnRemoteIP.js",
+ "RequestListColumnResponseHeader.js",
+ "RequestListColumnScheme.js",
+ "RequestListColumnSetCookies.js",
+ "RequestListColumnStatus.js",
+ "RequestListColumnTime.js",
+ "RequestListColumnTransferredSize.js",
+ "RequestListColumnType.js",
+ "RequestListColumnUrl.js",
+ "RequestListColumnWaterfall.js",
+ "RequestListContent.js",
+ "RequestListEmptyNotice.js",
+ "RequestListHeader.js",
+ "RequestListItem.js",
+)
diff --git a/devtools/client/netmonitor/src/components/search/SearchPanel.js b/devtools/client/netmonitor/src/components/search/SearchPanel.js
new file mode 100644
index 0000000000..11301a7d9c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/search/SearchPanel.js
@@ -0,0 +1,264 @@
+/* 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, span } = dom;
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.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 TreeViewClass = require("resource://devtools/client/shared/components/tree/TreeView.js");
+const TreeView = createFactory(TreeViewClass);
+const LabelCell = createFactory(
+ require("resource://devtools/client/shared/components/tree/LabelCell.js")
+);
+const {
+ SearchProvider,
+} = require("resource://devtools/client/netmonitor/src/components/search/search-provider.js");
+const Toolbar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/search/Toolbar.js")
+);
+const StatusBar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/search/StatusBar.js")
+);
+const {
+ limitTooltipLength,
+} = require("resource://devtools/client/netmonitor/src/utils/tooltips.js");
+// There are two levels in the search panel tree hierarchy:
+// 0: Resource - represents the source request object
+// 1: Search Result - represents a match coming from the parent resource
+const RESOURCE_LEVEL = 0;
+const SEARCH_RESULT_LEVEL = 1;
+
+/**
+ * This component is responsible for rendering all search results
+ * coming from the current search.
+ */
+class SearchPanel extends Component {
+ static get propTypes() {
+ return {
+ clearSearchResults: PropTypes.func.isRequired,
+ openSearch: PropTypes.func.isRequired,
+ closeSearch: PropTypes.func.isRequired,
+ search: PropTypes.func.isRequired,
+ caseSensitive: PropTypes.bool,
+ connector: PropTypes.object.isRequired,
+ addSearchQuery: PropTypes.func.isRequired,
+ query: PropTypes.string.isRequired,
+ results: PropTypes.array,
+ navigate: PropTypes.func.isRequired,
+ isDisplaying: PropTypes.bool.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.searchboxRef = createRef();
+ this.renderValue = this.renderValue.bind(this);
+ this.renderLabel = this.renderLabel.bind(this);
+ this.onClickTreeRow = this.onClickTreeRow.bind(this);
+ this.provider = SearchProvider;
+ }
+
+ componentDidMount() {
+ if (this.searchboxRef) {
+ this.searchboxRef.current.focus();
+ }
+ }
+
+ componentDidUpdate(prevProps) {
+ if (this.props.isDisplaying && !prevProps.isDisplaying) {
+ this.searchboxRef.current.focus();
+ }
+ }
+
+ onClickTreeRow(path, event, member) {
+ if (member.object.parentResource) {
+ this.props.navigate(member.object);
+ }
+ }
+
+ /**
+ * Custom TreeView label rendering. The search result
+ * value isn't rendered in separate column, but in the
+ * same column as the label (to save space).
+ */
+ renderLabel(props) {
+ const { member } = props;
+ const level = member.level || 0;
+ const className = level == RESOURCE_LEVEL ? "resourceCell" : "resultCell";
+
+ // Customize label rendering by adding a suffix/value
+ const renderSuffix = () => {
+ return dom.span(
+ {
+ className,
+ },
+ " ",
+ this.renderValue(props)
+ );
+ };
+
+ return LabelCell({
+ ...props,
+ title:
+ member.level == 1
+ ? limitTooltipLength(member.object.value)
+ : this.provider.getResourceTooltipLabel(member.object),
+ renderSuffix,
+ });
+ }
+
+ renderTree() {
+ const { results } = this.props;
+ return TreeView({
+ object: results,
+ provider: this.provider,
+ expandableStrings: false,
+ renderLabelCell: this.renderLabel,
+ columns: [],
+ onClickRow: this.onClickTreeRow,
+ });
+ }
+
+ /**
+ * Custom tree value rendering. This method is responsible for
+ * rendering highlighted query string within the search result
+ * result tree.
+ */
+ renderValue(props) {
+ const { member } = props;
+ const { query, caseSensitive } = this.props;
+
+ // Handle only second level (zero based) that displays
+ // the search result. Find the query string inside the
+ // search result value (`props.object`) and render it
+ // within a span element with proper class name.
+ // level 0 = resource name
+ if (member.level === SEARCH_RESULT_LEVEL) {
+ const { object } = member;
+
+ // Handles multiple matches in a string
+ if (object.startIndex && object.startIndex.length > 1) {
+ let indexStart = 0;
+ const allMatches = object.startIndex.map((match, index) => {
+ if (index === 0) {
+ indexStart = match - 50;
+ }
+
+ const highlightedMatch = [
+ span(
+ { key: "match-" + match },
+ object.value.substring(indexStart, match - query.length)
+ ),
+ span(
+ {
+ className: "query-match",
+ key: "match-" + match + "-highlight",
+ },
+ object.value.substring(match - query.length, match)
+ ),
+ ];
+
+ indexStart = match;
+
+ return highlightedMatch;
+ });
+
+ return span(
+ {
+ title: limitTooltipLength(object.value),
+ },
+ allMatches
+ );
+ }
+
+ const indexStart = caseSensitive
+ ? object.value.indexOf(query)
+ : object.value.toLowerCase().indexOf(query.toLowerCase());
+ const indexEnd = indexStart + query.length;
+
+ // Handles a match in a string
+ if (indexStart >= 0) {
+ return span(
+ { title: limitTooltipLength(object.value) },
+ span({}, object.value.substring(0, indexStart)),
+ span(
+ { className: "query-match" },
+ object.value.substring(indexStart, indexStart + query.length)
+ ),
+ span({}, object.value.substring(indexEnd, object.value.length))
+ );
+ }
+
+ // Default for key:value matches where query might not
+ // be present in the value, but found in the key.
+ return span(
+ { title: limitTooltipLength(object.value) },
+ span({}, object.value)
+ );
+ }
+
+ return this.provider.getValue(member.object);
+ }
+
+ render() {
+ const {
+ openSearch,
+ closeSearch,
+ clearSearchResults,
+ connector,
+ addSearchQuery,
+ search,
+ } = this.props;
+ return div(
+ { className: "search-panel", style: { width: "100%" } },
+ Toolbar({
+ searchboxRef: this.searchboxRef,
+ openSearch,
+ closeSearch,
+ clearSearchResults,
+ addSearchQuery,
+ search,
+ connector,
+ }),
+ div(
+ { className: "search-panel-content", style: { width: "100%" } },
+ this.renderTree()
+ ),
+ StatusBar()
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ query: state.search.query,
+ caseSensitive: state.search.caseSensitive,
+ results: state.search.results,
+ ongoingSearch: state.search.ongoingSearch,
+ isDisplaying: state.ui.selectedActionBarTabId === PANELS.SEARCH,
+ status: state.search.status,
+ }),
+ dispatch => ({
+ closeSearch: () => dispatch(Actions.closeSearch()),
+ openSearch: () => dispatch(Actions.openSearch()),
+ search: () => dispatch(Actions.search()),
+ clearSearchResults: () => dispatch(Actions.clearSearchResults()),
+ addSearchQuery: query => dispatch(Actions.addSearchQuery(query)),
+ navigate: searchResult => dispatch(Actions.navigate(searchResult)),
+ })
+)(SearchPanel);
diff --git a/devtools/client/netmonitor/src/components/search/StatusBar.js b/devtools/client/netmonitor/src/components/search/StatusBar.js
new file mode 100644
index 0000000000..31ecdeffe9
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/search/StatusBar.js
@@ -0,0 +1,97 @@
+/* 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 {
+ getSearchStatus,
+ getSearchResultCount,
+ getSearchResourceCount,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const { PluralForm } = require("resource://devtools/shared/plural-form.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const { div, span } = dom;
+const {
+ SEARCH_STATUS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * Displays the number of lines found for results and resource count (files)
+ */
+class StatusBar extends Component {
+ static get propTypes() {
+ return {
+ status: PropTypes.string,
+ resultsCount: PropTypes.string,
+ resourceCount: PropTypes.string,
+ };
+ }
+
+ getSearchStatusDoneLabel(lines, files) {
+ const matchingLines = PluralForm.get(
+ lines,
+ L10N.getStr("netmonitor.search.status.labels.matchingLines")
+ ).replace("#1", lines);
+ const matchingFiles = PluralForm.get(
+ files,
+ L10N.getStr("netmonitor.search.status.labels.fileCount")
+ ).replace("#1", files);
+
+ return L10N.getFormatStr(
+ "netmonitor.search.status.labels.done",
+ matchingLines,
+ matchingFiles
+ );
+ }
+
+ renderStatus() {
+ const { status, resultsCount, resourceCount } = this.props;
+
+ switch (status) {
+ case SEARCH_STATUS.FETCHING:
+ return L10N.getStr("netmonitor.search.status.labels.fetching");
+ case SEARCH_STATUS.DONE:
+ return this.getSearchStatusDoneLabel(resultsCount, resourceCount);
+ case SEARCH_STATUS.ERROR:
+ return L10N.getStr("netmonitor.search.status.labels.error");
+ case SEARCH_STATUS.CANCELED:
+ return L10N.getStr("netmonitor.search.status.labels.canceled");
+ default:
+ return "";
+ }
+ }
+
+ render() {
+ const { status } = this.props;
+ return div(
+ { className: "devtools-toolbar devtools-toolbar-bottom" },
+ div(
+ {
+ className: "status-bar-label",
+ title: this.renderStatus(),
+ },
+ this.renderStatus(),
+ status === SEARCH_STATUS.FETCHING
+ ? span({ className: "img loader" })
+ : ""
+ )
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ status: getSearchStatus(state),
+ resultsCount: getSearchResultCount(state),
+ resourceCount: getSearchResourceCount(state),
+}))(StatusBar);
diff --git a/devtools/client/netmonitor/src/components/search/Toolbar.js b/devtools/client/netmonitor/src/components/search/Toolbar.js
new file mode 100644
index 0000000000..0f39cfa17a
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/search/Toolbar.js
@@ -0,0 +1,160 @@
+/* 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 {
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.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 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 SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+
+/**
+ * Network Search toolbar component.
+ *
+ * Provides tools for greater control over search.
+ */
+class Toolbar extends Component {
+ static get propTypes() {
+ return {
+ searchboxRef: PropTypes.object.isRequired,
+ clearSearchResults: PropTypes.func.isRequired,
+ search: PropTypes.func.isRequired,
+ closeSearch: PropTypes.func.isRequired,
+ addSearchQuery: PropTypes.func.isRequired,
+ clearSearchResultAndCancel: PropTypes.func.isRequired,
+ caseSensitive: PropTypes.bool.isRequired,
+ toggleCaseSensitiveSearch: PropTypes.func.isRequired,
+ connector: PropTypes.object.isRequired,
+ query: PropTypes.string,
+ };
+ }
+
+ /**
+ * Render a separator.
+ */
+ renderSeparator() {
+ return span({ className: "devtools-separator" });
+ }
+
+ /**
+ * Handles what we do when key is pressed in search input.
+ * @param event
+ * @param conn
+ */
+ onKeyDown(event, connector) {
+ switch (event.key) {
+ case "Escape":
+ event.preventDefault();
+ this.props.closeSearch();
+ break;
+ case "Enter":
+ event.preventDefault();
+ this.props.addSearchQuery(event.target.value);
+ this.props.search(connector, event.target.value);
+ break;
+ }
+ }
+
+ renderModifiers() {
+ return div(
+ { className: "search-modifiers" },
+ span({ className: "pipe-divider" }),
+ this.renderCaseSensitiveButton()
+ );
+ }
+
+ /**
+ * Render a clear button to clear search results.
+ */
+ renderClearButton() {
+ return button({
+ className:
+ "devtools-button devtools-clear-icon ws-frames-list-clear-button",
+ title: L10N.getStr("netmonitor.search.toolbar.clear"),
+ onClick: () => {
+ this.props.clearSearchResults();
+ },
+ });
+ }
+
+ /**
+ * Render the case sensitive search modifier button
+ */
+ renderCaseSensitiveButton() {
+ const { caseSensitive, toggleCaseSensitiveSearch } = this.props;
+ const active = caseSensitive ? "checked" : "";
+
+ return button({
+ id: "devtools-network-search-caseSensitive",
+ className: `devtools-button ${active}`,
+ title: L10N.getStr("netmonitor.search.toolbar.caseSensitive"),
+ onClick: toggleCaseSensitiveSearch,
+ });
+ }
+
+ /**
+ * Render Search box.
+ */
+ renderFilterBox() {
+ const { addSearchQuery, clearSearchResultAndCancel, connector, query } =
+ this.props;
+ return SearchBox({
+ keyShortcut: "CmdOrCtrl+Shift+F",
+ placeholder: L10N.getStr("netmonitor.search.toolbar.inputPlaceholder"),
+ type: "search",
+ delay: FILTER_SEARCH_DELAY,
+ ref: this.props.searchboxRef,
+ value: query,
+ onClearButtonClick: () => clearSearchResultAndCancel(),
+ onChange: newQuery => addSearchQuery(newQuery),
+ onKeyDown: event => this.onKeyDown(event, connector),
+ });
+ }
+
+ render() {
+ return div(
+ {
+ id: "netmonitor-toolbar-container",
+ className: "devtools-toolbar devtools-input-toolbar",
+ },
+ this.renderFilterBox(),
+ this.renderModifiers()
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ caseSensitive: state.search.caseSensitive,
+ query: state.search.query,
+ }),
+ dispatch => ({
+ closeSearch: () => dispatch(Actions.closeSearch()),
+ openSearch: () => dispatch(Actions.openSearch()),
+ clearSearchResultAndCancel: () =>
+ dispatch(Actions.clearSearchResultAndCancel()),
+ toggleCaseSensitiveSearch: () =>
+ dispatch(Actions.toggleCaseSensitiveSearch()),
+ search: (connector, query) => dispatch(Actions.search(connector, query)),
+ addSearchQuery: query => dispatch(Actions.addSearchQuery(query)),
+ })
+)(Toolbar);
diff --git a/devtools/client/netmonitor/src/components/search/moz.build b/devtools/client/netmonitor/src/components/search/moz.build
new file mode 100644
index 0000000000..7c48392d10
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/search/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(
+ "search-provider.js",
+ "SearchPanel.js",
+ "StatusBar.js",
+ "Toolbar.js",
+)
diff --git a/devtools/client/netmonitor/src/components/search/search-provider.js b/devtools/client/netmonitor/src/components/search/search-provider.js
new file mode 100644
index 0000000000..d076f35856
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/search/search-provider.js
@@ -0,0 +1,91 @@
+/* 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 {
+ ObjectProvider,
+} = require("resource://devtools/client/shared/components/tree/ObjectProvider.js");
+const {
+ getFileName,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+/**
+ * This provider is responsible for providing data from the
+ * search reducer to the SearchPanel.
+ */
+const SearchProvider = {
+ ...ObjectProvider,
+
+ getChildren(object) {
+ if (Array.isArray(object)) {
+ return object;
+ } else if (object.resource) {
+ return object.results;
+ } else if (object.type) {
+ return [];
+ }
+ return ObjectProvider.getLabel(object);
+ },
+
+ hasChildren(object) {
+ return !!this.getChildren(object).length;
+ },
+
+ getLabel(object) {
+ if (object.resource) {
+ return this.getResourceLabel(object);
+ } else if (object.label) {
+ return object.label;
+ }
+ return ObjectProvider.getLabel(object);
+ },
+
+ getValue(object) {
+ if (object.resource) {
+ return "";
+ } else if (object.type) {
+ return object.value;
+ }
+ return ObjectProvider.getValue(object);
+ },
+
+ getKey(object) {
+ if (object.resource) {
+ return object.resource.id;
+ } else if (object.type) {
+ return object.key;
+ }
+ return ObjectProvider.getKey(object);
+ },
+
+ getType(object) {
+ if (object.resource) {
+ return "resource";
+ } else if (object.type) {
+ return "result";
+ }
+ return ObjectProvider.getType(object);
+ },
+
+ getResourceTooltipLabel(object) {
+ const { resource } = object;
+ if (resource.urlDetails?.url) {
+ return resource.urlDetails.url;
+ }
+
+ return this.getResourceLabel(object);
+ },
+
+ getResourceLabel(object) {
+ return (
+ getFileName(object.resource.urlDetails.baseNameWithQuery) ||
+ object.resource.urlDetails.host
+ );
+ },
+};
+
+module.exports = {
+ SearchProvider,
+};
diff --git a/devtools/client/netmonitor/src/connector/firefox-data-provider.js b/devtools/client/netmonitor/src/connector/firefox-data-provider.js
new file mode 100644
index 0000000000..9cdf6fc1d7
--- /dev/null
+++ b/devtools/client/netmonitor/src/connector/firefox-data-provider.js
@@ -0,0 +1,832 @@
+/* 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/. */
+/* eslint-disable block-scoped-var */
+
+"use strict";
+
+const {
+ EVENTS,
+ TEST_EVENTS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const { CurlUtils } = require("resource://devtools/client/shared/curl.js");
+const {
+ fetchHeaders,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const {
+ getLongStringFullText,
+} = require("resource://devtools/client/shared/string-utils.js");
+
+/**
+ * This object is responsible for fetching additional HTTP
+ * data from the backend over RDP protocol.
+ *
+ * The object also keeps track of RDP requests in-progress,
+ * so it's possible to determine whether all has been fetched
+ * or not.
+ */
+class FirefoxDataProvider {
+ /**
+ * Constructor for data provider
+ *
+ * @param {Object} commands Object defined from devtools/shared/commands to interact with the devtools backend
+ * @param {Object} actions set of actions fired during data fetching process.
+ * @param {Object} owner all events are fired on this object.
+ */
+ constructor({ commands, actions, owner }) {
+ // Options
+ this.commands = commands;
+ this.actions = actions || {};
+ this.actionsEnabled = true;
+
+ // Allow requesting of on-demand network data, this would be `false` when requests
+ // are cleared (as we clear also on the backend), and will be flipped back
+ // to true on the next `onNetworkResourceAvailable` call.
+ this._requestDataEnabled = true;
+
+ // `_requestDataEnabled` can only be used to prevent new calls to
+ // requestData. For pending/already started calls, we need to check if
+ // clear() was called during the call, which is the purpose of this counter.
+ this._lastRequestDataClearId = 0;
+
+ this.owner = owner;
+
+ // This holds stacktraces infomation temporarily. Stacktrace resources
+ // can come before or after (out of order) their related network events.
+ // This will hold stacktrace related info from the NETWORK_EVENT_STACKTRACE resource
+ // for the NETWORK_EVENT resource and vice versa.
+ this.stackTraces = new Map();
+ // Map of the stacktrace information keyed by the actor id's
+ this.stackTraceRequestInfoByActorID = new Map();
+
+ // For tracking unfinished requests
+ this.pendingRequests = new Set();
+
+ // Map[key string => Promise] used by `requestData` to prevent requesting the same
+ // request data twice.
+ this.lazyRequestData = new Map();
+
+ // Fetching data from the backend
+ this.getLongString = this.getLongString.bind(this);
+
+ // Event handlers
+ this.onNetworkResourceAvailable =
+ this.onNetworkResourceAvailable.bind(this);
+ this.onNetworkResourceUpdated = this.onNetworkResourceUpdated.bind(this);
+
+ this.onWebSocketOpened = this.onWebSocketOpened.bind(this);
+ this.onWebSocketClosed = this.onWebSocketClosed.bind(this);
+ this.onFrameSent = this.onFrameSent.bind(this);
+ this.onFrameReceived = this.onFrameReceived.bind(this);
+
+ this.onEventSourceConnectionClosed =
+ this.onEventSourceConnectionClosed.bind(this);
+ this.onEventReceived = this.onEventReceived.bind(this);
+ this.setEventStreamFlag = this.setEventStreamFlag.bind(this);
+ }
+
+ /*
+ * Cleans up all the internal states, this usually done before navigation
+ * (without the persist flag on).
+ */
+ clear() {
+ this.stackTraces.clear();
+ this.pendingRequests.clear();
+ this.lazyRequestData.clear();
+ this.stackTraceRequestInfoByActorID.clear();
+ this._requestDataEnabled = false;
+ this._lastRequestDataClearId++;
+ }
+
+ destroy() {
+ // TODO: clear() is called in the middle of the lifecycle of the
+ // FirefoxDataProvider, for clarity we are exposing it as a separate method.
+ // `destroy` should be updated to nullify relevant instance properties.
+ this.clear();
+ }
+
+ /**
+ * Enable/disable firing redux actions (enabled by default).
+ *
+ * @param {boolean} enable Set to true to fire actions.
+ */
+ enableActions(enable) {
+ this.actionsEnabled = enable;
+ }
+
+ /**
+ * Add a new network request to application state.
+ *
+ * @param {string} id request id
+ * @param {object} resource resource payload will be added to application state
+ */
+ async addRequest(id, resource) {
+ // Add to the pending requests which helps when deciding if the request is complete.
+ this.pendingRequests.add(id);
+
+ if (this.actionsEnabled && this.actions.addRequest) {
+ await this.actions.addRequest(id, resource, true);
+ }
+
+ this.emit(EVENTS.REQUEST_ADDED, id);
+ }
+
+ /**
+ * Update a network request if it already exists in application state.
+ *
+ * @param {string} id request id
+ * @param {object} data data payload will be updated to application state
+ */
+ async updateRequest(id, data) {
+ const {
+ responseContent,
+ responseCookies,
+ responseHeaders,
+ requestCookies,
+ requestHeaders,
+ requestPostData,
+ responseCache,
+ } = data;
+
+ // fetch request detail contents in parallel
+ const [
+ responseContentObj,
+ requestHeadersObj,
+ responseHeadersObj,
+ postDataObj,
+ requestCookiesObj,
+ responseCookiesObj,
+ responseCacheObj,
+ ] = await Promise.all([
+ this.fetchResponseContent(responseContent),
+ this.fetchRequestHeaders(requestHeaders),
+ this.fetchResponseHeaders(responseHeaders),
+ this.fetchPostData(requestPostData),
+ this.fetchRequestCookies(requestCookies),
+ this.fetchResponseCookies(responseCookies),
+ this.fetchResponseCache(responseCache),
+ ]);
+
+ const payload = Object.assign(
+ {},
+ data,
+ responseContentObj,
+ requestHeadersObj,
+ responseHeadersObj,
+ postDataObj,
+ requestCookiesObj,
+ responseCookiesObj,
+ responseCacheObj
+ );
+
+ if (this.actionsEnabled && this.actions.updateRequest) {
+ await this.actions.updateRequest(id, payload, true);
+ }
+
+ return payload;
+ }
+
+ async fetchResponseContent(responseContent) {
+ const payload = {};
+ if (responseContent?.content) {
+ const { text } = responseContent.content;
+ const response = await this.getLongString(text);
+ responseContent.content.text = response;
+ payload.responseContent = responseContent;
+ }
+ return payload;
+ }
+
+ async fetchRequestHeaders(requestHeaders) {
+ const payload = {};
+ if (requestHeaders?.headers?.length) {
+ const headers = await fetchHeaders(requestHeaders, this.getLongString);
+ if (headers) {
+ payload.requestHeaders = headers;
+ }
+ }
+ return payload;
+ }
+
+ async fetchResponseHeaders(responseHeaders) {
+ const payload = {};
+ if (responseHeaders?.headers?.length) {
+ const headers = await fetchHeaders(responseHeaders, this.getLongString);
+ if (headers) {
+ payload.responseHeaders = headers;
+ }
+ }
+ return payload;
+ }
+
+ async fetchPostData(requestPostData) {
+ const payload = {};
+ if (requestPostData?.postData) {
+ const { text } = requestPostData.postData;
+ const postData = await this.getLongString(text);
+ const headers = CurlUtils.getHeadersFromMultipartText(postData);
+
+ // Calculate total header size and don't forget to include
+ // two new-line characters at the end.
+ const headersSize = headers.reduce((acc, { name, value }) => {
+ return acc + name.length + value.length + 2;
+ }, 0);
+
+ requestPostData.postData.text = postData;
+ payload.requestPostData = {
+ ...requestPostData,
+ uploadHeaders: { headers, headersSize },
+ };
+ }
+ return payload;
+ }
+
+ async fetchRequestCookies(requestCookies) {
+ const payload = {};
+ if (requestCookies) {
+ const reqCookies = [];
+ // request store cookies in requestCookies or requestCookies.cookies
+ const cookies = requestCookies.cookies
+ ? requestCookies.cookies
+ : requestCookies;
+ // make sure cookies is iterable
+ if (typeof cookies[Symbol.iterator] === "function") {
+ for (const cookie of cookies) {
+ reqCookies.push(
+ Object.assign({}, cookie, {
+ value: await this.getLongString(cookie.value),
+ })
+ );
+ }
+ if (reqCookies.length) {
+ payload.requestCookies = reqCookies;
+ }
+ }
+ }
+ return payload;
+ }
+
+ async fetchResponseCookies(responseCookies) {
+ const payload = {};
+ if (responseCookies) {
+ const resCookies = [];
+ // response store cookies in responseCookies or responseCookies.cookies
+ const cookies = responseCookies.cookies
+ ? responseCookies.cookies
+ : responseCookies;
+ // make sure cookies is iterable
+ if (typeof cookies[Symbol.iterator] === "function") {
+ for (const cookie of cookies) {
+ resCookies.push(
+ Object.assign({}, cookie, {
+ value: await this.getLongString(cookie.value),
+ })
+ );
+ }
+ if (resCookies.length) {
+ payload.responseCookies = resCookies;
+ }
+ }
+ }
+ return payload;
+ }
+
+ async fetchResponseCache(responseCache) {
+ const payload = {};
+ if (responseCache) {
+ payload.responseCache = await responseCache;
+ payload.responseCacheAvailable = false;
+ }
+ return payload;
+ }
+
+ /**
+ * Public API used by the Toolbox: Tells if there is still any pending request.
+ *
+ * @return {boolean} returns true if pending requests still exist in the queue.
+ */
+ hasPendingRequests() {
+ return this.pendingRequests.size > 0;
+ }
+
+ /**
+ * Fetches the full text of a LongString.
+ *
+ * @param {object|string} stringGrip
+ * The long string grip containing the corresponding actor.
+ * If you pass in a plain string (by accident or because you're lazy),
+ * then a promise of the same string is simply returned.
+ * @return {object}
+ * A promise that is resolved when the full string contents
+ * are available, or rejected if something goes wrong.
+ */
+ async getLongString(stringGrip) {
+ const payload = await getLongStringFullText(
+ this.commands.client,
+ stringGrip
+ );
+ this.emitForTests(TEST_EVENTS.LONGSTRING_RESOLVED, { payload });
+ return payload;
+ }
+
+ /**
+ * Retrieve the stack-trace information for the given StackTracesActor.
+ *
+ * @param object actor
+ * - {Object} targetFront: the target front.
+ *
+ * - {String} resourceId: the resource id for the network request".
+ * @return {object}
+ */
+ async _getStackTraceFromWatcher(actor) {
+ // If we request the stack trace for the navigation request,
+ // t was coming from previous page content process, which may no longer be around.
+ // In any case, the previous target is destroyed and we can't fetch the stack anymore.
+ let stacktrace = [];
+ if (!actor.targetFront.isDestroyed()) {
+ const networkContentFront = await actor.targetFront.getFront(
+ "networkContent"
+ );
+ stacktrace = await networkContentFront.getStackTrace(
+ actor.stacktraceResourceId
+ );
+ }
+ return { stacktrace };
+ }
+
+ /**
+ * The handler for when the network event stacktrace resource is available.
+ * The resource contains basic info, the actual stacktrace is fetched lazily
+ * using requestData.
+ * @param {object} resource The network event stacktrace resource
+ */
+ async onStackTraceAvailable(resource) {
+ if (!this.stackTraces.has(resource.resourceId)) {
+ // If no stacktrace info exists, this means the network event
+ // has not fired yet, lets store useful info for the NETWORK_EVENT
+ // resource.
+ this.stackTraces.set(resource.resourceId, resource);
+ } else {
+ // If stacktrace info exists, this means the network event has already
+ // fired, so lets just update the reducer with the necessary stacktrace info.
+ const request = this.stackTraces.get(resource.resourceId);
+ request.cause.stacktraceAvailable = resource.stacktraceAvailable;
+ request.cause.lastFrame = resource.lastFrame;
+
+ this.stackTraces.delete(resource.resourceId);
+
+ this.stackTraceRequestInfoByActorID.set(request.actor, {
+ targetFront: resource.targetFront,
+ stacktraceResourceId: resource.resourceId,
+ });
+
+ if (this.actionsEnabled && this.actions.updateRequest) {
+ await this.actions.updateRequest(request.actor, request, true);
+ }
+ }
+ }
+
+ /**
+ * The handler for when the network event resource is available.
+ *
+ * @param {object} resource The network event resource
+ */
+ async onNetworkResourceAvailable(resource) {
+ const { actor, stacktraceResourceId, cause } = resource;
+
+ if (!this._requestDataEnabled) {
+ this._requestDataEnabled = true;
+ }
+
+ // Check if a stacktrace resource already exists for this network resource.
+ if (this.stackTraces.has(stacktraceResourceId)) {
+ const { stacktraceAvailable, lastFrame, targetFront } =
+ this.stackTraces.get(stacktraceResourceId);
+
+ resource.cause.stacktraceAvailable = stacktraceAvailable;
+ resource.cause.lastFrame = lastFrame;
+
+ this.stackTraces.delete(stacktraceResourceId);
+ // We retrieve preliminary information about the stacktrace from the
+ // NETWORK_EVENT_STACKTRACE resource via `this.stackTraces` Map,
+ // The actual stacktrace is fetched lazily based on the actor id, using
+ // the targetFront and the stacktrace resource id therefore we
+ // map these for easy access.
+ this.stackTraceRequestInfoByActorID.set(actor, {
+ targetFront,
+ stacktraceResourceId,
+ });
+ } else if (cause) {
+ // If the stacktrace for this request is not available, and we
+ // expect that this request should have a stacktrace, lets store
+ // some useful info for when the NETWORK_EVENT_STACKTRACE resource
+ // finally comes.
+ this.stackTraces.set(stacktraceResourceId, { actor, cause });
+ }
+ await this.addRequest(actor, resource);
+ this.emitForTests(TEST_EVENTS.NETWORK_EVENT, resource);
+ }
+
+ /**
+ * The handler for when the network event resource is updated.
+ *
+ * @param {object} resource The updated network event resource.
+ */
+ async onNetworkResourceUpdated(resource) {
+ // Identify the channel as SSE if mimeType is event-stream.
+ if (resource?.mimeType?.includes("text/event-stream")) {
+ await this.setEventStreamFlag(resource.actor);
+ }
+
+ this.pendingRequests.delete(resource.actor);
+ if (this.actionsEnabled && this.actions.updateRequest) {
+ await this.actions.updateRequest(resource.actor, resource, true);
+ }
+
+ // This event is fired only once per request, once all the properties are fetched
+ // from `onNetworkResourceUpdated`. There should be no more RDP requests after this.
+ // Note that this event might be consumed by extension so, emit it in production
+ // release as well.
+ this.emitForTests(TEST_EVENTS.NETWORK_EVENT_UPDATED, resource.actor);
+ this.emit(EVENTS.PAYLOAD_READY, resource);
+ }
+
+ /**
+ * The "webSocketOpened" message type handler.
+ *
+ * @param {number} httpChannelId the channel ID
+ * @param {string} effectiveURI the effective URI of the page
+ * @param {string} protocols webSocket protocols
+ * @param {string} extensions
+ */
+ async onWebSocketOpened(httpChannelId, effectiveURI, protocols, extensions) {}
+
+ /**
+ * The "webSocketClosed" message type handler.
+ *
+ * @param {number} httpChannelId
+ * @param {boolean} wasClean
+ * @param {number} code
+ * @param {string} reason
+ */
+ async onWebSocketClosed(httpChannelId, wasClean, code, reason) {
+ if (this.actionsEnabled && this.actions.closeConnection) {
+ await this.actions.closeConnection(httpChannelId, wasClean, code, reason);
+ }
+ }
+
+ /**
+ * The "frameSent" message type handler.
+ *
+ * @param {number} httpChannelId the channel ID
+ * @param {object} data websocket frame information
+ */
+ async onFrameSent(httpChannelId, data) {
+ this.addMessage(httpChannelId, data);
+ }
+
+ /**
+ * The "frameReceived" message type handler.
+ *
+ * @param {number} httpChannelId the channel ID
+ * @param {object} data websocket frame information
+ */
+ async onFrameReceived(httpChannelId, data) {
+ this.addMessage(httpChannelId, data);
+ }
+
+ /**
+ * Add a new WebSocket frame to application state.
+ *
+ * @param {number} httpChannelId the channel ID
+ * @param {object} data websocket frame information
+ */
+ async addMessage(httpChannelId, data) {
+ if (this.actionsEnabled && this.actions.addMessage) {
+ await this.actions.addMessage(httpChannelId, data, true);
+ }
+ // TODO: Emit an event for test here
+ }
+
+ /**
+ * Public connector API to lazily request HTTP details from the backend.
+ *
+ * The method focus on:
+ * - calling the right actor method,
+ * - emitting an event to tell we start fetching some request data,
+ * - call data processing method.
+ *
+ * @param {string} actor actor id (used as request id)
+ * @param {string} method identifier of the data we want to fetch
+ *
+ * @return {Promise} return a promise resolved when data is received.
+ */
+ requestData(actor, method) {
+ // if this is `false`, do not try to request data as requests on the backend
+ // might no longer exist (usually `false` after requests are cleared).
+ if (!this._requestDataEnabled) {
+ return Promise.resolve();
+ }
+ // Key string used in `lazyRequestData`. We use this Map to prevent requesting
+ // the same data twice at the same time.
+ const key = `${actor}-${method}`;
+ let promise = this.lazyRequestData.get(key);
+ // If a request is pending, reuse it.
+ if (promise) {
+ return promise;
+ }
+ // Fetch the data
+ promise = this._requestData(actor, method).then(async payload => {
+ // Remove the request from the cache, any new call to requestData will fetch the
+ // data again.
+ this.lazyRequestData.delete(key);
+
+ if (this.actionsEnabled && this.actions.updateRequest) {
+ await this.actions.updateRequest(
+ actor,
+ {
+ ...payload,
+ // Lockdown *Available property once we fetch data from back-end.
+ // Using this as a flag to prevent fetching arrived data again.
+ [`${method}Available`]: false,
+ },
+ true
+ );
+ }
+
+ return payload;
+ });
+
+ this.lazyRequestData.set(key, promise);
+
+ return promise;
+ }
+
+ /**
+ * Internal helper used to request HTTP details from the backend.
+ *
+ * This is internal method that focus on:
+ * - calling the right actor method,
+ * - emitting an event to tell we start fetching some request data,
+ * - call data processing method.
+ *
+ * @param {string} actor actor id (used as request id)
+ * @param {string} method identifier of the data we want to fetch
+ *
+ * @return {Promise} return a promise resolved when data is received.
+ */
+ async _requestData(actor, method) {
+ // Backup the lastRequestDataClearId before doing any async processing.
+ const lastRequestDataClearId = this._lastRequestDataClearId;
+
+ // Calculate real name of the client getter.
+ const clientMethodName = `get${method
+ .charAt(0)
+ .toUpperCase()}${method.slice(1)}`;
+ // The name of the callback that processes request response
+ const callbackMethodName = `on${method
+ .charAt(0)
+ .toUpperCase()}${method.slice(1)}`;
+ // And the event to fire before updating this data
+ const updatingEventName = `UPDATING_${method
+ .replace(/([A-Z])/g, "_$1")
+ .toUpperCase()}`;
+
+ // Emit event that tell we just start fetching some data
+ this.emitForTests(EVENTS[updatingEventName], actor);
+
+ // Make sure we fetch the real actor data instead of cloned actor
+ // e.g. CustomRequestPanel will clone a request with additional '-clone' actor id
+ const actorID = actor.replace("-clone", "");
+
+ // 'getStackTrace' is the only one to be fetched via the NetworkContent actor in content process
+ // while all other attributes are fetched from the NetworkEvent actors, running in the parent process
+ let response;
+ if (
+ clientMethodName == "getStackTrace" &&
+ this.commands.resourceCommand.hasResourceCommandSupport(
+ this.commands.resourceCommand.TYPES.NETWORK_EVENT_STACKTRACE
+ )
+ ) {
+ const requestInfo = this.stackTraceRequestInfoByActorID.get(actorID);
+ const { stacktrace } = await this._getStackTraceFromWatcher(requestInfo);
+ this.stackTraceRequestInfoByActorID.delete(actorID);
+ response = { from: actor, stacktrace };
+ } else {
+ // We don't create fronts for NetworkEvent actors,
+ // so that we have to do the request manually via DevToolsClient.request()
+ try {
+ const packet = {
+ to: actorID,
+ type: clientMethodName,
+ };
+ response = await this.commands.client.request(packet);
+ } catch (e) {
+ if (this._lastRequestDataClearId !== lastRequestDataClearId) {
+ // If lastRequestDataClearId was updated, FirefoxDataProvider:clear()
+ // was called and all network event actors have been destroyed.
+ // Swallow errors to avoid unhandled promise rejections in tests.
+ console.warn(
+ `Firefox Data Provider destroyed while requesting data: ${e.message}`
+ );
+ // Return an empty response packet to avoid too many callback errors.
+ response = { from: actor };
+ } else {
+ throw new Error(
+ `Error while calling method ${clientMethodName}: ${e.message}`
+ );
+ }
+ }
+ }
+
+ // Restore clone actor id
+ if (actor.includes("-clone")) {
+ // Because response's properties are read-only, we create a new response
+ response = { ...response, from: `${response.from}-clone` };
+ }
+
+ // Call data processing method.
+ return this[callbackMethodName](response);
+ }
+
+ /**
+ * Handles additional information received for a "requestHeaders" packet.
+ *
+ * @param {object} response the message received from the server.
+ */
+ async onRequestHeaders(response) {
+ const payload = await this.updateRequest(response.from, {
+ requestHeaders: response,
+ });
+ this.emitForTests(TEST_EVENTS.RECEIVED_REQUEST_HEADERS, response);
+ return payload.requestHeaders;
+ }
+
+ /**
+ * Handles additional information received for a "responseHeaders" packet.
+ *
+ * @param {object} response the message received from the server.
+ */
+ async onResponseHeaders(response) {
+ const payload = await this.updateRequest(response.from, {
+ responseHeaders: response,
+ });
+ this.emitForTests(TEST_EVENTS.RECEIVED_RESPONSE_HEADERS, response);
+ return payload.responseHeaders;
+ }
+
+ /**
+ * Handles additional information received for a "requestCookies" packet.
+ *
+ * @param {object} response the message received from the server.
+ */
+ async onRequestCookies(response) {
+ const payload = await this.updateRequest(response.from, {
+ requestCookies: response,
+ });
+ this.emitForTests(TEST_EVENTS.RECEIVED_REQUEST_COOKIES, response);
+ return payload.requestCookies;
+ }
+
+ /**
+ * Handles additional information received for a "requestPostData" packet.
+ *
+ * @param {object} response the message received from the server.
+ */
+ async onRequestPostData(response) {
+ const payload = await this.updateRequest(response.from, {
+ requestPostData: response,
+ });
+ this.emitForTests(TEST_EVENTS.RECEIVED_REQUEST_POST_DATA, response);
+ return payload.requestPostData;
+ }
+
+ /**
+ * Handles additional information received for a "securityInfo" packet.
+ *
+ * @param {object} response the message received from the server.
+ */
+ async onSecurityInfo(response) {
+ const payload = await this.updateRequest(response.from, {
+ securityInfo: response.securityInfo,
+ });
+ this.emitForTests(TEST_EVENTS.RECEIVED_SECURITY_INFO, response);
+ return payload.securityInfo;
+ }
+
+ /**
+ * Handles additional information received for a "responseCookies" packet.
+ *
+ * @param {object} response the message received from the server.
+ */
+ async onResponseCookies(response) {
+ const payload = await this.updateRequest(response.from, {
+ responseCookies: response,
+ });
+ this.emitForTests(TEST_EVENTS.RECEIVED_RESPONSE_COOKIES, response);
+ return payload.responseCookies;
+ }
+
+ /**
+ * Handles additional information received for a "responseCache" packet.
+ * @param {object} response the message received from the server.
+ */
+ async onResponseCache(response) {
+ const payload = await this.updateRequest(response.from, {
+ responseCache: response,
+ });
+ this.emitForTests(TEST_EVENTS.RECEIVED_RESPONSE_CACHE, response);
+ return payload.responseCache;
+ }
+
+ /**
+ * Handles additional information received via "getResponseContent" request.
+ *
+ * @param {object} response the message received from the server.
+ */
+ async onResponseContent(response) {
+ const payload = await this.updateRequest(response.from, {
+ // We have to ensure passing mimeType as fetchResponseContent needs it from
+ // updateRequest. It will convert the LongString in `response.content.text` to a
+ // string.
+ mimeType: response.content.mimeType,
+ responseContent: response,
+ });
+ this.emitForTests(TEST_EVENTS.RECEIVED_RESPONSE_CONTENT, response);
+ return payload.responseContent;
+ }
+
+ /**
+ * Handles additional information received for a "eventTimings" packet.
+ *
+ * @param {object} response the message received from the server.
+ */
+ async onEventTimings(response) {
+ const payload = await this.updateRequest(response.from, {
+ eventTimings: response,
+ });
+
+ // This event is utilized only in tests but, DAMP is using it too
+ // and running DAMP test doesn't set the `devtools.testing` flag.
+ // So, emit this event even in the production mode.
+ // See also: https://bugzilla.mozilla.org/show_bug.cgi?id=1578215
+ this.emit(EVENTS.RECEIVED_EVENT_TIMINGS, response);
+ return payload.eventTimings;
+ }
+
+ /**
+ * Handles information received for a "stackTrace" packet.
+ *
+ * @param {object} response the message received from the server.
+ */
+ async onStackTrace(response) {
+ const payload = await this.updateRequest(response.from, {
+ stacktrace: response.stacktrace,
+ });
+ this.emitForTests(TEST_EVENTS.RECEIVED_EVENT_STACKTRACE, response);
+ return payload.stacktrace;
+ }
+
+ /**
+ * Handle EventSource events.
+ */
+
+ async onEventSourceConnectionClosed(httpChannelId) {
+ if (this.actionsEnabled && this.actions.closeConnection) {
+ await this.actions.closeConnection(httpChannelId);
+ }
+ }
+
+ async onEventReceived(httpChannelId, data) {
+ // Dispatch the same action used by websocket inspector.
+ this.addMessage(httpChannelId, data);
+ }
+
+ async setEventStreamFlag(actorId) {
+ if (this.actionsEnabled && this.actions.setEventStreamFlag) {
+ await this.actions.setEventStreamFlag(actorId, true);
+ }
+ }
+
+ /**
+ * Fire events for the owner object.
+ */
+ emit(type, data) {
+ if (this.owner) {
+ this.owner.emit(type, data);
+ }
+ }
+
+ /**
+ * Fire test events for the owner object. These events are
+ * emitted only when tests are running.
+ */
+ emitForTests(type, data) {
+ if (this.owner) {
+ this.owner.emitForTests(type, data);
+ }
+ }
+}
+
+module.exports = FirefoxDataProvider;
diff --git a/devtools/client/netmonitor/src/connector/har-metadata-collector.js b/devtools/client/netmonitor/src/connector/har-metadata-collector.js
new file mode 100644
index 0000000000..c0227065a5
--- /dev/null
+++ b/devtools/client/netmonitor/src/connector/har-metadata-collector.js
@@ -0,0 +1,97 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const {
+ TYPES,
+} = require("resource://devtools/shared/commands/resource/resource-command.js");
+
+/**
+ * This collector class is dedicated to recording additional metadata necessary
+ * to build HAR files. The actual request data will be provided by the
+ * netmonitor which is already monitoring for requests.
+ *
+ * The only purpose of this class is to record additional document and network
+ * events, which will help to assign requests to individual pages.
+ *
+ * It should be created and destroyed by the main netmonitor data collector.
+ */
+class HarMetadataCollector {
+ #commands;
+ #initialTargetTitle;
+ #navigationRequests;
+ #targetTitlesPerURL;
+
+ constructor(commands) {
+ this.#commands = commands;
+ }
+
+ /**
+ * Stop recording and clear the state.
+ */
+ destroy() {
+ this.clear();
+
+ this.#commands.resourceCommand.unwatchResources(
+ [TYPES.DOCUMENT_EVENT, TYPES.NETWORK_EVENT],
+ {
+ onAvailable: this.#onResourceAvailable,
+ }
+ );
+ }
+
+ /**
+ * Reset the current state.
+ */
+ clear() {
+ this.#navigationRequests = [];
+ this.#targetTitlesPerURL = new Map();
+ this.#initialTargetTitle = this.#commands.targetCommand.targetFront.title;
+ }
+
+ /**
+ * Start recording additional events for HAR files building.
+ */
+ async connect() {
+ this.clear();
+
+ await this.#commands.resourceCommand.watchResources(
+ [TYPES.DOCUMENT_EVENT, TYPES.NETWORK_EVENT],
+ {
+ onAvailable: this.#onResourceAvailable,
+ }
+ );
+ }
+
+ getHarData() {
+ return {
+ initialTargetTitle: this.#initialTargetTitle,
+ navigationRequests: this.#navigationRequests,
+ targetTitlesPerURL: this.#targetTitlesPerURL,
+ };
+ }
+
+ #onResourceAvailable = resources => {
+ for (const resource of resources) {
+ if (resource.resourceType === TYPES.DOCUMENT_EVENT) {
+ if (
+ resource.name === "dom-complete" &&
+ resource.targetFront.isTopLevel
+ ) {
+ this.#targetTitlesPerURL.set(
+ resource.targetFront.url,
+ resource.targetFront.title
+ );
+ }
+ } else if (resource.resourceType === TYPES.NETWORK_EVENT) {
+ if (resource.isNavigationRequest) {
+ this.#navigationRequests.push(resource);
+ }
+ }
+ }
+ };
+}
+
+exports.HarMetadataCollector = HarMetadataCollector;
diff --git a/devtools/client/netmonitor/src/connector/index.js b/devtools/client/netmonitor/src/connector/index.js
new file mode 100644
index 0000000000..b1f23a2269
--- /dev/null
+++ b/devtools/client/netmonitor/src/connector/index.js
@@ -0,0 +1,543 @@
+/* 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 {
+ ACTIVITY_TYPE,
+ EVENTS,
+ TEST_EVENTS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const FirefoxDataProvider = require("resource://devtools/client/netmonitor/src/connector/firefox-data-provider.js");
+const {
+ getDisplayedTimingMarker,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+const {
+ TYPES,
+} = require("resource://devtools/shared/commands/resource/resource-command.js");
+
+// Network throttling
+loader.lazyRequireGetter(
+ this,
+ "throttlingProfiles",
+ "resource://devtools/client/shared/components/throttling/profiles.js"
+);
+
+loader.lazyRequireGetter(
+ this,
+ "HarMetadataCollector",
+ "resource://devtools/client/netmonitor/src/connector/har-metadata-collector.js",
+ true
+);
+
+const DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF = "devtools.netmonitor.persistlog";
+
+/**
+ * Connector to Firefox backend.
+ */
+class Connector {
+ constructor() {
+ // Public methods
+ this.connect = this.connect.bind(this);
+ this.disconnect = this.disconnect.bind(this);
+ this.willNavigate = this.willNavigate.bind(this);
+ this.navigate = this.navigate.bind(this);
+ this.triggerActivity = this.triggerActivity.bind(this);
+ this.viewSourceInDebugger = this.viewSourceInDebugger.bind(this);
+ this.requestData = this.requestData.bind(this);
+ this.getTimingMarker = this.getTimingMarker.bind(this);
+ this.updateNetworkThrottling = this.updateNetworkThrottling.bind(this);
+
+ // Internals
+ this.getLongString = this.getLongString.bind(this);
+ this.onResourceAvailable = this.onResourceAvailable.bind(this);
+ this.onResourceUpdated = this.onResourceUpdated.bind(this);
+ this.updatePersist = this.updatePersist.bind(this);
+
+ this.networkFront = null;
+ }
+
+ static NETWORK_RESOURCES = [
+ TYPES.NETWORK_EVENT,
+ TYPES.NETWORK_EVENT_STACKTRACE,
+ TYPES.WEBSOCKET,
+ TYPES.SERVER_SENT_EVENT,
+ ];
+
+ get currentTarget() {
+ return this.commands.targetCommand.targetFront;
+ }
+
+ /**
+ * Connect to the backend.
+ *
+ * @param {Object} connection object with e.g. reference to the Toolbox.
+ * @param {Object} actions (optional) is used to fire Redux actions to update store.
+ * @param {Object} getState (optional) is used to get access to the state.
+ */
+ async connect(connection, actions, getState) {
+ this.actions = actions;
+ this.getState = getState;
+ this.toolbox = connection.toolbox;
+ this.commands = this.toolbox.commands;
+ this.networkCommand = this.commands.networkCommand;
+
+ // The owner object (NetMonitorAPI) received all events.
+ this.owner = connection.owner;
+
+ this.networkFront =
+ await this.commands.watcherFront.getNetworkParentActor();
+
+ this.dataProvider = new FirefoxDataProvider({
+ commands: this.commands,
+ actions: this.actions,
+ owner: this.owner,
+ });
+
+ this._harMetadataCollector = new HarMetadataCollector(this.commands);
+ await this._harMetadataCollector.connect();
+
+ await this.commands.resourceCommand.watchResources([TYPES.DOCUMENT_EVENT], {
+ onAvailable: this.onResourceAvailable,
+ });
+
+ await this.resume(false);
+
+ // Server side persistance of the data across reload is disabled by default.
+ // Ensure enabling it, if the related frontend pref is true.
+ if (Services.prefs.getBoolPref(DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF)) {
+ await this.updatePersist();
+ }
+ Services.prefs.addObserver(
+ DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF,
+ this.updatePersist
+ );
+ }
+
+ disconnect() {
+ // As this function might be called twice, we need to guard if already called.
+ if (this._destroyed) {
+ return;
+ }
+
+ this._destroyed = true;
+
+ this.commands.resourceCommand.unwatchResources([TYPES.DOCUMENT_EVENT], {
+ onAvailable: this.onResourceAvailable,
+ });
+
+ this.pause();
+
+ Services.prefs.removeObserver(
+ DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF,
+ this.updatePersist
+ );
+
+ if (this.actions) {
+ this.actions.batchReset();
+ }
+
+ this.dataProvider.destroy();
+ this.dataProvider = null;
+ this._harMetadataCollector.destroy();
+ }
+
+ clear() {
+ // Clear all the caches in the data provider
+ this.dataProvider.clear();
+
+ this._harMetadataCollector.clear();
+
+ this.commands.resourceCommand.clearResources(Connector.NETWORK_RESOURCES);
+ this.emitForTests("clear-network-resources");
+
+ // Disable the realted network logs in the webconsole
+ this.toolbox.disableAllConsoleNetworkLogs();
+ }
+
+ pause() {
+ return this.commands.resourceCommand.unwatchResources(
+ Connector.NETWORK_RESOURCES,
+ {
+ onAvailable: this.onResourceAvailable,
+ onUpdated: this.onResourceUpdated,
+ }
+ );
+ }
+
+ resume(ignoreExistingResources = true) {
+ return this.commands.resourceCommand.watchResources(
+ Connector.NETWORK_RESOURCES,
+ {
+ onAvailable: this.onResourceAvailable,
+ onUpdated: this.onResourceUpdated,
+ ignoreExistingResources,
+ }
+ );
+ }
+
+ async onResourceAvailable(resources, { areExistingResources }) {
+ for (const resource of resources) {
+ if (resource.resourceType === TYPES.DOCUMENT_EVENT) {
+ this.onDocEvent(resource, { areExistingResources });
+ continue;
+ }
+
+ if (resource.resourceType === TYPES.NETWORK_EVENT) {
+ this.dataProvider.onNetworkResourceAvailable(resource);
+ continue;
+ }
+
+ if (resource.resourceType === TYPES.NETWORK_EVENT_STACKTRACE) {
+ this.dataProvider.onStackTraceAvailable(resource);
+ continue;
+ }
+
+ if (resource.resourceType === TYPES.WEBSOCKET) {
+ const { wsMessageType } = resource;
+
+ switch (wsMessageType) {
+ case "webSocketOpened": {
+ this.dataProvider.onWebSocketOpened(
+ resource.httpChannelId,
+ resource.effectiveURI,
+ resource.protocols,
+ resource.extensions
+ );
+ break;
+ }
+ case "webSocketClosed": {
+ this.dataProvider.onWebSocketClosed(
+ resource.httpChannelId,
+ resource.wasClean,
+ resource.code,
+ resource.reason
+ );
+ break;
+ }
+ case "frameReceived": {
+ this.dataProvider.onFrameReceived(
+ resource.httpChannelId,
+ resource.data
+ );
+ break;
+ }
+ case "frameSent": {
+ this.dataProvider.onFrameSent(
+ resource.httpChannelId,
+ resource.data
+ );
+ break;
+ }
+ }
+ continue;
+ }
+
+ if (resource.resourceType === TYPES.SERVER_SENT_EVENT) {
+ const { messageType, httpChannelId, data } = resource;
+ switch (messageType) {
+ case "eventSourceConnectionClosed": {
+ this.dataProvider.onEventSourceConnectionClosed(httpChannelId);
+ break;
+ }
+ case "eventReceived": {
+ this.dataProvider.onEventReceived(httpChannelId, data);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ async onResourceUpdated(updates) {
+ for (const { resource, update } of updates) {
+ this.dataProvider.onNetworkResourceUpdated(resource, update);
+ }
+ }
+
+ enableActions(enable) {
+ this.dataProvider.enableActions(enable);
+ }
+
+ willNavigate() {
+ if (this.actions) {
+ if (!Services.prefs.getBoolPref(DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF)) {
+ this.actions.batchReset();
+ this.actions.clearRequests();
+ } else {
+ // If the log is persistent, just clear all accumulated timing markers.
+ this.actions.clearTimingMarkers();
+ }
+ }
+
+ if (this.actions && this.getState) {
+ const state = this.getState();
+ // Resume is done automatically on page reload/navigation.
+ if (!state.requests.recording) {
+ this.actions.toggleRecording();
+ }
+
+ // Stop any ongoing search.
+ if (state.search.ongoingSearch) {
+ this.actions.stopOngoingSearch();
+ }
+ }
+ }
+
+ navigate() {
+ if (!this.dataProvider.hasPendingRequests()) {
+ this.onReloaded();
+ return;
+ }
+ const listener = () => {
+ if (this.dataProvider && this.dataProvider.hasPendingRequests()) {
+ return;
+ }
+ if (this.owner) {
+ this.owner.off(EVENTS.PAYLOAD_READY, listener);
+ }
+ // Netmonitor may already be destroyed,
+ // so do not try to notify the listeners
+ if (this.dataProvider) {
+ this.onReloaded();
+ }
+ };
+ if (this.owner) {
+ this.owner.on(EVENTS.PAYLOAD_READY, listener);
+ }
+ }
+
+ onReloaded() {
+ const panel = this.toolbox.getPanel("netmonitor");
+ if (panel) {
+ panel.emit("reloaded");
+ }
+ }
+
+ /**
+ * The "DOMContentLoaded" and "Load" events sent by the console actor.
+ *
+ * @param {object} resource The DOCUMENT_EVENT resource
+ */
+ onDocEvent(resource, { areExistingResources }) {
+ if (!resource.targetFront.isTopLevel) {
+ // Only consider top level document, and ignore remote iframes top document
+ return;
+ }
+
+ // Netmonitor does not support dom-loading
+ if (
+ resource.name != "dom-interactive" &&
+ resource.name != "dom-complete" &&
+ resource.name != "will-navigate"
+ ) {
+ return;
+ }
+
+ if (resource.name == "will-navigate") {
+ // When we open the netmonitor while the page already started loading,
+ // we don't want to clear it. So here, we ignore will-navigate events
+ // which were stored in the ResourceCommand cache and only consider
+ // the live one coming straight from the server.
+ if (!areExistingResources) {
+ this.willNavigate();
+ }
+ return;
+ }
+
+ if (this.actions) {
+ this.actions.addTimingMarker(resource);
+ }
+
+ if (resource.name === "dom-complete") {
+ this.navigate();
+ }
+
+ this.emitForTests(TEST_EVENTS.TIMELINE_EVENT, resource);
+ }
+
+ async updatePersist() {
+ const enabled = Services.prefs.getBoolPref(
+ DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF
+ );
+
+ await this.networkFront.setPersist(enabled);
+
+ this.emitForTests(TEST_EVENTS.PERSIST_CHANGED, enabled);
+ }
+
+ /**
+ * Triggers a specific "activity" to be performed by the frontend.
+ * This can be, for example, triggering reloads or enabling/disabling cache.
+ *
+ * @param {number} type The activity type. See the ACTIVITY_TYPE const.
+ * @return {object} A promise resolved once the activity finishes and the frontend
+ * is back into "standby" mode.
+ */
+ triggerActivity(type) {
+ // Puts the frontend into "standby" (when there's no particular activity).
+ const standBy = () => {
+ this.currentActivity = ACTIVITY_TYPE.NONE;
+ };
+
+ // Reconfigures the tab, optionally triggering a reload.
+ const reconfigureTab = async options => {
+ await this.commands.targetConfigurationCommand.updateConfiguration(
+ options
+ );
+ };
+
+ // Reconfigures the tab and waits for the target to finish navigating.
+ const reconfigureTabAndReload = async options => {
+ await reconfigureTab(options);
+ await this.commands.targetCommand.reloadTopLevelTarget();
+ };
+
+ switch (type) {
+ case ACTIVITY_TYPE.RELOAD.WITH_CACHE_DEFAULT:
+ return reconfigureTabAndReload({}).then(standBy);
+ case ACTIVITY_TYPE.RELOAD.WITH_CACHE_ENABLED:
+ this.currentActivity = ACTIVITY_TYPE.ENABLE_CACHE;
+ this.commands.resourceCommand
+ .waitForNextResource(
+ this.commands.resourceCommand.TYPES.DOCUMENT_EVENT,
+ {
+ ignoreExistingResources: true,
+ predicate(resource) {
+ return resource.name == "will-navigate";
+ },
+ }
+ )
+ .then(() => {
+ this.currentActivity = type;
+ });
+ return reconfigureTabAndReload({
+ cacheDisabled: false,
+ }).then(standBy);
+ case ACTIVITY_TYPE.RELOAD.WITH_CACHE_DISABLED:
+ this.currentActivity = ACTIVITY_TYPE.DISABLE_CACHE;
+ this.commands.resourceCommand
+ .waitForNextResource(
+ this.commands.resourceCommand.TYPES.DOCUMENT_EVENT,
+ {
+ ignoreExistingResources: true,
+ predicate(resource) {
+ return resource.name == "will-navigate";
+ },
+ }
+ )
+ .then(() => {
+ this.currentActivity = type;
+ });
+ return reconfigureTabAndReload({
+ cacheDisabled: true,
+ }).then(standBy);
+ case ACTIVITY_TYPE.ENABLE_CACHE:
+ this.currentActivity = type;
+ return reconfigureTab({
+ cacheDisabled: false,
+ }).then(standBy);
+ case ACTIVITY_TYPE.DISABLE_CACHE:
+ this.currentActivity = type;
+ return reconfigureTab({
+ cacheDisabled: true,
+ }).then(standBy);
+ }
+ this.currentActivity = ACTIVITY_TYPE.NONE;
+ return Promise.reject(new Error("Invalid activity type"));
+ }
+
+ /**
+ * Fetches the full text of a LongString.
+ *
+ * @param {object|string} stringGrip
+ * The long string grip containing the corresponding actor.
+ * If you pass in a plain string (by accident or because you're lazy),
+ * then a promise of the same string is simply returned.
+ * @return {object}
+ * A promise that is resolved when the full string contents
+ * are available, or rejected if something goes wrong.
+ */
+ getLongString(stringGrip) {
+ return this.dataProvider.getLongString(stringGrip);
+ }
+
+ /**
+ * Used for HAR generation.
+ */
+ getHarData() {
+ return this._harMetadataCollector.getHarData();
+ }
+
+ /**
+ * Getter that returns the current toolbox instance.
+ * @return {Toolbox} toolbox instance
+ */
+ getToolbox() {
+ return this.toolbox;
+ }
+
+ /**
+ * Open a given source in Debugger
+ * @param {string} sourceURL source url
+ * @param {number} sourceLine source line number
+ */
+ viewSourceInDebugger(sourceURL, sourceLine, sourceColumn) {
+ if (this.toolbox) {
+ this.toolbox.viewSourceInDebugger(sourceURL, sourceLine, sourceColumn);
+ }
+ }
+
+ /**
+ * Fetch networkEventUpdate websocket message from back-end when
+ * data provider is connected.
+ * @param {object} request network request instance
+ * @param {string} type NetworkEventUpdate type
+ */
+ requestData(request, type) {
+ return this.dataProvider.requestData(request, type);
+ }
+
+ getTimingMarker(name) {
+ if (!this.getState) {
+ return -1;
+ }
+
+ const state = this.getState();
+ return getDisplayedTimingMarker(state, name);
+ }
+
+ async updateNetworkThrottling(enabled, profile) {
+ if (!enabled) {
+ this.networkFront.clearNetworkThrottling();
+ } else {
+ // The profile can be either a profile id which is used to
+ // search the predefined throttle profiles or a profile object
+ // as defined in the trottle tests.
+ if (typeof profile === "string") {
+ profile = throttlingProfiles.find(({ id }) => id == profile);
+ }
+ const { download, upload, latency } = profile;
+ await this.networkFront.setNetworkThrottling({
+ downloadThroughput: download,
+ uploadThroughput: upload,
+ latency,
+ });
+ }
+
+ this.emitForTests(TEST_EVENTS.THROTTLING_CHANGED, { profile });
+ }
+
+ /**
+ * Fire events for the owner object. These events are only
+ * used in tests so, don't fire them in production release.
+ */
+ emitForTests(type, data) {
+ if (this.owner) {
+ this.owner.emitForTests(type, data);
+ }
+ }
+}
+module.exports.Connector = Connector;
diff --git a/devtools/client/netmonitor/src/connector/moz.build b/devtools/client/netmonitor/src/connector/moz.build
new file mode 100644
index 0000000000..4f65ddea0e
--- /dev/null
+++ b/devtools/client/netmonitor/src/connector/moz.build
@@ -0,0 +1,9 @@
+# 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(
+ "firefox-data-provider.js",
+ "har-metadata-collector.js",
+ "index.js",
+)
diff --git a/devtools/client/netmonitor/src/constants.js b/devtools/client/netmonitor/src/constants.js
new file mode 100644
index 0000000000..cd4ce309d0
--- /dev/null
+++ b/devtools/client/netmonitor/src/constants.js
@@ -0,0 +1,597 @@
+/* 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 actionTypes = {
+ ADD_REQUEST: "ADD_REQUEST",
+ SET_EVENT_STREAM_FLAG: "SET_EVENT_STREAM_FLAG",
+ ADD_TIMING_MARKER: "ADD_TIMING_MARKER",
+ ADD_BLOCKED_URL: "ADD_BLOCKED_URL",
+ BATCH_ACTIONS: "BATCH_ACTIONS",
+ BATCH_ENABLE: "BATCH_ENABLE",
+ BATCH_FLUSH: "BATCH_FLUSH",
+ BLOCK_SELECTED_REQUEST_DONE: "BLOCK_SELECTED_REQUEST_DONE",
+ CLEAR_REQUESTS: "CLEAR_REQUESTS",
+ CLEAR_TIMING_MARKERS: "CLEAR_TIMING_MARKERS",
+ CLONE_REQUEST: "CLONE_REQUEST",
+ CLONE_SELECTED_REQUEST: "CLONE_SELECTED_REQUEST",
+ ENABLE_REQUEST_FILTER_TYPE_ONLY: "ENABLE_REQUEST_FILTER_TYPE_ONLY",
+ OPEN_NETWORK_DETAILS: "OPEN_NETWORK_DETAILS",
+ OPEN_ACTION_BAR: "OPEN_ACTION_BAR",
+ RESIZE_NETWORK_DETAILS: "RESIZE_NETWORK_DETAILS",
+ RIGHT_CLICK_REQUEST: "RIGHT_CLICK_REQUEST",
+ ENABLE_PERSISTENT_LOGS: "ENABLE_PERSISTENT_LOGS",
+ DISABLE_BROWSER_CACHE: "DISABLE_BROWSER_CACHE",
+ OPEN_STATISTICS: "OPEN_STATISTICS",
+ PERSIST_CHANGED: "PERSIST_CHANGED",
+ PRESELECT_REQUEST: "PRESELECT_REQUEST",
+ REMOVE_SELECTED_CUSTOM_REQUEST: "REMOVE_SELECTED_CUSTOM_REQUEST",
+ RESET_COLUMNS: "RESET_COLUMNS",
+ SELECT_REQUEST: "SELECT_REQUEST",
+ SELECT_DETAILS_PANEL_TAB: "SELECT_DETAILS_PANEL_TAB",
+ SELECT_ACTION_BAR_TAB: "SELECT_ACTION_BAR_TAB",
+ SEND_CUSTOM_REQUEST: "SEND_CUSTOM_REQUEST",
+ SET_REQUEST_FILTER_TEXT: "SET_REQUEST_FILTER_TEXT",
+ SORT_BY: "SORT_BY",
+ SYNCED_BLOCKED_URLS: "SYNCED_BLOCKED_URLS",
+ TOGGLE_BLOCKING_ENABLED: "TOGGLE_BLOCKING_ENABLED",
+ REMOVE_BLOCKED_URL: "REMOVE_BLOCKED_URL",
+ REMOVE_ALL_BLOCKED_URLS: "REMOVE_ALL_BLOCKED_URLS",
+ ENABLE_ALL_BLOCKED_URLS: "ENABLE_ALL_BLOCKED_URLS",
+ DISABLE_ALL_BLOCKED_URLS: "DISABLE_ALL_BLOCKED_URLS",
+ TOGGLE_BLOCKED_URL: "TOGGLE_BLOCKED_URL",
+ UPDATE_BLOCKED_URL: "UPDATE_BLOCKED_URL",
+ DISABLE_MATCHING_URLS: "DISABLE_MATCHING_URLS",
+ REQUEST_BLOCKING_UPDATE_COMPLETE: "REQUEST_BLOCKING_UPDATE_COMPLETE",
+ TOGGLE_COLUMN: "TOGGLE_COLUMN",
+ SET_RECORDING_STATE: "SET_RECORDING_STATE",
+ TOGGLE_REQUEST_FILTER_TYPE: "TOGGLE_REQUEST_FILTER_TYPE",
+ UNBLOCK_SELECTED_REQUEST_DONE: "UNBLOCK_SELECTED_REQUEST_DONE",
+ UPDATE_REQUEST: "UPDATE_REQUEST",
+ WATERFALL_RESIZE: "WATERFALL_RESIZE",
+ SET_COLUMNS_WIDTH: "SET_COLUMNS_WIDTH",
+ MSG_ADD: "MSG_ADD",
+ MSG_SELECT: "MSG_SELECT",
+ MSG_OPEN_DETAILS: "MSG_OPEN_DETAILS",
+ MSG_CLEAR: "MSG_CLEAR",
+ MSG_TOGGLE_FILTER_TYPE: "MSG_TOGGLE_FILTER_TYPE",
+ MSG_TOGGLE_CONTROL: "MSG_TOGGLE_CONTROL",
+ MSG_SET_FILTER_TEXT: "MSG_SET_FILTER_TEXT",
+ MSG_TOGGLE_COLUMN: "MSG_TOGGLE_COLUMN",
+ MSG_RESET_COLUMNS: "MSG_RESET_COLUMNS",
+ MSG_CLOSE_CONNECTION: "MSG_CLOSE_CONNECTION",
+ SET_HEADERS_URL_PREVIEW_EXPANDED: "SET_HEADERS_URL_PREVIEW_EXPANDED",
+
+ // Search
+ ADD_SEARCH_QUERY: "ADD_SEARCH_QUERY",
+ ADD_SEARCH_RESULT: "ADD_SEARCH_RESULT",
+ CLEAR_SEARCH_RESULTS: "CLEAR_SEARCH_RESULTS",
+ ADD_ONGOING_SEARCH: "ADD_ONGOING_SEARCH",
+ TOGGLE_SEARCH_CASE_SENSITIVE_SEARCH: "TOGGLE_SEARCH_CASE_SENSITIVE_SEARCH",
+ UPDATE_SEARCH_STATUS: "UPDATE_SEARCH_STATUS",
+ SET_TARGET_SEARCH_RESULT: "SET_TARGET_SEARCH_RESULT",
+};
+
+// Search status types
+const SEARCH_STATUS = {
+ INITIAL: "INITIAL",
+ FETCHING: "FETCHING",
+ CANCELED: "CANCELED",
+ DONE: "DONE",
+ ERROR: "ERROR",
+};
+
+const CHANNEL_TYPE = {
+ WEB_SOCKET: "WEB_SOCKET",
+ EVENT_STREAM: "EVENT_STREAM",
+};
+
+// Descriptions for what this frontend is currently doing.
+const ACTIVITY_TYPE = {
+ // Standing by and handling requests normally.
+ NONE: 0,
+
+ // Forcing the target to reload with cache enabled or disabled.
+ RELOAD: {
+ WITH_CACHE_ENABLED: 1,
+ WITH_CACHE_DISABLED: 2,
+ WITH_CACHE_DEFAULT: 3,
+ },
+
+ // Enabling or disabling the cache without triggering a reload.
+ ENABLE_CACHE: 3,
+ DISABLE_CACHE: 4,
+};
+
+// The panel's window global is an EventEmitter firing the following events:
+const EVENTS = {
+ // When a network event is added to the view
+ REQUEST_ADDED: "NetMonitor:RequestAdded",
+
+ // When request headers begin receiving.
+ UPDATING_REQUEST_HEADERS: "NetMonitor:NetworkEventUpdating:RequestHeaders",
+
+ // When request cookies begin receiving.
+ UPDATING_REQUEST_COOKIES: "NetMonitor:NetworkEventUpdating:RequestCookies",
+
+ // When request post data begins receiving.
+ UPDATING_REQUEST_POST_DATA: "NetMonitor:NetworkEventUpdating:RequestPostData",
+
+ // When security information begins receiving.
+ UPDATING_SECURITY_INFO: "NetMonitor:NetworkEventUpdating:SecurityInfo",
+
+ // When response headers begin receiving.
+ UPDATING_RESPONSE_HEADERS: "NetMonitor:NetworkEventUpdating:ResponseHeaders",
+
+ // When response cookies begin receiving.
+ UPDATING_RESPONSE_COOKIES: "NetMonitor:NetworkEventUpdating:ResponseCookies",
+
+ // When event timings begin and finish receiving.
+ UPDATING_EVENT_TIMINGS: "NetMonitor:NetworkEventUpdating:EventTimings",
+ RECEIVED_EVENT_TIMINGS: "NetMonitor:NetworkEventUpdated:EventTimings",
+
+ // When response content updates receiving.
+ UPDATING_RESPONSE_CONTENT: "NetMonitor:NetworkEventUpdating:ResponseContent",
+
+ UPDATING_RESPONSE_CACHE: "NetMonitor:NetworkEventUpdating:ResponseCache",
+
+ // Fired once the connection is established
+ CONNECTED: "connected",
+
+ // When request payload (HTTP details data) are fetched from the backend.
+ PAYLOAD_READY: "NetMonitor:PayloadReady",
+};
+
+const TEST_EVENTS = {
+ // When a network or timeline event is received.
+ // See https://firefox-source-docs.mozilla.org/devtools-user/web_console/remoting/ for
+ // more information about what each packet is supposed to deliver.
+ NETWORK_EVENT: "NetMonitor:NetworkEvent",
+ NETWORK_EVENT_UPDATED: "NetMonitor:NetworkEventUpdated",
+ TIMELINE_EVENT: "NetMonitor:TimelineEvent",
+
+ // When response content begins receiving.
+ STARTED_RECEIVING_RESPONSE: "NetMonitor:NetworkEventUpdating:ResponseStart",
+
+ // When request headers finish receiving.
+ RECEIVED_REQUEST_HEADERS: "NetMonitor:NetworkEventUpdated:RequestHeaders",
+
+ // When response headers finish receiving.
+ RECEIVED_RESPONSE_HEADERS: "NetMonitor:NetworkEventUpdated:ResponseHeaders",
+
+ // When request cookies finish receiving.
+ RECEIVED_REQUEST_COOKIES: "NetMonitor:NetworkEventUpdated:RequestCookies",
+
+ // When request post data finishes receiving.
+ RECEIVED_REQUEST_POST_DATA: "NetMonitor:NetworkEventUpdated:RequestPostData",
+
+ // When security information finishes receiving.
+ RECEIVED_SECURITY_INFO: "NetMonitor:NetworkEventUpdated:SecurityInfo",
+
+ // When response cookies finish receiving.
+ RECEIVED_RESPONSE_COOKIES: "NetMonitor:NetworkEventUpdated:ResponseCookies",
+
+ RECEIVED_RESPONSE_CACHE: "NetMonitor:NetworkEventUpdated:ResponseCache",
+
+ // When response content finishes receiving.
+ RECEIVED_RESPONSE_CONTENT: "NetMonitor:NetworkEventUpdated:ResponseContent",
+
+ // When stack-trace finishes receiving.
+ RECEIVED_EVENT_STACKTRACE: "NetMonitor:NetworkEventUpdated:StackTrace",
+
+ // When throttling is set on the backend.
+ THROTTLING_CHANGED: "NetMonitor:ThrottlingChanged",
+
+ // When a long string is resolved
+ LONGSTRING_RESOLVED: "NetMonitor:LongStringResolved",
+};
+
+const UPDATE_PROPS = [
+ "method",
+ "url",
+ "remotePort",
+ "remoteAddress",
+ "status",
+ "statusText",
+ "httpVersion",
+ "isRacing",
+ "securityState",
+ "securityInfo",
+ "securityInfoAvailable",
+ "mimeType",
+ "contentSize",
+ "transferredSize",
+ "totalTime",
+ "eventTimings",
+ "eventTimingsAvailable",
+ "headersSize",
+ "customQueryValue",
+ "requestHeaders",
+ "requestHeadersAvailable",
+ "requestHeadersFromUploadStream",
+ "requestCookies",
+ "requestCookiesAvailable",
+ "requestPostData",
+ "requestPostDataAvailable",
+ "responseHeaders",
+ "responseHeadersAvailable",
+ "responseCookies",
+ "responseCookiesAvailable",
+ "responseContent",
+ "responseContentAvailable",
+ "responseCache",
+ "responseCacheAvailable",
+ "formDataSections",
+ "stacktrace",
+ "isThirdPartyTrackingResource",
+ "referrerPolicy",
+ "priority",
+ "blockedReason",
+ "blockingExtension",
+ "channelId",
+ "waitingTime",
+];
+
+const PANELS = {
+ COOKIES: "cookies",
+ HEADERS: "headers",
+ MESSAGES: "messages",
+ REQUEST: "request",
+ RESPONSE: "response",
+ CACHE: "cache",
+ SECURITY: "security",
+ STACK_TRACE: "stack-trace",
+ TIMINGS: "timings",
+ HTTP_CUSTOM_REQUEST: "network-action-bar-HTTP-custom-request",
+ SEARCH: "network-action-bar-search",
+ BLOCKING: "network-action-bar-blocked",
+};
+
+const RESPONSE_HEADERS = [
+ "Cache-Control",
+ "Connection",
+ "Content-Encoding",
+ "Content-Length",
+ "ETag",
+ "Keep-Alive",
+ "Last-Modified",
+ "Server",
+ "Vary",
+];
+
+const HEADERS = [
+ {
+ name: "status",
+ label: "status3",
+ canFilter: true,
+ filterKey: "status-code",
+ },
+ {
+ name: "method",
+ canFilter: true,
+ },
+ {
+ name: "domain",
+ canFilter: true,
+ },
+ {
+ name: "file",
+ canFilter: false,
+ },
+ {
+ name: "url",
+ canFilter: true,
+ },
+ {
+ name: "protocol",
+ canFilter: true,
+ },
+ {
+ name: "scheme",
+ canFilter: true,
+ },
+ {
+ name: "remoteip",
+ canFilter: true,
+ filterKey: "remote-ip",
+ },
+ {
+ name: "cause",
+ canFilter: true,
+ },
+ {
+ name: "initiator",
+ canFilter: true,
+ },
+ {
+ name: "type",
+ canFilter: false,
+ },
+ {
+ name: "cookies",
+ canFilter: false,
+ },
+ {
+ name: "setCookies",
+ boxName: "set-cookies",
+ canFilter: false,
+ },
+ {
+ name: "transferred",
+ canFilter: true,
+ },
+ {
+ name: "contentSize",
+ boxName: "size",
+ filterKey: "size",
+ canFilter: true,
+ },
+ {
+ name: "priority",
+ boxName: "priority",
+ canFilter: true,
+ },
+ {
+ name: "startTime",
+ boxName: "start-time",
+ canFilter: false,
+ subMenu: "timings",
+ },
+ {
+ name: "endTime",
+ boxName: "end-time",
+ canFilter: false,
+ subMenu: "timings",
+ },
+ {
+ name: "responseTime",
+ boxName: "response-time",
+ canFilter: false,
+ subMenu: "timings",
+ },
+ {
+ name: "duration",
+ canFilter: false,
+ subMenu: "timings",
+ },
+ {
+ name: "latency",
+ canFilter: false,
+ subMenu: "timings",
+ },
+ ...RESPONSE_HEADERS.map(header => ({
+ name: header,
+ boxName: "response-header",
+ canFilter: false,
+ subMenu: "responseHeaders",
+ noLocalization: true,
+ })),
+ {
+ name: "waterfall",
+ canFilter: false,
+ },
+];
+
+const HEADER_FILTERS = HEADERS.filter(h => h.canFilter).map(
+ h => h.filterKey || h.name
+);
+
+const FILTER_FLAGS = [
+ ...HEADER_FILTERS,
+ "set-cookie-domain",
+ "set-cookie-name",
+ "set-cookie-value",
+ "mime-type",
+ "larger-than",
+ "transferred-larger-than",
+ "is",
+ "has-response-header",
+ "regexp",
+];
+
+const FILTER_TAGS = [
+ "html",
+ "css",
+ "js",
+ "xhr",
+ "fonts",
+ "images",
+ "media",
+ "ws",
+ "other",
+];
+
+const MESSAGE_HEADERS = [
+ {
+ name: "data",
+ width: "40%",
+ },
+ {
+ name: "size",
+ width: "12%",
+ },
+ {
+ name: "opCode",
+ width: "9%",
+ },
+ {
+ name: "maskBit",
+ width: "9%",
+ },
+ {
+ name: "finBit",
+ width: "9%",
+ },
+ {
+ name: "time",
+ width: "20%",
+ },
+ {
+ name: "eventName",
+ width: "9%",
+ },
+ {
+ name: "lastEventId",
+ width: "9%",
+ },
+ {
+ name: "retry",
+ width: "9%",
+ },
+];
+
+const REQUESTS_WATERFALL = {
+ BACKGROUND_TICKS_MULTIPLE: 5, // ms
+ BACKGROUND_TICKS_SCALES: 3,
+ BACKGROUND_TICKS_SPACING_MIN: 10, // px
+ BACKGROUND_TICKS_COLOR_RGB: [128, 136, 144],
+ // 8-bit value of the alpha component of the tick color
+ BACKGROUND_TICKS_OPACITY_MIN: 32,
+ BACKGROUND_TICKS_OPACITY_ADD: 32,
+ // Colors for timing markers (theme colors, see variables.css)
+ DOMCONTENTLOADED_TICKS_COLOR: "highlight-blue",
+ LOAD_TICKS_COLOR: "highlight-red",
+ // Opacity for the timing markers
+ TICKS_COLOR_OPACITY: 192,
+ HEADER_TICKS_MULTIPLE: 5, // ms
+ HEADER_TICKS_SPACING_MIN: 60, // px
+ // Reserve extra space for rendering waterfall time label
+ LABEL_WIDTH: 50, // px
+};
+
+const TIMING_KEYS = [
+ "blocked",
+ "dns",
+ "connect",
+ "ssl",
+ "send",
+ "wait",
+ "receive",
+];
+
+// Minimal width of Network Monitor column is 30px, for Waterfall 150px
+// Default width of columns (which are not defined in DEFAULT_COLUMNS_DATA) is 8%
+const MIN_COLUMN_WIDTH = 30; // in px
+const DEFAULT_COLUMN_WIDTH = 8; // in %
+/**
+ * A mapping of HTTP status codes.
+ */
+const SUPPORTED_HTTP_CODES = [
+ "100",
+ "101",
+ "200",
+ "201",
+ "202",
+ "203",
+ "204",
+ "205",
+ "206",
+ "300",
+ "301",
+ "302",
+ "303",
+ "304",
+ "307",
+ "308",
+ "400",
+ "401",
+ "403",
+ "404",
+ "405",
+ "406",
+ "407",
+ "408",
+ "409",
+ "410",
+ "411",
+ "412",
+ "413",
+ "414",
+ "415",
+ "416",
+ "417",
+ "418",
+ "422",
+ "425",
+ "426",
+ "428",
+ "429",
+ "431",
+ "451",
+ "500",
+ "501",
+ "502",
+ "503",
+ "504",
+ "505",
+ "511",
+];
+
+// Keys are the codes provided by server, values are localization messages
+// prefixed by "netmonitor.blocked."
+const BLOCKED_REASON_MESSAGES = {
+ devtools: "Blocked by DevTools",
+ 1001: "CORS disabled",
+ 1002: "CORS Failed",
+ 1003: "CORS Not HTTP",
+ 1004: "CORS Multiple Origin Not Allowed",
+ 1005: "CORS Missing Allow Origin",
+ 1006: "CORS No Allow Credentials",
+ 1007: "CORS Allow Origin Not Matching Origin",
+ 1008: "CORS Missing Allow Credentials",
+ 1009: "CORS Origin Header Missing",
+ 1010: "CORS External Redirect Not Allowed",
+ 1011: "CORS Preflight Did Not Succeed",
+ 1012: "CORS Invalid Allow Method",
+ 1013: "CORS Method Not Found",
+ 1014: "CORS Invalid Allow Header",
+ 1015: "CORS Missing Allow Header",
+ 2001: "Malware",
+ 2002: "Phishing",
+ 2003: "Unwanted",
+ 2004: "Tracking",
+ 2005: "Blocked",
+ 2006: "Harmful",
+ 2007: "Cryptomining",
+ 2008: "Fingerprinting",
+ 2009: "Socialtracking",
+ 3001: "Mixed Block",
+ 4000: "CSP",
+ 4001: "CSP No Data Protocol",
+ 4002: "CSP Web Extension",
+ 4003: "CSP Content Blocked",
+ 4004: "CSP Data Document",
+ 4005: "CSP Web Browser",
+ 4006: "CSP Preload",
+ 5000: "Not same-origin",
+ 6000: "Blocked By Extension",
+};
+
+const general = {
+ ACTIVITY_TYPE,
+ EVENTS,
+ TEST_EVENTS,
+ FILTER_SEARCH_DELAY: 200,
+ UPDATE_PROPS,
+ HEADERS,
+ MESSAGE_HEADERS,
+ RESPONSE_HEADERS,
+ FILTER_FLAGS,
+ FILTER_TAGS,
+ REQUESTS_WATERFALL,
+ PANELS,
+ TIMING_KEYS,
+ MIN_COLUMN_WIDTH,
+ DEFAULT_COLUMN_WIDTH,
+ SUPPORTED_HTTP_CODES,
+ BLOCKED_REASON_MESSAGES,
+ SEARCH_STATUS,
+ AUTO_EXPAND_MAX_LEVEL: 7,
+ AUTO_EXPAND_MAX_NODES: 50,
+ CHANNEL_TYPE,
+};
+
+// flatten constants
+module.exports = Object.assign({}, general, actionTypes);
diff --git a/devtools/client/netmonitor/src/create-store.js b/devtools/client/netmonitor/src/create-store.js
new file mode 100644
index 0000000000..0056e9fe2e
--- /dev/null
+++ b/devtools/client/netmonitor/src/create-store.js
@@ -0,0 +1,172 @@
+/* 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 {
+ applyMiddleware,
+ createStore,
+} = require("resource://devtools/client/shared/vendor/redux.js");
+
+const {
+ waitUntilService,
+} = require("resource://devtools/client/shared/redux/middleware/wait-service.js");
+
+const {
+ MIN_COLUMN_WIDTH,
+ DEFAULT_COLUMN_WIDTH,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Middleware
+const batching = require("resource://devtools/client/netmonitor/src/middleware/batching.js");
+const prefs = require("resource://devtools/client/netmonitor/src/middleware/prefs.js");
+const {
+ thunk,
+} = require("resource://devtools/client/shared/redux/middleware/thunk.js");
+const throttling = require("resource://devtools/client/netmonitor/src/middleware/throttling.js");
+const eventTelemetry = require("resource://devtools/client/netmonitor/src/middleware/event-telemetry.js");
+const requestBlocking = require("resource://devtools/client/netmonitor/src/middleware/request-blocking.js");
+
+// Reducers
+const rootReducer = require("resource://devtools/client/netmonitor/src/reducers/index.js");
+const {
+ FilterTypes,
+ Filters,
+} = require("resource://devtools/client/netmonitor/src/reducers/filters.js");
+const {
+ Requests,
+} = require("resource://devtools/client/netmonitor/src/reducers/requests.js");
+const {
+ Sort,
+} = require("resource://devtools/client/netmonitor/src/reducers/sort.js");
+const {
+ TimingMarkers,
+} = require("resource://devtools/client/netmonitor/src/reducers/timing-markers.js");
+const {
+ UI,
+ Columns,
+ ColumnsData,
+} = require("resource://devtools/client/netmonitor/src/reducers/ui.js");
+const {
+ Messages,
+ getMessageDefaultColumnsState,
+} = require("resource://devtools/client/netmonitor/src/reducers/messages.js");
+const {
+ Search,
+} = require("resource://devtools/client/netmonitor/src/reducers/search.js");
+
+/**
+ * Configure state and middleware for the Network monitor tool.
+ */
+function configureStore(connector, commands, telemetry) {
+ // Prepare initial state.
+ const initialState = {
+ filters: new Filters({
+ requestFilterTypes: getFilterState(),
+ }),
+ requests: new Requests(),
+ sort: new Sort(),
+ timingMarkers: new TimingMarkers(),
+ ui: UI({
+ columns: getColumnState(),
+ columnsData: getColumnsData(),
+ }),
+ messages: Messages({
+ columns: getMessageColumnState(),
+ }),
+ search: new Search(),
+ };
+
+ // Prepare middleware.
+ const middleware = applyMiddleware(
+ requestBlocking(commands),
+ thunk({ connector, commands }),
+ prefs,
+ batching,
+ throttling(connector),
+ eventTelemetry(connector, telemetry),
+ waitUntilService
+ );
+
+ return createStore(rootReducer, initialState, middleware);
+}
+
+// Helpers
+
+/**
+ * Get column state from preferences.
+ */
+function getColumnState() {
+ const columns = Columns();
+ const visibleColumns = getPref("devtools.netmonitor.visibleColumns");
+
+ const state = {};
+ for (const col in columns) {
+ state[col] = visibleColumns.includes(col);
+ }
+
+ return state;
+}
+
+/**
+ * Get column state of Messages from preferences.
+ */
+function getMessageColumnState() {
+ const columns = getMessageDefaultColumnsState();
+ const visibleColumns = getPref("devtools.netmonitor.msg.visibleColumns");
+
+ const state = {};
+ for (const col in columns) {
+ state[col] = visibleColumns.includes(col);
+ }
+
+ return state;
+}
+
+/**
+ * Get columns data (width, min-width)
+ */
+function getColumnsData() {
+ const columnsData = getPref("devtools.netmonitor.columnsData");
+ if (!columnsData.length) {
+ return ColumnsData();
+ }
+
+ const newMap = new Map();
+ columnsData.forEach(col => {
+ if (col.name) {
+ col.minWidth = col.minWidth ? col.minWidth : MIN_COLUMN_WIDTH;
+ col.width = col.width ? col.width : DEFAULT_COLUMN_WIDTH;
+ newMap.set(col.name, col);
+ }
+ });
+
+ return newMap;
+}
+
+/**
+ * Get filter state from preferences.
+ */
+function getFilterState() {
+ const activeFilters = {};
+ const filters = getPref("devtools.netmonitor.filters");
+ filters.forEach(filter => {
+ activeFilters[filter] = true;
+ });
+ return new FilterTypes(activeFilters);
+}
+
+/**
+ * Get json data from preferences
+ */
+
+function getPref(pref) {
+ try {
+ return JSON.parse(Services.prefs.getCharPref(pref));
+ } catch (_) {
+ return [];
+ }
+}
+
+exports.configureStore = configureStore;
diff --git a/devtools/client/netmonitor/src/har/README.md b/devtools/client/netmonitor/src/har/README.md
new file mode 100644
index 0000000000..fe3e362aaf
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/README.md
@@ -0,0 +1,42 @@
+# HAR
+HAR stands for `HTTP Archive` format used by various HTTP monitoring tools
+to export collected data. This format is based on JSON and is supported by
+many tools on the market including all main browsers (Firefox/Chrome/IE/Edge etc.)
+
+HAR spec:
+* http://www.softwareishard.com/blog/har-12-spec/
+* https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HAR/Overview.html
+
+HAR adopters:
+* http://www.softwareishard.com/blog/har-adopters/
+
+# Netmonitor
+Network monitor tool (in Firefox) supports exporting data in HAR format and
+the implementation consists from the following objects.
+
+## HarAutomation
+This object is responsible for automated HAR export. It listens for Network
+activity and triggers HAR export when the page is loaded.
+
+The user needs to enable `devtools.netmonitor.har.enableAutoExportToFile` pref
+and restart Firefox to switch this automation tool on.
+
+## HarBuilder
+This object is responsible for building HAR object (JSON). It gets all
+HTTP requests currently displayed in the Network panel and builds valid HAR.
+This object lazy loads all necessary data from the backend if needed,
+so the result structure is complete.
+
+## HarCollector
+This object is responsible for collecting data related to all HTTP requests
+executed by the page (including inner iframes). The final export is triggered
+by HarAutomation at the right time.
+
+Note: this object is using it's own logic to fetch data from the backend.
+It should reuse the Netmonitor Connector (src/connector/index),
+so we don't have to maintain two code paths.
+
+## HarExporter
+This object represents the main public API designed to access export logic.
+Clients, such as the Network panel itself, or WebExtensions API should use
+this object to trigger exporting of collected HTTP data from the panel.
diff --git a/devtools/client/netmonitor/src/har/har-automation.js b/devtools/client/netmonitor/src/har/har-automation.js
new file mode 100644
index 0000000000..b3c4153d1e
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/har-automation.js
@@ -0,0 +1,253 @@
+/* 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 {
+ HarCollector,
+} = require("resource://devtools/client/netmonitor/src/har/har-collector.js");
+const {
+ HarExporter,
+} = require("resource://devtools/client/netmonitor/src/har/har-exporter.js");
+const {
+ HarUtils,
+} = require("resource://devtools/client/netmonitor/src/har/har-utils.js");
+const {
+ getLongStringFullText,
+} = require("resource://devtools/client/shared/string-utils.js");
+
+const prefDomain = "devtools.netmonitor.har.";
+
+// Helper tracer. Should be generic sharable by other modules (bug 1171927)
+const trace = {
+ log(...args) {},
+};
+
+/**
+ * This object is responsible for automated HAR export. It listens
+ * for Network activity, collects all HTTP data and triggers HAR
+ * export when the page is loaded.
+ *
+ * The user needs to enable the following preference to make the
+ * auto-export work: devtools.netmonitor.har.enableAutoExportToFile
+ *
+ * HAR files are stored within directory that is specified in this
+ * preference: devtools.netmonitor.har.defaultLogDir
+ *
+ * If the default log directory preference isn't set the following
+ * directory is used by default: <profile>/har/logs
+ */
+function HarAutomation() {}
+
+HarAutomation.prototype = {
+ // Initialization
+
+ async initialize(toolbox) {
+ this.toolbox = toolbox;
+ this.commands = toolbox.commands;
+
+ await this.startMonitoring();
+ },
+
+ destroy() {
+ if (this.collector) {
+ this.collector.stop();
+ }
+
+ if (this.tabWatcher) {
+ this.tabWatcher.disconnect();
+ }
+ },
+
+ // Automation
+
+ async startMonitoring() {
+ await this.toolbox.resourceCommand.watchResources(
+ [this.toolbox.resourceCommand.TYPES.DOCUMENT_EVENT],
+ {
+ onAvailable: resources => {
+ // Only consider top level document, and ignore remote iframes top document
+ if (
+ resources.find(
+ r => r.name == "will-navigate" && r.targetFront.isTopLevel
+ )
+ ) {
+ this.pageLoadBegin();
+ }
+ if (
+ resources.find(
+ r => r.name == "dom-complete" && r.targetFront.isTopLevel
+ )
+ ) {
+ this.pageLoadDone();
+ }
+ },
+ ignoreExistingResources: true,
+ }
+ );
+ },
+
+ pageLoadBegin(response) {
+ this.resetCollector();
+ },
+
+ resetCollector() {
+ if (this.collector) {
+ this.collector.stop();
+ }
+
+ // A page is about to be loaded, start collecting HTTP
+ // data from events sent from the backend.
+ this.collector = new HarCollector({
+ commands: this.commands,
+ });
+
+ this.collector.start();
+ },
+
+ /**
+ * A page is done loading, export collected data. Note that
+ * some requests for additional page resources might be pending,
+ * so export all after all has been properly received from the backend.
+ *
+ * This collector still works and collects any consequent HTTP
+ * traffic (e.g. XHRs) happening after the page is loaded and
+ * The additional traffic can be exported by executing
+ * triggerExport on this object.
+ */
+ pageLoadDone(response) {
+ trace.log("HarAutomation.pageLoadDone; ", response);
+
+ if (this.collector) {
+ this.collector.waitForHarLoad().then(collector => {
+ return this.autoExport();
+ });
+ }
+ },
+
+ autoExport() {
+ const autoExport = Services.prefs.getBoolPref(
+ prefDomain + "enableAutoExportToFile"
+ );
+
+ if (!autoExport) {
+ return Promise.resolve();
+ }
+
+ // Auto export to file is enabled, so save collected data
+ // into a file and use all the default options.
+ const data = {
+ fileName: Services.prefs.getCharPref(prefDomain + "defaultFileName"),
+ };
+
+ return this.executeExport(data);
+ },
+
+ // Public API
+
+ /**
+ * Export all what is currently collected.
+ */
+ triggerExport(data) {
+ if (!data.fileName) {
+ data.fileName = Services.prefs.getCharPref(
+ prefDomain + "defaultFileName"
+ );
+ }
+
+ return this.executeExport(data);
+ },
+
+ /**
+ * Clear currently collected data.
+ */
+ clear() {
+ this.resetCollector();
+ },
+
+ // HAR Export
+
+ /**
+ * Execute HAR export. This method fetches all data from the
+ * Network panel (asynchronously) and saves it into a file.
+ */
+ async executeExport(data) {
+ const items = this.collector.getItems();
+ const { title } = this.commands.targetCommand.targetFront;
+
+ const netMonitor = await this.toolbox.getNetMonitorAPI();
+ const connector = await netMonitor.getHarExportConnector();
+
+ const options = {
+ connector,
+ requestData: null,
+ getTimingMarker: null,
+ getString: this.getString.bind(this),
+ view: this,
+ items,
+ };
+
+ options.defaultFileName = data.fileName;
+ options.compress = data.compress;
+ options.title = data.title || title;
+ options.id = data.id;
+ options.jsonp = data.jsonp;
+ options.includeResponseBodies = data.includeResponseBodies;
+ options.jsonpCallback = data.jsonpCallback;
+ options.forceExport = data.forceExport;
+
+ trace.log("HarAutomation.executeExport; " + data.fileName, options);
+
+ const jsonString = await HarExporter.fetchHarData(options);
+
+ // Save the HAR file if the file name is provided.
+ if (jsonString && options.defaultFileName) {
+ const file = getDefaultTargetFile(options);
+ if (file) {
+ HarUtils.saveToFile(file, jsonString, options.compress);
+ }
+ }
+
+ return jsonString;
+ },
+
+ /**
+ * Fetches the full text of a string.
+ */
+ async getString(stringGrip) {
+ const fullText = await getLongStringFullText(
+ this.commands.client,
+ stringGrip
+ );
+ return fullText;
+ },
+};
+
+// Protocol Helpers
+
+/**
+ * Returns target file for exported HAR data.
+ */
+function getDefaultTargetFile(options) {
+ const path =
+ options.defaultLogDir ||
+ Services.prefs.getCharPref("devtools.netmonitor.har.defaultLogDir");
+ const folder = HarUtils.getLocalDirectory(path);
+
+ const host = new URL(options.connector.currentTarget.url);
+ const fileName = HarUtils.getHarFileName(
+ options.defaultFileName,
+ options.jsonp,
+ options.compress,
+ host.hostname
+ );
+
+ folder.append(fileName);
+ folder.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("0666", 8));
+
+ return folder;
+}
+
+// Exports from this module
+exports.HarAutomation = HarAutomation;
diff --git a/devtools/client/netmonitor/src/har/har-builder-utils.js b/devtools/client/netmonitor/src/har/har-builder-utils.js
new file mode 100644
index 0000000000..e669263681
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/har-builder-utils.js
@@ -0,0 +1,30 @@
+/* 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";
+
+/**
+ * Currently supported HAR version.
+ */
+const HAR_VERSION = "1.2";
+
+function buildHarLog(appInfo) {
+ return {
+ log: {
+ version: HAR_VERSION,
+ creator: {
+ name: appInfo.name,
+ version: appInfo.version,
+ },
+ browser: {
+ name: appInfo.name,
+ version: appInfo.version,
+ },
+ pages: [],
+ entries: [],
+ },
+ };
+}
+
+exports.buildHarLog = buildHarLog;
diff --git a/devtools/client/netmonitor/src/har/har-builder.js b/devtools/client/netmonitor/src/har/har-builder.js
new file mode 100644
index 0000000000..9361df7f03
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/har-builder.js
@@ -0,0 +1,656 @@
+/* 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 appInfo = Services.appinfo;
+const { LocalizationHelper } = require("resource://devtools/shared/l10n.js");
+const { CurlUtils } = require("resource://devtools/client/shared/curl.js");
+const {
+ getFormDataSections,
+ getUrlQuery,
+ parseQueryString,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ buildHarLog,
+} = require("resource://devtools/client/netmonitor/src/har/har-builder-utils.js");
+const L10N = new LocalizationHelper("devtools/client/locales/har.properties");
+const {
+ TIMING_KEYS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * This object is responsible for building HAR file. See HAR spec:
+ * https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HAR/Overview.html
+ * http://www.softwareishard.com/blog/har-12-spec/
+ *
+ * @param {Object} options
+ * configuration object
+ * @param {Boolean} options.connector
+ * Set to true to include HTTP response bodies in the result data
+ * structure.
+ * @param {String} options.id
+ * ID of the exported page.
+ * @param {Boolean} options.includeResponseBodies
+ * Set to true to include HTTP response bodies in the result data
+ * structure.
+ * @param {Array} options.items
+ * List of network events to be exported.
+ * @param {Boolean} options.supportsMultiplePages
+ * Set to true to create distinct page entries for each navigation.
+ */
+var HarBuilder = function (options) {
+ this._connector = options.connector;
+ this._id = options.id;
+ this._includeResponseBodies = options.includeResponseBodies;
+ this._items = options.items;
+ // Page id counter, only used when options.supportsMultiplePages is true.
+ this._pageId = options.supportsMultiplePages ? 0 : options.id;
+ this._pageMap = [];
+ this._supportsMultiplePages = options.supportsMultiplePages;
+ this._title = this._connector.currentTarget.title;
+};
+
+HarBuilder.prototype = {
+ // Public API
+
+ /**
+ * This is the main method used to build the entire result HAR data.
+ * The process is asynchronous since it can involve additional RDP
+ * communication (e.g. resolving long strings).
+ *
+ * @returns {Promise} A promise that resolves to the HAR object when
+ * the entire build process is done.
+ */
+ async build() {
+ this.promises = [];
+
+ // Build basic structure for data.
+ const harLog = buildHarLog(appInfo);
+
+ // Build pages.
+ this.buildPages(harLog.log);
+
+ // Build entries.
+ for (const request of this._items) {
+ const entry = await this.buildEntry(harLog.log, request);
+ if (entry) {
+ harLog.log.entries.push(entry);
+ }
+ }
+
+ // Some data needs to be fetched from the backend during the
+ // build process, so wait till all is done.
+ await Promise.all(this.promises);
+
+ return harLog;
+ },
+
+ // Helpers
+
+ buildPages(log) {
+ if (this._supportsMultiplePages) {
+ this.buildPagesFromTargetTitles(log);
+ } else if (this._items.length) {
+ const firstRequest = this._items[0];
+ const page = this.buildPage(this._title, firstRequest);
+ log.pages.push(page);
+ this._pageMap[this._id] = page;
+ }
+ },
+
+ buildPagesFromTargetTitles(log) {
+ // Retrieve the additional HAR data collected by the connector.
+ const { initialTargetTitle, navigationRequests, targetTitlesPerURL } =
+ this._connector.getHarData();
+ const firstNavigationRequest = navigationRequests[0];
+ const firstRequest = this._items[0];
+
+ if (
+ !firstNavigationRequest ||
+ firstRequest.resourceId !== firstNavigationRequest.resourceId
+ ) {
+ // If the first request is not a navigation request, it must be related
+ // to the initial page. Create a first page entry for such early requests.
+ const initialPage = this.buildPage(initialTargetTitle, firstRequest);
+ log.pages.push(initialPage);
+ }
+
+ for (const request of navigationRequests) {
+ if (targetTitlesPerURL.has(request.url)) {
+ const title = targetTitlesPerURL.get(request.url);
+ const page = this.buildPage(title, request);
+ log.pages.push(page);
+ } else {
+ console.warn(
+ `Could not find any page corresponding to a navigation to ${request.url}`
+ );
+ }
+ }
+ },
+
+ buildPage(title, networkEvent) {
+ const page = {};
+
+ page.id = "page_" + this._pageId;
+ page.pageTimings = this.buildPageTimings(page, networkEvent);
+ page.startedDateTime = dateToHarString(new Date(networkEvent.startedMs));
+ page.title = title;
+
+ // Increase the pageId, for upcoming calls to buildPage.
+ // If supportsMultiplePages is disabled this method is only called once.
+ this._pageId++;
+
+ return page;
+ },
+
+ getPage(log, entry) {
+ const existingPage = log.pages.findLast(
+ ({ startedDateTime }) => startedDateTime <= entry.startedDateTime
+ );
+
+ if (!existingPage) {
+ throw new Error(
+ "Could not find a page for request: " + entry.request.url
+ );
+ }
+
+ return existingPage;
+ },
+
+ async buildEntry(log, networkEvent) {
+ const entry = {};
+ entry.startedDateTime = dateToHarString(new Date(networkEvent.startedMs));
+
+ let { eventTimings, id } = networkEvent;
+ try {
+ if (!eventTimings && this._connector.requestData) {
+ eventTimings = await this._connector.requestData(id, "eventTimings");
+ }
+
+ entry.request = await this.buildRequest(networkEvent);
+ entry.response = await this.buildResponse(networkEvent);
+ entry.cache = await this.buildCache(networkEvent);
+ } catch (e) {
+ // Ignore any request for which we can't retrieve lazy data
+ // The request has most likely been destroyed on the server side,
+ // either because persist is disabled or the request's target/WindowGlobal/process
+ // has been destroyed.
+ console.warn("HAR builder failed on", networkEvent.url, e, e.stack);
+ return null;
+ }
+ entry.timings = eventTimings ? eventTimings.timings : {};
+
+ // Calculate total time by summing all timings. Note that
+ // `networkEvent.totalTime` can't be used since it doesn't have to
+ // correspond to plain summary of individual timings.
+ // With TCP Fast Open and TLS early data sending data can
+ // start at the same time as connect (we can send data on
+ // TCP syn packet). Also TLS handshake can carry application
+ // data thereby overlapping a sending data period and TLS
+ // handshake period.
+ entry.time = TIMING_KEYS.reduce((sum, type) => {
+ const time = entry.timings[type];
+ return typeof time != "undefined" && time != -1 ? sum + time : sum;
+ }, 0);
+
+ // Security state isn't part of HAR spec, and so create
+ // custom field that needs to use '_' prefix.
+ entry._securityState = networkEvent.securityState;
+
+ if (networkEvent.remoteAddress) {
+ entry.serverIPAddress = networkEvent.remoteAddress;
+ }
+
+ if (networkEvent.remotePort) {
+ entry.connection = networkEvent.remotePort + "";
+ }
+
+ const page = this.getPage(log, entry);
+ entry.pageref = page.id;
+
+ return entry;
+ },
+
+ buildPageTimings(page, networkEvent) {
+ // Event timing info isn't available
+ const timings = {
+ onContentLoad: -1,
+ onLoad: -1,
+ };
+
+ // TODO: This method currently ignores the networkEvent and always retrieves
+ // the same timing markers for all pages. Seee Bug 1833806.
+ if (this._connector.getTimingMarker) {
+ timings.onContentLoad = this._connector.getTimingMarker(
+ "firstDocumentDOMContentLoadedTimestamp"
+ );
+ timings.onLoad = this._connector.getTimingMarker(
+ "firstDocumentLoadTimestamp"
+ );
+ }
+
+ return timings;
+ },
+
+ async buildRequest(networkEvent) {
+ // When using HarAutomation, HarCollector will automatically fetch requestHeaders
+ // and requestCookies, but when we use it from netmonitor, FirefoxDataProvider
+ // should fetch it itself lazily, via requestData.
+
+ let { id, requestHeaders } = networkEvent;
+ if (!requestHeaders && this._connector.requestData) {
+ requestHeaders = await this._connector.requestData(id, "requestHeaders");
+ }
+
+ let { requestCookies } = networkEvent;
+ if (!requestCookies && this._connector.requestData) {
+ requestCookies = await this._connector.requestData(id, "requestCookies");
+ }
+
+ const request = {
+ bodySize: 0,
+ };
+ request.method = networkEvent.method;
+ request.url = networkEvent.url;
+ request.httpVersion = networkEvent.httpVersion || "";
+ request.headers = this.buildHeaders(requestHeaders);
+ request.headers = this.appendHeadersPostData(request.headers, networkEvent);
+ request.cookies = this.buildCookies(requestCookies);
+ request.queryString = parseQueryString(getUrlQuery(networkEvent.url)) || [];
+ request.headersSize = requestHeaders.headersSize;
+ request.postData = await this.buildPostData(networkEvent);
+
+ if (request.postData?.text) {
+ request.bodySize = request.postData.text.length;
+ }
+
+ return request;
+ },
+
+ /**
+ * Fetch all header values from the backend (if necessary) and
+ * build the result HAR structure.
+ *
+ * @param {Object} input Request or response header object.
+ */
+ buildHeaders(input) {
+ if (!input) {
+ return [];
+ }
+
+ return this.buildNameValuePairs(input.headers);
+ },
+
+ appendHeadersPostData(input = [], networkEvent) {
+ if (!networkEvent.requestPostData) {
+ return input;
+ }
+
+ this.fetchData(networkEvent.requestPostData.postData.text).then(value => {
+ const multipartHeaders = CurlUtils.getHeadersFromMultipartText(value);
+ for (const header of multipartHeaders) {
+ input.push(header);
+ }
+ });
+
+ return input;
+ },
+
+ buildCookies(input) {
+ if (!input) {
+ return [];
+ }
+
+ return this.buildNameValuePairs(input.cookies || input);
+ },
+
+ buildNameValuePairs(entries) {
+ const result = [];
+
+ // HAR requires headers array to be presented, so always
+ // return at least an empty array.
+ if (!entries) {
+ return result;
+ }
+
+ // Make sure header values are fully fetched from the server.
+ entries.forEach(entry => {
+ this.fetchData(entry.value).then(value => {
+ result.push({
+ name: entry.name,
+ value,
+ });
+ });
+ });
+
+ return result;
+ },
+
+ async buildPostData(networkEvent) {
+ // When using HarAutomation, HarCollector will automatically fetch requestPostData
+ // and requestHeaders, but when we use it from netmonitor, FirefoxDataProvider
+ // should fetch it itself lazily, via requestData.
+ let { id, requestHeaders, requestPostData } = networkEvent;
+ let requestHeadersFromUploadStream;
+
+ if (!requestPostData && this._connector.requestData) {
+ requestPostData = await this._connector.requestData(
+ id,
+ "requestPostData"
+ );
+ requestHeadersFromUploadStream = requestPostData.uploadHeaders;
+ }
+
+ if (!requestPostData.postData.text) {
+ return undefined;
+ }
+
+ if (!requestHeaders && this._connector.requestData) {
+ requestHeaders = await this._connector.requestData(id, "requestHeaders");
+ }
+
+ const postData = {
+ mimeType: findValue(requestHeaders.headers, "content-type"),
+ params: [],
+ text: requestPostData.postData.text,
+ };
+
+ if (requestPostData.postDataDiscarded) {
+ postData.comment = L10N.getStr("har.requestBodyNotIncluded");
+ return postData;
+ }
+
+ // If we are dealing with URL encoded body, parse parameters.
+ if (
+ CurlUtils.isUrlEncodedRequest({
+ headers: requestHeaders.headers,
+ postDataText: postData.text,
+ })
+ ) {
+ postData.mimeType = "application/x-www-form-urlencoded";
+ // Extract form parameters and produce nice HAR array.
+ const formDataSections = await getFormDataSections(
+ requestHeaders,
+ requestHeadersFromUploadStream,
+ requestPostData,
+ this._connector.getLongString
+ );
+
+ formDataSections.forEach(section => {
+ const paramsArray = parseQueryString(section);
+ if (paramsArray) {
+ postData.params = [...postData.params, ...paramsArray];
+ }
+ });
+ }
+
+ return postData;
+ },
+
+ async buildResponse(networkEvent) {
+ // When using HarAutomation, HarCollector will automatically fetch responseHeaders
+ // and responseCookies, but when we use it from netmonitor, FirefoxDataProvider
+ // should fetch it itself lazily, via requestData.
+
+ let { id, responseCookies, responseHeaders } = networkEvent;
+ if (!responseHeaders && this._connector.requestData) {
+ responseHeaders = await this._connector.requestData(
+ id,
+ "responseHeaders"
+ );
+ }
+
+ if (!responseCookies && this._connector.requestData) {
+ responseCookies = await this._connector.requestData(
+ id,
+ "responseCookies"
+ );
+ }
+
+ const response = {
+ status: 0,
+ };
+
+ // Arbitrary value if it's aborted to make sure status has a number
+ if (networkEvent.status) {
+ response.status = parseInt(networkEvent.status, 10);
+ }
+ response.statusText = networkEvent.statusText || "";
+ response.httpVersion = networkEvent.httpVersion || "";
+
+ response.headers = this.buildHeaders(responseHeaders);
+ response.cookies = this.buildCookies(responseCookies);
+ response.content = await this.buildContent(networkEvent);
+
+ const headers = responseHeaders ? responseHeaders.headers : null;
+ const headersSize = responseHeaders ? responseHeaders.headersSize : -1;
+
+ response.redirectURL = findValue(headers, "Location");
+ response.headersSize = headersSize;
+
+ // 'bodySize' is size of the received response body in bytes.
+ // Set to zero in case of responses coming from the cache (304).
+ // Set to -1 if the info is not available.
+ if (typeof networkEvent.transferredSize != "number") {
+ response.bodySize = response.status == 304 ? 0 : -1;
+ } else {
+ response.bodySize = networkEvent.transferredSize;
+ }
+
+ return response;
+ },
+
+ async buildContent(networkEvent) {
+ const content = {
+ mimeType: networkEvent.mimeType,
+ size: -1,
+ };
+
+ // When using HarAutomation, HarCollector will automatically fetch responseContent,
+ // but when we use it from netmonitor, FirefoxDataProvider should fetch it itself
+ // lazily, via requestData.
+ let { responseContent } = networkEvent;
+ if (!responseContent && this._connector.requestData) {
+ responseContent = await this._connector.requestData(
+ networkEvent.id,
+ "responseContent"
+ );
+ }
+ if (responseContent?.content) {
+ content.size = responseContent.content.size;
+ content.encoding = responseContent.content.encoding;
+ }
+
+ const includeBodies = this._includeResponseBodies;
+ const contentDiscarded = responseContent
+ ? responseContent.contentDiscarded
+ : false;
+
+ // The comment is appended only if the response content
+ // is explicitly discarded.
+ if (!includeBodies || contentDiscarded) {
+ content.comment = L10N.getStr("har.responseBodyNotIncluded");
+ return content;
+ }
+
+ if (responseContent) {
+ const { text } = responseContent.content;
+ this.fetchData(text).then(value => {
+ content.text = value;
+ });
+ }
+
+ return content;
+ },
+
+ async buildCache(networkEvent) {
+ const cache = {};
+
+ // if resource has changed, return early
+ if (networkEvent.status != "304") {
+ return cache;
+ }
+
+ if (networkEvent.responseCacheAvailable && this._connector.requestData) {
+ const responseCache = await this._connector.requestData(
+ networkEvent.id,
+ "responseCache"
+ );
+ if (responseCache.cache) {
+ cache.afterRequest = this.buildCacheEntry(responseCache.cache);
+ }
+ } else if (networkEvent.responseCache?.cache) {
+ cache.afterRequest = this.buildCacheEntry(
+ networkEvent.responseCache.cache
+ );
+ } else {
+ cache.afterRequest = null;
+ }
+
+ return cache;
+ },
+
+ buildCacheEntry(cacheEntry) {
+ const cache = {};
+
+ if (typeof cacheEntry !== "undefined") {
+ cache.expires = findKeys(cacheEntry, ["expirationTime", "expires"]);
+ cache.lastFetched = findKeys(cacheEntry, ["lastFetched"]);
+
+ // TODO: eTag support
+ // Har format expects cache entries to provide information about eTag,
+ // however this is not currently exposed on nsICacheEntry.
+ // This should be stored under cache.eTag. See Bug 1799844.
+
+ cache.fetchCount = findKeys(cacheEntry, ["fetchCount"]);
+
+ // har-importer.js, along with other files, use buildCacheEntry
+ // initial value comes from properties without underscores.
+ // this checks for both in appropriate order.
+ cache._dataSize = findKeys(cacheEntry, ["storageDataSize", "_dataSize"]);
+ cache._lastModified = findKeys(cacheEntry, [
+ "lastModified",
+ "_lastModified",
+ ]);
+ cache._device = findKeys(cacheEntry, ["deviceID", "_device"]);
+ }
+
+ return cache;
+ },
+
+ // RDP Helpers
+
+ fetchData(string) {
+ const promise = this._connector.getLongString(string).then(value => {
+ return value;
+ });
+
+ // Building HAR is asynchronous and not done till all
+ // collected promises are resolved.
+ this.promises.push(promise);
+
+ return promise;
+ },
+};
+
+// Helpers
+
+/**
+ * Find specified keys within an object.
+ * Searches object for keys passed in, returns first value returned,
+ * or an empty string.
+ *
+ * @param obj (object)
+ * @param keys (array)
+ * @returns {string}
+ */
+function findKeys(obj, keys) {
+ if (!keys) {
+ return "";
+ }
+
+ const keyFound = keys.filter(key => obj[key]);
+ if (!keys.length) {
+ return "";
+ }
+
+ const value = obj[keyFound[0]];
+ if (typeof value === "undefined" || typeof value === "object") {
+ return "";
+ }
+
+ return String(value);
+}
+
+/**
+ * Find specified value within an array of name-value pairs
+ * (used for headers, cookies and cache entries)
+ */
+function findValue(arr, name) {
+ if (!arr) {
+ return "";
+ }
+
+ name = name.toLowerCase();
+ const result = arr.find(entry => entry.name.toLowerCase() == name);
+ return result ? result.value : "";
+}
+
+/**
+ * Generate HAR representation of a date.
+ * (YYYY-MM-DDThh:mm:ss.sTZD, e.g. 2009-07-24T19:20:30.45+01:00)
+ * See also HAR Schema: http://janodvarko.cz/har/viewer/
+ *
+ * Note: it would be great if we could utilize Date.toJSON(), but
+ * it doesn't return proper time zone offset.
+ *
+ * An example:
+ * This helper returns: 2015-05-29T16:10:30.424+02:00
+ * Date.toJSON() returns: 2015-05-29T14:10:30.424Z
+ *
+ * @param date {Date} The date object we want to convert.
+ */
+function dateToHarString(date) {
+ function f(n, c) {
+ if (!c) {
+ c = 2;
+ }
+ let s = String(n);
+ while (s.length < c) {
+ s = "0" + s;
+ }
+ return s;
+ }
+
+ const result =
+ date.getFullYear() +
+ "-" +
+ f(date.getMonth() + 1) +
+ "-" +
+ f(date.getDate()) +
+ "T" +
+ f(date.getHours()) +
+ ":" +
+ f(date.getMinutes()) +
+ ":" +
+ f(date.getSeconds()) +
+ "." +
+ f(date.getMilliseconds(), 3);
+
+ let offset = date.getTimezoneOffset();
+ const positive = offset > 0;
+
+ // Convert to positive number before using Math.floor (see issue 5512)
+ offset = Math.abs(offset);
+ const offsetHours = Math.floor(offset / 60);
+ const offsetMinutes = Math.floor(offset % 60);
+ const prettyOffset =
+ (positive > 0 ? "-" : "+") + f(offsetHours) + ":" + f(offsetMinutes);
+
+ return result + prettyOffset;
+}
+
+// Exports from this module
+exports.HarBuilder = HarBuilder;
diff --git a/devtools/client/netmonitor/src/har/har-collector.js b/devtools/client/netmonitor/src/har/har-collector.js
new file mode 100644
index 0000000000..c5a4ae959d
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/har-collector.js
@@ -0,0 +1,488 @@
+/* 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 {
+ getLongStringFullText,
+} = require("resource://devtools/client/shared/string-utils.js");
+
+// Helper tracer. Should be generic sharable by other modules (bug 1171927)
+const trace = {
+ log(...args) {},
+};
+
+/**
+ * This object is responsible for collecting data related to all
+ * HTTP requests executed by the page (including inner iframes).
+ */
+function HarCollector(options) {
+ this.commands = options.commands;
+
+ this.onResourceAvailable = this.onResourceAvailable.bind(this);
+ this.onResourceUpdated = this.onResourceUpdated.bind(this);
+ this.onRequestHeaders = this.onRequestHeaders.bind(this);
+ this.onRequestCookies = this.onRequestCookies.bind(this);
+ this.onRequestPostData = this.onRequestPostData.bind(this);
+ this.onResponseHeaders = this.onResponseHeaders.bind(this);
+ this.onResponseCookies = this.onResponseCookies.bind(this);
+ this.onResponseContent = this.onResponseContent.bind(this);
+ this.onEventTimings = this.onEventTimings.bind(this);
+
+ this.clear();
+}
+
+HarCollector.prototype = {
+ // Connection
+
+ async start() {
+ await this.commands.resourceCommand.watchResources(
+ [this.commands.resourceCommand.TYPES.NETWORK_EVENT],
+ {
+ onAvailable: this.onResourceAvailable,
+ onUpdated: this.onResourceUpdated,
+ }
+ );
+ },
+
+ async stop() {
+ await this.commands.resourceCommand.unwatchResources(
+ [this.commands.resourceCommand.TYPES.NETWORK_EVENT],
+ {
+ onAvailable: this.onResourceAvailable,
+ onUpdated: this.onResourceUpdated,
+ }
+ );
+ },
+
+ clear() {
+ // Any pending requests events will be ignored (they turn
+ // into zombies, since not present in the files array).
+ this.files = new Map();
+ this.items = [];
+ this.firstRequestStart = -1;
+ this.lastRequestStart = -1;
+ this.requests = [];
+ },
+
+ waitForHarLoad() {
+ // There should be yet another timeout e.g.:
+ // 'devtools.netmonitor.har.pageLoadTimeout'
+ // that should force export even if page isn't fully loaded.
+ return new Promise(resolve => {
+ this.waitForResponses().then(() => {
+ trace.log("HarCollector.waitForHarLoad; DONE HAR loaded!");
+ resolve(this);
+ });
+ });
+ },
+
+ waitForResponses() {
+ trace.log("HarCollector.waitForResponses; " + this.requests.length);
+
+ // All requests for additional data must be received to have complete
+ // HTTP info to generate the result HAR file. So, wait for all current
+ // promises. Note that new promises (requests) can be generated during the
+ // process of HTTP data collection.
+ return waitForAll(this.requests).then(() => {
+ // All responses are received from the backend now. We yet need to
+ // wait for a little while to see if a new request appears. If yes,
+ // lets's start gathering HTTP data again. If no, we can declare
+ // the page loaded.
+ // If some new requests appears in the meantime the promise will
+ // be rejected and we need to wait for responses all over again.
+
+ this.pageLoadDeferred = this.waitForTimeout().then(
+ () => {
+ // Page loaded!
+ },
+ () => {
+ trace.log(
+ "HarCollector.waitForResponses; NEW requests " +
+ "appeared during page timeout!"
+ );
+ // New requests executed, let's wait again.
+ return this.waitForResponses();
+ }
+ );
+ return this.pageLoadDeferred;
+ });
+ },
+
+ // Page Loaded Timeout
+
+ /**
+ * The page is loaded when there are no new requests within given period
+ * of time. The time is set in preferences:
+ * 'devtools.netmonitor.har.pageLoadedTimeout'
+ */
+ waitForTimeout() {
+ // The auto-export is not done if the timeout is set to zero (or less).
+ // This is useful in cases where the export is done manually through
+ // API exposed to the content.
+ const timeout = Services.prefs.getIntPref(
+ "devtools.netmonitor.har.pageLoadedTimeout"
+ );
+
+ trace.log("HarCollector.waitForTimeout; " + timeout);
+
+ return new Promise((resolve, reject) => {
+ if (timeout <= 0) {
+ resolve();
+ }
+ this.pageLoadReject = reject;
+ this.pageLoadTimeout = setTimeout(() => {
+ trace.log("HarCollector.onPageLoadTimeout;");
+ resolve();
+ }, timeout);
+ });
+ },
+
+ resetPageLoadTimeout() {
+ // Remove the current timeout.
+ if (this.pageLoadTimeout) {
+ trace.log("HarCollector.resetPageLoadTimeout;");
+
+ clearTimeout(this.pageLoadTimeout);
+ this.pageLoadTimeout = null;
+ }
+
+ // Reject the current page load promise
+ if (this.pageLoadReject) {
+ this.pageLoadReject();
+ this.pageLoadReject = null;
+ }
+ },
+
+ // Collected Data
+
+ getFile(actorId) {
+ return this.files.get(actorId);
+ },
+
+ getItems() {
+ return this.items;
+ },
+
+ // Event Handlers
+
+ onResourceAvailable(resources) {
+ for (const resource of resources) {
+ trace.log("HarCollector.onNetworkEvent; ", resource);
+
+ const { actor, startedDateTime, method, url, isXHR } = resource;
+ const startTime = Date.parse(startedDateTime);
+
+ if (this.firstRequestStart == -1) {
+ this.firstRequestStart = startTime;
+ }
+
+ if (this.lastRequestEnd < startTime) {
+ this.lastRequestEnd = startTime;
+ }
+
+ let file = this.getFile(actor);
+ if (file) {
+ console.error(
+ "HarCollector.onNetworkEvent; ERROR " + "existing file conflict!"
+ );
+ continue;
+ }
+
+ file = {
+ id: actor,
+ startedDeltaMs: startTime - this.firstRequestStart,
+ startedMs: startTime,
+ method,
+ url,
+ isXHR,
+ };
+
+ this.files.set(actor, file);
+
+ // Mimic the Net panel data structure
+ this.items.push(file);
+ }
+ },
+
+ onResourceUpdated(updates) {
+ for (const { resource } of updates) {
+ // Skip events from unknown actors (not in the list).
+ // It can happen when there are zombie requests received after
+ // the target is closed or multiple tabs are attached through
+ // one connection (one DevToolsClient object).
+ const file = this.getFile(resource.actor);
+ if (!file) {
+ return;
+ }
+
+ const includeResponseBodies = Services.prefs.getBoolPref(
+ "devtools.netmonitor.har.includeResponseBodies"
+ );
+
+ [
+ {
+ type: "eventTimings",
+ method: "getEventTimings",
+ callbackName: "onEventTimings",
+ },
+ {
+ type: "requestHeaders",
+ method: "getRequestHeaders",
+ callbackName: "onRequestHeaders",
+ },
+ {
+ type: "requestPostData",
+ method: "getRequestPostData",
+ callbackName: "onRequestPostData",
+ },
+ {
+ type: "responseHeaders",
+ method: "getResponseHeaders",
+ callbackName: "onResponseHeaders",
+ },
+ { type: "responseStart" },
+ {
+ type: "responseContent",
+ method: "getResponseContent",
+ callbackName: "onResponseContent",
+ },
+ {
+ type: "requestCookies",
+ method: "getRequestCookies",
+ callbackName: "onRequestCookies",
+ },
+ {
+ type: "responseCookies",
+ method: "getResponseCookies",
+ callbackName: "onResponseCookies",
+ },
+ ].forEach(updateType => {
+ trace.log(
+ "HarCollector.onNetworkEventUpdate; " + updateType.type,
+ resource
+ );
+
+ let request;
+ if (resource[`${updateType.type}Available`]) {
+ if (updateType.type == "responseStart") {
+ file.httpVersion = resource.httpVersion;
+ file.status = resource.status;
+ file.statusText = resource.statusText;
+ } else if (updateType.type == "responseContent") {
+ file.contentSize = resource.contentSize;
+ file.mimeType = resource.mimeType;
+ file.transferredSize = resource.transferredSize;
+ if (includeResponseBodies) {
+ request = this.getData(
+ resource.actor,
+ updateType.method,
+ this[updateType.callbackName]
+ );
+ }
+ } else {
+ request = this.getData(
+ resource.actor,
+ updateType.method,
+ this[updateType.callbackName]
+ );
+ }
+ }
+
+ if (request) {
+ this.requests.push(request);
+ }
+ this.resetPageLoadTimeout();
+ });
+ }
+ },
+
+ async getData(actor, method, callback) {
+ const file = this.getFile(actor);
+
+ trace.log(
+ "HarCollector.getData; REQUEST " + method + ", " + file.url,
+ file
+ );
+
+ // Bug 1519082: We don't create fronts for NetworkEvent actors,
+ // so that we have to do the request manually via DevToolsClient.request()
+ const packet = {
+ to: actor,
+ type: method,
+ };
+ const response = await this.commands.client.request(packet);
+
+ trace.log(
+ "HarCollector.getData; RESPONSE " + method + ", " + file.url,
+ response
+ );
+ callback(response);
+ return response;
+ },
+
+ /**
+ * Handles additional information received for a "requestHeaders" packet.
+ *
+ * @param object response
+ * The message received from the server.
+ */
+ onRequestHeaders(response) {
+ const file = this.getFile(response.from);
+ file.requestHeaders = response;
+
+ this.getLongHeaders(response.headers);
+ },
+
+ /**
+ * Handles additional information received for a "requestCookies" packet.
+ *
+ * @param object response
+ * The message received from the server.
+ */
+ onRequestCookies(response) {
+ const file = this.getFile(response.from);
+ file.requestCookies = response;
+
+ this.getLongHeaders(response.cookies);
+ },
+
+ /**
+ * Handles additional information received for a "requestPostData" packet.
+ *
+ * @param object response
+ * The message received from the server.
+ */
+ onRequestPostData(response) {
+ trace.log("HarCollector.onRequestPostData;", response);
+
+ const file = this.getFile(response.from);
+ file.requestPostData = response;
+
+ // Resolve long string
+ const { text } = response.postData;
+ if (typeof text == "object") {
+ this.getString(text).then(value => {
+ response.postData.text = value;
+ });
+ }
+ },
+
+ /**
+ * Handles additional information received for a "responseHeaders" packet.
+ *
+ * @param object response
+ * The message received from the server.
+ */
+ onResponseHeaders(response) {
+ const file = this.getFile(response.from);
+ file.responseHeaders = response;
+
+ this.getLongHeaders(response.headers);
+ },
+
+ /**
+ * Handles additional information received for a "responseCookies" packet.
+ *
+ * @param object response
+ * The message received from the server.
+ */
+ onResponseCookies(response) {
+ const file = this.getFile(response.from);
+ file.responseCookies = response;
+
+ this.getLongHeaders(response.cookies);
+ },
+
+ /**
+ * Handles additional information received for a "responseContent" packet.
+ *
+ * @param object response
+ * The message received from the server.
+ */
+ onResponseContent(response) {
+ const file = this.getFile(response.from);
+ file.responseContent = response;
+
+ // Resolve long string
+ const { text } = response.content;
+ if (typeof text == "object") {
+ this.getString(text).then(value => {
+ response.content.text = value;
+ });
+ }
+ },
+
+ /**
+ * Handles additional information received for a "eventTimings" packet.
+ *
+ * @param object response
+ * The message received from the server.
+ */
+ onEventTimings(response) {
+ const file = this.getFile(response.from);
+ file.eventTimings = response;
+ file.totalTime = response.totalTime;
+ },
+
+ // Helpers
+
+ getLongHeaders(headers) {
+ for (const header of headers) {
+ if (typeof header.value == "object") {
+ try {
+ this.getString(header.value).then(value => {
+ header.value = value;
+ });
+ } catch (error) {
+ trace.log("HarCollector.getLongHeaders; ERROR when getString", error);
+ }
+ }
+ }
+ },
+
+ /**
+ * Fetches the full text of a string.
+ *
+ * @param object | string stringGrip
+ * The long string grip containing the corresponding actor.
+ * If you pass in a plain string (by accident or because you're lazy),
+ * then a promise of the same string is simply returned.
+ * @return object Promise
+ * A promise that is resolved when the full string contents
+ * are available, or rejected if something goes wrong.
+ */
+ async getString(stringGrip) {
+ const promise = getLongStringFullText(this.commands.client, stringGrip);
+ this.requests.push(promise);
+ return promise;
+ },
+};
+
+// Helpers
+
+/**
+ * Helper function that allows to wait for array of promises. It is
+ * possible to dynamically add new promises in the provided array.
+ * The function will wait even for the newly added promises.
+ * (this isn't possible with the default Promise.all);
+ */
+function waitForAll(promises) {
+ // Remove all from the original array and get clone of it.
+ const clone = promises.splice(0, promises.length);
+
+ // Wait for all promises in the given array.
+ return Promise.all(clone).then(() => {
+ // If there are new promises (in the original array)
+ // to wait for - chain them!
+ if (promises.length) {
+ return waitForAll(promises);
+ }
+
+ return undefined;
+ });
+}
+
+// Exports from this module
+exports.HarCollector = HarCollector;
diff --git a/devtools/client/netmonitor/src/har/har-exporter.js b/devtools/client/netmonitor/src/har/har-exporter.js
new file mode 100644
index 0000000000..fb401c2737
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/har-exporter.js
@@ -0,0 +1,230 @@
+/* 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 DevToolsUtils = require("resource://devtools/shared/DevToolsUtils.js");
+const JSZip = require("resource://devtools/client/shared/vendor/jszip.js");
+const clipboardHelper = require("resource://devtools/shared/platform/clipboard.js");
+const {
+ HarUtils,
+} = require("resource://devtools/client/netmonitor/src/har/har-utils.js");
+const {
+ HarBuilder,
+} = require("resource://devtools/client/netmonitor/src/har/har-builder.js");
+
+var uid = 1;
+
+// Helper tracer. Should be generic sharable by other modules (bug 1171927)
+const trace = {
+ log(...args) {},
+};
+
+/**
+ * This object represents the main public API designed to access
+ * Network export logic. Clients, such as the Network panel itself,
+ * should use this API to export collected HTTP data from the panel.
+ */
+const HarExporter = {
+ // Public API
+
+ /**
+ * Save collected HTTP data from the Network panel into HAR file.
+ *
+ * @param Object options
+ * Configuration object
+ *
+ * The following options are supported:
+ *
+ * - includeResponseBodies {Boolean}: If set to true, HTTP response bodies
+ * are also included in the HAR file (can produce significantly bigger
+ * amount of data).
+ *
+ * - items {Array}: List of Network requests to be exported.
+ *
+ * - jsonp {Boolean}: If set to true the export format is HARP (support
+ * for JSONP syntax).
+ *
+ * - jsonpCallback {String}: Default name of JSONP callback (used for
+ * HARP format).
+ *
+ * - compress {Boolean}: If set to true the final HAR file is zipped.
+ * This represents great disk-space optimization.
+ *
+ * - defaultFileName {String}: Default name of the target HAR file.
+ * The default file name supports the format specifier %date to output the
+ * current date/time.
+ *
+ * - defaultLogDir {String}: Default log directory for automated logs.
+ *
+ * - id {String}: ID of the page (used in the HAR file).
+ *
+ * - title {String}: Title of the page (used in the HAR file).
+ *
+ * - forceExport {Boolean}: The result HAR file is created even if
+ * there are no HTTP entries.
+ */
+ async save(options) {
+ // Set default options related to save operation.
+ const defaultFileName = Services.prefs.getCharPref(
+ "devtools.netmonitor.har.defaultFileName"
+ );
+ const compress = Services.prefs.getBoolPref(
+ "devtools.netmonitor.har.compress"
+ );
+
+ trace.log("HarExporter.save; " + defaultFileName, options);
+
+ let data = await this.fetchHarData(options);
+
+ const host = new URL(options.connector.currentTarget.url);
+
+ const fileName = HarUtils.getHarFileName(
+ defaultFileName,
+ options.jsonp,
+ compress,
+ host.hostname
+ );
+
+ if (compress) {
+ data = await JSZip()
+ .file(fileName, data)
+ .generateAsync({
+ compression: "DEFLATE",
+ platform: Services.appinfo.OS === "WINNT" ? "DOS" : "UNIX",
+ type: "uint8array",
+ });
+ } else {
+ data = new TextEncoder().encode(data);
+ }
+
+ DevToolsUtils.saveAs(window, data, fileName);
+ },
+
+ /**
+ * Copy HAR string into the clipboard.
+ *
+ * @param Object options
+ * Configuration object, see save() for detailed description.
+ */
+ copy(options) {
+ return this.fetchHarData(options).then(jsonString => {
+ clipboardHelper.copyString(jsonString);
+ return jsonString;
+ });
+ },
+
+ /**
+ * Get HAR data as JSON object.
+ *
+ * @param Object options
+ * Configuration object, see save() for detailed description.
+ */
+ getHar(options) {
+ return this.fetchHarData(options).then(data => {
+ return data ? JSON.parse(data) : null;
+ });
+ },
+
+ // Helpers
+
+ fetchHarData(options) {
+ // Generate page ID
+ options.id = options.id || uid++;
+
+ // Set default generic HAR export options.
+ if (typeof options.jsonp != "boolean") {
+ options.jsonp = Services.prefs.getBoolPref(
+ "devtools.netmonitor.har.jsonp"
+ );
+ }
+ if (typeof options.includeResponseBodies != "boolean") {
+ options.includeResponseBodies = Services.prefs.getBoolPref(
+ "devtools.netmonitor.har.includeResponseBodies"
+ );
+ }
+ if (typeof options.jsonpCallback != "boolean") {
+ options.jsonpCallback = Services.prefs.getCharPref(
+ "devtools.netmonitor.har.jsonpCallback"
+ );
+ }
+ if (typeof options.forceExport != "boolean") {
+ options.forceExport = Services.prefs.getBoolPref(
+ "devtools.netmonitor.har.forceExport"
+ );
+ }
+ if (typeof options.supportsMultiplePages != "boolean") {
+ options.supportsMultiplePages = Services.prefs.getBoolPref(
+ "devtools.netmonitor.har.multiple-pages"
+ );
+ }
+
+ // Build HAR object.
+ return this.buildHarData(options)
+ .then(har => {
+ // Do not export an empty HAR file, unless the user
+ // explicitly says so (using the forceExport option).
+ if (!har.log.entries.length && !options.forceExport) {
+ return Promise.resolve();
+ }
+
+ let jsonString = this.stringify(har);
+ if (!jsonString) {
+ return Promise.resolve();
+ }
+
+ // If JSONP is wanted, wrap the string in a function call
+ if (options.jsonp) {
+ // This callback name is also used in HAR Viewer by default.
+ // http://www.softwareishard.com/har/viewer/
+ const callbackName = options.jsonpCallback || "onInputData";
+ jsonString = callbackName + "(" + jsonString + ");";
+ }
+
+ return jsonString;
+ })
+ .catch(function onError(err) {
+ console.error(err);
+ });
+ },
+
+ /**
+ * Build HAR data object. This object contains all HTTP data
+ * collected by the Network panel. The process is asynchronous
+ * since it can involve additional RDP communication (e.g. resolving
+ * long strings).
+ */
+ async buildHarData(options) {
+ // Disconnect from redux actions/store.
+ options.connector.enableActions(false);
+
+ // Build HAR object from collected data.
+ const builder = new HarBuilder(options);
+ const result = await builder.build();
+
+ // Connect to redux actions again.
+ options.connector.enableActions(true);
+
+ return result;
+ },
+
+ /**
+ * Build JSON string from the HAR data object.
+ */
+ stringify(har) {
+ if (!har) {
+ return null;
+ }
+
+ try {
+ return JSON.stringify(har, null, " ");
+ } catch (err) {
+ console.error(err);
+ return undefined;
+ }
+ },
+};
+
+// Exports from this module
+exports.HarExporter = HarExporter;
diff --git a/devtools/client/netmonitor/src/har/har-importer.js b/devtools/client/netmonitor/src/har/har-importer.js
new file mode 100644
index 0000000000..2246a29086
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/har-importer.js
@@ -0,0 +1,166 @@
+/* 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 {
+ TIMING_KEYS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ getUrlDetails,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+var guid = 0;
+
+/**
+ * This object is responsible for importing HAR file. See HAR spec:
+ * https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HAR/Overview.html
+ * http://www.softwareishard.com/blog/har-12-spec/
+ */
+var HarImporter = function (actions) {
+ this.actions = actions;
+};
+
+HarImporter.prototype = {
+ /**
+ * This is the main method used to import HAR data.
+ */
+ import(har) {
+ const json = JSON.parse(har);
+ this.doImport(json);
+ },
+
+ doImport(har) {
+ this.actions.clearRequests();
+
+ // Helper map for pages.
+ const pages = new Map();
+ har.log.pages.forEach(page => {
+ pages.set(page.id, page);
+ });
+
+ // Iterate all entries/requests and generate state.
+ har.log.entries.forEach(entry => {
+ const requestId = String(++guid);
+ const startedMs = Date.parse(entry.startedDateTime);
+
+ // Add request
+ this.actions.addRequest(
+ requestId,
+ {
+ startedMs,
+ method: entry.request.method,
+ url: entry.request.url,
+ urlDetails: getUrlDetails(entry.request.url),
+ isXHR: false,
+ cause: {
+ loadingDocumentUri: "",
+ stackTraceAvailable: false,
+ type: "",
+ },
+ fromCache: false,
+ fromServiceWorker: false,
+ },
+ false
+ );
+
+ // Update request
+ const data = {
+ requestHeaders: {
+ headers: entry.request.headers,
+ headersSize: entry.request.headersSize,
+ rawHeaders: "",
+ },
+ responseHeaders: {
+ headers: entry.response.headers,
+ headersSize: entry.response.headersSize,
+ rawHeaders: "",
+ },
+ requestCookies: entry.request.cookies,
+ responseCookies: entry.response.cookies,
+ requestPostData: {
+ postData: entry.request.postData || {},
+ postDataDiscarded: false,
+ },
+ responseContent: {
+ content: entry.response.content,
+ contentDiscarded: false,
+ },
+ eventTimings: {
+ timings: entry.timings,
+ },
+ totalTime: TIMING_KEYS.reduce((sum, type) => {
+ const time = entry.timings[type];
+ return typeof time != "undefined" && time != -1 ? sum + time : sum;
+ }, 0),
+
+ httpVersion: entry.request.httpVersion,
+ contentSize: entry.response.content.size,
+ mimeType: entry.response.content.mimeType,
+ remoteAddress: entry.serverIPAddress,
+ remotePort: entry.connection,
+ status: entry.response.status,
+ statusText: entry.response.statusText,
+ transferredSize: entry.response.bodySize,
+ securityState: entry._securityState,
+
+ // Avoid auto-fetching data from the backend
+ eventTimingsAvailable: false,
+ requestCookiesAvailable: false,
+ requestHeadersAvailable: false,
+ responseContentAvailable: false,
+ responseStartAvailable: false,
+ responseCookiesAvailable: false,
+ responseHeadersAvailable: false,
+ securityInfoAvailable: false,
+ requestPostDataAvailable: false,
+ };
+
+ if (entry.cache.afterRequest) {
+ const { afterRequest } = entry.cache;
+ data.responseCache = {
+ cache: {
+ expires: afterRequest.expires,
+ fetchCount: afterRequest.fetchCount,
+ lastFetched: afterRequest.lastFetched,
+ // TODO: eTag support, see Bug 1799844.
+ // eTag: afterRequest.eTag,
+ _dataSize: afterRequest._dataSize,
+ _lastModified: afterRequest._lastModified,
+ _device: afterRequest._device,
+ },
+ };
+ }
+
+ this.actions.updateRequest(requestId, data, false);
+
+ // Page timing markers
+ const pageTimings = pages.get(entry.pageref)?.pageTimings;
+ let onContentLoad = (pageTimings && pageTimings.onContentLoad) || 0;
+ let onLoad = (pageTimings && pageTimings.onLoad) || 0;
+
+ // Set 0 as the default value
+ onContentLoad = onContentLoad != -1 ? onContentLoad : 0;
+ onLoad = onLoad != -1 ? onLoad : 0;
+
+ // Add timing markers
+ if (onContentLoad > 0) {
+ this.actions.addTimingMarker({
+ name: "dom-interactive",
+ time: startedMs + onContentLoad,
+ });
+ }
+
+ if (onLoad > 0) {
+ this.actions.addTimingMarker({
+ name: "dom-complete",
+ time: startedMs + onLoad,
+ });
+ }
+ });
+ },
+};
+
+// Exports from this module
+exports.HarImporter = HarImporter;
diff --git a/devtools/client/netmonitor/src/har/har-menu-utils.js b/devtools/client/netmonitor/src/har/har-menu-utils.js
new file mode 100644
index 0000000000..756d9d9f96
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/har-menu-utils.js
@@ -0,0 +1,118 @@
+/* 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");
+const EventEmitter = require("resource://devtools/shared/event-emitter.js");
+
+loader.lazyRequireGetter(
+ this,
+ "HarExporter",
+ "resource://devtools/client/netmonitor/src/har/har-exporter.js",
+ true
+);
+
+loader.lazyGetter(this, "HarImporter", function () {
+ return require("resource://devtools/client/netmonitor/src/har/har-importer.js")
+ .HarImporter;
+});
+
+/**
+ * Helper object with HAR related context menu actions.
+ */
+var HarMenuUtils = {
+ /**
+ * Copy HAR from the network panel content to the clipboard.
+ */
+ async copyAllAsHar(requests, connector) {
+ const har = await HarExporter.copy(
+ this.getDefaultHarOptions(requests, connector)
+ );
+
+ // We cannot easily expect the clipboard content from tests, instead we emit
+ // a test event.
+ HarMenuUtils.emitForTests("copy-all-as-har-done", har);
+
+ return har;
+ },
+
+ /**
+ * Save HAR from the network panel content to a file.
+ */
+ saveAllAsHar(requests, connector) {
+ // This will not work in launchpad
+ // document.execCommand(‘cut’/‘copy’) was denied because it was not called from
+ // inside a short running user-generated event handler.
+ // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Interact_with_the_clipboard
+ return HarExporter.save(this.getDefaultHarOptions(requests, connector));
+ },
+
+ /**
+ * Import HAR file and preview its content in the Network panel.
+ */
+ openHarFile(actions, openSplitConsole) {
+ const fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
+ fp.init(
+ window,
+ L10N.getStr("netmonitor.har.importHarDialogTitle"),
+ Ci.nsIFilePicker.modeOpen
+ );
+
+ // Append file filters
+ fp.appendFilter(
+ L10N.getStr("netmonitor.har.importDialogHARFilter"),
+ "*.har"
+ );
+ fp.appendFilter(L10N.getStr("netmonitor.har.importDialogAllFilter"), "*.*");
+
+ fp.open(rv => {
+ if (rv == Ci.nsIFilePicker.returnOK) {
+ const file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
+ file.initWithPath(fp.file.path);
+ readFile(file).then(har => {
+ if (har) {
+ this.appendPreview(har, actions, openSplitConsole);
+ }
+ });
+ }
+ });
+ },
+
+ appendPreview(har, actions, openSplitConsole) {
+ try {
+ const importer = new HarImporter(actions);
+ importer.import(har);
+ } catch (err) {
+ if (openSplitConsole) {
+ openSplitConsole("Error while processing HAR file: " + err.message);
+ }
+ }
+ },
+
+ getDefaultHarOptions(requests, connector) {
+ return {
+ connector,
+ items: requests,
+ };
+ },
+};
+
+// Helpers
+
+function readFile(file) {
+ return new Promise(resolve => {
+ IOUtils.read(file.path).then(data => {
+ const decoder = new TextDecoder();
+ resolve(decoder.decode(data));
+ });
+ });
+}
+
+EventEmitter.decorate(HarMenuUtils);
+
+// Exports from this module
+exports.HarMenuUtils = HarMenuUtils;
diff --git a/devtools/client/netmonitor/src/har/har-utils.js b/devtools/client/netmonitor/src/har/har-utils.js
new file mode 100644
index 0000000000..fc7ae533f1
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/har-utils.js
@@ -0,0 +1,167 @@
+/* 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 { XPCOMUtils } = ChromeUtils.importESModule(
+ "resource://gre/modules/XPCOMUtils.sys.mjs"
+);
+
+XPCOMUtils.defineLazyGetter(this, "ZipWriter", function () {
+ return Components.Constructor("@mozilla.org/zipwriter;1", "nsIZipWriter");
+});
+
+const OPEN_FLAGS = {
+ RDONLY: parseInt("0x01", 16),
+ WRONLY: parseInt("0x02", 16),
+ CREATE_FILE: parseInt("0x08", 16),
+ APPEND: parseInt("0x10", 16),
+ TRUNCATE: parseInt("0x20", 16),
+ EXCL: parseInt("0x80", 16),
+};
+
+function formatDate(date) {
+ const year = String(date.getFullYear() % 100).padStart(2, "0");
+ const month = String(date.getMonth() + 1).padStart(2, "0");
+ const day = String(date.getDate()).padStart(2, "0");
+ const hour = String(date.getHours()).padStart(2, "0");
+ const minutes = String(date.getMinutes()).padStart(2, "0");
+ const seconds = String(date.getSeconds()).padStart(2, "0");
+
+ return `${year}-${month}-${day} ${hour}-${minutes}-${seconds}`;
+}
+
+/**
+ * Helper API for HAR export features.
+ */
+var HarUtils = {
+ getHarFileName(defaultFileName, jsonp, compress, hostname) {
+ const extension = jsonp ? ".harp" : ".har";
+
+ const now = new Date();
+ let name = defaultFileName.replace(/%date/g, formatDate(now));
+ name = name.replace(/%hostname/g, hostname);
+ name = name.replace(/\:/gm, "-", "");
+ name = name.replace(/\//gm, "_", "");
+
+ let fileName = name + extension;
+
+ // Default file extension is zip if compressing is on.
+ if (compress) {
+ fileName += ".zip";
+ }
+
+ return fileName;
+ },
+
+ /**
+ * Save HAR string into a given file. The file might be compressed
+ * if specified in the options.
+ *
+ * @param {File} file Target file where the HAR string (JSON)
+ * should be stored.
+ * @param {String} jsonString HAR data (JSON or JSONP)
+ * @param {Boolean} compress The result file is zipped if set to true.
+ */
+ saveToFile(file, jsonString, compress) {
+ const openFlags =
+ OPEN_FLAGS.WRONLY | OPEN_FLAGS.CREATE_FILE | OPEN_FLAGS.TRUNCATE;
+
+ try {
+ const foStream = Cc[
+ "@mozilla.org/network/file-output-stream;1"
+ ].createInstance(Ci.nsIFileOutputStream);
+
+ const permFlags = parseInt("0666", 8);
+ foStream.init(file, openFlags, permFlags, 0);
+
+ const convertor = Cc[
+ "@mozilla.org/intl/converter-output-stream;1"
+ ].createInstance(Ci.nsIConverterOutputStream);
+ convertor.init(foStream, "UTF-8");
+
+ // The entire jsonString can be huge so, write the data in chunks.
+ const chunkLength = 1024 * 1024;
+ for (let i = 0; i <= jsonString.length; i++) {
+ const data = jsonString.substr(i, chunkLength + 1);
+ if (data) {
+ convertor.writeString(data);
+ }
+
+ i = i + chunkLength;
+ }
+
+ // this closes foStream
+ convertor.close();
+ } catch (err) {
+ console.error(err);
+ return false;
+ }
+
+ // If no compressing then bail out.
+ if (!compress) {
+ return true;
+ }
+
+ // Remember name of the original file, it'll be replaced by a zip file.
+ const originalFilePath = file.path;
+ const originalFileName = file.leafName;
+
+ try {
+ // Rename using unique name (the file is going to be removed).
+ file.moveTo(null, "temp" + new Date().getTime() + "temphar");
+
+ // Create compressed file with the original file path name.
+ const zipFile = Cc["@mozilla.org/file/local;1"].createInstance(
+ Ci.nsIFile
+ );
+ zipFile.initWithPath(originalFilePath);
+
+ // The file within the zipped file doesn't use .zip extension.
+ let fileName = originalFileName;
+ if (fileName.indexOf(".zip") == fileName.length - 4) {
+ fileName = fileName.substr(0, fileName.indexOf(".zip"));
+ }
+
+ const zip = new ZipWriter();
+ zip.open(zipFile, openFlags);
+ zip.addEntryFile(
+ fileName,
+ Ci.nsIZipWriter.COMPRESSION_DEFAULT,
+ file,
+ false
+ );
+ zip.close();
+
+ // Remove the original file (now zipped).
+ file.remove(true);
+ return true;
+ } catch (err) {
+ console.error(err);
+
+ // Something went wrong (disk space?) rename the original file back.
+ file.moveTo(null, originalFileName);
+ }
+
+ return false;
+ },
+
+ getLocalDirectory(path) {
+ let dir;
+
+ if (!path) {
+ dir = Services.dirsvc.get("ProfD", Ci.nsIFile);
+ dir.append("har");
+ dir.append("logs");
+ } else {
+ dir = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
+ dir.initWithPath(path);
+ }
+
+ return dir;
+ },
+};
+
+// Exports from this module
+exports.HarUtils = HarUtils;
diff --git a/devtools/client/netmonitor/src/har/moz.build b/devtools/client/netmonitor/src/har/moz.build
new file mode 100644
index 0000000000..3a73373c43
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/moz.build
@@ -0,0 +1,19 @@
+# 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(
+ "har-automation.js",
+ "har-builder-utils.js",
+ "har-builder.js",
+ "har-collector.js",
+ "har-exporter.js",
+ "har-importer.js",
+ "har-menu-utils.js",
+ "har-utils.js",
+)
+
+BROWSER_CHROME_MANIFESTS += [
+ "test/browser-harautomation.ini",
+ "test/browser.ini",
+]
diff --git a/devtools/client/netmonitor/src/har/test/browser-harautomation.ini b/devtools/client/netmonitor/src/har/test/browser-harautomation.ini
new file mode 100644
index 0000000000..61ee56be44
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/browser-harautomation.ini
@@ -0,0 +1,16 @@
+[DEFAULT]
+tags = devtools
+subsuite = devtools
+prefs=
+ # This preference needs to be set before starting Firefox, so we use a
+ # dedicated browser.ini
+ devtools.netmonitor.har.enableAutoExportToFile=true
+
+support-files =
+ head.js
+ !/devtools/client/netmonitor/test/head.js
+ !/devtools/client/netmonitor/test/html_simple-test-page.html
+ !/devtools/client/shared/test/shared-head.js
+ !/devtools/client/shared/test/telemetry-test-helpers.js
+
+[browser_harautomation_simple.js]
diff --git a/devtools/client/netmonitor/src/har/test/browser.ini b/devtools/client/netmonitor/src/har/test/browser.ini
new file mode 100644
index 0000000000..c45b2b0358
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/browser.ini
@@ -0,0 +1,29 @@
+[DEFAULT]
+tags = devtools
+subsuite = devtools
+skip-if = http3 # Bug 1829298
+support-files =
+ head.js
+ html_har_import-test-page.html
+ html_har_multipage_iframe.html
+ html_har_multipage_page.html
+ html_har_post-data-test-page.html
+ sjs_cache-test-server.sjs
+ sjs_cookies-test-server.sjs
+ !/devtools/client/netmonitor/test/head.js
+ !/devtools/client/netmonitor/test/html_simple-test-page.html
+ !/devtools/client/shared/test/shared-head.js
+ !/devtools/client/shared/test/telemetry-test-helpers.js
+
+[browser_net_har_copy_all_as_har.js]
+skip-if =
+ !debug && os == "mac" #Bug 1622925
+ !debug && os == "linux" #Bug 1622925
+ win10_2004 # Bug 1723573
+ win11_2009 # Bug 1797751
+[browser_net_har_import.js]
+[browser_net_har_import_no-mime.js]
+[browser_net_har_multipage.js]
+[browser_net_har_post_data.js]
+[browser_net_har_post_data_on_get.js]
+[browser_net_har_throttle_upload.js]
diff --git a/devtools/client/netmonitor/src/har/test/browser_harautomation_simple.js b/devtools/client/netmonitor/src/har/test/browser_harautomation_simple.js
new file mode 100644
index 0000000000..9da746d28f
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/browser_harautomation_simple.js
@@ -0,0 +1,35 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const HAR_FILENAME = "test_filename.har";
+
+// We expect the HAR file to be created on reload in profD/har/logs
+const HAR_PATH = ["har", "logs", HAR_FILENAME];
+
+/**
+ * Smoke test for automated HAR export.
+ * Note that the `enableAutoExportToFile` is set from browser-harautomation.ini
+ * because the preference needs to be set before starting the browser.
+ */
+add_task(async function () {
+ // Set a simple test filename for the exported HAR.
+ await pushPref("devtools.netmonitor.har.defaultFileName", "test_filename");
+
+ const tab = await addTab(SIMPLE_URL);
+ const toolbox = await gDevTools.showToolboxForTab(tab, {
+ toolId: "inspector",
+ });
+
+ await reloadBrowser();
+
+ info("Wait until the HAR file is created in the profile directory");
+ await waitUntil(() => FileUtils.getFile("ProfD", HAR_PATH).exists());
+
+ const harFile = FileUtils.getFile("ProfD", HAR_PATH);
+ ok(harFile.exists(), "HAR file was automatically created");
+
+ await toolbox.destroy();
+ await removeTab(tab);
+});
diff --git a/devtools/client/netmonitor/src/har/test/browser_net_har_copy_all_as_har.js b/devtools/client/netmonitor/src/har/test/browser_net_har_copy_all_as_har.js
new file mode 100644
index 0000000000..ab4302883c
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/browser_net_har_copy_all_as_har.js
@@ -0,0 +1,220 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Basic tests for exporting Network panel content into HAR format.
+ */
+
+const EXPECTED_REQUEST_HEADER_COUNT = 9;
+const EXPECTED_RESPONSE_HEADER_COUNT = 6;
+
+add_task(async function () {
+ // Disable tcp fast open, because it is setting a response header indicator
+ // (bug 1352274). TCP Fast Open is not present on all platforms therefore the
+ // number of response headers will vary depending on the platform.
+ await pushPref("network.tcp.tcp_fastopen_enable", false);
+ const { tab, monitor, toolbox } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+
+ await testSimpleReload({ tab, monitor, toolbox });
+ await testResponseBodyLimits({ tab, monitor, toolbox });
+ await testManyReloads({ tab, monitor, toolbox });
+ await testClearedRequests({ tab, monitor, toolbox });
+
+ // Do not use teardown(monitor) as testClearedRequests register broken requests
+ // which never complete and would block on waitForAllNetworkUpdateEvents
+ await closeTabAndToolbox();
+});
+
+async function testSimpleReload({ tab, monitor, toolbox }) {
+ info("Test with a simple page reload");
+
+ const har = await reloadAndCopyAllAsHar({ tab, monitor, toolbox });
+
+ // Check out HAR log
+ isnot(har.log, null, "The HAR log must exist");
+ is(har.log.creator.name, "Firefox", "The creator field must be set");
+ is(har.log.browser.name, "Firefox", "The browser field must be set");
+ is(har.log.pages.length, 1, "There must be one page");
+ is(har.log.entries.length, 1, "There must be one request");
+
+ const page = har.log.pages[0];
+
+ is(page.title, "Network Monitor test page", "There must be some page title");
+ ok("onContentLoad" in page.pageTimings, "There must be onContentLoad time");
+ ok("onLoad" in page.pageTimings, "There must be onLoad time");
+
+ const entry = har.log.entries[0];
+ assertNavigationRequestEntry(entry);
+
+ info("We get the response content and timings when doing a simple reload");
+ isnot(entry.response.content.text, undefined, "Check response body");
+ is(entry.response.content.text.length, 465, "Response body is complete");
+ isnot(entry.timings, undefined, "Check timings");
+}
+
+async function testResponseBodyLimits({ tab, monitor, toolbox }) {
+ info("Test response body limit (non zero).");
+ await pushPref("devtools.netmonitor.responseBodyLimit", 10);
+ let har = await reloadAndCopyAllAsHar({ tab, monitor, toolbox });
+ let entry = har.log.entries[0];
+ is(entry.response.content.text.length, 10, "Response body must be truncated");
+
+ info("Test response body limit (zero).");
+ await pushPref("devtools.netmonitor.responseBodyLimit", 0);
+ har = await reloadAndCopyAllAsHar({ tab, monitor, toolbox });
+ entry = har.log.entries[0];
+ is(
+ entry.response.content.text.length,
+ 465,
+ "Response body must not be truncated"
+ );
+}
+
+async function testManyReloads({ tab, monitor, toolbox }) {
+ const har = await reloadAndCopyAllAsHar({
+ tab,
+ monitor,
+ toolbox,
+ reloadTwice: true,
+ });
+ // In most cases, we will have two requests, but sometimes,
+ // the first one might be missing as we couldn't fetch any lazy data for it.
+ ok(har.log.entries.length >= 1, "There must be at least one request");
+ info(
+ "Assert the first navigation request which has been cancelled by the second reload"
+ );
+ // Requests may come out of order, so try to find the bogus cancelled request
+ let entry = har.log.entries.find(e => e.response.status == 0);
+ if (entry) {
+ ok(entry, "Found the cancelled request");
+ is(entry.request.method, "GET", "Method is set");
+ is(entry.request.url, SIMPLE_URL, "URL is set");
+ // We always get the following headers:
+ // "Host", "User-agent", "Accept", "Accept-Language", "Accept-Encoding", "Connection"
+ // but are missing the three last headers:
+ // "Upgrade-Insecure-Requests", "Pragma", "Cache-Control"
+ is(entry.request.headers.length, 6, "But headers are partialy populated");
+ is(entry.response.status, 0, "And status is set to 0");
+ }
+
+ entry = har.log.entries.find(e => e.response.status != 0);
+ assertNavigationRequestEntry(entry);
+}
+
+async function testClearedRequests({ tab, monitor, toolbox }) {
+ info("Navigate to an empty page");
+ const topDocumentURL =
+ "https://example.org/document-builder.sjs?html=empty-document";
+ const iframeURL =
+ "https://example.org/document-builder.sjs?html=" +
+ encodeURIComponent(
+ `iframe<script>fetch("/document-builder.sjs?html=iframe-request")</script>`
+ );
+
+ await waitForAllNetworkUpdateEvents();
+ await navigateTo(topDocumentURL);
+
+ info("Create an iframe doing a request and remove the iframe.");
+ info(
+ "Doing this, should notify a network request that is destroyed on the server side"
+ );
+ const onNetworkEvents = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [iframeURL],
+ async function (_iframeURL) {
+ const iframe = content.document.createElement("iframe");
+ iframe.setAttribute("src", _iframeURL);
+ content.document.body.appendChild(iframe);
+ }
+ );
+ // Wait for the two request to be processed (iframe doc + fetch requests)
+ // before removing the iframe so that the netmonitor is able to fetch
+ // all lazy data without throwing
+ await onNetworkEvents;
+ await waitForAllNetworkUpdateEvents();
+
+ info("Remove the iframe so that lazy request data are freed");
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.document.querySelector("iframe").remove();
+ });
+
+ // HAR will try to re-fetch lazy data and may throw on the iframe fetch request.
+ // This subtest is meants to verify we aren't throwing here and HAR export
+ // works fine, even if some requests can't be fetched.
+ const har = await copyAllAsHARWithContextMenu(monitor);
+ is(har.log.entries.length, 2, "There must be two requests");
+ is(
+ har.log.entries[0].request.url,
+ topDocumentURL,
+ "First request is for the top level document"
+ );
+ is(
+ har.log.entries[1].request.url,
+ iframeURL,
+ "Second request is for the iframe"
+ );
+ info(
+ "The fetch request doesn't appear in HAR export, because its lazy data is freed and we completely ignore the request."
+ );
+}
+
+function assertNavigationRequestEntry(entry) {
+ info("Assert that the entry relates to the navigation request");
+ ok(entry.time > 0, "Check the total time");
+ is(entry.request.method, "GET", "Check the method");
+ is(entry.request.url, SIMPLE_URL, "Check the URL");
+ is(
+ entry.request.headers.length,
+ EXPECTED_REQUEST_HEADER_COUNT,
+ "Check number of request headers"
+ );
+ is(entry.response.status, 200, "Check response status");
+ is(entry.response.statusText, "OK", "Check response status text");
+ is(
+ entry.response.headers.length,
+ EXPECTED_RESPONSE_HEADER_COUNT,
+ "Check number of response headers"
+ );
+ is(
+ entry.response.content.mimeType,
+ "text/html",
+ "Check response content type"
+ );
+}
+/**
+ * Reload the page and copy all as HAR.
+ */
+async function reloadAndCopyAllAsHar({
+ tab,
+ monitor,
+ toolbox,
+ reloadTwice = false,
+}) {
+ const { store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const onNetworkEvent = waitForNetworkEvents(monitor, 1);
+ const { onDomCompleteResource } =
+ await waitForNextTopLevelDomCompleteResource(toolbox.commands);
+
+ if (reloadTwice) {
+ reloadBrowser();
+ }
+ await reloadBrowser();
+
+ info("Waiting for network events");
+ await onNetworkEvent;
+ info("Waiting for DOCUMENT_EVENT dom-complete resource");
+ await onDomCompleteResource;
+
+ return copyAllAsHARWithContextMenu(monitor);
+}
diff --git a/devtools/client/netmonitor/src/har/test/browser_net_har_import.js b/devtools/client/netmonitor/src/har/test/browser_net_har_import.js
new file mode 100644
index 0000000000..879966e653
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/browser_net_har_import.js
@@ -0,0 +1,149 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests for importing HAR data.
+ */
+add_task(async () => {
+ const { tab, monitor } = await initNetMonitor(
+ HAR_EXAMPLE_URL + "html_har_import-test-page.html",
+ { requestCount: 1 }
+ );
+
+ info("Starting test... ");
+
+ const { actions, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { HarImporter } = windowRequire(
+ "devtools/client/netmonitor/src/har/har-importer"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute one POST request on the page and wait till its done.
+ const wait = waitForNetworkEvents(monitor, 3);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.executeTest();
+ });
+ await wait;
+
+ // Copy HAR into the clipboard
+ const json1 = await copyAllAsHARWithContextMenu(monitor, { asString: true });
+
+ // Import HAR string
+ const importer = new HarImporter(actions);
+ importer.import(json1);
+
+ // Copy HAR into the clipboard again
+ const json2 = await copyAllAsHARWithContextMenu(monitor, { asString: true });
+
+ // Compare exported HAR data
+ const har1 = JSON.parse(json1);
+ const har2 = JSON.parse(json2);
+
+ // Explicit tests
+ is(har2.log.entries.length, 3, "There must be expected number of requests");
+ ok(
+ har2.log.pages[0].title.endsWith("Network Monitor Test Page"),
+ "There must be some page title"
+ );
+ ok(
+ !!har2.log.entries[0].request.headers.length,
+ "There must be some request headers"
+ );
+ ok(
+ !!har2.log.entries[0].response.headers.length,
+ "There must be some response headers"
+ );
+ is(
+ har2.log.entries[1].response.cookies.length,
+ 3,
+ "There must be expected number of cookies"
+ );
+ is(
+ har2.log.entries[1]._securityState,
+ "insecure",
+ "There must be expected security state"
+ );
+ is(har2.log.entries[2].response.status, 304, "There must be expected status");
+
+ // Complex test comparing exported & imported HARs.
+ ok(compare(har1.log, har2.log, ["log"]), "Exported HAR must be the same");
+
+ // Clean up
+ return teardown(monitor);
+});
+
+/**
+ * Check equality of HAR files.
+ */
+function compare(obj1, obj2, path) {
+ const keys1 = Object.getOwnPropertyNames(obj1).sort();
+ const keys2 = Object.getOwnPropertyNames(obj2).sort();
+
+ const name = path.join("/");
+
+ is(
+ keys1.length,
+ keys2.length,
+ "There must be the same number of keys for: " + name
+ );
+ if (keys1.length != keys2.length) {
+ return false;
+ }
+
+ is(keys1.join(), keys2.join(), "There must be the same keys for: " + name);
+ if (keys1.join() != keys2.join()) {
+ return false;
+ }
+
+ // Page IDs are generated and don't have to be the same after import.
+ const ignore = [
+ "log/entries/0/pageref",
+ "log/entries/1/pageref",
+ "log/entries/2/pageref",
+ "log/pages/0/id",
+ "log/pages/1/id",
+ "log/pages/2/id",
+ ];
+
+ let result = true;
+ for (let i = 0; i < keys1.length; i++) {
+ const key = keys1[i];
+ const prop1 = obj1[key];
+ const prop2 = obj2[key];
+
+ if (prop1 instanceof Array) {
+ if (!(prop2 instanceof Array)) {
+ ok(false, "Arrays are not the same " + name);
+ result = false;
+ break;
+ }
+ if (!compare(prop1, prop2, path.concat(key))) {
+ result = false;
+ break;
+ }
+ } else if (prop1 instanceof Object) {
+ if (!(prop2 instanceof Object)) {
+ ok(false, "Objects are not the same in: " + name);
+ result = false;
+ break;
+ }
+ if (!compare(prop1, prop2, path.concat(key))) {
+ result = false;
+ break;
+ }
+ } else if (prop1 !== prop2) {
+ const propName = name + "/" + key;
+ if (!ignore.includes(propName)) {
+ is(prop1, prop2, "Values are not the same: " + propName);
+ result = false;
+ break;
+ }
+ }
+ }
+
+ return result;
+}
diff --git a/devtools/client/netmonitor/src/har/test/browser_net_har_import_no-mime.js b/devtools/client/netmonitor/src/har/test/browser_net_har_import_no-mime.js
new file mode 100644
index 0000000000..91c5160217
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/browser_net_har_import_no-mime.js
@@ -0,0 +1,78 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests importing HAR with missing `response.content.mimeType` does not crash the netmonitor.
+ */
+add_task(async () => {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+
+ const { document, actions, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ const { HarImporter } = windowRequire(
+ "devtools/client/netmonitor/src/har/har-importer"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Invalid HAR json which should contain `entries[0].response.content.mimeType`
+ const invalidHarJSON = {
+ log: {
+ version: "1.2",
+ pages: [
+ {
+ title: "bla",
+ },
+ ],
+ entries: [
+ {
+ request: {
+ method: "POST",
+ url: "https://bla.com",
+ httpVersion: "",
+ headers: [],
+ cookies: [],
+ queryString: [],
+ },
+ response: {
+ content: {
+ size: 1231,
+ text: '{"requests":[{"uri":"https://bla.com"}]}',
+ },
+ headers: [],
+ },
+ timings: {},
+ cache: {},
+ },
+ ],
+ },
+ };
+
+ // Import invalid Har file
+ const importer = new HarImporter(actions);
+ importer.import(JSON.stringify(invalidHarJSON));
+
+ const waitForResponsePanelOpen = waitUntil(() =>
+ document.querySelector("#response-panel")
+ );
+
+ // Open the response details panel
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelector(".request-list-item")
+ );
+ clickOnSidebarTab(document, "response");
+
+ await waitForResponsePanelOpen;
+ ok(true, "The response panel opened");
+
+ // Clean up
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/src/har/test/browser_net_har_multipage.js b/devtools/client/netmonitor/src/har/test/browser_net_har_multipage.js
new file mode 100644
index 0000000000..38936f73fe
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/browser_net_har_multipage.js
@@ -0,0 +1,153 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+requestLongerTimeout(2);
+
+const MULTIPAGE_IFRAME_URL = HAR_EXAMPLE_URL + "html_har_multipage_iframe.html";
+const MULTIPAGE_PAGE_URL = HAR_EXAMPLE_URL + "html_har_multipage_page.html";
+
+/**
+ * Tests HAR export with navigations and multipage support
+ */
+add_task(async function () {
+ await testHARWithNavigation({ enableMultipage: false, filter: false });
+ await testHARWithNavigation({ enableMultipage: true, filter: false });
+ await testHARWithNavigation({ enableMultipage: false, filter: true });
+ await testHARWithNavigation({ enableMultipage: true, filter: true });
+});
+
+async function testHARWithNavigation({ enableMultipage, filter }) {
+ await pushPref("devtools.netmonitor.persistlog", true);
+ await pushPref("devtools.netmonitor.har.multiple-pages", enableMultipage);
+
+ const { tab, monitor } = await initNetMonitor(MULTIPAGE_PAGE_URL + "?page1", {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+
+ const { store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Perform 3 additional requests");
+ let onNetworkEvents = waitForNetworkEvents(monitor, 3);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.sendRequests(3);
+ });
+ await onNetworkEvents;
+
+ info("Navigate to a second page where we will not perform any extra request");
+ onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await navigateTo(MULTIPAGE_PAGE_URL + "?page2");
+ await onNetworkEvents;
+
+ info("Navigate to a third page where we will not perform any extra request");
+ onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await navigateTo(MULTIPAGE_PAGE_URL + "?page3");
+ await onNetworkEvents;
+
+ info("Perform 2 additional requests");
+ onNetworkEvents = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.sendRequests(2);
+ });
+ await onNetworkEvents;
+
+ info("Create an iframe which will perform 2 additional requests");
+ onNetworkEvents = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [MULTIPAGE_IFRAME_URL],
+ async function (url) {
+ const iframe = content.document.createElement("iframe");
+ const onLoad = new Promise(resolve =>
+ iframe.addEventListener("load", resolve, { once: true })
+ );
+ content.content.document.body.appendChild(iframe);
+ iframe.setAttribute("src", url);
+ await onLoad;
+ }
+ );
+ await onNetworkEvents;
+
+ if (filter) {
+ info("Start filtering requests");
+ store.dispatch(Actions.setRequestFilterText("?request"));
+ }
+
+ info("Trigger Copy All As HAR from the context menu");
+ const har = await copyAllAsHARWithContextMenu(monitor);
+
+ // Check out the HAR log.
+ isnot(har.log, null, "The HAR log must exist");
+
+ if (enableMultipage) {
+ is(har.log.pages.length, 3, "There must be three pages");
+ } else {
+ is(har.log.pages.length, 1, "There must be one page");
+ }
+
+ if (!filter) {
+ // Expect 9 requests:
+ // - 3 requests performed with sendRequests on the first page
+ // - 1 navigation request to the second page
+ // - 1 navigation request to the third page
+ // - 2 requests performed with sendRequests on the third page
+ // - 1 request to load an iframe on the third page
+ // - 1 request from the iframe on the third page
+ is(har.log.entries.length, 9, "There must be 9 requests");
+ } else {
+ // Same but we only expect the fetch requests
+ is(har.log.entries.length, 6, "There must be 6 requests");
+ }
+
+ if (enableMultipage) {
+ // With multipage enabled, check that the page entries are valid and that
+ // requests are referencing the expected page id.
+ assertPageDetails(har.log.pages[0], "page_0", "HAR Multipage test page");
+ assertPageRequests(har.log.entries, 0, 2, har.log.pages[0].id);
+
+ assertPageDetails(har.log.pages[1], "page_1", "HAR Multipage test page");
+ if (filter) {
+ // When filtering, we don't expect any request to match page_1
+ } else {
+ assertPageRequests(har.log.entries, 3, 3, har.log.pages[1].id);
+ }
+
+ assertPageDetails(har.log.pages[2], "page_2", "HAR Multipage test page");
+ if (filter) {
+ assertPageRequests(har.log.entries, 3, 5, har.log.pages[2].id);
+ } else {
+ assertPageRequests(har.log.entries, 4, 8, har.log.pages[2].id);
+ }
+ } else {
+ is(har.log.pages[0].id, "page_1");
+ // Without multipage, all requests are associated with the only page entry.
+ for (const entry of har.log.entries) {
+ is(entry.pageref, "page_1");
+ }
+ }
+
+ // Clean up
+ return teardown(monitor);
+}
+
+function assertPageDetails(page, expectedId, expectedTitle) {
+ is(page.id, expectedId, "Page has the expected id");
+ is(page.title, expectedTitle, "Page has the expected title");
+}
+
+function assertPageRequests(entries, startIndex, endIndex, expectedPageId) {
+ for (let i = startIndex; i < endIndex + 1; i++) {
+ const entry = entries[i];
+ is(
+ entry.pageref,
+ expectedPageId,
+ `Entry ${i} is attached to page id: ${expectedPageId}`
+ );
+ }
+}
diff --git a/devtools/client/netmonitor/src/har/test/browser_net_har_post_data.js b/devtools/client/netmonitor/src/har/test/browser_net_har_post_data.js
new file mode 100644
index 0000000000..0640364a39
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/browser_net_har_post_data.js
@@ -0,0 +1,51 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests for exporting POST data into HAR format.
+ */
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ HAR_EXAMPLE_URL + "html_har_post-data-test-page.html",
+ { requestCount: 1 }
+ );
+
+ info("Starting test... ");
+
+ const { store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute one POST request on the page and wait till its done.
+ const wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.executeTest();
+ });
+ await wait;
+
+ // Copy HAR into the clipboard (asynchronous).
+ const har = await copyAllAsHARWithContextMenu(monitor);
+
+ // Check out the HAR log.
+ isnot(har.log, null, "The HAR log must exist");
+ is(har.log.pages.length, 1, "There must be one page");
+ is(har.log.entries.length, 1, "There must be one request");
+
+ const entry = har.log.entries[0];
+ is(
+ entry.request.postData.mimeType,
+ "application/json",
+ "Check post data content type"
+ );
+ is(
+ entry.request.postData.text,
+ "{'first': 'John', 'last': 'Doe'}",
+ "Check post data payload"
+ );
+
+ // Clean up
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/src/har/test/browser_net_har_post_data_on_get.js b/devtools/client/netmonitor/src/har/test/browser_net_har_post_data_on_get.js
new file mode 100644
index 0000000000..206fc43da6
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/browser_net_har_post_data_on_get.js
@@ -0,0 +1,43 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests for exporting POST data into HAR format.
+ */
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ HAR_EXAMPLE_URL + "html_har_post-data-test-page.html",
+ { requestCount: 1 }
+ );
+
+ info("Starting test... ");
+
+ const { store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute one GET request on the page and wait till its done.
+ const wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.executeTest3();
+ });
+ await wait;
+
+ // Copy HAR into the clipboard (asynchronous).
+ const har = await copyAllAsHARWithContextMenu(monitor);
+
+ // Check out the HAR log.
+ isnot(har.log, null, "The HAR log must exist");
+ is(har.log.pages.length, 1, "There must be one page");
+ is(har.log.entries.length, 1, "There must be one request");
+
+ const entry = har.log.entries[0];
+
+ is(entry.request.postData, undefined, "Check post data is not present");
+
+ // Clean up
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/src/har/test/browser_net_har_throttle_upload.js b/devtools/client/netmonitor/src/har/test/browser_net_har_throttle_upload.js
new file mode 100644
index 0000000000..24f7d482ca
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/browser_net_har_throttle_upload.js
@@ -0,0 +1,69 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Test timing of upload when throttling.
+
+"use strict";
+
+add_task(async function () {
+ await throttleUploadTest(true);
+ await throttleUploadTest(false);
+});
+
+async function throttleUploadTest(actuallyThrottle) {
+ const { tab, monitor } = await initNetMonitor(
+ HAR_EXAMPLE_URL + "html_har_post-data-test-page.html",
+ { requestCount: 1 }
+ );
+
+ info("Starting test... (actuallyThrottle = " + actuallyThrottle + ")");
+
+ const { connector, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const size = 4096;
+ const uploadSize = actuallyThrottle ? size / 3 : 0;
+
+ const throttleProfile = {
+ latency: 0,
+ download: 200000,
+ upload: uploadSize,
+ };
+
+ info("sending throttle request");
+ await connector.updateNetworkThrottling(true, throttleProfile);
+
+ // Execute one POST request on the page and wait till its done.
+ const wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [{ size }],
+ async function (args) {
+ content.wrappedJSObject.executeTest2(args.size);
+ }
+ );
+ await wait;
+
+ // Copy HAR into the clipboard (asynchronous).
+ const har = await copyAllAsHARWithContextMenu(monitor);
+
+ // Check out the HAR log.
+ isnot(har.log, null, "The HAR log must exist");
+ is(har.log.pages.length, 1, "There must be one page");
+ is(har.log.entries.length, 1, "There must be one request");
+
+ const entry = har.log.entries[0];
+ is(entry.request.postData.text, "x".repeat(size), "Check post data payload");
+
+ const wasTwoSeconds = entry.timings.send >= 2000;
+ if (actuallyThrottle) {
+ ok(wasTwoSeconds, "upload should have taken more than 2 seconds");
+ } else {
+ ok(!wasTwoSeconds, "upload should not have taken more than 2 seconds");
+ }
+
+ // Clean up
+ await teardown(monitor);
+}
diff --git a/devtools/client/netmonitor/src/har/test/head.js b/devtools/client/netmonitor/src/har/test/head.js
new file mode 100644
index 0000000000..b41ea580fd
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/head.js
@@ -0,0 +1,45 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* eslint no-unused-vars: [2, {"vars": "local", "args": "none"}] */
+/* import-globals-from ../../../test/head.js */
+
+// Load the NetMonitor head.js file to share its API.
+var netMonitorHead =
+ "chrome://mochitests/content/browser/devtools/client/netmonitor/test/head.js";
+Services.scriptloader.loadSubScript(netMonitorHead, this);
+
+// Directory with HAR related test files.
+const HAR_EXAMPLE_URL =
+ "http://example.com/browser/devtools/client/netmonitor/src/har/test/";
+
+/**
+ * Trigger a "copy all as har" from the context menu of the requests list.
+
+ * @param {Object} monitor
+ * The network monitor object
+ */
+async function copyAllAsHARWithContextMenu(monitor, { asString = false } = {}) {
+ const { HarMenuUtils } = monitor.panelWin.windowRequire(
+ "devtools/client/netmonitor/src/har/har-menu-utils"
+ );
+
+ info("Open the context menu on the first visible request.");
+ const firstRequest =
+ monitor.panelWin.document.querySelectorAll(".request-list-item")[0];
+
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequest);
+
+ info("Trigger Copy All As HAR from the context menu");
+ const onHarCopyDone = HarMenuUtils.once("copy-all-as-har-done");
+ await selectContextMenuItem(monitor, "request-list-context-copy-all-as-har");
+ const jsonString = await onHarCopyDone;
+
+ if (asString) {
+ return jsonString;
+ }
+ return JSON.parse(jsonString);
+}
diff --git a/devtools/client/netmonitor/src/har/test/html_har_import-test-page.html b/devtools/client/netmonitor/src/har/test/html_har_import-test-page.html
new file mode 100644
index 0000000000..04d5ec33ba
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/html_har_import-test-page.html
@@ -0,0 +1,51 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor Test Page</title>
+ </head>
+
+ <body>
+ <p>HAR import test</p>
+
+ <script type="text/javascript">
+ /* exported executeTest, executeTest2, executeTest3 */
+ "use strict";
+
+ function post(address, data) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", address, true);
+ xhr.setRequestHeader("Content-Type", "application/json");
+ xhr.onload = resolve;
+ xhr.send(data);
+ });
+ }
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address);
+ xhr.onload = resolve;
+ xhr.send();
+ });
+ }
+
+ async function executeTest() {
+ const url = "html_har_import-test-page.html";
+ const data = "{'first': 'John', 'last': 'Doe'}";
+ await post(url, data);
+ await get("sjs_cookies-test-server.sjs");
+ await get("sjs_cache-test-server.sjs");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/src/har/test/html_har_multipage_iframe.html b/devtools/client/netmonitor/src/har/test/html_har_multipage_iframe.html
new file mode 100644
index 0000000000..4e0fc96344
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/html_har_multipage_iframe.html
@@ -0,0 +1,24 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor HAR Multipage test iframe</title>
+ </head>
+
+ <body>
+ <p>HAR Multipage test iframe</p>
+
+ <script type="text/javascript">
+ "use strict";
+ fetch("?request-from-iframe");
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/src/har/test/html_har_multipage_page.html b/devtools/client/netmonitor/src/har/test/html_har_multipage_page.html
new file mode 100644
index 0000000000..d36fbca52b
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/html_har_multipage_page.html
@@ -0,0 +1,30 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>HAR Multipage test page</title>
+ </head>
+
+ <body>
+ <p>HAR Multipage test page</p>
+
+ <script type="text/javascript">
+ /* exported sendRequests */
+ "use strict";
+
+ async function sendRequests(requestsCount) {
+ for (let i = 0; i < requestsCount; i++) {
+ fetch("?request" + i);
+ }
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/src/har/test/html_har_post-data-test-page.html b/devtools/client/netmonitor/src/har/test/html_har_post-data-test-page.html
new file mode 100644
index 0000000000..5e42c6139d
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/html_har_post-data-test-page.html
@@ -0,0 +1,55 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor Test Page</title>
+ </head>
+
+ <body>
+ <p>HAR POST data test</p>
+
+ <script type="text/javascript">
+ /* exported executeTest, executeTest2, executeTest3 */
+ "use strict";
+
+ function post(address, data) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", address, true);
+ xhr.setRequestHeader("Content-Type", "application/json");
+ xhr.send(data);
+ }
+
+ function get(address) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address);
+ xhr.send();
+ }
+
+ function executeTest() {
+ const url = "html_har_post-data-test-page.html";
+ const data = "{'first': 'John', 'last': 'Doe'}";
+ post(url, data);
+ }
+
+ function executeTest2(size) {
+ const url = "html_har_post-data-test-page.html";
+ const data = "x".repeat(size);
+ post(url, data);
+ }
+
+ function executeTest3(size) {
+ const url = "html_har_post-data-test-page.html";
+ get(url);
+ }
+
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/src/har/test/sjs_cache-test-server.sjs b/devtools/client/netmonitor/src/har/test/sjs_cache-test-server.sjs
new file mode 100644
index 0000000000..66081fe1bb
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/sjs_cache-test-server.sjs
@@ -0,0 +1,14 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.setStatusLine(request.httpVersion, 304, "Not Modified");
+ response.setHeader(
+ "Cache-Control",
+ "no-transform,public,max-age=300,s-maxage=900"
+ );
+ response.setHeader("Expires", "Thu, 01 Dec 2100 20:00:00 GMT");
+ response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
+ response.write("Hello from cache!");
+}
diff --git a/devtools/client/netmonitor/src/har/test/sjs_cookies-test-server.sjs b/devtools/client/netmonitor/src/har/test/sjs_cookies-test-server.sjs
new file mode 100644
index 0000000000..a86a0f13cd
--- /dev/null
+++ b/devtools/client/netmonitor/src/har/test/sjs_cookies-test-server.sjs
@@ -0,0 +1,10 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.setHeader("Set-Cookie", "tom=cool; Max-Age=10; HttpOnly", true);
+ response.setHeader("Set-Cookie", "bob=true; Max-Age=10; HttpOnly", true);
+ response.setHeader("Set-Cookie", "foo=bar; Max-Age=10; HttpOnly", true);
+ response.write("Hello world!");
+}
diff --git a/devtools/client/netmonitor/src/middleware/batching.js b/devtools/client/netmonitor/src/middleware/batching.js
new file mode 100644
index 0000000000..9d8c57084c
--- /dev/null
+++ b/devtools/client/netmonitor/src/middleware/batching.js
@@ -0,0 +1,146 @@
+/* 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 {
+ BATCH_ACTIONS,
+ BATCH_ENABLE,
+ BATCH_RESET,
+ BATCH_FLUSH,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const REQUESTS_REFRESH_RATE = 50; // ms
+
+/**
+ * Middleware that watches for actions with a "batch = true" value in their meta field.
+ * These actions are queued and dispatched as one batch after a timeout.
+ * Special actions that are handled by this middleware:
+ * - BATCH_ENABLE can be used to enable and disable the batching.
+ * - BATCH_RESET discards the actions that are currently in the queue.
+ */
+function batchingMiddleware(store) {
+ return next => {
+ let queuedActions = [];
+ let enabled = true;
+ let flushTask = null;
+
+ return action => {
+ if (action.type === BATCH_ENABLE) {
+ return setEnabled(action.enabled);
+ }
+
+ if (action.type === BATCH_RESET) {
+ return resetQueue();
+ }
+
+ if (action.type === BATCH_FLUSH) {
+ return flushQueue();
+ }
+
+ if (action.meta?.batch) {
+ if (!enabled) {
+ next(action);
+ return Promise.resolve();
+ }
+
+ queuedActions.push(action);
+
+ if (!flushTask) {
+ flushTask = new DelayedTask(flushActions, REQUESTS_REFRESH_RATE);
+ }
+
+ return flushTask.promise;
+ }
+
+ return next(action);
+ };
+
+ function setEnabled(value) {
+ enabled = value;
+
+ // If disabling the batching, flush the actions that have been queued so far
+ if (!enabled && flushTask) {
+ flushTask.runNow();
+ }
+ }
+
+ function resetQueue() {
+ queuedActions = [];
+
+ if (flushTask) {
+ flushTask.cancel();
+ flushTask = null;
+ }
+ }
+
+ function flushQueue() {
+ if (flushTask) {
+ flushTask.runNow();
+ }
+ }
+
+ function flushActions() {
+ const actions = queuedActions;
+ queuedActions = [];
+
+ next({
+ type: BATCH_ACTIONS,
+ actions,
+ });
+
+ flushTask = null;
+ }
+ };
+}
+
+/**
+ * Create a delayed task that calls the specified task function after a delay.
+ */
+function DelayedTask(taskFn, delay) {
+ this._promise = new Promise((resolve, reject) => {
+ this.runTask = cancel => {
+ if (cancel) {
+ reject("Task cancelled");
+ } else {
+ taskFn();
+ resolve();
+ }
+ this.runTask = null;
+ };
+ this.timeout = setTimeout(this.runTask, delay);
+ }).catch(console.error);
+}
+
+DelayedTask.prototype = {
+ /**
+ * Return a promise that is resolved after the task is performed or canceled.
+ */
+ get promise() {
+ return this._promise;
+ },
+
+ /**
+ * Cancel the execution of the task.
+ */
+ cancel() {
+ clearTimeout(this.timeout);
+ if (this.runTask) {
+ this.runTask(true);
+ }
+ },
+
+ /**
+ * Execute the scheduled task immediately, without waiting for the timeout.
+ * Resolves the promise correctly.
+ */
+ runNow() {
+ clearTimeout(this.timeout);
+ if (this.runTask) {
+ this.runTask();
+ }
+ },
+};
+
+module.exports = batchingMiddleware;
diff --git a/devtools/client/netmonitor/src/middleware/event-telemetry.js b/devtools/client/netmonitor/src/middleware/event-telemetry.js
new file mode 100644
index 0000000000..026dfab4ba
--- /dev/null
+++ b/devtools/client/netmonitor/src/middleware/event-telemetry.js
@@ -0,0 +1,192 @@
+/* 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 {
+ TOGGLE_REQUEST_FILTER_TYPE,
+ ENABLE_REQUEST_FILTER_TYPE_ONLY,
+ SET_REQUEST_FILTER_TEXT,
+ SELECT_DETAILS_PANEL_TAB,
+ SEND_CUSTOM_REQUEST,
+ ENABLE_PERSISTENT_LOGS,
+ MSG_SELECT,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const {
+ CHANGE_NETWORK_THROTTLING,
+} = require("resource://devtools/client/shared/components/throttling/actions.js");
+
+/**
+ * Event telemetry middleware is responsible for logging
+ * various events to telemetry. This helps to track Network
+ * panel usage.
+ */
+function eventTelemetryMiddleware(connector, telemetry) {
+ return store => next => action => {
+ const oldState = store.getState();
+ const res = next(action);
+ const toolbox = connector.getToolbox();
+ if (!toolbox) {
+ return res;
+ }
+
+ if (action.skipTelemetry) {
+ return res;
+ }
+
+ const state = store.getState();
+
+ const filterChangeActions = [
+ TOGGLE_REQUEST_FILTER_TYPE,
+ ENABLE_REQUEST_FILTER_TYPE_ONLY,
+ SET_REQUEST_FILTER_TEXT,
+ ];
+
+ // Record telemetry event when filter changes.
+ if (filterChangeActions.includes(action.type)) {
+ filterChange({
+ action,
+ state,
+ oldState,
+ telemetry,
+ });
+ }
+
+ // Record telemetry event when side panel is selected.
+ if (action.type == SELECT_DETAILS_PANEL_TAB) {
+ sidePanelChange({
+ state,
+ oldState,
+ telemetry,
+ });
+ }
+
+ // Record telemetry event when a request is resent.
+ if (action.type == SEND_CUSTOM_REQUEST) {
+ sendCustomRequest({
+ telemetry,
+ });
+ }
+
+ // Record telemetry event when throttling is changed.
+ if (action.type == CHANGE_NETWORK_THROTTLING) {
+ throttlingChange({
+ action,
+ telemetry,
+ });
+ }
+
+ // Record telemetry event when log persistence changes.
+ if (action.type == ENABLE_PERSISTENT_LOGS) {
+ persistenceChange({
+ telemetry,
+ state,
+ });
+ }
+
+ // Record telemetry event when message is selected.
+ if (action.type == MSG_SELECT) {
+ selectMessage({
+ telemetry,
+ });
+ }
+
+ return res;
+ };
+}
+
+/**
+ * This helper function is executed when filter related action is fired.
+ * It's responsible for recording "filters_changed" telemetry event.
+ */
+function filterChange({ action, state, oldState, telemetry }) {
+ const oldFilterState = oldState.filters;
+ const filterState = state.filters;
+ const activeFilters = [];
+ const inactiveFilters = [];
+
+ for (const [key, value] of Object.entries(filterState.requestFilterTypes)) {
+ if (value) {
+ activeFilters.push(key);
+ } else {
+ inactiveFilters.push(key);
+ }
+ }
+
+ let trigger;
+ if (
+ action.type === TOGGLE_REQUEST_FILTER_TYPE ||
+ action.type === ENABLE_REQUEST_FILTER_TYPE_ONLY
+ ) {
+ trigger = action.filter;
+ } else if (action.type === SET_REQUEST_FILTER_TEXT) {
+ if (
+ oldFilterState.requestFilterText !== "" &&
+ filterState.requestFilterText !== ""
+ ) {
+ return;
+ }
+
+ trigger = "text";
+ }
+
+ telemetry.recordEvent("filters_changed", "netmonitor", null, {
+ trigger,
+ active: activeFilters.join(","),
+ inactive: inactiveFilters.join(","),
+ });
+}
+
+/**
+ * This helper function is executed when side panel is selected.
+ * It's responsible for recording "sidepanel_tool_changed"
+ * telemetry event.
+ */
+function sidePanelChange({ state, oldState, telemetry }) {
+ telemetry.recordEvent("sidepanel_changed", "netmonitor", null, {
+ oldpanel: oldState.ui.detailsPanelSelectedTab,
+ newpanel: state.ui.detailsPanelSelectedTab,
+ });
+}
+
+/**
+ * This helper function is executed when a request is resent.
+ * It's responsible for recording "edit_resend" telemetry event.
+ */
+function sendCustomRequest({ telemetry }) {
+ telemetry.recordEvent("edit_resend", "netmonitor");
+}
+
+/**
+ * This helper function is executed when network throttling is changed.
+ * It's responsible for recording "throttle_changed" telemetry event.
+ */
+function throttlingChange({ action, telemetry }) {
+ telemetry.recordEvent("throttle_changed", "netmonitor", null, {
+ mode: action.profile,
+ });
+}
+
+/**
+ * This helper function is executed when log persistence is changed.
+ * It's responsible for recording "persist_changed" telemetry event.
+ */
+function persistenceChange({ telemetry, state }) {
+ telemetry.recordEvent(
+ "persist_changed",
+ "netmonitor",
+ String(state.ui.persistentLogsEnabled)
+ );
+}
+
+/**
+ * This helper function is executed when a WS frame is selected.
+ * It's responsible for recording "select_ws_frame" telemetry event.
+ */
+function selectMessage({ telemetry }) {
+ telemetry.recordEvent("select_ws_frame", "netmonitor");
+}
+
+module.exports = eventTelemetryMiddleware;
diff --git a/devtools/client/netmonitor/src/middleware/moz.build b/devtools/client/netmonitor/src/middleware/moz.build
new file mode 100644
index 0000000000..4e551c24c8
--- /dev/null
+++ b/devtools/client/netmonitor/src/middleware/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/.
+
+DevToolsModules(
+ "batching.js",
+ "event-telemetry.js",
+ "prefs.js",
+ "request-blocking.js",
+ "throttling.js",
+)
diff --git a/devtools/client/netmonitor/src/middleware/prefs.js b/devtools/client/netmonitor/src/middleware/prefs.js
new file mode 100644
index 0000000000..6034a95dbf
--- /dev/null
+++ b/devtools/client/netmonitor/src/middleware/prefs.js
@@ -0,0 +1,116 @@
+/* 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 {
+ ENABLE_REQUEST_FILTER_TYPE_ONLY,
+ RESET_COLUMNS,
+ TOGGLE_COLUMN,
+ TOGGLE_REQUEST_FILTER_TYPE,
+ ENABLE_PERSISTENT_LOGS,
+ DISABLE_BROWSER_CACHE,
+ SET_COLUMNS_WIDTH,
+ WS_TOGGLE_COLUMN,
+ WS_RESET_COLUMNS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * Update the relevant prefs when:
+ * - a column has been toggled
+ * - a filter type has been set
+ */
+function prefsMiddleware(store) {
+ return next => action => {
+ const res = next(action);
+ switch (action.type) {
+ case ENABLE_REQUEST_FILTER_TYPE_ONLY:
+ case TOGGLE_REQUEST_FILTER_TYPE:
+ const filters = Object.entries(
+ store.getState().filters.requestFilterTypes
+ )
+ .filter(([type, check]) => check)
+ .map(([type, check]) => type);
+ Services.prefs.setCharPref(
+ "devtools.netmonitor.filters",
+ JSON.stringify(filters)
+ );
+ break;
+ case ENABLE_PERSISTENT_LOGS:
+ const enabled = store.getState().ui.persistentLogsEnabled;
+ Services.prefs.setBoolPref("devtools.netmonitor.persistlog", enabled);
+ break;
+ case DISABLE_BROWSER_CACHE:
+ Services.prefs.setBoolPref(
+ "devtools.cache.disabled",
+ store.getState().ui.browserCacheDisabled
+ );
+ break;
+ case TOGGLE_COLUMN:
+ persistVisibleColumns(store.getState());
+ break;
+ case RESET_COLUMNS:
+ persistVisibleColumns(store.getState());
+ persistColumnsData(store.getState());
+ break;
+ case SET_COLUMNS_WIDTH:
+ persistColumnsData(store.getState());
+ break;
+ case WS_TOGGLE_COLUMN:
+ case WS_RESET_COLUMNS:
+ persistVisibleWebSocketsColumns(store.getState());
+ break;
+ }
+ return res;
+ };
+}
+
+/**
+ * Store list of visible columns into preferences.
+ */
+function persistVisibleColumns(state) {
+ const visibleColumns = [];
+ const { columns } = state.ui;
+ for (const column in columns) {
+ if (columns[column]) {
+ visibleColumns.push(column);
+ }
+ }
+
+ Services.prefs.setCharPref(
+ "devtools.netmonitor.visibleColumns",
+ JSON.stringify(visibleColumns)
+ );
+}
+
+/**
+ * Store list of visible columns into preferences.
+ */
+function persistVisibleWebSocketsColumns(state) {
+ const visibleColumns = [];
+ const { columns } = state.messages;
+ for (const column in columns) {
+ if (columns[column]) {
+ visibleColumns.push(column);
+ }
+ }
+
+ Services.prefs.setCharPref(
+ "devtools.netmonitor.msg.visibleColumns",
+ JSON.stringify(visibleColumns)
+ );
+}
+
+/**
+ * Store columns data (width, min-width, etc.) into preferences.
+ */
+function persistColumnsData(state) {
+ const columnsData = [...state.ui.columnsData.values()];
+ Services.prefs.setCharPref(
+ "devtools.netmonitor.columnsData",
+ JSON.stringify(columnsData)
+ );
+}
+
+module.exports = prefsMiddleware;
diff --git a/devtools/client/netmonitor/src/middleware/request-blocking.js b/devtools/client/netmonitor/src/middleware/request-blocking.js
new file mode 100644
index 0000000000..bb2a310a8d
--- /dev/null
+++ b/devtools/client/netmonitor/src/middleware/request-blocking.js
@@ -0,0 +1,58 @@
+/* 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 {
+ ADD_BLOCKED_URL,
+ REMOVE_BLOCKED_URL,
+ TOGGLE_BLOCKED_URL,
+ UPDATE_BLOCKED_URL,
+ TOGGLE_BLOCKING_ENABLED,
+ DISABLE_MATCHING_URLS,
+ ENABLE_ALL_BLOCKED_URLS,
+ DISABLE_ALL_BLOCKED_URLS,
+ REMOVE_ALL_BLOCKED_URLS,
+ REQUEST_BLOCKING_UPDATE_COMPLETE,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const BLOCKING_EVENTS = [
+ ADD_BLOCKED_URL,
+ REMOVE_BLOCKED_URL,
+ TOGGLE_BLOCKED_URL,
+ UPDATE_BLOCKED_URL,
+ TOGGLE_BLOCKING_ENABLED,
+ DISABLE_MATCHING_URLS,
+ ENABLE_ALL_BLOCKED_URLS,
+ DISABLE_ALL_BLOCKED_URLS,
+ REMOVE_ALL_BLOCKED_URLS,
+];
+
+/**
+ * This middleware is responsible for syncing the list of blocking patterns/urls with the backed.
+ * It utilizes the NetworkCommand and `setBlockedUrls` function to sent the current list to the server
+ * every time it's been modified.
+ */
+function requestBlockingMiddleware(commands) {
+ return store => next => async action => {
+ const res = next(action);
+
+ if (BLOCKING_EVENTS.includes(action.type)) {
+ const { blockedUrls, blockingEnabled } = store.getState().requestBlocking;
+ const urls = blockingEnabled
+ ? blockedUrls.reduce((arr, { enabled, url }) => {
+ if (enabled) {
+ arr.push(url);
+ }
+ return arr;
+ }, [])
+ : [];
+ await commands.networkCommand.setBlockedUrls(urls);
+ store.dispatch({ type: REQUEST_BLOCKING_UPDATE_COMPLETE });
+ }
+ return res;
+ };
+}
+
+module.exports = requestBlockingMiddleware;
diff --git a/devtools/client/netmonitor/src/middleware/throttling.js b/devtools/client/netmonitor/src/middleware/throttling.js
new file mode 100644
index 0000000000..30f5a9b5f4
--- /dev/null
+++ b/devtools/client/netmonitor/src/middleware/throttling.js
@@ -0,0 +1,26 @@
+/* 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 {
+ CHANGE_NETWORK_THROTTLING,
+} = require("resource://devtools/client/shared/components/throttling/actions.js");
+
+/**
+ * Network throttling middleware is responsible for
+ * updating/syncing currently connected backend
+ * according to user actions.
+ */
+function throttlingMiddleware(connector) {
+ return store => next => action => {
+ const res = next(action);
+ if (action.type === CHANGE_NETWORK_THROTTLING) {
+ connector.updateNetworkThrottling(action.enabled, action.profile);
+ }
+ return res;
+ };
+}
+
+module.exports = throttlingMiddleware;
diff --git a/devtools/client/netmonitor/src/moz.build b/devtools/client/netmonitor/src/moz.build
new file mode 100644
index 0000000000..b3ba8c5060
--- /dev/null
+++ b/devtools/client/netmonitor/src/moz.build
@@ -0,0 +1,23 @@
+# 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 += [
+ "actions",
+ "components",
+ "connector",
+ "har",
+ "middleware",
+ "reducers",
+ "selectors",
+ "utils",
+ "widgets",
+ "workers",
+]
+
+DevToolsModules(
+ "api.js",
+ "app.js",
+ "constants.js",
+ "create-store.js",
+)
diff --git a/devtools/client/netmonitor/src/reducers/batching.js b/devtools/client/netmonitor/src/reducers/batching.js
new file mode 100644
index 0000000000..bc4f02beb2
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/batching.js
@@ -0,0 +1,27 @@
+/* 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 {
+ BATCH_ACTIONS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * A reducer to handle batched actions. For each action in the BATCH_ACTIONS array,
+ * the reducer is called successively on the array of batched actions, resulting in
+ * only one state update.
+ */
+function batchingReducer(nextReducer) {
+ return function reducer(state, action) {
+ switch (action.type) {
+ case BATCH_ACTIONS:
+ return action.actions.reduce(reducer, state);
+ default:
+ return nextReducer(state, action);
+ }
+ };
+}
+
+module.exports = batchingReducer;
diff --git a/devtools/client/netmonitor/src/reducers/filters.js b/devtools/client/netmonitor/src/reducers/filters.js
new file mode 100644
index 0000000000..4635f6f94a
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/filters.js
@@ -0,0 +1,102 @@
+/* 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 {
+ ENABLE_REQUEST_FILTER_TYPE_ONLY,
+ TOGGLE_REQUEST_FILTER_TYPE,
+ SET_REQUEST_FILTER_TEXT,
+ FILTER_TAGS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+function FilterTypes(overrideParams = {}) {
+ const allFilterTypes = ["all"].concat(FILTER_TAGS);
+ // filter only those keys which are valid filter tags
+ overrideParams = Object.keys(overrideParams)
+ .filter(key => allFilterTypes.includes(key))
+ .reduce((obj, key) => {
+ obj[key] = overrideParams[key];
+ return obj;
+ }, {});
+ const filterTypes = allFilterTypes.reduce(
+ (o, tag) => Object.assign(o, { [tag]: false }),
+ {}
+ );
+ return Object.assign({}, filterTypes, overrideParams);
+}
+
+function Filters(overrideParams = {}) {
+ return Object.assign(
+ {
+ requestFilterTypes: new FilterTypes({ all: true }),
+ requestFilterText: "",
+ },
+ overrideParams
+ );
+}
+
+function toggleRequestFilterType(state, action) {
+ const { filter } = action;
+ let newState;
+
+ // Ignore unknown filter type
+ if (!state.hasOwnProperty(filter)) {
+ return state;
+ }
+ if (filter === "all") {
+ return new FilterTypes({ all: true });
+ }
+
+ newState = { ...state };
+ newState.all = false;
+ newState[filter] = !state[filter];
+
+ if (!Object.values(newState).includes(true)) {
+ newState = new FilterTypes({ all: true });
+ }
+
+ return newState;
+}
+
+function enableRequestFilterTypeOnly(state, action) {
+ const { filter } = action;
+
+ // Ignore unknown filter type
+ if (!state.hasOwnProperty(filter)) {
+ return state;
+ }
+
+ return new FilterTypes({ [filter]: true });
+}
+
+function filters(state = new Filters(), action) {
+ state = { ...state };
+ switch (action.type) {
+ case ENABLE_REQUEST_FILTER_TYPE_ONLY:
+ state.requestFilterTypes = enableRequestFilterTypeOnly(
+ state.requestFilterTypes,
+ action
+ );
+ break;
+ case TOGGLE_REQUEST_FILTER_TYPE:
+ state.requestFilterTypes = toggleRequestFilterType(
+ state.requestFilterTypes,
+ action
+ );
+ break;
+ case SET_REQUEST_FILTER_TEXT:
+ state.requestFilterText = action.text;
+ break;
+ default:
+ break;
+ }
+ return state;
+}
+
+module.exports = {
+ FilterTypes,
+ Filters,
+ filters,
+};
diff --git a/devtools/client/netmonitor/src/reducers/index.js b/devtools/client/netmonitor/src/reducers/index.js
new file mode 100644
index 0000000000..d73765f795
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/index.js
@@ -0,0 +1,47 @@
+/* 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 {
+ combineReducers,
+} = require("resource://devtools/client/shared/vendor/redux.js");
+const batchingReducer = require("resource://devtools/client/netmonitor/src/reducers/batching.js");
+const requestBlockingReducer = require("resource://devtools/client/netmonitor/src/reducers/request-blocking.js");
+const {
+ requestsReducer,
+} = require("resource://devtools/client/netmonitor/src/reducers/requests.js");
+const {
+ search,
+} = require("resource://devtools/client/netmonitor/src/reducers/search.js");
+const {
+ sortReducer,
+} = require("resource://devtools/client/netmonitor/src/reducers/sort.js");
+const {
+ filters,
+} = require("resource://devtools/client/netmonitor/src/reducers/filters.js");
+const {
+ timingMarkers,
+} = require("resource://devtools/client/netmonitor/src/reducers/timing-markers.js");
+const {
+ ui,
+} = require("resource://devtools/client/netmonitor/src/reducers/ui.js");
+const {
+ messages,
+} = require("resource://devtools/client/netmonitor/src/reducers/messages.js");
+const networkThrottling = require("resource://devtools/client/shared/components/throttling/reducer.js");
+
+module.exports = batchingReducer(
+ combineReducers({
+ filters,
+ messages,
+ networkThrottling,
+ requestBlocking: requestBlockingReducer,
+ requests: requestsReducer,
+ search,
+ sort: sortReducer,
+ timingMarkers,
+ ui,
+ })
+);
diff --git a/devtools/client/netmonitor/src/reducers/messages.js b/devtools/client/netmonitor/src/reducers/messages.js
new file mode 100644
index 0000000000..27d7da28c7
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/messages.js
@@ -0,0 +1,335 @@
+/* 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 {
+ SELECT_REQUEST,
+ MSG_ADD,
+ MSG_SELECT,
+ MSG_OPEN_DETAILS,
+ MSG_CLEAR,
+ MSG_TOGGLE_FILTER_TYPE,
+ MSG_TOGGLE_CONTROL,
+ MSG_SET_FILTER_TEXT,
+ MSG_TOGGLE_COLUMN,
+ MSG_RESET_COLUMNS,
+ MSG_CLOSE_CONNECTION,
+ CHANNEL_TYPE,
+ SET_EVENT_STREAM_FLAG,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * The default column states for the MessageListItem component.
+ */
+const defaultColumnsState = {
+ data: true,
+ size: false,
+ time: true,
+};
+
+const defaultWSColumnsState = {
+ ...defaultColumnsState,
+ opCode: false,
+ maskBit: false,
+ finBit: false,
+};
+
+const defaultSSEColumnsState = {
+ ...defaultColumnsState,
+ eventName: false,
+ lastEventId: false,
+ retry: false,
+};
+
+/**
+ * Returns a new object of default cols.
+ */
+function getMessageDefaultColumnsState(channelType) {
+ let columnsState = defaultColumnsState;
+ const { EVENT_STREAM, WEB_SOCKET } = CHANNEL_TYPE;
+
+ if (channelType === WEB_SOCKET) {
+ columnsState = defaultWSColumnsState;
+ } else if (channelType === EVENT_STREAM) {
+ columnsState = defaultSSEColumnsState;
+ }
+
+ return Object.assign({}, columnsState);
+}
+
+/**
+ * This structure stores list of all WebSocket and EventSource messages received
+ * from the backend.
+ */
+function Messages(initialState = {}) {
+ const { EVENT_STREAM, WEB_SOCKET } = CHANNEL_TYPE;
+
+ return {
+ // Map with all requests (key = resourceId, value = array of message objects)
+ messages: new Map(),
+ messageFilterText: "",
+ // Default filter type is "all",
+ messageFilterType: "all",
+ showControlFrames: false,
+ selectedMessage: null,
+ messageDetailsOpen: false,
+ currentChannelId: null,
+ currentChannelType: null,
+ currentRequestId: null,
+ closedConnections: new Map(),
+ columns: null,
+ sseColumns: getMessageDefaultColumnsState(EVENT_STREAM),
+ wsColumns: getMessageDefaultColumnsState(WEB_SOCKET),
+ ...initialState,
+ };
+}
+
+/**
+ * When a network request is selected,
+ * set the current resourceId affiliated with the connection.
+ */
+function setCurrentChannel(state, action) {
+ if (!action.request) {
+ return state;
+ }
+
+ const { id, cause, resourceId, isEventStream } = action.request;
+ const { EVENT_STREAM, WEB_SOCKET } = CHANNEL_TYPE;
+ let currentChannelType = null;
+ let columnsKey = "columns";
+ if (cause.type === "websocket") {
+ currentChannelType = WEB_SOCKET;
+ columnsKey = "wsColumns";
+ } else if (isEventStream) {
+ currentChannelType = EVENT_STREAM;
+ columnsKey = "sseColumns";
+ }
+
+ return {
+ ...state,
+ columns:
+ currentChannelType === state.currentChannelType
+ ? { ...state.columns }
+ : { ...state[columnsKey] },
+ currentChannelId: resourceId,
+ currentChannelType,
+ currentRequestId: id,
+ // Default filter text is empty string for a new connection
+ messageFilterText: "",
+ };
+}
+
+/**
+ * If the request is already selected and isEventStream flag
+ * is added later, we need to update currentChannelType & columns.
+ */
+function updateCurrentChannel(state, action) {
+ if (state.currentRequestId === action.id) {
+ const currentChannelType = CHANNEL_TYPE.EVENT_STREAM;
+ return {
+ ...state,
+ columns: { ...state.sseColumns },
+ currentChannelType,
+ };
+ }
+ return state;
+}
+
+/**
+ * Appending new message into the map.
+ */
+function addMessage(state, action) {
+ const { httpChannelId } = action;
+ const nextState = { ...state };
+
+ const newMessage = {
+ httpChannelId,
+ ...action.data,
+ };
+
+ nextState.messages = mapSet(
+ nextState.messages,
+ newMessage.httpChannelId,
+ newMessage
+ );
+
+ return nextState;
+}
+
+/**
+ * Select specific message.
+ */
+function selectMessage(state, action) {
+ return {
+ ...state,
+ selectedMessage: action.message,
+ messageDetailsOpen: action.open,
+ };
+}
+
+/**
+ * Shows/Hides the MessagePayload component.
+ */
+function openMessageDetails(state, action) {
+ return {
+ ...state,
+ messageDetailsOpen: action.open,
+ };
+}
+
+/**
+ * Clear messages of the request from the state.
+ */
+function clearMessages(state) {
+ const nextState = { ...state };
+ const defaultState = Messages();
+ nextState.messages = new Map(state.messages);
+ nextState.messages.delete(nextState.currentChannelId);
+
+ // Reset fields to default state.
+ nextState.selectedMessage = defaultState.selectedMessage;
+ nextState.messageDetailsOpen = defaultState.messageDetailsOpen;
+
+ return nextState;
+}
+
+/**
+ * Toggle the message filter type of the connection.
+ */
+function toggleMessageFilterType(state, action) {
+ return {
+ ...state,
+ messageFilterType: action.filter,
+ };
+}
+
+/**
+ * Toggle control frames for the WebSocket connection.
+ */
+function toggleControlFrames(state, action) {
+ return {
+ ...state,
+ showControlFrames: !state.showControlFrames,
+ };
+}
+
+/**
+ * Set the filter text of the current channelId.
+ */
+function setMessageFilterText(state, action) {
+ return {
+ ...state,
+ messageFilterText: action.text,
+ };
+}
+
+/**
+ * Toggle the user specified column view state.
+ */
+function toggleColumn(state, action) {
+ const { column } = action;
+ let columnsKey = null;
+ if (state.currentChannelType === CHANNEL_TYPE.WEB_SOCKET) {
+ columnsKey = "wsColumns";
+ } else {
+ columnsKey = "sseColumns";
+ }
+ const newColumnsState = {
+ ...state[columnsKey],
+ [column]: !state[columnsKey][column],
+ };
+ return {
+ ...state,
+ columns: newColumnsState,
+ [columnsKey]: newColumnsState,
+ };
+}
+
+/**
+ * Reset back to default columns view state.
+ */
+function resetColumns(state) {
+ let columnsKey = null;
+ if (state.currentChannelType === CHANNEL_TYPE.WEB_SOCKET) {
+ columnsKey = "wsColumns";
+ } else {
+ columnsKey = "sseColumns";
+ }
+ const newColumnsState = getMessageDefaultColumnsState(
+ state.currentChannelType
+ );
+ return {
+ ...state,
+ [columnsKey]: newColumnsState,
+ columns: newColumnsState,
+ };
+}
+
+function closeConnection(state, action) {
+ const { httpChannelId, code, reason } = action;
+ const nextState = { ...state };
+
+ nextState.closedConnections.set(httpChannelId, {
+ code,
+ reason,
+ });
+
+ return nextState;
+}
+
+/**
+ * Append new item into existing map and return new map.
+ */
+function mapSet(map, key, value) {
+ const newMap = new Map(map);
+ if (newMap.has(key)) {
+ const messagesArray = [...newMap.get(key)];
+ messagesArray.push(value);
+ newMap.set(key, messagesArray);
+ return newMap;
+ }
+ return newMap.set(key, [value]);
+}
+
+/**
+ * This reducer is responsible for maintaining list of
+ * messages within the Network panel.
+ */
+function messages(state = Messages(), action) {
+ switch (action.type) {
+ case SELECT_REQUEST:
+ return setCurrentChannel(state, action);
+ case SET_EVENT_STREAM_FLAG:
+ return updateCurrentChannel(state, action);
+ case MSG_ADD:
+ return addMessage(state, action);
+ case MSG_SELECT:
+ return selectMessage(state, action);
+ case MSG_OPEN_DETAILS:
+ return openMessageDetails(state, action);
+ case MSG_CLEAR:
+ return clearMessages(state);
+ case MSG_TOGGLE_FILTER_TYPE:
+ return toggleMessageFilterType(state, action);
+ case MSG_TOGGLE_CONTROL:
+ return toggleControlFrames(state, action);
+ case MSG_SET_FILTER_TEXT:
+ return setMessageFilterText(state, action);
+ case MSG_TOGGLE_COLUMN:
+ return toggleColumn(state, action);
+ case MSG_RESET_COLUMNS:
+ return resetColumns(state);
+ case MSG_CLOSE_CONNECTION:
+ return closeConnection(state, action);
+ default:
+ return state;
+ }
+}
+
+module.exports = {
+ Messages,
+ messages,
+ getMessageDefaultColumnsState,
+};
diff --git a/devtools/client/netmonitor/src/reducers/moz.build b/devtools/client/netmonitor/src/reducers/moz.build
new file mode 100644
index 0000000000..bd9d238761
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/moz.build
@@ -0,0 +1,16 @@
+# 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(
+ "batching.js",
+ "filters.js",
+ "index.js",
+ "messages.js",
+ "request-blocking.js",
+ "requests.js",
+ "search.js",
+ "sort.js",
+ "timing-markers.js",
+ "ui.js",
+)
diff --git a/devtools/client/netmonitor/src/reducers/request-blocking.js b/devtools/client/netmonitor/src/reducers/request-blocking.js
new file mode 100644
index 0000000000..ffd0d8c97a
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/request-blocking.js
@@ -0,0 +1,187 @@
+/* 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 {
+ ADD_BLOCKED_URL,
+ DISABLE_MATCHING_URLS,
+ TOGGLE_BLOCKED_URL,
+ UPDATE_BLOCKED_URL,
+ REMOVE_BLOCKED_URL,
+ REMOVE_ALL_BLOCKED_URLS,
+ ENABLE_ALL_BLOCKED_URLS,
+ DISABLE_ALL_BLOCKED_URLS,
+ TOGGLE_BLOCKING_ENABLED,
+ SYNCED_BLOCKED_URLS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+function RequestBlocking() {
+ return {
+ blockedUrls: [],
+ blockingSynced: false,
+ blockingEnabled: true,
+ };
+}
+
+function requestBlockingReducer(state = RequestBlocking(), action) {
+ switch (action.type) {
+ case ADD_BLOCKED_URL:
+ return addBlockedUrl(state, action);
+ case REMOVE_BLOCKED_URL:
+ return removeBlockedUrl(state, action);
+ case REMOVE_ALL_BLOCKED_URLS:
+ return removeAllBlockedUrls(state, action);
+ case UPDATE_BLOCKED_URL:
+ return updateBlockedUrl(state, action);
+ case TOGGLE_BLOCKED_URL:
+ return toggleBlockedUrl(state, action);
+ case TOGGLE_BLOCKING_ENABLED:
+ return toggleBlockingEnabled(state, action);
+ case ENABLE_ALL_BLOCKED_URLS:
+ return enableAllBlockedUrls(state, action);
+ case DISABLE_ALL_BLOCKED_URLS:
+ return disableAllBlockedUrls(state, action);
+ case DISABLE_MATCHING_URLS:
+ return disableOrRemoveMatchingUrls(state, action);
+ case SYNCED_BLOCKED_URLS:
+ return syncedBlockedUrls(state, action);
+ default:
+ return state;
+ }
+}
+
+function syncedBlockedUrls(state, action) {
+ // Indicates whether the blocked url has been synced
+ // with the server once. We don't need to do it once netmonitor is open.
+ return {
+ ...state,
+ blockingSynced: action.synced,
+ };
+}
+
+function toggleBlockingEnabled(state, action) {
+ return {
+ ...state,
+ blockingEnabled: action.enabled,
+ };
+}
+
+function addBlockedUrl(state, action) {
+ // The user can paste in a list of URLS so we need to cleanse the input
+ // Pasting a list turns new lines into spaces
+ const uniqueUrls = [...new Set(action.url.split(" "))].map(url => url.trim());
+
+ const newUrls = uniqueUrls
+ // Ensure the URL isn't already blocked
+ .filter(url => url && !state.blockedUrls.some(item => item.url === url))
+ // Add new URLs as enabled by default
+ .map(url => ({ url, enabled: true }));
+
+ // If the user is trying to block a URL that's currently in the list but disabled,
+ // re-enable the old item
+ const currentBlockedUrls = state.blockedUrls.map(item =>
+ uniqueUrls.includes(item.url) ? { url: item.url, enabled: true } : item
+ );
+
+ const blockedUrls = [...currentBlockedUrls, ...newUrls];
+ return {
+ ...state,
+ blockedUrls,
+ };
+}
+
+function removeBlockedUrl(state, action) {
+ return {
+ ...state,
+ blockedUrls: state.blockedUrls.filter(item => item.url != action.url),
+ };
+}
+
+function removeAllBlockedUrls(state, action) {
+ return {
+ ...state,
+ blockedUrls: [],
+ };
+}
+
+function enableAllBlockedUrls(state, action) {
+ const blockedUrls = state.blockedUrls.map(item => ({
+ ...item,
+ enabled: true,
+ }));
+ return {
+ ...state,
+ blockedUrls,
+ };
+}
+
+function disableAllBlockedUrls(state, action) {
+ const blockedUrls = state.blockedUrls.map(item => ({
+ ...item,
+ enabled: false,
+ }));
+ return {
+ ...state,
+ blockedUrls,
+ };
+}
+
+function updateBlockedUrl(state, action) {
+ const { oldUrl, newUrl } = action;
+ let { blockedUrls } = state;
+
+ if (!blockedUrls.find(item => item.url === newUrl)) {
+ blockedUrls = blockedUrls.map(item => {
+ if (item.url === oldUrl) {
+ return { ...item, url: newUrl };
+ }
+ return item;
+ });
+ } else {
+ blockedUrls = blockedUrls.filter(item => item.url != oldUrl);
+ }
+
+ return {
+ ...state,
+ blockedUrls,
+ };
+}
+
+function toggleBlockedUrl(state, action) {
+ const blockedUrls = state.blockedUrls.map(item => {
+ if (item.url === action.url) {
+ return { ...item, enabled: !item.enabled };
+ }
+ return item;
+ });
+
+ return {
+ ...state,
+ blockedUrls,
+ };
+}
+
+function disableOrRemoveMatchingUrls(state, action) {
+ const blockedUrls = state.blockedUrls
+ .map(item => {
+ // If the url matches exactly, remove the entry
+ if (action.url === item.url) {
+ return null;
+ }
+ // If just a partial match, disable the entry
+ if (action.url.includes(item.url)) {
+ return { ...item, enabled: false };
+ }
+ return item;
+ })
+ .filter(Boolean);
+
+ return {
+ ...state,
+ blockedUrls,
+ };
+}
+
+module.exports = requestBlockingReducer;
diff --git a/devtools/client/netmonitor/src/reducers/requests.js b/devtools/client/netmonitor/src/reducers/requests.js
new file mode 100644
index 0000000000..0bc503727e
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/requests.js
@@ -0,0 +1,313 @@
+/* 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 {
+ processNetworkUpdates,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ ADD_REQUEST,
+ SET_EVENT_STREAM_FLAG,
+ CLEAR_REQUESTS,
+ CLONE_REQUEST,
+ CLONE_SELECTED_REQUEST,
+ OPEN_NETWORK_DETAILS,
+ REMOVE_SELECTED_CUSTOM_REQUEST,
+ RIGHT_CLICK_REQUEST,
+ SELECT_REQUEST,
+ PRESELECT_REQUEST,
+ SEND_CUSTOM_REQUEST,
+ SET_RECORDING_STATE,
+ UPDATE_REQUEST,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * This structure stores list of all HTTP requests received
+ * from the backend. It's using plain JS structures to store
+ * data instead of ImmutableJS, which is performance expensive.
+ */
+function Requests() {
+ return {
+ // Map with all requests (key = actor ID, value = request object)
+ requests: [],
+ // Selected request ID
+ selectedId: null,
+ // Right click request represents the last request that was clicked
+ clickedRequestId: null,
+ // @backward-compact { version 85 } The preselectedId can either be
+ // the actor id on old servers, or the resourceId on new ones.
+ preselectedId: null,
+ // True if the monitor is recording HTTP traffic
+ recording: true,
+ // Auxiliary fields to hold requests stats
+ firstStartedMs: +Infinity,
+ lastEndedMs: -Infinity,
+ };
+}
+
+/**
+ * This reducer is responsible for maintaining list of request
+ * within the Network panel.
+ */
+function requestsReducer(state = Requests(), action) {
+ switch (action.type) {
+ // Appending new request into the list/map.
+ case ADD_REQUEST: {
+ return addRequest(state, action);
+ }
+
+ // Update an existing request (with received data).
+ case UPDATE_REQUEST: {
+ return updateRequest(state, action);
+ }
+
+ // Add isEventStream flag to a request.
+ case SET_EVENT_STREAM_FLAG: {
+ return setEventStreamFlag(state, action);
+ }
+
+ // Remove all requests in the list. Create fresh new state
+ // object, but keep value of the `recording` field.
+ case CLEAR_REQUESTS: {
+ return {
+ ...Requests(),
+ recording: state.recording,
+ };
+ }
+
+ // Select specific request.
+ case SELECT_REQUEST: {
+ return {
+ ...state,
+ clickedRequestId: action.id,
+ selectedId: action.id,
+ };
+ }
+
+ // Clone selected request for re-send.
+ case CLONE_REQUEST: {
+ return cloneRequest(state, action.id);
+ }
+
+ case CLONE_SELECTED_REQUEST: {
+ return cloneRequest(state, state.selectedId);
+ }
+
+ case RIGHT_CLICK_REQUEST: {
+ return {
+ ...state,
+ clickedRequestId: action.id,
+ };
+ }
+
+ case PRESELECT_REQUEST: {
+ return {
+ ...state,
+ preselectedId: action.id,
+ };
+ }
+
+ // Removing temporary cloned request (created for re-send, but canceled).
+ case REMOVE_SELECTED_CUSTOM_REQUEST: {
+ return closeCustomRequest(state);
+ }
+
+ // Re-sending an existing request.
+ case SEND_CUSTOM_REQUEST: {
+ // When a new request with a given id is added in future, select it immediately.
+ // where we know in advance the ID of the request, at a time when it
+ // wasn't sent yet.
+ return closeCustomRequest({ ...state, preselectedId: action.id });
+ }
+
+ // Pause/resume button clicked.
+ case SET_RECORDING_STATE: {
+ return {
+ ...state,
+ recording: action.recording,
+ };
+ }
+
+ // Side bar with request details opened.
+ case OPEN_NETWORK_DETAILS: {
+ const nextState = { ...state };
+ if (!action.open) {
+ nextState.selectedId = null;
+ return nextState;
+ }
+
+ if (!state.selectedId && action.defaultSelectedId) {
+ nextState.selectedId = action.defaultSelectedId;
+ return nextState;
+ }
+
+ return state;
+ }
+
+ default:
+ return state;
+ }
+}
+
+// Helpers
+
+function addRequest(state, action) {
+ const nextState = { ...state };
+ // The target front is not used and cannot be serialized by redux
+ // eslint-disable-next-line no-unused-vars
+ const { targetFront, ...requestData } = action.data;
+ const newRequest = {
+ id: action.id,
+ ...requestData,
+ };
+
+ nextState.requests = [...state.requests, newRequest];
+
+ // Update the started/ended timestamps.
+ const { startedMs } = action.data;
+ if (startedMs < state.firstStartedMs) {
+ nextState.firstStartedMs = startedMs;
+ }
+ if (startedMs > state.lastEndedMs) {
+ nextState.lastEndedMs = startedMs;
+ }
+
+ // Select the request if it was preselected and there is no other selection.
+ if (state.preselectedId) {
+ if (state.preselectedId === action.id) {
+ nextState.selectedId = state.selectedId || state.preselectedId;
+ }
+ // @backward-compact { version 85 } The preselectedId can be resourceId
+ // instead of actor id when a custom request is created, and could not be
+ // selected immediately because it was not yet in the request map.
+ else if (state.preselectedId === newRequest.resourceId) {
+ nextState.selectedId = action.id;
+ }
+ nextState.preselectedId = null;
+ }
+
+ return nextState;
+}
+
+function updateRequest(state, action) {
+ const { requests, lastEndedMs } = state;
+
+ const { id } = action;
+ const index = requests.findIndex(needle => needle.id === id);
+ if (index === -1) {
+ return state;
+ }
+ const request = requests[index];
+
+ const nextRequest = {
+ ...request,
+ ...processNetworkUpdates(action.data),
+ };
+ const requestEndTime =
+ nextRequest.startedMs +
+ (nextRequest.eventTimings ? nextRequest.eventTimings.totalTime : 0);
+
+ const nextRequests = [...requests];
+ nextRequests[index] = nextRequest;
+ return {
+ ...state,
+ requests: nextRequests,
+ lastEndedMs: requestEndTime > lastEndedMs ? requestEndTime : lastEndedMs,
+ };
+}
+
+function setEventStreamFlag(state, action) {
+ const { requests } = state;
+ const { id } = action;
+ const index = requests.findIndex(needle => needle.id === id);
+ if (index === -1) {
+ return state;
+ }
+
+ const request = requests[index];
+
+ const nextRequest = {
+ ...request,
+ isEventStream: true,
+ };
+
+ const nextRequests = [...requests];
+ nextRequests[index] = nextRequest;
+ return {
+ ...state,
+ requests: nextRequests,
+ };
+}
+
+function cloneRequest(state, id) {
+ const { requests } = state;
+
+ if (!id) {
+ return state;
+ }
+
+ const clonedRequest = requests.find(needle => needle.id === id);
+ if (!clonedRequest) {
+ return state;
+ }
+
+ const newRequest = {
+ id: clonedRequest.id + "-clone",
+ method: clonedRequest.method,
+ cause: clonedRequest.cause,
+ url: clonedRequest.url,
+ urlDetails: clonedRequest.urlDetails,
+ requestHeaders: clonedRequest.requestHeaders,
+ requestPostData: clonedRequest.requestPostData,
+ requestPostDataAvailable: clonedRequest.requestPostDataAvailable,
+ requestHeadersAvailable: clonedRequest.requestHeadersAvailable,
+ isCustom: true,
+ };
+
+ return {
+ ...state,
+ requests: [...requests, newRequest],
+ selectedId: newRequest.id,
+ preselectedId: id,
+ };
+}
+
+/**
+ * Remove the currently selected custom request.
+ */
+function closeCustomRequest(state) {
+ const { requests, selectedId, preselectedId } = state;
+
+ if (!selectedId) {
+ return state;
+ }
+
+ // Find the cloned requests to be removed
+ const removedRequest = requests.find(needle => needle.id === selectedId);
+
+ // If the custom request is already in the Map, select it immediately,
+ // and reset `preselectedId` attribute.
+ // @backward-compact { version 85 } The preselectId can also be a resourceId
+ // or an actor id.
+ const customRequest = requests.find(
+ needle => needle.id === preselectedId || needle.resourceId === preselectedId
+ );
+ const hasPreselectedId = preselectedId && customRequest;
+
+ return {
+ ...state,
+ // Only custom requests can be removed
+ [removedRequest?.isCustom && "requests"]: requests.filter(
+ item => item.id !== selectedId
+ ),
+ preselectedId: hasPreselectedId ? null : preselectedId,
+ selectedId: hasPreselectedId ? customRequest.id : null,
+ };
+}
+
+module.exports = {
+ Requests,
+ requestsReducer,
+};
diff --git a/devtools/client/netmonitor/src/reducers/search.js b/devtools/client/netmonitor/src/reducers/search.js
new file mode 100644
index 0000000000..91e843e18c
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/search.js
@@ -0,0 +1,118 @@
+/* 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 {
+ ADD_SEARCH_QUERY,
+ ADD_SEARCH_RESULT,
+ CLEAR_SEARCH_RESULTS,
+ ADD_ONGOING_SEARCH,
+ SEARCH_STATUS,
+ TOGGLE_SEARCH_CASE_SENSITIVE_SEARCH,
+ UPDATE_SEARCH_STATUS,
+ SET_TARGET_SEARCH_RESULT,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * Search reducer stores the following data:
+ * - query [String]: the string the user is looking for
+ * - results [Object]: the list of search results
+ * - ongoingSearch [Object]: the object representing the current search
+ * - status [String]: status of the current search (see constants.js)
+ */
+function Search(overrideParams = {}) {
+ return Object.assign(
+ {
+ query: "",
+ results: [],
+ ongoingSearch: null,
+ status: SEARCH_STATUS.INITIAL,
+ caseSensitive: false,
+ targetSearchResult: null,
+ },
+ overrideParams
+ );
+}
+
+function search(state = new Search(), action) {
+ switch (action.type) {
+ case ADD_SEARCH_QUERY:
+ return onAddSearchQuery(state, action);
+ case ADD_SEARCH_RESULT:
+ return onAddSearchResult(state, action);
+ case CLEAR_SEARCH_RESULTS:
+ return onClearSearchResults(state);
+ case ADD_ONGOING_SEARCH:
+ return onAddOngoingSearch(state, action);
+ case TOGGLE_SEARCH_CASE_SENSITIVE_SEARCH:
+ return onToggleCaseSensitiveSearch(state);
+ case UPDATE_SEARCH_STATUS:
+ return onUpdateSearchStatus(state, action);
+ case SET_TARGET_SEARCH_RESULT:
+ return onSetTargetSearchResult(state, action);
+ }
+ return state;
+}
+
+function onAddSearchQuery(state, action) {
+ return {
+ ...state,
+ query: action.query,
+ };
+}
+
+function onAddSearchResult(state, action) {
+ const { resource } = action;
+ const results = state.results.slice();
+ results.push({
+ resource,
+ results: action.result,
+ });
+
+ return {
+ ...state,
+ results,
+ };
+}
+
+function onClearSearchResults(state) {
+ return {
+ ...state,
+ results: [],
+ };
+}
+
+function onAddOngoingSearch(state, action) {
+ return {
+ ...state,
+ ongoingSearch: action.ongoingSearch,
+ };
+}
+
+function onToggleCaseSensitiveSearch(state) {
+ return {
+ ...state,
+ caseSensitive: !state.caseSensitive,
+ };
+}
+
+function onUpdateSearchStatus(state, action) {
+ return {
+ ...state,
+ status: action.status,
+ };
+}
+
+function onSetTargetSearchResult(state, action) {
+ return {
+ ...state,
+ targetSearchResult: action.searchResult,
+ };
+}
+
+module.exports = {
+ Search,
+ search,
+};
diff --git a/devtools/client/netmonitor/src/reducers/sort.js b/devtools/client/netmonitor/src/reducers/sort.js
new file mode 100644
index 0000000000..0d3486f57b
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/sort.js
@@ -0,0 +1,48 @@
+/* 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 {
+ SORT_BY,
+ RESET_COLUMNS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+function Sort() {
+ return {
+ // null means: sort by "waterfall", but don't highlight the table header
+ type: null,
+ ascending: true,
+ };
+}
+
+function sortReducer(state = new Sort(), action) {
+ switch (action.type) {
+ case SORT_BY: {
+ state = { ...state };
+ if (action.sortType != null && action.sortType == state.type) {
+ state.ascending = !state.ascending;
+ } else {
+ state.type = action.sortType;
+ state.ascending = true;
+ }
+ return state;
+ }
+
+ case RESET_COLUMNS: {
+ state = { ...state };
+ state.type = null;
+ state.ascending = true;
+ return state;
+ }
+
+ default:
+ return state;
+ }
+}
+
+module.exports = {
+ Sort,
+ sortReducer,
+};
diff --git a/devtools/client/netmonitor/src/reducers/timing-markers.js b/devtools/client/netmonitor/src/reducers/timing-markers.js
new file mode 100644
index 0000000000..4a41f9b495
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/timing-markers.js
@@ -0,0 +1,78 @@
+/* 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 {
+ ADD_REQUEST,
+ ADD_TIMING_MARKER,
+ CLEAR_TIMING_MARKERS,
+ CLEAR_REQUESTS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+function TimingMarkers() {
+ return {
+ firstDocumentDOMContentLoadedTimestamp: -1,
+ firstDocumentLoadTimestamp: -1,
+ firstDocumentRequestStartTimestamp: +Infinity,
+ };
+}
+
+function addRequest(state, action) {
+ const nextState = { ...state };
+ const { startedMs } = action.data;
+ if (startedMs < state.firstDocumentRequestStartTimestamp) {
+ nextState.firstDocumentRequestStartTimestamp = startedMs;
+ }
+
+ return nextState;
+}
+
+function addTimingMarker(state, action) {
+ state = { ...state };
+
+ if (
+ action.marker.name === "dom-interactive" &&
+ state.firstDocumentDOMContentLoadedTimestamp === -1
+ ) {
+ state.firstDocumentDOMContentLoadedTimestamp = action.marker.time;
+ return state;
+ }
+
+ if (
+ action.marker.name === "dom-complete" &&
+ state.firstDocumentLoadTimestamp === -1
+ ) {
+ state.firstDocumentLoadTimestamp = action.marker.time;
+ return state;
+ }
+
+ return state;
+}
+
+function clearTimingMarkers(state) {
+ return new TimingMarkers();
+}
+
+function timingMarkers(state = new TimingMarkers(), action) {
+ switch (action.type) {
+ case ADD_REQUEST:
+ return addRequest(state, action);
+
+ case ADD_TIMING_MARKER:
+ return addTimingMarker(state, action);
+
+ case CLEAR_REQUESTS:
+ case CLEAR_TIMING_MARKERS:
+ return clearTimingMarkers(state);
+
+ default:
+ return state;
+ }
+}
+
+module.exports = {
+ TimingMarkers,
+ timingMarkers,
+};
diff --git a/devtools/client/netmonitor/src/reducers/ui.js b/devtools/client/netmonitor/src/reducers/ui.js
new file mode 100644
index 0000000000..d1b405f033
--- /dev/null
+++ b/devtools/client/netmonitor/src/reducers/ui.js
@@ -0,0 +1,260 @@
+/* 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 {
+ CLEAR_REQUESTS,
+ OPEN_NETWORK_DETAILS,
+ OPEN_ACTION_BAR,
+ RESIZE_NETWORK_DETAILS,
+ ENABLE_PERSISTENT_LOGS,
+ DISABLE_BROWSER_CACHE,
+ OPEN_STATISTICS,
+ REMOVE_SELECTED_CUSTOM_REQUEST,
+ RESET_COLUMNS,
+ RESPONSE_HEADERS,
+ SELECT_DETAILS_PANEL_TAB,
+ SELECT_ACTION_BAR_TAB,
+ SEND_CUSTOM_REQUEST,
+ SELECT_REQUEST,
+ TOGGLE_COLUMN,
+ WATERFALL_RESIZE,
+ PANELS,
+ MIN_COLUMN_WIDTH,
+ SET_COLUMNS_WIDTH,
+ SET_HEADERS_URL_PREVIEW_EXPANDED,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const cols = {
+ status: true,
+ method: true,
+ domain: true,
+ file: true,
+ url: false,
+ protocol: false,
+ scheme: false,
+ remoteip: false,
+ initiator: true,
+ type: true,
+ cookies: false,
+ setCookies: false,
+ transferred: true,
+ contentSize: true,
+ priority: false,
+ startTime: false,
+ endTime: false,
+ responseTime: false,
+ duration: false,
+ latency: false,
+ waterfall: true,
+};
+
+function Columns() {
+ return Object.assign(
+ cols,
+ RESPONSE_HEADERS.reduce(
+ (acc, header) => Object.assign(acc, { [header]: false }),
+ {}
+ )
+ );
+}
+
+function ColumnsData() {
+ const defaultColumnsData = JSON.parse(
+ Services.prefs
+ .getDefaultBranch(null)
+ .getCharPref("devtools.netmonitor.columnsData")
+ );
+ return new Map(defaultColumnsData.map(i => [i.name, i]));
+}
+
+function UI(initialState = {}) {
+ return {
+ columns: Columns(),
+ columnsData: ColumnsData(),
+ detailsPanelSelectedTab: PANELS.HEADERS,
+ networkDetailsOpen: false,
+ networkDetailsWidth: null,
+ networkDetailsHeight: null,
+ persistentLogsEnabled: Services.prefs.getBoolPref(
+ "devtools.netmonitor.persistlog"
+ ),
+ browserCacheDisabled: Services.prefs.getBoolPref("devtools.cache.disabled"),
+ slowLimit: Services.prefs.getIntPref("devtools.netmonitor.audits.slow"),
+ statisticsOpen: false,
+ waterfallWidth: null,
+ networkActionOpen: false,
+ selectedActionBarTabId: null,
+ shouldExpandHeadersUrlPreview: false,
+ ...initialState,
+ };
+}
+
+function resetColumns(state) {
+ return {
+ ...state,
+ columns: Columns(),
+ columnsData: ColumnsData(),
+ };
+}
+
+function resizeWaterfall(state, action) {
+ return {
+ ...state,
+ waterfallWidth: action.width,
+ };
+}
+
+function openNetworkDetails(state, action) {
+ return {
+ ...state,
+ networkDetailsOpen: action.open,
+ };
+}
+
+function openNetworkAction(state, action) {
+ return {
+ ...state,
+ networkActionOpen: action.open,
+ };
+}
+
+function resizeNetworkDetails(state, action) {
+ return {
+ ...state,
+ networkDetailsWidth: action.width,
+ networkDetailsHeight: action.height,
+ };
+}
+
+function enablePersistentLogs(state, action) {
+ return {
+ ...state,
+ persistentLogsEnabled: action.enabled,
+ };
+}
+
+function disableBrowserCache(state, action) {
+ return {
+ ...state,
+ browserCacheDisabled: action.disabled,
+ };
+}
+
+function openStatistics(state, action) {
+ return {
+ ...state,
+ statisticsOpen: action.open,
+ };
+}
+
+function setDetailsPanelTab(state, action) {
+ return {
+ ...state,
+ detailsPanelSelectedTab: action.id,
+ };
+}
+
+function setActionBarTab(state, action) {
+ return {
+ ...state,
+ selectedActionBarTabId: action.id,
+ };
+}
+
+function setHeadersUrlPreviewExpanded(state, action) {
+ return {
+ ...state,
+ shouldExpandHeadersUrlPreview: action.expanded,
+ };
+}
+
+function toggleColumn(state, action) {
+ const { column } = action;
+
+ if (!state.columns.hasOwnProperty(column)) {
+ return state;
+ }
+
+ return {
+ ...state,
+ columns: {
+ ...state.columns,
+ [column]: !state.columns[column],
+ },
+ };
+}
+
+function setColumnsWidth(state, action) {
+ const { widths } = action;
+ const columnsData = new Map(state.columnsData);
+
+ widths.forEach(col => {
+ let data = columnsData.get(col.name);
+ if (!data) {
+ data = {
+ name: col.name,
+ minWidth: MIN_COLUMN_WIDTH,
+ };
+ }
+ columnsData.set(col.name, {
+ ...data,
+ width: col.width,
+ });
+ });
+
+ return {
+ ...state,
+ columnsData,
+ };
+}
+
+function ui(state = UI(), action) {
+ switch (action.type) {
+ case CLEAR_REQUESTS:
+ return openNetworkDetails(state, { open: false });
+ case OPEN_NETWORK_DETAILS:
+ return openNetworkDetails(state, action);
+ case RESIZE_NETWORK_DETAILS:
+ return resizeNetworkDetails(state, action);
+ case ENABLE_PERSISTENT_LOGS:
+ return enablePersistentLogs(state, action);
+ case DISABLE_BROWSER_CACHE:
+ return disableBrowserCache(state, action);
+ case OPEN_STATISTICS:
+ return openStatistics(state, action);
+ case RESET_COLUMNS:
+ return resetColumns(state);
+ case REMOVE_SELECTED_CUSTOM_REQUEST:
+ return openNetworkDetails(state, { open: true });
+ case SEND_CUSTOM_REQUEST:
+ return openNetworkDetails(state, { open: false });
+ case SELECT_DETAILS_PANEL_TAB:
+ return setDetailsPanelTab(state, action);
+ case SELECT_ACTION_BAR_TAB:
+ return setActionBarTab(state, action);
+ case SELECT_REQUEST:
+ return openNetworkDetails(state, { open: true });
+ case TOGGLE_COLUMN:
+ return toggleColumn(state, action);
+ case WATERFALL_RESIZE:
+ return resizeWaterfall(state, action);
+ case SET_COLUMNS_WIDTH:
+ return setColumnsWidth(state, action);
+ case OPEN_ACTION_BAR:
+ return openNetworkAction(state, action);
+ case SET_HEADERS_URL_PREVIEW_EXPANDED:
+ return setHeadersUrlPreviewExpanded(state, action);
+ default:
+ return state;
+ }
+}
+
+module.exports = {
+ Columns,
+ ColumnsData,
+ UI,
+ ui,
+};
diff --git a/devtools/client/netmonitor/src/selectors/index.js b/devtools/client/netmonitor/src/selectors/index.js
new file mode 100644
index 0000000000..52243d9a64
--- /dev/null
+++ b/devtools/client/netmonitor/src/selectors/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 requests = require("resource://devtools/client/netmonitor/src/selectors/requests.js");
+const search = require("resource://devtools/client/netmonitor/src/selectors/search.js");
+const timingMarkers = require("resource://devtools/client/netmonitor/src/selectors/timing-markers.js");
+const ui = require("resource://devtools/client/netmonitor/src/selectors/ui.js");
+const messages = require("resource://devtools/client/netmonitor/src/selectors/messages.js");
+
+Object.assign(exports, search, requests, timingMarkers, ui, messages);
diff --git a/devtools/client/netmonitor/src/selectors/messages.js b/devtools/client/netmonitor/src/selectors/messages.js
new file mode 100644
index 0000000000..d12b465b94
--- /dev/null
+++ b/devtools/client/netmonitor/src/selectors/messages.js
@@ -0,0 +1,162 @@
+/* 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 {
+ createSelector,
+} = require("resource://devtools/client/shared/vendor/reselect.js");
+
+/**
+ * Returns list of messages that are visible to the user.
+ * Filtered messages by types and text are factored in.
+ */
+const getDisplayedMessages = createSelector(
+ state => state.messages,
+ ({
+ messages,
+ messageFilterType,
+ showControlFrames,
+ messageFilterText,
+ currentChannelId,
+ }) => {
+ if (!currentChannelId || !messages.get(currentChannelId)) {
+ return [];
+ }
+
+ const messagesArray = messages.get(currentChannelId);
+ if (messageFilterType === "all" && messageFilterText.length === 0) {
+ return messagesArray.filter(message =>
+ typeFilter(message, messageFilterType, showControlFrames)
+ );
+ }
+
+ const filter = searchFilter(messageFilterText);
+
+ // If message payload is > 10,000 characters long, we check the LongStringActor payload string
+ return messagesArray.filter(
+ message =>
+ (message.payload.initial
+ ? filter(message.payload.initial)
+ : filter(message.payload)) &&
+ typeFilter(message, messageFilterType, showControlFrames)
+ );
+ }
+);
+
+function typeFilter(message, messageFilterType, showControlFrames) {
+ const controlFrames = [0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf];
+ const isControlFrame = controlFrames.includes(message.opCode);
+ if (messageFilterType === "all" || messageFilterType === message.type) {
+ return showControlFrames || !isControlFrame;
+ }
+ return false;
+}
+
+function searchFilter(messageFilterText) {
+ let regex;
+ if (looksLikeRegex(messageFilterText)) {
+ try {
+ regex = regexFromText(messageFilterText);
+ } catch (e) {}
+ }
+
+ return regex
+ ? payload => regex.test(payload)
+ : payload => payload.includes(messageFilterText);
+}
+
+function looksLikeRegex(text) {
+ return text.startsWith("/") && text.endsWith("/") && text.length > 2;
+}
+
+function regexFromText(text) {
+ return new RegExp(text.slice(1, -1), "im");
+}
+
+/**
+ * Checks if the selected message is visible.
+ * If the selected message is not visible, the SplitBox component
+ * should not show the MessagePayload component.
+ */
+const isSelectedMessageVisible = createSelector(
+ state => state.messages,
+ getDisplayedMessages,
+ ({ selectedMessage }, displayedMessages) =>
+ displayedMessages.some(message => message === selectedMessage)
+);
+
+/**
+ * Returns the current selected message.
+ */
+const getSelectedMessage = createSelector(
+ state => state.messages,
+ ({ selectedMessage }) => (selectedMessage ? selectedMessage : undefined)
+);
+
+/**
+ * Returns summary data of the list of messages that are visible to the user.
+ * Filtered messages by types and text are factored in.
+ */
+const getDisplayedMessagesSummary = createSelector(
+ getDisplayedMessages,
+ displayedMessages => {
+ let firstStartedMs = +Infinity;
+ let lastEndedMs = -Infinity;
+ let sentSize = 0;
+ let receivedSize = 0;
+ let totalSize = 0;
+
+ displayedMessages.forEach(message => {
+ if (message.type == "received") {
+ receivedSize += message.payload.length;
+ } else if (message.type == "sent") {
+ sentSize += message.payload.length;
+ }
+ totalSize += message.payload.length;
+ if (message.timeStamp < firstStartedMs) {
+ firstStartedMs = message.timeStamp;
+ }
+ if (message.timeStamp > lastEndedMs) {
+ lastEndedMs = message.timeStamp;
+ }
+ });
+
+ return {
+ count: displayedMessages.length,
+ totalMs: (lastEndedMs - firstStartedMs) / 1000,
+ sentSize,
+ receivedSize,
+ totalSize,
+ };
+ }
+);
+
+/**
+ * Returns if the currentChannelId is closed
+ */
+const isCurrentChannelClosed = createSelector(
+ state => state.messages,
+ ({ closedConnections, currentChannelId }) =>
+ closedConnections.has(currentChannelId)
+);
+
+/**
+ * Returns the closed connection details of the currentChannelId
+ * Null, if the connection is still open
+ */
+const getClosedConnectionDetails = createSelector(
+ state => state.messages,
+ ({ closedConnections, currentChannelId }) =>
+ closedConnections.get(currentChannelId)
+);
+
+module.exports = {
+ getSelectedMessage,
+ isSelectedMessageVisible,
+ getDisplayedMessages,
+ getDisplayedMessagesSummary,
+ isCurrentChannelClosed,
+ getClosedConnectionDetails,
+};
diff --git a/devtools/client/netmonitor/src/selectors/moz.build b/devtools/client/netmonitor/src/selectors/moz.build
new file mode 100644
index 0000000000..dcc4eac916
--- /dev/null
+++ b/devtools/client/netmonitor/src/selectors/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(
+ "index.js",
+ "messages.js",
+ "requests.js",
+ "search.js",
+ "timing-markers.js",
+ "ui.js",
+)
diff --git a/devtools/client/netmonitor/src/selectors/requests.js b/devtools/client/netmonitor/src/selectors/requests.js
new file mode 100644
index 0000000000..afe9b7ecaf
--- /dev/null
+++ b/devtools/client/netmonitor/src/selectors/requests.js
@@ -0,0 +1,198 @@
+/* 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 {
+ createSelector,
+} = require("resource://devtools/client/shared/vendor/reselect.js");
+const {
+ Filters,
+ isFreetextMatch,
+} = require("resource://devtools/client/netmonitor/src/utils/filter-predicates.js");
+const {
+ Sorters,
+} = require("resource://devtools/client/netmonitor/src/utils/sort-predicates.js");
+
+/**
+ * Take clones into account when sorting.
+ * If a request is a clone, use the original request for comparison.
+ * If one of the compared request is a clone of the other, sort them next to each other.
+ */
+function sortWithClones(requests, sorter, a, b) {
+ const aId = a.id,
+ bId = b.id;
+
+ if (aId.endsWith("-clone")) {
+ const aOrigId = aId.replace(/-clone$/, "");
+ if (aOrigId === bId) {
+ return +1;
+ }
+ a = requests.find(item => item.id === aOrigId);
+ }
+
+ if (bId.endsWith("-clone")) {
+ const bOrigId = bId.replace(/-clone$/, "");
+ if (bOrigId === aId) {
+ return -1;
+ }
+ b = requests.find(item => item.id === bOrigId);
+ }
+
+ const defaultSorter = () => false;
+ return sorter ? sorter(a, b) : defaultSorter;
+}
+
+/**
+ * Take clones into account when filtering. If a request is
+ * a clone, it's not filtered out.
+ */
+const getFilterWithCloneFn = createSelector(
+ state => state.filters,
+ filters => r => {
+ const matchesType = Object.keys(filters.requestFilterTypes).some(filter => {
+ if (r.id.endsWith("-clone")) {
+ return true;
+ }
+ return (
+ filters.requestFilterTypes[filter] &&
+ Filters[filter] &&
+ Filters[filter](r)
+ );
+ });
+ return matchesType && isFreetextMatch(r, filters.requestFilterText);
+ }
+);
+
+const getTypeFilterFn = createSelector(
+ state => state.filters,
+ filters => r => {
+ return Object.keys(filters.requestFilterTypes).some(filter => {
+ return (
+ filters.requestFilterTypes[filter] &&
+ Filters[filter] &&
+ Filters[filter](r)
+ );
+ });
+ }
+);
+
+const getSortFn = createSelector(
+ state => state.requests,
+ state => state.sort,
+ ({ requests }, sort) => {
+ const sorter = Sorters[sort.type || "waterfall"];
+ const ascending = sort.ascending ? +1 : -1;
+ return (a, b) => ascending * sortWithClones(requests, sorter, a, b);
+ }
+);
+
+const getSortedRequests = createSelector(
+ state => state.requests,
+ getSortFn,
+ ({ requests }, sortFn) => [...requests].sort(sortFn)
+);
+
+const getDisplayedRequests = createSelector(
+ state => state.requests,
+ getFilterWithCloneFn,
+ getSortFn,
+ ({ requests }, filterFn, sortFn) => requests.filter(filterFn).sort(sortFn)
+);
+
+const getTypeFilteredRequests = createSelector(
+ state => state.requests,
+ getTypeFilterFn,
+ ({ requests }, filterFn) => requests.filter(filterFn)
+);
+
+const getDisplayedRequestsSummary = createSelector(
+ getDisplayedRequests,
+ state => state.requests.lastEndedMs - state.requests.firstStartedMs,
+ (requests, totalMs) => {
+ if (requests.length === 0) {
+ return { count: 0, bytes: 0, ms: 0 };
+ }
+
+ const totalBytes = requests.reduce(
+ (totals, item) => {
+ if (typeof item.contentSize == "number") {
+ totals.contentSize += item.contentSize;
+ }
+
+ if (
+ typeof item.transferredSize == "number" &&
+ !(item.fromCache || item.status === "304")
+ ) {
+ totals.transferredSize += item.transferredSize;
+ }
+
+ return totals;
+ },
+ { contentSize: 0, transferredSize: 0 }
+ );
+
+ return {
+ count: requests.length,
+ contentSize: totalBytes.contentSize,
+ ms: totalMs,
+ transferredSize: totalBytes.transferredSize,
+ };
+ }
+);
+
+const getSelectedRequest = createSelector(
+ state => state.requests,
+ ({ selectedId, requests }) =>
+ selectedId ? requests.find(item => item.id === selectedId) : undefined
+);
+
+const isSelectedRequestVisible = createSelector(
+ state => state.requests,
+ getDisplayedRequests,
+ ({ selectedId }, displayedRequests) =>
+ displayedRequests.some(r => r.id === selectedId)
+);
+
+function getRequestById(state, id) {
+ return state.requests.requests.find(item => item.id === id);
+}
+
+function getRequestByChannelId(state, channelId) {
+ return [...state.requests.requests.values()].find(
+ r => r.resourceId == channelId
+ );
+}
+
+function getDisplayedRequestById(state, id) {
+ return getDisplayedRequests(state).find(r => r.id === id);
+}
+
+/**
+ * Returns the current recording boolean state (HTTP traffic is
+ * monitored or not monitored)
+ */
+function getRecordingState(state) {
+ return state.requests.recording;
+}
+
+const getClickedRequest = createSelector(
+ state => state.requests,
+ ({ requests, clickedRequestId }) =>
+ requests.find(request => request.id == clickedRequestId)
+);
+
+module.exports = {
+ getClickedRequest,
+ getDisplayedRequestById,
+ getDisplayedRequests,
+ getDisplayedRequestsSummary,
+ getRecordingState,
+ getRequestById,
+ getRequestByChannelId,
+ getSelectedRequest,
+ getSortedRequests,
+ getTypeFilteredRequests,
+ isSelectedRequestVisible,
+};
diff --git a/devtools/client/netmonitor/src/selectors/search.js b/devtools/client/netmonitor/src/selectors/search.js
new file mode 100644
index 0000000000..8ab0191a42
--- /dev/null
+++ b/devtools/client/netmonitor/src/selectors/search.js
@@ -0,0 +1,33 @@
+/* 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";
+
+function getOngoingSearch(state) {
+ return state.search.ongoingSearch;
+}
+
+function getSearchStatus(state) {
+ return state.search.status;
+}
+
+function getSearchResultCount(state) {
+ const { results } = state.search;
+ return (
+ (results.length !== 0
+ ? results.reduce((total, current) => total + current.results.length, 0)
+ : 0) + ""
+ );
+}
+
+function getSearchResourceCount(state) {
+ return state.search.results.length + "";
+}
+
+module.exports = {
+ getOngoingSearch,
+ getSearchStatus,
+ getSearchResultCount,
+ getSearchResourceCount,
+};
diff --git a/devtools/client/netmonitor/src/selectors/timing-markers.js b/devtools/client/netmonitor/src/selectors/timing-markers.js
new file mode 100644
index 0000000000..3855529904
--- /dev/null
+++ b/devtools/client/netmonitor/src/selectors/timing-markers.js
@@ -0,0 +1,18 @@
+/* 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";
+
+function getDisplayedTimingMarker(state, marker) {
+ const value = state.timingMarkers[marker];
+ if (value == -1) {
+ return value;
+ }
+
+ return value - state.timingMarkers.firstDocumentRequestStartTimestamp;
+}
+
+module.exports = {
+ getDisplayedTimingMarker,
+};
diff --git a/devtools/client/netmonitor/src/selectors/ui.js b/devtools/client/netmonitor/src/selectors/ui.js
new file mode 100644
index 0000000000..d9d8995a71
--- /dev/null
+++ b/devtools/client/netmonitor/src/selectors/ui.js
@@ -0,0 +1,81 @@
+/* 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 {
+ createSelector,
+} = require("resource://devtools/client/shared/vendor/reselect.js");
+const {
+ REQUESTS_WATERFALL,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const EPSILON = 0.001;
+
+const getWaterfallScale = createSelector(
+ state => state.requests.firstStartedMs,
+ state => state.requests.lastEndedMs,
+ state => state.timingMarkers.firstDocumentDOMContentLoadedTimestamp,
+ state => state.timingMarkers.firstDocumentLoadTimestamp,
+ state => state.ui.waterfallWidth,
+ (
+ firstStartedMs,
+ lastEndedMs,
+ firstDocumentDOMContentLoadedTimestamp,
+ firstDocumentLoadTimestamp,
+ waterfallWidth
+ ) => {
+ if (firstStartedMs === +Infinity || waterfallWidth === null) {
+ return null;
+ }
+
+ const lastEventMs = Math.max(
+ lastEndedMs,
+ firstDocumentDOMContentLoadedTimestamp,
+ firstDocumentLoadTimestamp
+ );
+ const longestWidth = lastEventMs - firstStartedMs;
+
+ // Reduce 20px for the last request's requests-list-timings-total
+ return Math.min(
+ Math.max(
+ (waterfallWidth - REQUESTS_WATERFALL.LABEL_WIDTH - 20) / longestWidth,
+ EPSILON
+ ),
+ 1
+ );
+ }
+);
+
+function getVisibleColumns(columns) {
+ return Object.entries(columns).filter(([_, shown]) => shown);
+}
+
+const getColumns = createSelector(
+ state => state.ui,
+ state => state.search,
+ (ui, search) => {
+ if (
+ ((ui.networkDetailsOpen || search.panelOpen) &&
+ getVisibleColumns(ui.columns).length === 1 &&
+ ui.columns.waterfall) ||
+ (!ui.networkDetailsOpen && !search.panelOpen)
+ ) {
+ return ui.columns;
+ }
+
+ // Remove the Waterfall/Timeline column from the list of available
+ // columns if the details side-bar is opened and more than one column is
+ // visible.
+ const columns = { ...ui.columns };
+ delete columns.waterfall;
+ return columns;
+ }
+);
+
+module.exports = {
+ getColumns,
+ getVisibleColumns,
+ getWaterfallScale,
+};
diff --git a/devtools/client/netmonitor/src/utils/context-menu-utils.js b/devtools/client/netmonitor/src/utils/context-menu-utils.js
new file mode 100644
index 0000000000..3b44ff20cc
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/context-menu-utils.js
@@ -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/. */
+
+"use strict";
+
+/**
+ * The default format for the content copied to the
+ * clipboard when the `Copy Value` option is selected.
+ */
+function baseCopyFormatter({ name, value, object, hasChildren }) {
+ if (hasChildren) {
+ return baseCopyAllFormatter({ [name]: value });
+ }
+ return `${value}`;
+}
+
+/**
+ * The default format for the content copied to the
+ * clipboard when the `Copy All` option is selected.
+ * @param {Object} object The whole data object
+ */
+function baseCopyAllFormatter(object) {
+ return JSON.stringify(object, null, "\t");
+}
+
+module.exports = {
+ contextMenuFormatters: {
+ baseCopyFormatter,
+ baseCopyAllFormatter,
+ },
+};
diff --git a/devtools/client/netmonitor/src/utils/doc-utils.js b/devtools/client/netmonitor/src/utils/doc-utils.js
new file mode 100644
index 0000000000..c08d96c453
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/doc-utils.js
@@ -0,0 +1,224 @@
+/* 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 {
+ SUPPORTED_HTTP_CODES,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * A mapping of header names to external documentation. Any header included
+ * here will show a MDN link alongside it.
+ */
+const SUPPORTED_HEADERS = [
+ "Accept",
+ "Accept-Charset",
+ "Accept-Encoding",
+ "Accept-Language",
+ "Accept-Ranges",
+ "Access-Control-Allow-Credentials",
+ "Access-Control-Allow-Headers",
+ "Access-Control-Allow-Methods",
+ "Access-Control-Allow-Origin",
+ "Access-Control-Expose-Headers",
+ "Access-Control-Max-Age",
+ "Access-Control-Request-Headers",
+ "Access-Control-Request-Method",
+ "Age",
+ "Allow",
+ "Authorization",
+ "Cache-Control",
+ "Clear-Site-Data",
+ "Connection",
+ "Content-Disposition",
+ "Content-Encoding",
+ "Content-Language",
+ "Content-Length",
+ "Content-Location",
+ "Content-Range",
+ "Content-Security-Policy",
+ "Content-Security-Policy-Report-Only",
+ "Content-Type",
+ "Cookie",
+ "Cookie2",
+ "DNT",
+ "Date",
+ "ETag",
+ "Early-Data",
+ "Expect",
+ "Expect-CT",
+ "Expires",
+ "Feature-Policy",
+ "Forwarded",
+ "From",
+ "Host",
+ "If-Match",
+ "If-Modified-Since",
+ "If-None-Match",
+ "If-Range",
+ "If-Unmodified-Since",
+ "Keep-Alive",
+ "Last-Modified",
+ "Location",
+ "Origin",
+ "Pragma",
+ "Proxy-Authenticate",
+ "Proxy-Authorization",
+ "Public-Key-Pins",
+ "Public-Key-Pins-Report-Only",
+ "Range",
+ "Referer",
+ "Referrer-Policy",
+ "Retry-After",
+ "Save-Data",
+ "Sec-Fetch-Dest",
+ "Sec-Fetch-Mode",
+ "Sec-Fetch-Site",
+ "Sec-Fetch-User",
+ "Sec-GPC",
+ "Server",
+ "Server-Timing",
+ "Set-Cookie",
+ "Set-Cookie2",
+ "SourceMap",
+ "Strict-Transport-Security",
+ "TE",
+ "Timing-Allow-Origin",
+ "Tk",
+ "Trailer",
+ "Transfer-Encoding",
+ "Upgrade-Insecure-Requests",
+ "User-Agent",
+ "Vary",
+ "Via",
+ "WWW-Authenticate",
+ "Warning",
+ "X-Content-Type-Options",
+ "X-DNS-Prefetch-Control",
+ "X-Forwarded-For",
+ "X-Forwarded-Host",
+ "X-Forwarded-Proto",
+ "X-Frame-Options",
+ "X-XSS-Protection",
+];
+
+const MDN_URL = "https://developer.mozilla.org/docs/";
+const MDN_STATUS_CODES_LIST_URL = `${MDN_URL}Web/HTTP/Status`;
+const getGAParams = (panelId = "netmonitor") => {
+ return `?utm_source=mozilla&utm_medium=devtools-${panelId}&utm_campaign=default`;
+};
+
+// Base URL to DevTools user docs
+const USER_DOC_URL = "https://firefox-source-docs.mozilla.org/devtools-user/";
+
+/**
+ * Get the MDN URL for the specified header.
+ *
+ * @param {string} header Name of the header for the baseURL to use.
+ *
+ * @return {string} The MDN URL for the header, or null if not available.
+ */
+function getHeadersURL(header) {
+ const lowerCaseHeader = header.toLowerCase();
+ const idx = SUPPORTED_HEADERS.findIndex(
+ item => item.toLowerCase() === lowerCaseHeader
+ );
+ return idx > -1
+ ? `${MDN_URL}Web/HTTP/Headers/${SUPPORTED_HEADERS[idx] + getGAParams()}`
+ : null;
+}
+
+/**
+ * Get the MDN URL for the specified HTTP status code.
+ *
+ * @param {string} HTTP status code for the baseURL to use.
+ *
+ * @return {string} The MDN URL for the HTTP status code, or null if not available.
+ */
+function getHTTPStatusCodeURL(statusCode, panelId) {
+ return (
+ (SUPPORTED_HTTP_CODES.includes(statusCode)
+ ? `${MDN_URL}Web/HTTP/Status/${statusCode}`
+ : MDN_STATUS_CODES_LIST_URL) + getGAParams(panelId)
+ );
+}
+
+/**
+ * Get the URL of the Timings tag for Network Monitor.
+ *
+ * @return {string} the URL of the Timings tag for Network Monitor.
+ */
+function getNetMonitorTimingsURL() {
+ return `${USER_DOC_URL}network_monitor/request_details/#network-monitor-request-details-timings-tab`;
+}
+
+/**
+ * Get the URL for Performance Analysis
+ *
+ * @return {string} The URL for the documentation of Performance Analysis.
+ */
+function getPerformanceAnalysisURL() {
+ return `${USER_DOC_URL}network_monitor/performance_analysis/`;
+}
+
+/**
+ * Get the URL for Filter box
+ *
+ * @return {string} The URL for the documentation of Filter box.
+ */
+function getFilterBoxURL() {
+ return `${USER_DOC_URL}network_monitor/request_list/#filtering-by-properties`;
+}
+
+/**
+ * Get the MDN URL for Tracking Protection
+ *
+ * @return {string} The MDN URL for the documentation of Tracking Protection.
+ */
+function getTrackingProtectionURL() {
+ return `${MDN_URL}Mozilla/Firefox/Privacy/Tracking_Protection${getGAParams()}`;
+}
+
+/**
+ * Get the MDN URL for CORS error reason, falls back to generic cors error page
+ * if reason is not understood.
+ *
+ * @param {int} reason: Blocked Reason message from `netmonitor/src/constants.js`
+ *
+ * @returns {string} the MDN URL for the documentation of CORS errors
+ */
+function getCORSErrorURL(reason) {
+ // Map from blocked reasons from netmonitor/src/constants.js to the correct
+ // URL fragment to append to MDN_URL
+ const reasonMap = new Map([
+ [1001, "CORSDisabled"],
+ [1002, "CORSDidNotSucceed"],
+ [1003, "CORSRequestNotHttp"],
+ [1004, "CORSMultipleAllowOriginNotAllowed"],
+ [1005, "CORSMissingAllowOrigin"],
+ [1006, "CORSNotSupportingCredentials"],
+ [1007, "CORSAllowOriginNotMatchingOrigin"],
+ [1008, "CORSMIssingAllowCredentials"],
+ [1009, "CORSOriginHeaderNotAdded"],
+ [1010, "CORSExternalRedirectNotAllowed"],
+ [1011, "CORSPreflightDidNotSucceed"],
+ [1012, "CORSInvalidAllowMethod"],
+ [1013, "CORSMethodNotFound"],
+ [1014, "CORSInvalidAllowHeader"],
+ [1015, "CORSMissingAllowHeaderFromPreflight"],
+ ]);
+ const urlFrag = reasonMap.get(reason) || "";
+ return `${MDN_URL}Web/HTTP/CORS/Errors/${urlFrag}`;
+}
+
+module.exports = {
+ getHeadersURL,
+ getHTTPStatusCodeURL,
+ getNetMonitorTimingsURL,
+ getPerformanceAnalysisURL,
+ getFilterBoxURL,
+ getTrackingProtectionURL,
+ getCORSErrorURL,
+};
diff --git a/devtools/client/netmonitor/src/utils/filter-autocomplete-provider.js b/devtools/client/netmonitor/src/utils/filter-autocomplete-provider.js
new file mode 100644
index 0000000000..991027c67b
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/filter-autocomplete-provider.js
@@ -0,0 +1,209 @@
+/* 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 {
+ FILTER_FLAGS,
+ SUPPORTED_HTTP_CODES,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const {
+ getRequestPriorityAsText,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+/**
+ * Generates a value for the given filter
+ * ie. if flag = status-code, will generate "200" from the given request item.
+ * For flags related to cookies, it might generate an array based on the request
+ * ie. ["cookie-name-1", "cookie-name-2", ...]
+ *
+ * @param {string} flag - flag specified in filter, ie. "status-code"
+ * @param {object} request - Network request item
+ * @return {string|Array} - The output is a string or an array based on the request
+ */
+function getAutocompleteValuesForFlag(flag, request) {
+ let values = [];
+ let { responseCookies = { cookies: [] } } = request;
+ responseCookies = responseCookies.cookies || responseCookies;
+
+ switch (flag) {
+ case "status-code":
+ // Sometimes status comes as Number
+ values.push(String(request.status));
+ break;
+ case "scheme":
+ values.push(request.urlDetails.scheme);
+ break;
+ case "domain":
+ values.push(request.urlDetails.host);
+ break;
+ case "remote-ip":
+ values.push(request.remoteAddress);
+ break;
+ case "cause":
+ values.push(request.cause.type);
+ break;
+ case "mime-type":
+ values.push((request.mimeType || "").replace(/;.+/, ""));
+ break;
+ case "set-cookie-name":
+ values = responseCookies.map(c => c.name);
+ break;
+ case "set-cookie-value":
+ values = responseCookies.map(c => c.value);
+ break;
+ case "priority":
+ values.push(getRequestPriorityAsText(request.priority));
+ break;
+ case "set-cookie-domain":
+ values = responseCookies.map(c =>
+ c.hasOwnProperty("domain") ? c.domain : request.urlDetails.host
+ );
+ break;
+ case "is":
+ values = ["cached", "from-cache", "running"];
+ break;
+ case "has-response-header":
+ // Some requests not having responseHeaders..?
+ values = request.responseHeaders
+ ? request.responseHeaders.headers.map(h => h.name)
+ : [];
+ break;
+ case "protocol":
+ values.push(request.httpVersion);
+ break;
+ case "method":
+ default:
+ values.push(request[flag]);
+ }
+
+ return values;
+}
+
+/**
+ * For a given lastToken passed ie. "is:", returns an array of populated flag
+ * values for consumption in autocompleteProvider
+ * ie. ["is:cached", "is:running", "is:from-cache"]
+ *
+ * @param {string} lastToken - lastToken parsed from filter input, ie "is:"
+ * @param {object} requests - List of requests from which values are generated
+ * @return {Array} - array of autocomplete values
+ */
+function getLastTokenFlagValues(lastToken, requests) {
+ // The last token must be a string like "method:GET" or "method:", Any token
+ // without a ":" cant be used to parse out flag values
+ if (!lastToken.includes(":")) {
+ return [];
+ }
+
+ // Parse out possible flag from lastToken
+ let [flag, typedFlagValue] = lastToken.split(":");
+ let isNegativeFlag = false;
+
+ // Check if flag is used with negative match
+ if (flag.startsWith("-")) {
+ flag = flag.slice(1);
+ isNegativeFlag = true;
+ }
+
+ // Flag is some random string, return
+ if (!FILTER_FLAGS.includes(flag)) {
+ return [];
+ }
+
+ let values = [];
+ for (const request of requests) {
+ values.push(...getAutocompleteValuesForFlag(flag, request));
+ }
+ values = [...new Set(values)];
+
+ return values
+ .filter(value => value)
+ .filter(value => {
+ if (typedFlagValue && value) {
+ const lowerTyped = typedFlagValue.toLowerCase();
+ const lowerValue = value.toLowerCase();
+ return lowerValue.includes(lowerTyped) && lowerValue !== lowerTyped;
+ }
+ return (
+ typeof value !== "undefined" && value !== "" && value !== "undefined"
+ );
+ })
+ .sort()
+ .map(value => (isNegativeFlag ? `-${flag}:${value}` : `${flag}:${value}`));
+}
+
+/**
+ * Generates an autocomplete list for the search-box for network monitor
+ *
+ * It expects an entire string of the searchbox ie "is:cached pr".
+ * The string is then tokenized into "is:cached" and "pr"
+ *
+ * @param {string} filter - The entire search string of the search box
+ * @param {object} requests - Iteratable object of requests displayed
+ * @return {Array} - The output is an array of objects as below
+ * [{value: "is:cached protocol", displayValue: "protocol"}[, ...]]
+ * `value` is used to update the search-box input box for given item
+ * `displayValue` is used to render the autocomplete list
+ */
+function autocompleteProvider(filter, requests) {
+ if (!filter) {
+ return [];
+ }
+
+ const negativeAutocompleteList = FILTER_FLAGS.map(item => `-${item}`);
+ const baseList = [...FILTER_FLAGS, ...negativeAutocompleteList].map(
+ item => `${item}:`
+ );
+
+ // The last token is used to filter the base autocomplete list
+ const tokens = filter.split(/\s+/g);
+ const lastToken = tokens[tokens.length - 1];
+ const previousTokens = tokens.slice(0, tokens.length - 1);
+
+ // Autocomplete list is not generated for empty lastToken
+ if (!lastToken) {
+ return [];
+ }
+
+ let autocompleteList;
+ const availableValues = getLastTokenFlagValues(lastToken, requests);
+ if (availableValues.length) {
+ autocompleteList = availableValues;
+ } else {
+ const isNegativeFlag = lastToken.startsWith("-");
+
+ // Stores list of HTTP codes that starts with value of lastToken
+ const filteredStatusCodes = SUPPORTED_HTTP_CODES.filter(item => {
+ item = isNegativeFlag ? item.substr(1) : item;
+ return item.toLowerCase().startsWith(lastToken.toLowerCase());
+ });
+
+ if (filteredStatusCodes.length) {
+ // Shows an autocomplete list of "status-code" values from filteredStatusCodes
+ autocompleteList = isNegativeFlag
+ ? filteredStatusCodes.map(item => `-status-code:${item}`)
+ : filteredStatusCodes.map(item => `status-code:${item}`);
+ } else {
+ // Shows an autocomplete list of values from baseList
+ // that starts with value of lastToken
+ autocompleteList = baseList.filter(item => {
+ return (
+ item.toLowerCase().startsWith(lastToken.toLowerCase()) &&
+ item.toLowerCase() !== lastToken.toLowerCase()
+ );
+ });
+ }
+ }
+
+ return autocompleteList.sort().map(item => ({
+ value: [...previousTokens, item].join(" "),
+ displayValue: item,
+ }));
+}
+
+module.exports = {
+ autocompleteProvider,
+};
diff --git a/devtools/client/netmonitor/src/utils/filter-predicates.js b/devtools/client/netmonitor/src/utils/filter-predicates.js
new file mode 100644
index 0000000000..63105dec0c
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/filter-predicates.js
@@ -0,0 +1,137 @@
+/* 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 {
+ isFreetextMatch,
+} = require("resource://devtools/client/netmonitor/src/utils/filter-text-utils.js");
+
+/**
+ * Predicates used when filtering items.
+ *
+ * @param object item
+ * The filtered item.
+ * @return boolean
+ * True if the item should be visible, false otherwise.
+ */
+function all() {
+ return true;
+}
+
+function isHtml({ mimeType }) {
+ return (
+ mimeType && (mimeType.includes("/html") || mimeType.includes("/xhtml+xml"))
+ );
+}
+
+function isCss({ mimeType }) {
+ return mimeType && mimeType.includes("/css");
+}
+
+function isJs({ mimeType }) {
+ return (
+ mimeType &&
+ (mimeType.includes("/ecmascript") ||
+ mimeType.includes("/javascript") ||
+ mimeType.includes("/x-javascript"))
+ );
+}
+
+function isXHR(item) {
+ // Show the request it is XHR, except if the request is a WS upgrade
+ return item.isXHR && !isWS(item);
+}
+
+function isFont({ url, mimeType }) {
+ // Fonts are a mess.
+ return (
+ (mimeType && (mimeType.includes("font/") || mimeType.includes("/font"))) ||
+ url.includes(".eot") ||
+ url.includes(".ttf") ||
+ url.includes(".otf") ||
+ url.includes(".woff")
+ );
+}
+
+function isImage({ mimeType, cause }) {
+ // We check cause.type so anything loaded via "img", "imageset", "lazy-img", etc. is in the right category
+ // When mimeType is not set to "image/", we still "detect" the image with cause.type (Bug-1654257)
+ return (
+ mimeType?.includes("image/") ||
+ cause?.type.includes("img") ||
+ cause?.type.includes("image")
+ );
+}
+
+function isMedia({ mimeType }) {
+ // Not including images.
+ return (
+ mimeType &&
+ (mimeType.includes("audio/") ||
+ mimeType.includes("video/") ||
+ mimeType.includes("model/") ||
+ mimeType === "application/vnd.apple.mpegurl" ||
+ mimeType === "application/x-mpegurl" ||
+ mimeType === "application/ogg")
+ );
+}
+
+function isWS({ requestHeaders, responseHeaders, cause }) {
+ // For the first call, the requestHeaders is not ready(empty),
+ // so checking for cause.type instead (Bug-1454962)
+ if (typeof cause.type === "string" && cause.type === "websocket") {
+ return true;
+ }
+ // Detect a websocket upgrade if request has an Upgrade header with value 'websocket'
+ if (!requestHeaders || !Array.isArray(requestHeaders.headers)) {
+ return false;
+ }
+
+ // Find the 'upgrade' header.
+ let upgradeHeader = requestHeaders.headers.find(header => {
+ return header.name.toLowerCase() == "upgrade";
+ });
+
+ // If no header found on request, check response - mainly to get
+ // something we can unit test, as it is impossible to set
+ // the Upgrade header on outgoing XHR as per the spec.
+ if (
+ !upgradeHeader &&
+ responseHeaders &&
+ Array.isArray(responseHeaders.headers)
+ ) {
+ upgradeHeader = responseHeaders.headers.find(header => {
+ return header.name.toLowerCase() == "upgrade";
+ });
+ }
+
+ // Return false if there is no such header or if its value isn't 'websocket'.
+ if (!upgradeHeader || upgradeHeader.value != "websocket") {
+ return false;
+ }
+
+ return true;
+}
+
+function isOther(item) {
+ const tests = [isHtml, isCss, isJs, isXHR, isFont, isImage, isMedia, isWS];
+ return tests.every(is => !is(item));
+}
+
+module.exports = {
+ Filters: {
+ all,
+ html: isHtml,
+ css: isCss,
+ js: isJs,
+ xhr: isXHR,
+ fonts: isFont,
+ images: isImage,
+ media: isMedia,
+ ws: isWS,
+ other: isOther,
+ },
+ isFreetextMatch,
+};
diff --git a/devtools/client/netmonitor/src/utils/filter-text-utils.js b/devtools/client/netmonitor/src/utils/filter-text-utils.js
new file mode 100644
index 0000000000..911e70e4bd
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/filter-text-utils.js
@@ -0,0 +1,291 @@
+/*
+ * Copyright (c) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+"use strict";
+
+const {
+ FILTER_FLAGS,
+ SUPPORTED_HTTP_CODES,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ getFormattedIPAndPort,
+ getRequestPriorityAsText,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ getUnicodeUrl,
+} = require("resource://devtools/client/shared/unicode-url.js");
+const {
+ getUrlBaseName,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+/*
+ The function `parseFilters` is from:
+ https://github.com/ChromeDevTools/devtools-frontend/
+
+ front_end/network/FilterSuggestionBuilder.js#L138-L163
+ Commit f340aefd7ec9b702de9366a812288cfb12111fce
+*/
+
+function parseFilters(query) {
+ const flags = [];
+ const text = [];
+ const parts = query.split(/\s+/);
+
+ for (const part of parts) {
+ if (!part) {
+ continue;
+ }
+ const colonIndex = part.indexOf(":");
+ if (colonIndex === -1) {
+ const isNegative = part.startsWith("-");
+ // Stores list of HTTP codes that starts with value of lastToken
+ const filteredStatusCodes = SUPPORTED_HTTP_CODES.filter(item => {
+ item = isNegative ? item.substr(1) : item;
+ return item.toLowerCase().startsWith(part.toLowerCase());
+ });
+
+ if (filteredStatusCodes.length) {
+ flags.push({
+ type: "status-code", // a standard key before a colon
+ value: isNegative ? part.substring(1) : part,
+ isNegative,
+ });
+ continue;
+ }
+
+ // Value of lastToken is just text that does not correspond to status codes
+ text.push(part);
+ continue;
+ }
+ let key = part.substring(0, colonIndex);
+ const negative = key.startsWith("-");
+ if (negative) {
+ key = key.substring(1);
+ }
+ if (!FILTER_FLAGS.includes(key)) {
+ text.push(part);
+ continue;
+ }
+ let value = part.substring(colonIndex + 1);
+ value = processFlagFilter(key, value);
+ flags.push({
+ type: key,
+ value,
+ negative,
+ });
+ }
+
+ return { text, flags };
+}
+
+function processFlagFilter(type, value) {
+ switch (type) {
+ case "regexp":
+ return value;
+ case "size":
+ case "transferred":
+ case "larger-than":
+ case "transferred-larger-than":
+ let multiplier = 1;
+ if (value.endsWith("k")) {
+ multiplier = 1000;
+ value = value.substring(0, value.length - 1);
+ } else if (value.endsWith("m")) {
+ multiplier = 1000 * 1000;
+ value = value.substring(0, value.length - 1);
+ }
+ const quantity = Number(value);
+ if (isNaN(quantity)) {
+ return null;
+ }
+ return quantity * multiplier;
+ default:
+ return value.toLowerCase();
+ }
+}
+
+function isFlagFilterMatch(item, { type, value, negative }) {
+ if (value == null) {
+ return false;
+ }
+
+ // Ensures when filter token is exactly a flag ie. "remote-ip:", all values are shown
+ if (value.length < 1) {
+ return true;
+ }
+
+ let match = true;
+ let { responseCookies = { cookies: [] } } = item;
+ responseCookies = responseCookies.cookies || responseCookies;
+
+ const matchers = {
+ "status-code": () =>
+ item.status && item.status.toString().startsWith(value),
+ method: () => item.method.toLowerCase() === value,
+ protocol: () => {
+ const protocol = item.httpVersion;
+ return typeof protocol === "string"
+ ? protocol.toLowerCase().includes(value)
+ : false;
+ },
+ domain: () => item.urlDetails.host.toLowerCase().includes(value),
+ "remote-ip": () => {
+ const data = getFormattedIPAndPort(item.remoteAddress, item.remotePort);
+ return data ? data.toLowerCase().includes(value) : false;
+ },
+ "has-response-header": () => {
+ if (typeof item.responseHeaders === "object") {
+ const { headers } = item.responseHeaders;
+ return headers.findIndex(h => h.name.toLowerCase() === value) > -1;
+ }
+ return false;
+ },
+ cause: () => {
+ const causeType = item.cause.type;
+ return typeof causeType === "string"
+ ? causeType.toLowerCase().includes(value)
+ : false;
+ },
+ initiator: () => {
+ const initiator = item.cause.lastFrame
+ ? getUrlBaseName(item.cause.lastFrame.filename) +
+ ":" +
+ item.cause.lastFrame.lineNumber
+ : "";
+ return typeof initiator === "string"
+ ? initiator.toLowerCase().includes(value)
+ : !value;
+ },
+ transferred: () => {
+ if (item.fromCache) {
+ return false;
+ }
+ return isSizeMatch(value, item.transferredSize);
+ },
+ size: () => isSizeMatch(value, item.contentSize),
+ "larger-than": () => item.contentSize > value,
+ "transferred-larger-than": () => {
+ if (item.fromCache) {
+ return false;
+ }
+ return item.transferredSize > value;
+ },
+ "mime-type": () => {
+ if (!item.mimeType) {
+ return false;
+ }
+ return item.mimeType.includes(value);
+ },
+ is: () => {
+ if (value === "from-cache" || value === "cached") {
+ return item.fromCache || item.status === "304";
+ }
+ if (value === "running") {
+ return !item.status;
+ }
+ return match;
+ },
+ scheme: () => item.urlDetails.scheme === value,
+ regexp: () => {
+ try {
+ const pattern = new RegExp(value);
+ return pattern.test(item.url);
+ } catch (e) {
+ return false;
+ }
+ },
+ priority: () =>
+ getRequestPriorityAsText(item.priority).toLowerCase() == value,
+ "set-cookie-domain": () => {
+ if (responseCookies.length) {
+ const { host } = item.urlDetails;
+ const i = responseCookies.findIndex(c => {
+ const domain = c.hasOwnProperty("domain") ? c.domain : host;
+ return domain.includes(value);
+ });
+ return i > -1;
+ }
+ return false;
+ },
+ "set-cookie-name": () =>
+ responseCookies.findIndex(c => c.name.toLowerCase().includes(value)) > -1,
+ "set-cookie-value": () =>
+ responseCookies.findIndex(c => c.value.toLowerCase().includes(value)) >
+ -1,
+ };
+
+ const matcher = matchers[type];
+ if (matcher) {
+ match = matcher();
+ }
+
+ return negative ? !match : match;
+}
+
+function isSizeMatch(value, size) {
+ return value >= size - size / 10 && value <= size + size / 10;
+}
+
+function isTextFilterMatch({ url }, text) {
+ const lowerCaseUrl = getUnicodeUrl(url).toLowerCase();
+ let lowerCaseText = text.toLowerCase();
+ const textLength = text.length;
+ // Support negative filtering
+ if (text.startsWith("-") && textLength > 1) {
+ lowerCaseText = lowerCaseText.substring(1, textLength);
+ return !lowerCaseUrl.includes(lowerCaseText);
+ }
+
+ // no text is a positive match
+ return !text || lowerCaseUrl.includes(lowerCaseText);
+}
+
+function isFreetextMatch(item, text) {
+ if (!text) {
+ return true;
+ }
+
+ const filters = parseFilters(text);
+ let match = true;
+
+ for (const textFilter of filters.text) {
+ match = match && isTextFilterMatch(item, textFilter);
+ }
+
+ for (const flagFilter of filters.flags) {
+ match = match && isFlagFilterMatch(item, flagFilter);
+ }
+
+ return match;
+}
+
+module.exports = {
+ isFreetextMatch,
+};
diff --git a/devtools/client/netmonitor/src/utils/firefox/moz.build b/devtools/client/netmonitor/src/utils/firefox/moz.build
new file mode 100644
index 0000000000..bb0acafdf7
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/firefox/moz.build
@@ -0,0 +1,8 @@
+# vim: set filetype=python:
+# 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(
+ "open-request-in-tab.js",
+)
diff --git a/devtools/client/netmonitor/src/utils/firefox/open-request-in-tab.js b/devtools/client/netmonitor/src/utils/firefox/open-request-in-tab.js
new file mode 100644
index 0000000000..20ea3dcba2
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/firefox/open-request-in-tab.js
@@ -0,0 +1,67 @@
+/* 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/. */
+
+// This file is a chrome-API-dependent version of the module
+// devtools/client/netmonitor/src/utils/open-request-in-tab.js, so that it can
+// take advantage of utilizing chrome APIs. But because of this, it isn't
+// intended to be used in Chrome-API-free applications, such as the Launchpad.
+//
+// Please keep in mind that if the feature in this file has changed, don't
+// forget to also change that accordingly in
+// devtools/client/netmonitor/src/utils/open-request-in-tab.js.
+
+"use strict";
+
+const {
+ gDevTools,
+} = require("resource://devtools/client/framework/devtools.js");
+
+/**
+ * Opens given request in a new tab.
+ */
+function openRequestInTab(url, requestHeaders, requestPostData) {
+ const win = Services.wm.getMostRecentWindow(gDevTools.chromeWindowType);
+ const rawData = requestPostData ? requestPostData.postData : null;
+ let postData;
+
+ if (rawData?.text) {
+ const stringStream = getInputStreamFromString(rawData.text);
+ postData = Cc["@mozilla.org/network/mime-input-stream;1"].createInstance(
+ Ci.nsIMIMEInputStream
+ );
+
+ const contentTypeHeader = requestHeaders.headers.find(e => {
+ return e.name.toLowerCase() === "content-type";
+ });
+
+ postData.addHeader(
+ "Content-Type",
+ contentTypeHeader
+ ? contentTypeHeader.value
+ : "application/x-www-form-urlencoded"
+ );
+ postData.setData(stringStream);
+ }
+ const { userContextId } = win.gBrowser.contentPrincipal;
+ win.gBrowser.selectedTab = win.gBrowser.addWebTab(url, {
+ // TODO this should be using the original request principal
+ triggeringPrincipal: Services.scriptSecurityManager.createNullPrincipal({
+ userContextId,
+ }),
+ userContextId,
+ postData,
+ });
+}
+
+function getInputStreamFromString(data) {
+ const stringStream = Cc[
+ "@mozilla.org/io/string-input-stream;1"
+ ].createInstance(Ci.nsIStringInputStream);
+ stringStream.data = data;
+ return stringStream;
+}
+
+module.exports = {
+ openRequestInTab,
+};
diff --git a/devtools/client/netmonitor/src/utils/format-utils.js b/devtools/client/netmonitor/src/utils/format-utils.js
new file mode 100644
index 0000000000..c0d5c29818
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/format-utils.js
@@ -0,0 +1,132 @@
+/* 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");
+
+// Constants for formatting bytes.
+const BYTES_IN_KB = 1000;
+const BYTES_IN_MB = Math.pow(BYTES_IN_KB, 2);
+const BYTES_IN_GB = Math.pow(BYTES_IN_KB, 3);
+const MAX_BYTES_SIZE = 1000;
+const MAX_KB_SIZE = 1000 * BYTES_IN_KB;
+const MAX_MB_SIZE = 1000 * BYTES_IN_MB;
+
+// Constants for formatting time.
+const MAX_MILLISECOND = 1000;
+const MAX_SECOND = 60 * MAX_MILLISECOND;
+
+const REQUEST_DECIMALS = 2;
+
+// Constants for formatting the priority, derived from nsISupportsPriority.idl
+const PRIORITY_HIGH = -10;
+const PRIORITY_NORMAL = 0;
+const PRIORITY_LOW = 10;
+
+function getSizeWithDecimals(size, decimals = REQUEST_DECIMALS) {
+ return L10N.numberWithDecimals(size, decimals);
+}
+
+function getTimeWithDecimals(time) {
+ return L10N.numberWithDecimals(time, REQUEST_DECIMALS);
+}
+
+function formatDecimals(size, decimals) {
+ return size % 1 > 0 ? decimals : 0;
+}
+
+/**
+ * Get a human-readable string from a number of bytes, with the B, kB, MB, or
+ * GB value.
+ */
+function getFormattedSize(bytes, decimals = REQUEST_DECIMALS) {
+ if (bytes < MAX_BYTES_SIZE) {
+ return L10N.getFormatStr("networkMenu.sizeB", bytes);
+ }
+ if (bytes < MAX_KB_SIZE) {
+ const kb = bytes / BYTES_IN_KB;
+ const formattedDecimals = formatDecimals(kb, decimals);
+
+ return L10N.getFormatStr(
+ "networkMenu.size.kB",
+ getSizeWithDecimals(kb, formattedDecimals)
+ );
+ }
+ if (bytes < MAX_MB_SIZE) {
+ const mb = bytes / BYTES_IN_MB;
+ const formattedDecimals = formatDecimals(mb, decimals);
+ return L10N.getFormatStr(
+ "networkMenu.sizeMB",
+ getSizeWithDecimals(mb, formattedDecimals)
+ );
+ }
+ const gb = bytes / BYTES_IN_GB;
+ const formattedDecimals = formatDecimals(gb, decimals);
+ return L10N.getFormatStr(
+ "networkMenu.sizeGB",
+ getSizeWithDecimals(gb, formattedDecimals)
+ );
+}
+
+/**
+ * Get a human-readable string from a number of time, with the ms, s, or min
+ * value.
+ */
+function getFormattedTime(ms) {
+ if (ms < MAX_MILLISECOND) {
+ return L10N.getFormatStr("networkMenu.millisecond", ms | 0);
+ }
+ if (ms < MAX_SECOND) {
+ const sec = ms / MAX_MILLISECOND;
+ return L10N.getFormatStr("networkMenu.second", getTimeWithDecimals(sec));
+ }
+ const min = ms / MAX_SECOND;
+ return L10N.getFormatStr("networkMenu.minute", getTimeWithDecimals(min));
+}
+
+/**
+ * Formats IP (v4 and v6) and port
+ *
+ * @param {string} ip - IP address
+ * @param {string} port
+ * @return {string} the formatted IP + port
+ */
+function getFormattedIPAndPort(ip, port) {
+ if (!port) {
+ return ip;
+ }
+ return ip.match(/:+/) ? `[${ip}]:${port}` : `${ip}:${port}`;
+}
+
+/**
+ * Formats the priority of a request
+ * Based on unix conventions
+ * See xpcom/threads/nsISupportsPriority.idl
+ *
+ * @param {Number} priority - request priority
+ */
+function getRequestPriorityAsText(priority) {
+ if (priority < PRIORITY_HIGH) {
+ return "Highest";
+ } else if (priority >= PRIORITY_HIGH && priority < PRIORITY_NORMAL) {
+ return "High";
+ } else if (priority === PRIORITY_NORMAL) {
+ return "Normal";
+ } else if (priority > PRIORITY_NORMAL && priority <= PRIORITY_LOW) {
+ return "Low";
+ }
+ return "Lowest";
+}
+
+module.exports = {
+ getFormattedIPAndPort,
+ getFormattedSize,
+ getFormattedTime,
+ getSizeWithDecimals,
+ getTimeWithDecimals,
+ getRequestPriorityAsText,
+};
diff --git a/devtools/client/netmonitor/src/utils/headers-provider.js b/devtools/client/netmonitor/src/utils/headers-provider.js
new file mode 100644
index 0000000000..a76e7d1c0e
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/headers-provider.js
@@ -0,0 +1,90 @@
+/* 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 {
+ ObjectProvider,
+} = require("resource://devtools/client/shared/components/tree/ObjectProvider.js");
+
+/**
+ * Custom tree provider.
+ *
+ * This provider is used to provide set of headers and is
+ * utilized by the HeadersPanel.
+ * The default ObjectProvider can't be used since it doesn't
+ * allow duplicities by design and so it can't support duplicity
+ * headers (more headers with the same name).
+ */
+var HeadersProvider = {
+ ...ObjectProvider,
+
+ getChildren(object) {
+ if (object && object.value instanceof HeaderList) {
+ return object.value.headers.map(
+ (header, index) => new Header(header.name, header.value, index)
+ );
+ }
+ return ObjectProvider.getChildren(object);
+ },
+
+ hasChildren(object) {
+ if (object.value instanceof HeaderList) {
+ return !!object.value.headers.length;
+ } else if (object instanceof Header) {
+ return false;
+ }
+ return ObjectProvider.hasChildren(object);
+ },
+
+ getLabel(object) {
+ if (object instanceof Header) {
+ return object.name;
+ }
+ return ObjectProvider.getLabel(object);
+ },
+
+ getValue(object) {
+ if (object instanceof Header) {
+ return object.value;
+ }
+ return ObjectProvider.getValue(object);
+ },
+
+ getKey(object) {
+ if (object instanceof Header) {
+ return object.key;
+ }
+ return ObjectProvider.getKey(object);
+ },
+
+ getType(object) {
+ if (object instanceof Header) {
+ return "string";
+ }
+ return ObjectProvider.getType(object);
+ },
+};
+
+/**
+ * Helper data structures for list of headers.
+ */
+function HeaderList(headers) {
+ // Clone, so the sort doesn't affect the original array.
+ this.headers = headers.slice(0);
+ this.headers.sort((a, b) => {
+ return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
+ });
+}
+
+function Header(name, value, key) {
+ this.name = name;
+ this.value = value;
+ this.key = key;
+}
+
+module.exports = {
+ HeadersProvider,
+ HeaderList,
+};
diff --git a/devtools/client/netmonitor/src/utils/l10n.js b/devtools/client/netmonitor/src/utils/l10n.js
new file mode 100644
index 0000000000..74c8b22299
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/l10n.js
@@ -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/. */
+
+"use strict";
+
+const { LocalizationHelper } = require("resource://devtools/shared/l10n.js");
+
+const NET_STRINGS_URI = "devtools/client/locales/netmonitor.properties";
+
+exports.L10N = new LocalizationHelper(NET_STRINGS_URI);
diff --git a/devtools/client/netmonitor/src/utils/moz.build b/devtools/client/netmonitor/src/utils/moz.build
new file mode 100644
index 0000000000..2eb6aec69c
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/moz.build
@@ -0,0 +1,27 @@
+# vim: set filetype=python:
+# 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 += [
+ "firefox",
+]
+
+DevToolsModules(
+ "context-menu-utils.js",
+ "doc-utils.js",
+ "filter-autocomplete-provider.js",
+ "filter-predicates.js",
+ "filter-text-utils.js",
+ "format-utils.js",
+ "headers-provider.js",
+ "l10n.js",
+ "open-request-in-tab.js",
+ "powershell.js",
+ "prefs.js",
+ "request-blocking.js",
+ "request-utils.js",
+ "sort-predicates.js",
+ "sort-utils.js",
+ "tooltips.js",
+)
diff --git a/devtools/client/netmonitor/src/utils/open-request-in-tab.js b/devtools/client/netmonitor/src/utils/open-request-in-tab.js
new file mode 100644
index 0000000000..cb63da61ec
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/open-request-in-tab.js
@@ -0,0 +1,63 @@
+/* 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/. */
+
+// This file is a chrome-API-free version of the module
+// devtools/client/netmonitor/src/utils/firefox/open-request-in-tab.js, so that
+// it can be used in Chrome-API-free applications, such as the Launchpad. But
+// because of this, it cannot take advantage of utilizing chrome APIs and should
+// implement the similar functionalities on its own.
+//
+// Please keep in mind that if the feature in this file has changed, don't
+// forget to also change that accordingly in
+// devtools/client/netmonitor/src/utils/firefox/open-request-in-tab.js.
+
+"use strict";
+
+loader.lazyRequireGetter(
+ this,
+ "openContentLink",
+ "resource://devtools/client/shared/link.js",
+ true
+);
+
+/**
+ * Opens given request in a new tab.
+ *
+ * For POST request supports application/x-www-form-urlencoded content-type only.
+ */
+function openRequestInTab(url, requestHeaders, requestPostData) {
+ if (!requestPostData) {
+ openContentLink(url, { relatedToCurrent: true });
+ } else {
+ openPostRequestInTabHelper({
+ url,
+ data: requestPostData.postData,
+ });
+ }
+}
+
+function openPostRequestInTabHelper({ url, data }) {
+ const form = document.createElement("form");
+ form.target = "_blank";
+ form.action = url;
+ form.method = "post";
+
+ if (data) {
+ for (const key in data) {
+ const input = document.createElement("input");
+ input.name = key;
+ input.value = data[key];
+ form.appendChild(input);
+ }
+ }
+
+ form.hidden = true;
+ document.body.appendChild(form);
+ form.submit();
+ form.remove();
+}
+
+module.exports = {
+ openRequestInTab,
+};
diff --git a/devtools/client/netmonitor/src/utils/powershell.js b/devtools/client/netmonitor/src/utils/powershell.js
new file mode 100644
index 0000000000..2efcfd8faa
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/powershell.js
@@ -0,0 +1,142 @@
+/* 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/. */
+
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Anthony Ricaud <rik@webkit.org>
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2022 Mozilla Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// Utility to generate commands to invoke a request for powershell
+"use strict";
+
+// Some of these headers are passed in as seperate `Invoke-WebRequest` parameters so ignore
+// when building the headers list, others are not to neccesarily restrict the request.
+const IGNORED_HEADERS = [
+ "connection",
+ "proxy-connection",
+ "content-length",
+ "expect",
+ "range",
+ "host",
+ "content-type",
+ "user-agent",
+ "cookie",
+];
+/**
+ * This escapes strings for the powershell command
+ *
+ * 1. Escape the backtick, dollar sign and the double quotes See https://www.rlmueller.net/PowerShellEscape.htm
+ * 2. Convert any non printing ASCII characters found, using the ASCII code.
+ */
+function escapeStr(str) {
+ return `"${str
+ .replace(/[`\$"]/g, "`$&")
+ .replace(/[^\x20-\x7E]/g, char => "$([char]" + char.charCodeAt(0) + ")")}"`;
+}
+
+const PowerShell = {
+ generateCommand(url, method, headers, postData, cookies) {
+ const parameters = [];
+
+ // Create a WebSession to pass the information about cookies
+ // See https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.2#-websession
+ const session = [];
+ for (const { name, value, domain } of cookies) {
+ if (!session.length) {
+ session.push(
+ "$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession"
+ );
+ }
+ session.push(
+ `$session.Cookies.Add((New-Object System.Net.Cookie(${escapeStr(
+ name
+ )}, ${escapeStr(value)}, "/", ${escapeStr(
+ domain || new URL(url).host
+ )})))`
+ );
+ }
+
+ parameters.push(`-Uri ${escapeStr(url)}`);
+
+ if (method !== "GET") {
+ parameters.push(`-Method ${method}`);
+ }
+
+ if (session.length) {
+ parameters.push("-WebSession $session");
+ }
+
+ const userAgent = headers.find(
+ ({ name }) => name.toLowerCase() === "user-agent"
+ );
+ if (userAgent) {
+ parameters.push("-UserAgent " + escapeStr(userAgent.value));
+ }
+
+ const headersStr = [];
+ for (let { name, value } of headers) {
+ // Translate any HTTP2 pseudo headers to HTTP headers
+ name = name.replace(/^:/, "");
+
+ if (IGNORED_HEADERS.includes(name.toLowerCase())) {
+ continue;
+ }
+ headersStr.push(`${escapeStr(name)} = ${escapeStr(value)}`);
+ }
+ if (headersStr.length) {
+ parameters.push(`-Headers @{\n${headersStr.join("\n ")}\n}`);
+ }
+
+ const contentType = headers.find(
+ header => header.name.toLowerCase() === "content-type"
+ );
+ if (contentType) {
+ parameters.push("-ContentType " + escapeStr(contentType.value));
+ }
+
+ const formData = postData.text;
+ if (formData) {
+ // Encode bytes if any of the characters is not an ASCII printing character (not between Space character and ~ character)
+ // a-zA-Z0-9 etc. See http://www.asciitable.com/
+ const body = /[^\x20-\x7E]/.test(formData)
+ ? "([System.Text.Encoding]::UTF8.GetBytes(" + escapeStr(formData) + "))"
+ : escapeStr(formData);
+ parameters.push("-Body " + body);
+ }
+
+ return `${
+ session.length ? session.join("\n").concat("\n") : ""
+ // -UseBasicParsing is added for backward compatibility.
+ // See https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.2#-usebasicparsing
+ }Invoke-WebRequest -UseBasicParsing ${parameters.join(" `\n")}`;
+ },
+};
+
+exports.PowerShell = PowerShell;
diff --git a/devtools/client/netmonitor/src/utils/prefs.js b/devtools/client/netmonitor/src/utils/prefs.js
new file mode 100644
index 0000000000..3c988f4294
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/prefs.js
@@ -0,0 +1,18 @@
+/* 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 { PrefsHelper } = require("resource://devtools/client/shared/prefs.js");
+
+/**
+ * Shortcuts for accessing various network monitor preferences.
+ */
+exports.Prefs = new PrefsHelper("devtools.netmonitor", {
+ networkDetailsWidth: ["Int", "panes-network-details-width"],
+ networkDetailsHeight: ["Int", "panes-network-details-height"],
+ visibleColumns: ["Json", "visibleColumns"],
+ columnsData: ["Json", "columnsData"],
+ filters: ["Json", "filters"],
+});
diff --git a/devtools/client/netmonitor/src/utils/request-blocking.js b/devtools/client/netmonitor/src/utils/request-blocking.js
new file mode 100644
index 0000000000..67b217afe0
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/request-blocking.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";
+
+function hasMatchingBlockingRequestPattern(blockedUrls, url) {
+ return blockedUrls.some(blockedUrl => url.includes(blockedUrl));
+}
+
+module.exports = {
+ hasMatchingBlockingRequestPattern,
+};
diff --git a/devtools/client/netmonitor/src/utils/request-utils.js b/devtools/client/netmonitor/src/utils/request-utils.js
new file mode 100644
index 0000000000..11273016be
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/request-utils.js
@@ -0,0 +1,769 @@
+/* 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 {
+ getUnicodeUrl,
+ getUnicodeUrlPath,
+ getUnicodeHostname,
+} = require("resource://devtools/client/shared/unicode-url.js");
+
+const {
+ UPDATE_PROPS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const CONTENT_MIME_TYPE_ABBREVIATIONS = {
+ ecmascript: "js",
+ javascript: "js",
+ "x-javascript": "js",
+};
+
+/**
+ * Extracts any urlencoded form data sections (e.g. "?foo=bar&baz=42") from a
+ * POST request.
+ *
+ * @param {object} headers - the "requestHeaders".
+ * @param {object} uploadHeaders - the "requestHeadersFromUploadStream".
+ * @param {object} postData - the "requestPostData".
+ * @return {array} a promise list that is resolved with the extracted form data.
+ */
+async function getFormDataSections(
+ headers,
+ uploadHeaders,
+ postData,
+ getLongString
+) {
+ const formDataSections = [];
+
+ const requestHeaders = headers.headers;
+ const payloadHeaders = uploadHeaders ? uploadHeaders.headers : [];
+ const allHeaders = [...payloadHeaders, ...requestHeaders];
+
+ const contentTypeHeader = allHeaders.find(e => {
+ return e.name.toLowerCase() == "content-type";
+ });
+
+ const contentTypeLongString = contentTypeHeader
+ ? contentTypeHeader.value
+ : "";
+
+ const contentType = await getLongString(contentTypeLongString);
+
+ if (contentType && contentType.includes("x-www-form-urlencoded")) {
+ const postDataLongString = postData.postData.text;
+ const text = await getLongString(postDataLongString);
+
+ for (const section of text.trim().split(/\r\n|\r|\n/)) {
+ // Before displaying it, make sure this section of the POST data
+ // isn't a line containing upload stream headers.
+ if (payloadHeaders.every(header => !section.startsWith(header.name))) {
+ formDataSections.push(section);
+ }
+ }
+ }
+
+ return formDataSections;
+}
+
+/**
+ * Fetch headers full content from actor server
+ *
+ * @param {object} headers - a object presents headers data
+ * @return {object} a headers object with updated content payload
+ */
+async function fetchHeaders(headers, getLongString) {
+ for (const { value } of headers.headers) {
+ headers.headers.value = await getLongString(value);
+ }
+ return headers;
+}
+
+/**
+ * Fetch network event update packets from actor server
+ * Expect to fetch a couple of network update packets from a given request.
+ *
+ * @param {function} requestData - requestData function for lazily fetch data
+ * @param {object} request - request object
+ * @param {array} updateTypes - a list of network event update types
+ */
+function fetchNetworkUpdatePacket(requestData, request, updateTypes) {
+ const promises = [];
+ if (request) {
+ updateTypes.forEach(updateType => {
+ // Only stackTrace will be handled differently
+ if (updateType === "stackTrace") {
+ if (request.cause.stacktraceAvailable && !request.stacktrace) {
+ promises.push(requestData(request.id, updateType));
+ }
+ return;
+ }
+
+ if (request[`${updateType}Available`] && !request[updateType]) {
+ promises.push(requestData(request.id, updateType));
+ }
+ });
+ }
+
+ return Promise.all(promises);
+}
+
+/**
+ * Form a data: URI given a mime type, encoding, and some text.
+ *
+ * @param {string} mimeType - mime type
+ * @param {string} encoding - encoding to use; if not set, the
+ * text will be base64-encoded.
+ * @param {string} text - text of the URI.
+ * @return {string} a data URI
+ */
+function formDataURI(mimeType, encoding, text) {
+ if (!encoding) {
+ encoding = "base64";
+ text = btoa(unescape(encodeURIComponent(text)));
+ }
+ return "data:" + mimeType + ";" + encoding + "," + text;
+}
+
+/**
+ * Write out a list of headers into a chunk of text
+ *
+ * @param {array} headers - array of headers info { name, value }
+ * @param {string} preHeaderText - first line of the headers request/response
+ * @return {string} list of headers in text format
+ */
+function writeHeaderText(headers, preHeaderText) {
+ let result = "";
+ if (preHeaderText) {
+ result += preHeaderText + "\r\n";
+ }
+ result += headers.map(({ name, value }) => name + ": " + value).join("\r\n");
+ result += "\r\n\r\n";
+ return result;
+}
+
+/**
+ * Decode base64 string.
+ *
+ * @param {string} url - a string
+ * @return {string} decoded string
+ */
+function decodeUnicodeBase64(string) {
+ try {
+ return decodeURIComponent(atob(string));
+ } catch (err) {
+ // Ignore error and return input string directly.
+ }
+ return string;
+}
+
+/**
+ * Helper for getting an abbreviated string for a mime type.
+ *
+ * @param {string} mimeType - mime type
+ * @return {string} abbreviated mime type
+ */
+function getAbbreviatedMimeType(mimeType) {
+ if (!mimeType) {
+ return "";
+ }
+ const abbrevType = (mimeType.split(";")[0].split("/")[1] || "").split("+")[0];
+ return CONTENT_MIME_TYPE_ABBREVIATIONS[abbrevType] || abbrevType;
+}
+
+/**
+ * Helpers for getting a filename from a mime type.
+ *
+ * @param {string} baseNameWithQuery - unicode basename and query of a url
+ * @return {string} unicode filename portion of a url
+ */
+function getFileName(baseNameWithQuery) {
+ const basename = baseNameWithQuery && baseNameWithQuery.split("?")[0];
+ return basename && basename.includes(".") ? basename : null;
+}
+
+/**
+ * Helpers for retrieving a URL object from a string
+ *
+ * @param {string} url - unvalidated url string
+ * @return {URL} The URL object
+ */
+function getUrl(url) {
+ try {
+ return new URL(url);
+ } catch (err) {
+ return null;
+ }
+}
+
+/**
+ * Helpers for retrieving the value of a URL object property
+ *
+ * @param {string} input - unvalidated url string
+ * @param {string} string - desired property in the URL object
+ * @return {string} unicode query of a url
+ */
+function getUrlProperty(input, property) {
+ const url = getUrl(input);
+ return url?.[property] ? url[property] : "";
+}
+
+/**
+ * Helpers for getting the last portion of a url.
+ * For example helper returns "basename" from http://domain.com/path/basename
+ * If basename portion is empty, it returns the url pathname.
+ *
+ * @param {string} input - unvalidated url string
+ * @return {string} unicode basename of a url
+ */
+function getUrlBaseName(url) {
+ const pathname = getUrlProperty(url, "pathname");
+ return getUnicodeUrlPath(pathname.replace(/\S*\//, "") || pathname || "/");
+}
+
+/**
+ * Helpers for getting the query portion of a url.
+ *
+ * @param {string} url - unvalidated url string
+ * @return {string} unicode query of a url
+ */
+function getUrlQuery(url) {
+ return getUrlProperty(url, "search").replace(/^\?/, "");
+}
+
+/**
+ * Helpers for getting unicode name and query portions of a url.
+ *
+ * @param {string} url - unvalidated url string
+ * @return {string} unicode basename and query portions of a url
+ */
+function getUrlBaseNameWithQuery(url) {
+ const basename = getUrlBaseName(url);
+ const search = getUrlProperty(url, "search");
+ return basename + getUnicodeUrlPath(search);
+}
+
+/**
+ * Helpers for getting hostname portion of an URL.
+ *
+ * @param {string} url - unvalidated url string
+ * @return {string} unicode hostname of a url
+ */
+function getUrlHostName(url) {
+ return getUrlProperty(url, "hostname");
+}
+
+/**
+ * Helpers for getting host portion of an URL.
+ *
+ * @param {string} url - unvalidated url string
+ * @return {string} unicode host of a url
+ */
+function getUrlHost(url) {
+ return getUrlProperty(url, "host");
+}
+
+/**
+ * Helpers for getting the shceme portion of a url.
+ * For example helper returns "http" from http://domain.com/path/basename
+ *
+ * @param {string} url - unvalidated url string
+ * @return {string} string scheme of a url
+ */
+function getUrlScheme(url) {
+ const protocol = getUrlProperty(url, "protocol");
+ return protocol.replace(":", "").toLowerCase();
+}
+
+/**
+ * Extract several details fields from a URL at once.
+ */
+function getUrlDetails(url) {
+ const baseNameWithQuery = getUrlBaseNameWithQuery(url);
+ let host = getUrlHost(url);
+ const hostname = getUrlHostName(url);
+ const unicodeUrl = getUnicodeUrl(url);
+ const scheme = getUrlScheme(url);
+
+ // If the hostname contains unreadable ASCII characters, we need to do the
+ // following two steps:
+ // 1. Converting the unreadable hostname to a readable Unicode domain name.
+ // For example, converting xn--g6w.xn--8pv into a Unicode domain name.
+ // 2. Replacing the unreadable hostname portion in the `host` with the
+ // readable hostname.
+ // For example, replacing xn--g6w.xn--8pv:8000 with [Unicode domain]:8000
+ // After finishing the two steps, we get a readable `host`.
+ const unicodeHostname = getUnicodeHostname(hostname);
+ if (unicodeHostname !== hostname) {
+ host = host.replace(hostname, unicodeHostname);
+ }
+
+ // Mark local hosts specially, where "local" is as defined in the W3C
+ // spec for secure contexts.
+ // http://www.w3.org/TR/powerful-features/
+ //
+ // * If the name falls under 'localhost'
+ // * If the name is an IPv4 address within 127.0.0.0/8
+ // * If the name is an IPv6 address within ::1/128
+ //
+ // IPv6 parsing is a little sloppy; it assumes that the address has
+ // been validated before it gets here.
+ const isLocal =
+ hostname.match(/(.+\.)?localhost$/) ||
+ hostname.match(/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}/) ||
+ hostname.match(/\[[0:]+1\]/);
+
+ return {
+ baseNameWithQuery,
+ host,
+ scheme,
+ unicodeUrl,
+ isLocal,
+ url,
+ };
+}
+
+/**
+ * Parse a url's query string into its components
+ *
+ * @param {string} query - query string of a url portion
+ * @return {array} array of query params { name, value }
+ */
+function parseQueryString(query) {
+ if (!query) {
+ return null;
+ }
+ return query
+ .replace(/^[?&]/, "")
+ .split("&")
+ .map(e => {
+ const param = e.split("=");
+ return {
+ name: param[0] ? getUnicodeUrlPath(param[0].replace(/\+/g, " ")) : "",
+ value: param[1]
+ ? getUnicodeUrlPath(param.slice(1).join("=").replace(/\+/g, " "))
+ : "",
+ };
+ });
+}
+
+/**
+ * Parse a string of formdata sections into its components
+ *
+ * @param {string} sections - sections of formdata joined by &
+ * @return {array} array of formdata params { name, value }
+ */
+function parseFormData(sections) {
+ if (!sections) {
+ return [];
+ }
+
+ return sections
+ .replace(/^&/, "")
+ .split("&")
+ .map(e => {
+ const param = e.split("=");
+ return {
+ name: param[0] ? getUnicodeUrlPath(param[0]) : "",
+ value: param[1] ? getUnicodeUrlPath(param[1]) : "",
+ };
+ });
+}
+
+/**
+ * Reduces an IP address into a number for easier sorting
+ *
+ * @param {string} ip - IP address to reduce
+ * @return {number} the number representing the IP address
+ */
+function ipToLong(ip) {
+ if (!ip) {
+ // Invalid IP
+ return -1;
+ }
+
+ let base;
+ let octets = ip.split(".");
+
+ if (octets.length === 4) {
+ // IPv4
+ base = 10;
+ } else if (ip.includes(":")) {
+ // IPv6
+ const numberOfZeroSections =
+ 8 - ip.replace(/^:+|:+$/g, "").split(/:+/g).length;
+ octets = ip
+ .replace("::", `:${"0:".repeat(numberOfZeroSections)}`)
+ .replace(/^:|:$/g, "")
+ .split(":");
+ base = 16;
+ } else {
+ // Invalid IP
+ return -1;
+ }
+ return octets
+ .map((val, ix, arr) => {
+ return parseInt(val, base) * Math.pow(256, arr.length - 1 - ix);
+ })
+ .reduce((sum, val) => {
+ return sum + val;
+ }, 0);
+}
+
+/**
+ * Compare two objects on a subset of their properties
+ */
+function propertiesEqual(props, item1, item2) {
+ return item1 === item2 || props.every(p => item1[p] === item2[p]);
+}
+
+/**
+ * Calculate the start time of a request, which is the time from start
+ * of 1st request until the start of this request.
+ *
+ * Without a firstRequestStartedMs argument the wrong time will be returned.
+ * However, it can be omitted when comparing two start times and neither supplies
+ * a firstRequestStartedMs.
+ */
+function getStartTime(item, firstRequestStartedMs = 0) {
+ return item.startedMs - firstRequestStartedMs;
+}
+
+/**
+ * Calculate the end time of a request, which is the time from start
+ * of 1st request until the end of this response.
+ *
+ * Without a firstRequestStartedMs argument the wrong time will be returned.
+ * However, it can be omitted when comparing two end times and neither supplies
+ * a firstRequestStartedMs.
+ */
+function getEndTime(item, firstRequestStartedMs = 0) {
+ const { startedMs, totalTime } = item;
+ return startedMs + totalTime - firstRequestStartedMs;
+}
+
+/**
+ * Calculate the response time of a request, which is the time from start
+ * of 1st request until the beginning of download of this response.
+ *
+ * Without a firstRequestStartedMs argument the wrong time will be returned.
+ * However, it can be omitted when comparing two response times and neither supplies
+ * a firstRequestStartedMs.
+ */
+function getResponseTime(item, firstRequestStartedMs = 0) {
+ const { startedMs, totalTime, eventTimings = { timings: {} } } = item;
+ return (
+ startedMs + totalTime - firstRequestStartedMs - eventTimings.timings.receive
+ );
+}
+
+/**
+ * Format the protocols used by the request.
+ */
+function getFormattedProtocol(item) {
+ const { httpVersion = "", responseHeaders = { headers: [] } } = item;
+ const protocol = [httpVersion];
+ responseHeaders.headers.some(h => {
+ if (h.hasOwnProperty("name") && h.name.toLowerCase() === "x-firefox-spdy") {
+ /**
+ * First we make sure h.value is defined and not an empty string.
+ * Then check that HTTP version and x-firefox-spdy == "http/1.1".
+ * If not, check that HTTP version and x-firefox-spdy have the same
+ * numeric value when of the forms "http/<x>" and "h<x>" respectively.
+ * If not, will push to protocol the non-standard x-firefox-spdy value.
+ *
+ * @see https://bugzilla.mozilla.org/show_bug.cgi?id=1501357
+ */
+ if (h.value !== undefined && h.value.length) {
+ if (
+ h.value.toLowerCase() !== "http/1.1" ||
+ protocol[0].toLowerCase() !== "http/1.1"
+ ) {
+ if (
+ parseFloat(h.value.toLowerCase().split("")[1]) !==
+ parseFloat(protocol[0].toLowerCase().split("/")[1])
+ ) {
+ protocol.push(h.value);
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ });
+ return protocol.join("+");
+}
+
+/**
+ * Get the value of a particular response header, or null if not
+ * present.
+ */
+function getResponseHeader(item, header) {
+ const { responseHeaders } = item;
+ if (!responseHeaders || !responseHeaders.headers.length) {
+ return null;
+ }
+ header = header.toLowerCase();
+ for (const responseHeader of responseHeaders.headers) {
+ if (responseHeader.name.toLowerCase() == header) {
+ return responseHeader.value;
+ }
+ }
+ return null;
+}
+
+/**
+ * Get the value of a particular request header, or null if not
+ * present.
+ */
+function getRequestHeader(item, header) {
+ const { requestHeaders } = item;
+ if (!requestHeaders || !requestHeaders.headers.length) {
+ return null;
+ }
+ header = header.toLowerCase();
+ for (const requestHeader of requestHeaders.headers) {
+ if (requestHeader.name.toLowerCase() == header) {
+ return requestHeader.value;
+ }
+ }
+ return null;
+}
+
+/**
+ * Extracts any urlencoded form data sections from a POST request.
+ */
+async function updateFormDataSections(props) {
+ const { connector, request = {}, updateRequest } = props;
+ let {
+ id,
+ formDataSections,
+ requestHeaders,
+ requestHeadersAvailable,
+ requestHeadersFromUploadStream,
+ requestPostData,
+ requestPostDataAvailable,
+ } = request;
+
+ if (requestHeadersAvailable && !requestHeaders) {
+ requestHeaders = await connector.requestData(id, "requestHeaders");
+ }
+
+ if (requestPostDataAvailable && !requestPostData) {
+ requestPostData = await connector.requestData(id, "requestPostData");
+ }
+
+ if (
+ !formDataSections &&
+ requestHeaders &&
+ requestPostData &&
+ requestHeadersFromUploadStream
+ ) {
+ formDataSections = await getFormDataSections(
+ requestHeaders,
+ requestHeadersFromUploadStream,
+ requestPostData,
+ connector.getLongString
+ );
+
+ updateRequest(request.id, { formDataSections }, true);
+ }
+}
+
+/**
+ * This helper function helps to resolve the full payload of a message
+ * that is wrapped in a LongStringActor object.
+ */
+async function getMessagePayload(payload, getLongString) {
+ const result = await getLongString(payload);
+ return result;
+}
+
+/**
+ * This helper function is used for additional processing of
+ * incoming network update packets. It makes sure the only valid
+ * update properties and the values are correct.
+ * It's used by Network and Console panel reducers.
+ * @param {object} update
+ * The new update payload
+ * @param {object} request
+ * The current request in the state
+ */
+function processNetworkUpdates(update) {
+ const newRequest = {};
+ for (const [key, value] of Object.entries(update)) {
+ if (UPDATE_PROPS.includes(key)) {
+ newRequest[key] = value;
+ if (key == "requestPostData") {
+ newRequest.requestHeadersFromUploadStream = value.uploadHeaders;
+ }
+ }
+ }
+ return newRequest;
+}
+
+/**
+ * This method checks that the response is base64 encoded by
+ * comparing these 2 values:
+ * 1. The original response
+ * 2. The value of doing a base64 decode on the
+ * response and then base64 encoding the result.
+ * If the values are different or an error is thrown,
+ * the method will return false.
+ */
+function isBase64(payload) {
+ try {
+ return btoa(atob(payload)) == payload;
+ } catch (err) {
+ return false;
+ }
+}
+
+/**
+ * Checks if the payload is of JSON type.
+ * This function also handles JSON with XSSI-escaping characters by stripping them
+ * and returning the stripped chars in the strippedChars property
+ * This function also handles Base64 encoded JSON.
+ * @returns {Object} shape:
+ * {Object} json: parsed JSON object
+ * {Error} error: JSON parsing error
+ * {string} strippedChars: XSSI stripped chars removed from JSON payload
+ */
+function parseJSON(payloadUnclean) {
+ let json;
+ const jsonpRegex = /^\s*([\w$]+)\s*\(\s*([^]*)\s*\)\s*;?\s*$/;
+ const [, jsonpCallback, jsonp] = payloadUnclean.match(jsonpRegex) || [];
+ if (jsonpCallback && jsonp) {
+ let error;
+ try {
+ json = parseJSON(jsonp).json;
+ } catch (err) {
+ error = err;
+ }
+ return { json, error, jsonpCallback };
+ }
+
+ let { payload, strippedChars, error } = removeXSSIString(payloadUnclean);
+
+ try {
+ json = JSON.parse(payload);
+ } catch (err) {
+ if (isBase64(payload)) {
+ try {
+ json = JSON.parse(atob(payload));
+ } catch (err64) {
+ error = err64;
+ }
+ } else {
+ error = err;
+ }
+ }
+
+ // Do not present JSON primitives (e.g. boolean, strings in quotes, numbers)
+ // as JSON expandable tree.
+ if (!error) {
+ if (typeof json !== "object") {
+ return {};
+ }
+ }
+ return {
+ json,
+ error,
+ strippedChars,
+ };
+}
+
+/**
+ * Removes XSSI prevention sequences from JSON payloads
+ * @param {string} payloadUnclean: JSON payload that may or may have a
+ * XSSI prevention sequence
+ * @returns {Object} Shape:
+ * {string} payload: the JSON witht the XSSI prevention sequence removed
+ * {string} strippedChars: XSSI string that was removed, null if no XSSI
+ * prevention sequence was found
+ * {Error} error: error attempting to strip XSSI prevention sequence
+ */
+function removeXSSIString(payloadUnclean) {
+ // Regex that finds the XSSI protection sequences )]}'\n for(;;); and while(1);
+ const xssiRegex = /(^\)\]\}',?\n)|(^for ?\(;;\);?)|(^while ?\(1\);?)/;
+ let payload, strippedChars, error;
+ const xssiRegexMatch = payloadUnclean.match(xssiRegex);
+
+ // Remove XSSI string if there was one found
+ if (xssiRegexMatch?.length > 0) {
+ const xssiLen = xssiRegexMatch[0].length;
+ try {
+ // substring the payload by the length of the XSSI match to remove it
+ // and save the match to report
+ payload = payloadUnclean.substring(xssiLen);
+ strippedChars = xssiRegexMatch[0];
+ } catch (err) {
+ error = err;
+ payload = payloadUnclean;
+ }
+ } else {
+ // if there was no XSSI match just return the raw payload
+ payload = payloadUnclean;
+ }
+ return {
+ payload,
+ strippedChars,
+ error,
+ };
+}
+
+/**
+ * Computes the request headers of an HTTP request
+ *
+ * @param {string} method: request method
+ * @param {string} httpVersion: request http version
+ * @param {object} requestHeaders: request headers
+ * @param {object} urlDetails: request url details
+ *
+ * @return {string} the request headers
+ */
+function getRequestHeadersRawText(
+ method,
+ httpVersion,
+ requestHeaders,
+ urlDetails
+) {
+ const url = new URL(urlDetails.url);
+ const path = url ? `${url.pathname}${url.search}` : "<unknown>";
+ const preHeaderText = `${method} ${path} ${httpVersion}`;
+ return writeHeaderText(requestHeaders.headers, preHeaderText).trim();
+}
+
+module.exports = {
+ decodeUnicodeBase64,
+ getFormDataSections,
+ fetchHeaders,
+ fetchNetworkUpdatePacket,
+ formDataURI,
+ writeHeaderText,
+ getAbbreviatedMimeType,
+ getFileName,
+ getEndTime,
+ getFormattedProtocol,
+ getMessagePayload,
+ getRequestHeader,
+ getResponseHeader,
+ getResponseTime,
+ getStartTime,
+ getUrlBaseName,
+ getUrlBaseNameWithQuery,
+ getUrlDetails,
+ getUrlHost,
+ getUrlHostName,
+ getUrlQuery,
+ getUrlScheme,
+ parseQueryString,
+ parseFormData,
+ updateFormDataSections,
+ processNetworkUpdates,
+ propertiesEqual,
+ ipToLong,
+ parseJSON,
+ getRequestHeadersRawText,
+};
diff --git a/devtools/client/netmonitor/src/utils/sort-predicates.js b/devtools/client/netmonitor/src/utils/sort-predicates.js
new file mode 100644
index 0000000000..839a37d00e
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/sort-predicates.js
@@ -0,0 +1,319 @@
+/* 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 {
+ getAbbreviatedMimeType,
+ getEndTime,
+ getResponseTime,
+ getResponseHeader,
+ getStartTime,
+ ipToLong,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ RESPONSE_HEADERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ getUrlBaseName,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+/**
+ * Predicates used when sorting items.
+ *
+ * @param object first
+ * The first item used in the comparison.
+ * @param object second
+ * The second item used in the comparison.
+ * @return number
+ * <0 to sort first to a lower index than second
+ * =0 to leave first and second unchanged with respect to each other
+ * >0 to sort second to a lower index than first
+ */
+
+function compareValues(first, second) {
+ if (first === second) {
+ return 0;
+ }
+ return first > second ? 1 : -1;
+}
+
+function waterfall(first, second) {
+ const result = compareValues(first.startedMs, second.startedMs);
+ return result || compareValues(first.id, second.id);
+}
+
+function priority(first, second) {
+ const result = compareValues(first.priority, second.priority);
+ return result || waterfall(first, second);
+}
+
+function status(first, second) {
+ const result = compareValues(getStatusValue(first), getStatusValue(second));
+ return result || waterfall(first, second);
+}
+
+function method(first, second) {
+ const result = compareValues(first.method, second.method);
+ return result || waterfall(first, second);
+}
+
+function file(first, second) {
+ const firstUrl = first.urlDetails.baseNameWithQuery.toLowerCase();
+ const secondUrl = second.urlDetails.baseNameWithQuery.toLowerCase();
+ const result = compareValues(firstUrl, secondUrl);
+ return result || waterfall(first, second);
+}
+
+function url(first, second) {
+ const firstUrl = first.url.toLowerCase();
+ const secondUrl = second.url.toLowerCase();
+ const result = compareValues(firstUrl, secondUrl);
+ return result || waterfall(first, second);
+}
+
+function protocol(first, second) {
+ const result = compareValues(first.httpVersion, second.httpVersion);
+ return result || waterfall(first, second);
+}
+
+function scheme(first, second) {
+ const result = compareValues(
+ first.urlDetails.scheme,
+ second.urlDetails.scheme
+ );
+ return result || waterfall(first, second);
+}
+
+function startTime(first, second) {
+ const result = compareValues(getStartTime(first), getStartTime(second));
+ return result || waterfall(first, second);
+}
+
+function endTime(first, second) {
+ const result = compareValues(getEndTime(first), getEndTime(second));
+ return result || waterfall(first, second);
+}
+
+function responseTime(first, second) {
+ const result = compareValues(getResponseTime(first), getResponseTime(second));
+ return result || waterfall(first, second);
+}
+
+function duration(first, second) {
+ const result = compareValues(first.totalTime, second.totalTime);
+ return result || waterfall(first, second);
+}
+
+function latency(first, second) {
+ const { eventTimings: firstEventTimings = { timings: {} } } = first;
+ const { eventTimings: secondEventTimings = { timings: {} } } = second;
+ const result = compareValues(
+ firstEventTimings.timings.wait,
+ secondEventTimings.timings.wait
+ );
+ return result || waterfall(first, second);
+}
+
+function compareHeader(header, first, second) {
+ const firstValue = getResponseHeader(first, header) || "";
+ const secondValue = getResponseHeader(second, header) || "";
+
+ let result;
+
+ switch (header) {
+ case "Content-Length": {
+ result = compareValues(
+ parseInt(firstValue, 10) || 0,
+ parseInt(secondValue, 10) || 0
+ );
+ break;
+ }
+ case "Last-Modified": {
+ result = compareValues(
+ new Date(firstValue).valueOf() || -1,
+ new Date(secondValue).valueOf() || -1
+ );
+ break;
+ }
+ default: {
+ result = compareValues(firstValue, secondValue);
+ break;
+ }
+ }
+
+ return result || waterfall(first, second);
+}
+
+const responseHeaders = RESPONSE_HEADERS.reduce(
+ (acc, header) =>
+ Object.assign(acc, {
+ [header]: (first, second) => compareHeader(header, first, second),
+ }),
+ {}
+);
+
+function domain(first, second) {
+ const firstDomain = first.urlDetails.host.toLowerCase();
+ const secondDomain = second.urlDetails.host.toLowerCase();
+ const result = compareValues(firstDomain, secondDomain);
+ return result || waterfall(first, second);
+}
+
+function remoteip(first, second) {
+ const firstIP = ipToLong(first.remoteAddress);
+ const secondIP = ipToLong(second.remoteAddress);
+ const result = compareValues(firstIP, secondIP);
+ return result || waterfall(first, second);
+}
+
+function cause(first, second) {
+ const firstCause = first.cause.type;
+ const secondCause = second.cause.type;
+ const result = compareValues(firstCause, secondCause);
+ return result || waterfall(first, second);
+}
+
+function initiator(first, second) {
+ const firstCause = first.cause.type;
+ const secondCause = second.cause.type;
+
+ let firstInitiator = "";
+ let firstInitiatorLineNumber = 0;
+
+ if (first.cause.lastFrame) {
+ firstInitiator = getUrlBaseName(first.cause.lastFrame.filename);
+ firstInitiatorLineNumber = first.cause.lastFrame.lineNumber;
+ }
+
+ let secondInitiator = "";
+ let secondInitiatorLineNumber = 0;
+
+ if (second.cause.lastFrame) {
+ secondInitiator = getUrlBaseName(second.cause.lastFrame.filename);
+ secondInitiatorLineNumber = second.cause.lastFrame.lineNumber;
+ }
+
+ let result;
+ // if both initiators don't have a stack trace, compare their causes
+ if (!firstInitiator && !secondInitiator) {
+ result = compareValues(firstCause, secondCause);
+ } else if (!firstInitiator || !secondInitiator) {
+ // if one initiator doesn't have a stack trace but the other does, former should precede the latter
+ result = compareValues(firstInitiatorLineNumber, secondInitiatorLineNumber);
+ } else {
+ result = compareValues(firstInitiator, secondInitiator);
+ if (result === 0) {
+ result = compareValues(
+ firstInitiatorLineNumber,
+ secondInitiatorLineNumber
+ );
+ }
+ }
+
+ return result || waterfall(first, second);
+}
+
+function setCookies(first, second) {
+ let { responseCookies: firstResponseCookies = { cookies: [] } } = first;
+ let { responseCookies: secondResponseCookies = { cookies: [] } } = second;
+ firstResponseCookies = firstResponseCookies.cookies || firstResponseCookies;
+ secondResponseCookies =
+ secondResponseCookies.cookies || secondResponseCookies;
+ const result = compareValues(
+ firstResponseCookies.length,
+ secondResponseCookies.length
+ );
+ return result || waterfall(first, second);
+}
+
+function cookies(first, second) {
+ let { requestCookies: firstRequestCookies = { cookies: [] } } = first;
+ let { requestCookies: secondRequestCookies = { cookies: [] } } = second;
+ firstRequestCookies = firstRequestCookies.cookies || firstRequestCookies;
+ secondRequestCookies = secondRequestCookies.cookies || secondRequestCookies;
+ const result = compareValues(
+ firstRequestCookies.length,
+ secondRequestCookies.length
+ );
+ return result || waterfall(first, second);
+}
+
+function type(first, second) {
+ const firstType = getAbbreviatedMimeType(first.mimeType).toLowerCase();
+ const secondType = getAbbreviatedMimeType(second.mimeType).toLowerCase();
+ const result = compareValues(firstType, secondType);
+ return result || waterfall(first, second);
+}
+
+function getStatusValue(item) {
+ let value;
+ if (item.blockedReason) {
+ value = typeof item.blockedReason == "number" ? -item.blockedReason : -1000;
+ } else if (item.status == null) {
+ value = -2;
+ } else {
+ value = item.status;
+ }
+ return value;
+}
+
+function getTransferedSizeValue(item) {
+ let value;
+ if (item.blockedReason) {
+ // Also properly group/sort various blocked reasons.
+ value = typeof item.blockedReason == "number" ? -item.blockedReason : -1000;
+ } else if (item.fromCache || item.status === "304") {
+ value = -2;
+ } else if (item.fromServiceWorker) {
+ value = -3;
+ } else if (typeof item.transferredSize == "number") {
+ value = item.transferredSize;
+ if (item.isRacing && typeof item.isRacing == "boolean") {
+ value = -4;
+ }
+ } else if (item.transferredSize === null) {
+ value = -5;
+ }
+ return value;
+}
+
+function transferred(first, second) {
+ const result = compareValues(
+ getTransferedSizeValue(first),
+ getTransferedSizeValue(second)
+ );
+ return result || waterfall(first, second);
+}
+
+function contentSize(first, second) {
+ const result = compareValues(first.contentSize, second.contentSize);
+ return result || waterfall(first, second);
+}
+
+const sorters = {
+ status,
+ method,
+ domain,
+ file,
+ protocol,
+ scheme,
+ cookies,
+ setCookies,
+ remoteip,
+ cause,
+ initiator,
+ type,
+ transferred,
+ contentSize,
+ startTime,
+ endTime,
+ responseTime,
+ duration,
+ latency,
+ waterfall,
+ url,
+ priority,
+};
+exports.Sorters = Object.assign(sorters, responseHeaders);
diff --git a/devtools/client/netmonitor/src/utils/sort-utils.js b/devtools/client/netmonitor/src/utils/sort-utils.js
new file mode 100644
index 0000000000..a7f49417e8
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/sort-utils.js
@@ -0,0 +1,42 @@
+/* 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";
+
+/**
+ * Sorts object by keys in alphabetical order
+ * If object has nested children, it sorts the child-elements also by keys
+ * @param {object} which should be sorted by keys in alphabetical order
+ */
+function sortObjectKeys(object) {
+ if (object == null) {
+ return null;
+ }
+
+ if (Array.isArray(object)) {
+ for (let i = 0; i < object.length; i++) {
+ if (typeof object[i] === "object") {
+ object[i] = sortObjectKeys(object[i]);
+ }
+ }
+ return object;
+ }
+
+ return Object.keys(object)
+ .sort(function (left, right) {
+ return left.toLowerCase().localeCompare(right.toLowerCase());
+ })
+ .reduce((acc, key) => {
+ if (typeof object[key] === "object") {
+ acc[key] = sortObjectKeys(object[key]);
+ } else {
+ acc[key] = object[key];
+ }
+ return acc;
+ }, Object.create(null));
+}
+
+module.exports = {
+ sortObjectKeys,
+};
diff --git a/devtools/client/netmonitor/src/utils/tooltips.js b/devtools/client/netmonitor/src/utils/tooltips.js
new file mode 100644
index 0000000000..1f35346353
--- /dev/null
+++ b/devtools/client/netmonitor/src/utils/tooltips.js
@@ -0,0 +1,18 @@
+/* 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";
+
+/**
+ * Returns first 128 characters of value for use as a tooltip.
+ * @param object
+ * @returns {*}
+ */
+function limitTooltipLength(object) {
+ return object.length > 128 ? object.substring(0, 128) + "…" : object;
+}
+
+module.exports = {
+ limitTooltipLength,
+};
diff --git a/devtools/client/netmonitor/src/widgets/HeadersPanelContextMenu.js b/devtools/client/netmonitor/src/widgets/HeadersPanelContextMenu.js
new file mode 100644
index 0000000000..6f159ded73
--- /dev/null
+++ b/devtools/client/netmonitor/src/widgets/HeadersPanelContextMenu.js
@@ -0,0 +1,137 @@
+/* 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");
+const {
+ contextMenuFormatters,
+} = require("resource://devtools/client/netmonitor/src/utils/context-menu-utils.js");
+
+loader.lazyRequireGetter(
+ this,
+ "copyString",
+ "resource://devtools/shared/platform/clipboard.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "showMenu",
+ "resource://devtools/client/shared/components/menu/utils.js",
+ true
+);
+
+class HeadersPanelContextMenu {
+ constructor(props = {}) {
+ this.props = props;
+ this.copyAll = this.copyAll.bind(this);
+ this.copyValue = this.copyValue.bind(this);
+ }
+
+ /**
+ * Handle the context menu opening.
+ * @param {Object} event open event
+ * @param {Object} selection object representing the current selection
+ */
+ open(event = {}, selection) {
+ const { target } = event;
+ const menuItems = [
+ {
+ id: "headers-panel-context-menu-copyvalue",
+ label: L10N.getStr("netmonitor.context.copyValue"),
+ accesskey: L10N.getStr("netmonitor.context.copyValue.accesskey"),
+ click: () => {
+ const { name, value } = getSummaryContent(
+ target.closest(".tabpanel-summary-container")
+ );
+ this.copyValue(
+ { name, value, object: null, hasChildren: false },
+ selection
+ );
+ },
+ },
+ {
+ id: "headers-panel-context-menu-copyall",
+ label: L10N.getStr("netmonitor.context.copyAll"),
+ accesskey: L10N.getStr("netmonitor.context.copyAll.accesskey"),
+ click: () => {
+ const root = target.closest(".summary");
+ const object = {};
+ if (root) {
+ const { children } = root;
+ for (let i = 0; i < children.length; i++) {
+ const content = getSummaryContent(children[i]);
+ object[content.name] = content.value;
+ }
+ }
+ return this.copyAll(object, selection);
+ },
+ },
+ ];
+
+ showMenu(menuItems, {
+ screenX: event.screenX,
+ screenY: event.screenY,
+ });
+ }
+
+ /**
+ * Copies all.
+ * @param {Object} object the whole tree data
+ * @param {Object} selection object representing the current selection
+ */
+ copyAll(object, selection) {
+ let buffer = "";
+ if (selection.toString() !== "") {
+ buffer = selection.toString();
+ } else {
+ const { customFormatters } = this.props;
+ buffer = contextMenuFormatters.baseCopyAllFormatter(object);
+ if (customFormatters?.copyAllFormatter) {
+ buffer = customFormatters.copyAllFormatter(
+ object,
+ contextMenuFormatters.baseCopyAllFormatter
+ );
+ }
+ }
+ try {
+ copyString(buffer);
+ } catch (error) {}
+ }
+
+ /**
+ * Copies the value of a single item.
+ * @param {Object} object data object for specific node
+ * @param {Object} selection object representing the current selection
+ */
+ copyValue(object, selection) {
+ let buffer = "";
+ if (selection.toString() !== "") {
+ buffer = selection.toString();
+ } else {
+ const { customFormatters } = this.props;
+ buffer = contextMenuFormatters.baseCopyFormatter(object);
+ if (customFormatters?.copyFormatter) {
+ buffer = customFormatters.copyFormatter(
+ object,
+ contextMenuFormatters.baseCopyFormatter
+ );
+ }
+ }
+ try {
+ copyString(buffer);
+ } catch (error) {}
+ }
+}
+
+function getSummaryContent(el) {
+ return {
+ name: el.querySelector(".tabpanel-summary-label").textContent,
+ value: el.querySelector(".tabpanel-summary-value").textContent,
+ };
+}
+
+module.exports = HeadersPanelContextMenu;
diff --git a/devtools/client/netmonitor/src/widgets/PropertiesViewContextMenu.js b/devtools/client/netmonitor/src/widgets/PropertiesViewContextMenu.js
new file mode 100644
index 0000000000..8d823444c2
--- /dev/null
+++ b/devtools/client/netmonitor/src/widgets/PropertiesViewContextMenu.js
@@ -0,0 +1,113 @@
+/* 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");
+const {
+ contextMenuFormatters,
+} = require("resource://devtools/client/netmonitor/src/utils/context-menu-utils.js");
+
+loader.lazyRequireGetter(
+ this,
+ "copyString",
+ "resource://devtools/shared/platform/clipboard.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "showMenu",
+ "resource://devtools/client/shared/components/menu/utils.js",
+ true
+);
+
+class PropertiesViewContextMenu {
+ constructor(props = {}) {
+ this.props = props;
+ this.copyAll = this.copyAll.bind(this);
+ this.copyValue = this.copyValue.bind(this);
+ }
+
+ /**
+ * Handle the context menu opening.
+ * @param {Object} event open event
+ * @param {Object} selection object representing the current selection
+ * @param {Object} data object containing information
+ * @param {Object} data.member member of the right-clicked row
+ * @param {Object} data.object the whole tree data
+ */
+ open(event = {}, selection, { member, object }) {
+ const menuItems = [
+ {
+ id: "properties-view-context-menu-copyvalue",
+ label: L10N.getStr("netmonitor.context.copyValue"),
+ accesskey: L10N.getStr("netmonitor.context.copyValue.accesskey"),
+ click: () => this.copyValue(member, selection),
+ },
+ {
+ id: "properties-view-context-menu-copyall",
+ label: L10N.getStr("netmonitor.context.copyAll"),
+ accesskey: L10N.getStr("netmonitor.context.copyAll.accesskey"),
+ click: () => this.copyAll(object, selection),
+ },
+ ];
+
+ showMenu(menuItems, {
+ screenX: event.screenX,
+ screenY: event.screenY,
+ });
+ }
+
+ /**
+ * Copies all.
+ * @param {Object} object the whole tree data
+ * @param {Object} selection object representing the current selection
+ */
+ copyAll(object, selection) {
+ let buffer = "";
+ if (selection.toString() !== "") {
+ buffer = selection.toString();
+ } else {
+ const { customFormatters } = this.props;
+ buffer = contextMenuFormatters.baseCopyAllFormatter(object);
+ if (customFormatters?.copyAllFormatter) {
+ buffer = customFormatters.copyAllFormatter(
+ object,
+ contextMenuFormatters.baseCopyAllFormatter
+ );
+ }
+ }
+ try {
+ copyString(buffer);
+ } catch (error) {}
+ }
+
+ /**
+ * Copies the value of a single item.
+ * @param {Object} member member of the right-clicked row
+ * @param {Object} selection object representing the current selection
+ */
+ copyValue(member, selection) {
+ let buffer = "";
+ if (selection.toString() !== "") {
+ buffer = selection.toString();
+ } else {
+ const { customFormatters } = this.props;
+ buffer = contextMenuFormatters.baseCopyFormatter(member);
+ if (customFormatters?.copyFormatter) {
+ buffer = customFormatters.copyFormatter(
+ member,
+ contextMenuFormatters.baseCopyFormatter
+ );
+ }
+ }
+ try {
+ copyString(buffer);
+ } catch (error) {}
+ }
+}
+
+module.exports = PropertiesViewContextMenu;
diff --git a/devtools/client/netmonitor/src/widgets/RequestBlockingContextMenu.js b/devtools/client/netmonitor/src/widgets/RequestBlockingContextMenu.js
new file mode 100644
index 0000000000..f6a10b0ca3
--- /dev/null
+++ b/devtools/client/netmonitor/src/widgets/RequestBlockingContextMenu.js
@@ -0,0 +1,78 @@
+/* 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
+);
+
+class RequestBlockingContextMenu {
+ constructor(props) {
+ this.props = props;
+ }
+
+ createMenu(contextMenuOptions) {
+ const {
+ removeAllBlockedUrls,
+ disableAllBlockedUrls,
+ enableAllBlockedUrls,
+ } = this.props;
+
+ const { disableDisableAllBlockedUrls, disableEnableAllBlockedUrls } =
+ contextMenuOptions;
+
+ const menu = [
+ {
+ id: "request-blocking-enable-all",
+ label: L10N.getStr(
+ "netmonitor.requestBlockingMenu.enableAllBlockedUrls"
+ ),
+ accesskey: "",
+ disabled: disableEnableAllBlockedUrls,
+ visible: true,
+ click: () => enableAllBlockedUrls(),
+ },
+ {
+ id: "request-blocking-disable-all",
+ label: L10N.getStr(
+ "netmonitor.requestBlockingMenu.disableAllBlockedUrls"
+ ),
+ accesskey: "",
+ disabled: disableDisableAllBlockedUrls,
+ visible: true,
+ click: () => disableAllBlockedUrls(),
+ },
+ {
+ id: "request-blocking-remove-all",
+ label: L10N.getStr(
+ "netmonitor.requestBlockingMenu.removeAllBlockedUrls"
+ ),
+ accesskey: "",
+ visible: true,
+ click: () => removeAllBlockedUrls(),
+ },
+ ];
+
+ return menu;
+ }
+
+ open(event, contextMenuOptions) {
+ const menu = this.createMenu(contextMenuOptions);
+
+ showMenu(menu, {
+ screenX: event.screenX,
+ screenY: event.screenY,
+ });
+ }
+}
+
+module.exports = RequestBlockingContextMenu;
diff --git a/devtools/client/netmonitor/src/widgets/RequestListContextMenu.js b/devtools/client/netmonitor/src/widgets/RequestListContextMenu.js
new file mode 100644
index 0000000000..1702cdbc64
--- /dev/null
+++ b/devtools/client/netmonitor/src/widgets/RequestListContextMenu.js
@@ -0,0 +1,793 @@
+/* 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");
+const {
+ formDataURI,
+ getUrlQuery,
+ getUrlBaseName,
+ parseQueryString,
+ getRequestHeadersRawText,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ hasMatchingBlockingRequestPattern,
+} = require("resource://devtools/client/netmonitor/src/utils/request-blocking.js");
+
+loader.lazyRequireGetter(
+ this,
+ "Curl",
+ "resource://devtools/client/shared/curl.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "saveAs",
+ "resource://devtools/shared/DevToolsUtils.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "PowerShell",
+ "resource://devtools/client/netmonitor/src/utils/powershell.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "copyString",
+ "resource://devtools/shared/platform/clipboard.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "showMenu",
+ "resource://devtools/client/shared/components/menu/utils.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "HarMenuUtils",
+ "resource://devtools/client/netmonitor/src/har/har-menu-utils.js",
+ true
+);
+
+const { OS } = Services.appinfo;
+
+class RequestListContextMenu {
+ constructor(props) {
+ this.props = props;
+ }
+
+ createCopySubMenu(clickedRequest, requests) {
+ const { connector } = this.props;
+
+ const {
+ id,
+ formDataSections,
+ method,
+ mimeType,
+ httpVersion,
+ requestHeaders,
+ requestHeadersAvailable,
+ requestPostData,
+ requestPostDataAvailable,
+ responseHeaders,
+ responseHeadersAvailable,
+ responseContent,
+ responseContentAvailable,
+ url,
+ } = clickedRequest;
+
+ const copySubMenu = [];
+
+ copySubMenu.push({
+ id: "request-list-context-copy-url",
+ label: L10N.getStr("netmonitor.context.copyUrl"),
+ accesskey: L10N.getStr("netmonitor.context.copyUrl.accesskey"),
+ visible: !!clickedRequest,
+ click: () => this.copyUrl(url),
+ });
+
+ copySubMenu.push({
+ id: "request-list-context-copy-url-params",
+ label: L10N.getStr("netmonitor.context.copyUrlParams"),
+ accesskey: L10N.getStr("netmonitor.context.copyUrlParams.accesskey"),
+ visible: !!(clickedRequest && getUrlQuery(url)),
+ click: () => this.copyUrlParams(url),
+ });
+
+ copySubMenu.push({
+ id: "request-list-context-copy-post-data",
+ label: L10N.getFormatStr("netmonitor.context.copyRequestData", method),
+ accesskey: L10N.getStr("netmonitor.context.copyRequestData.accesskey"),
+ // Menu item will be visible even if data hasn't arrived, so we need to check
+ // *Available property and then fetch data lazily once user triggers the action.
+ visible: !!(
+ clickedRequest &&
+ (requestPostDataAvailable || requestPostData)
+ ),
+ click: () => this.copyPostData(id, formDataSections, requestPostData),
+ });
+
+ if (OS === "WINNT") {
+ copySubMenu.push({
+ id: "request-list-context-copy-as-curl-win",
+ label: L10N.getFormatStr(
+ "netmonitor.context.copyAsCurl.win",
+ L10N.getStr("netmonitor.context.copyAsCurl")
+ ),
+ accesskey: L10N.getStr("netmonitor.context.copyAsCurl.win.accesskey"),
+ // Menu item will be visible even if data hasn't arrived, so we need to check
+ // *Available property and then fetch data lazily once user triggers the action.
+ visible: !!clickedRequest,
+ click: () =>
+ this.copyAsCurl(
+ id,
+ url,
+ method,
+ httpVersion,
+ requestHeaders,
+ requestPostData,
+ responseHeaders,
+ "WINNT"
+ ),
+ });
+
+ copySubMenu.push({
+ id: "request-list-context-copy-as-curl-posix",
+ label: L10N.getFormatStr(
+ "netmonitor.context.copyAsCurl.posix",
+ L10N.getStr("netmonitor.context.copyAsCurl")
+ ),
+ accesskey: L10N.getStr("netmonitor.context.copyAsCurl.posix.accesskey"),
+ // Menu item will be visible even if data hasn't arrived, so we need to check
+ // *Available property and then fetch data lazily once user triggers the action.
+ visible: !!clickedRequest,
+ click: () =>
+ this.copyAsCurl(
+ id,
+ url,
+ method,
+ httpVersion,
+ requestHeaders,
+ requestPostData,
+ responseHeaders,
+ "Linux"
+ ),
+ });
+ } else {
+ copySubMenu.push({
+ id: "request-list-context-copy-as-curl",
+ label: L10N.getStr("netmonitor.context.copyAsCurl"),
+ accesskey: L10N.getStr("netmonitor.context.copyAsCurl.accesskey"),
+ // Menu item will be visible even if data hasn't arrived, so we need to check
+ // *Available property and then fetch data lazily once user triggers the action.
+ visible: !!clickedRequest,
+ click: () =>
+ this.copyAsCurl(
+ id,
+ url,
+ method,
+ httpVersion,
+ requestHeaders,
+ requestPostData,
+ responseHeaders
+ ),
+ });
+ }
+
+ copySubMenu.push({
+ id: "request-list-context-copy-as-powershell",
+ label: L10N.getStr("netmonitor.context.copyAsPowerShell"),
+ accesskey: L10N.getStr("netmonitor.context.copyAsPowerShell.accesskey"),
+ // Menu item will be visible even if data hasn't arrived, so we need to check
+ // *Available property and then fetch data lazily once user triggers the action.
+ visible: !!clickedRequest,
+ click: () => this.copyAsPowerShell(clickedRequest),
+ });
+
+ copySubMenu.push({
+ id: "request-list-context-copy-as-fetch",
+ label: L10N.getStr("netmonitor.context.copyAsFetch"),
+ accesskey: L10N.getStr("netmonitor.context.copyAsFetch.accesskey"),
+ visible: !!clickedRequest,
+ click: () =>
+ this.copyAsFetch(id, url, method, requestHeaders, requestPostData),
+ });
+
+ copySubMenu.push({
+ type: "separator",
+ visible: copySubMenu.slice(0, 4).some(subMenu => subMenu.visible),
+ });
+
+ copySubMenu.push({
+ id: "request-list-context-copy-request-headers",
+ label: L10N.getStr("netmonitor.context.copyRequestHeaders"),
+ accesskey: L10N.getStr("netmonitor.context.copyRequestHeaders.accesskey"),
+ // Menu item will be visible even if data hasn't arrived, so we need to check
+ // *Available property and then fetch data lazily once user triggers the action.
+ visible: !!(
+ clickedRequest &&
+ (requestHeadersAvailable || requestHeaders)
+ ),
+ click: () => this.copyRequestHeaders(id, clickedRequest),
+ });
+
+ copySubMenu.push({
+ id: "response-list-context-copy-response-headers",
+ label: L10N.getStr("netmonitor.context.copyResponseHeaders"),
+ accesskey: L10N.getStr(
+ "netmonitor.context.copyResponseHeaders.accesskey"
+ ),
+ // Menu item will be visible even if data hasn't arrived, so we need to check
+ // *Available property and then fetch data lazily once user triggers the action.
+ visible: !!(
+ clickedRequest &&
+ (responseHeadersAvailable || responseHeaders)
+ ),
+ click: () => this.copyResponseHeaders(id, responseHeaders),
+ });
+
+ copySubMenu.push({
+ id: "request-list-context-copy-response",
+ label: L10N.getStr("netmonitor.context.copyResponse"),
+ accesskey: L10N.getStr("netmonitor.context.copyResponse.accesskey"),
+ // Menu item will be visible even if data hasn't arrived, so we need to check
+ // *Available property and then fetch data lazily once user triggers the action.
+ visible: !!(
+ clickedRequest &&
+ (responseContentAvailable || responseContent)
+ ),
+ click: () => this.copyResponse(id, responseContent),
+ });
+
+ copySubMenu.push({
+ id: "request-list-context-copy-image-as-data-uri",
+ label: L10N.getStr("netmonitor.context.copyImageAsDataUri"),
+ accesskey: L10N.getStr("netmonitor.context.copyImageAsDataUri.accesskey"),
+ visible: !!(
+ clickedRequest &&
+ (responseContentAvailable || responseContent) &&
+ mimeType &&
+ mimeType.includes("image/")
+ ),
+ click: () => this.copyImageAsDataUri(id, mimeType, responseContent),
+ });
+
+ copySubMenu.push({
+ type: "separator",
+ visible: copySubMenu.slice(5, 9).some(subMenu => subMenu.visible),
+ });
+
+ copySubMenu.push({
+ id: "request-list-context-copy-all-as-har",
+ label: L10N.getStr("netmonitor.context.copyAllAsHar"),
+ accesskey: L10N.getStr("netmonitor.context.copyAllAsHar.accesskey"),
+ visible: !!requests.length,
+ click: () => HarMenuUtils.copyAllAsHar(requests, connector),
+ });
+
+ return copySubMenu;
+ }
+
+ createMenu(clickedRequest, requests, blockedUrls) {
+ const {
+ connector,
+ cloneRequest,
+ openDetailsPanelTab,
+ openHTTPCustomRequestTab,
+ closeHTTPCustomRequestTab,
+ sendCustomRequest,
+ sendHTTPCustomRequest,
+ openStatistics,
+ openRequestInTab,
+ openRequestBlockingAndAddUrl,
+ openRequestBlockingAndDisableUrls,
+ removeBlockedUrl,
+ } = this.props;
+
+ const {
+ id,
+ isCustom,
+ method,
+ mimeType,
+ requestHeaders,
+ requestPostData,
+ responseContent,
+ responseContentAvailable,
+ url,
+ } = clickedRequest;
+
+ const copySubMenu = this.createCopySubMenu(clickedRequest, requests);
+ const newEditAndResendPref = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend"
+ );
+
+ return [
+ {
+ label: L10N.getStr("netmonitor.context.copyValue"),
+ accesskey: L10N.getStr("netmonitor.context.copyValue.accesskey"),
+ visible: !!clickedRequest,
+ submenu: copySubMenu,
+ },
+ {
+ id: "request-list-context-save-all-as-har",
+ label: L10N.getStr("netmonitor.context.saveAllAsHar"),
+ accesskey: L10N.getStr("netmonitor.context.saveAllAsHar.accesskey"),
+ visible: !!requests.length,
+ click: () => HarMenuUtils.saveAllAsHar(requests, connector),
+ },
+ {
+ id: "request-list-context-save-image-as",
+ label: L10N.getStr("netmonitor.context.saveImageAs"),
+ accesskey: L10N.getStr("netmonitor.context.saveImageAs.accesskey"),
+ visible: !!(
+ clickedRequest &&
+ (responseContentAvailable || responseContent) &&
+ mimeType &&
+ mimeType.includes("image/")
+ ),
+ click: () => this.saveImageAs(id, url, responseContent),
+ },
+ {
+ type: "separator",
+ visible: copySubMenu.slice(10, 14).some(subMenu => subMenu.visible),
+ },
+ {
+ id: "request-list-context-resend-only",
+ label: L10N.getStr("netmonitor.context.resend.label"),
+ accesskey: L10N.getStr("netmonitor.context.resend.accesskey"),
+ visible: !!(clickedRequest && !isCustom),
+ click: () => {
+ if (!newEditAndResendPref) {
+ cloneRequest(id);
+ sendCustomRequest();
+ } else {
+ sendHTTPCustomRequest(clickedRequest);
+ }
+ },
+ },
+
+ {
+ id: "request-list-context-edit-resend",
+ label: L10N.getStr("netmonitor.context.editAndResend"),
+ accesskey: L10N.getStr("netmonitor.context.editAndResend.accesskey"),
+ visible: !!(clickedRequest && !isCustom),
+ click: () => {
+ this.fetchRequestHeaders(id).then(() => {
+ if (!newEditAndResendPref) {
+ cloneRequest(id);
+ openDetailsPanelTab();
+ } else {
+ closeHTTPCustomRequestTab();
+ openHTTPCustomRequestTab();
+ }
+ });
+ },
+ },
+ {
+ id: "request-list-context-block-url",
+ label: L10N.getStr("netmonitor.context.blockURL"),
+ visible: !hasMatchingBlockingRequestPattern(
+ blockedUrls,
+ clickedRequest.url
+ ),
+ click: () => {
+ openRequestBlockingAndAddUrl(clickedRequest.url);
+ },
+ },
+ {
+ id: "request-list-context-unblock-url",
+ label: L10N.getStr("netmonitor.context.unblockURL"),
+ visible: hasMatchingBlockingRequestPattern(
+ blockedUrls,
+ clickedRequest.url
+ ),
+ click: () => {
+ if (
+ blockedUrls.find(blockedUrl => blockedUrl === clickedRequest.url)
+ ) {
+ removeBlockedUrl(clickedRequest.url);
+ } else {
+ openRequestBlockingAndDisableUrls(clickedRequest.url);
+ }
+ },
+ },
+ {
+ type: "separator",
+ visible: copySubMenu.slice(15, 16).some(subMenu => subMenu.visible),
+ },
+ {
+ id: "request-list-context-newtab",
+ label: L10N.getStr("netmonitor.context.newTab"),
+ accesskey: L10N.getStr("netmonitor.context.newTab.accesskey"),
+ visible: !!clickedRequest,
+ click: () => openRequestInTab(id, url, requestHeaders, requestPostData),
+ },
+ {
+ id: "request-list-context-open-in-debugger",
+ label: L10N.getStr("netmonitor.context.openInDebugger"),
+ accesskey: L10N.getStr("netmonitor.context.openInDebugger.accesskey"),
+ visible: !!(
+ clickedRequest &&
+ mimeType &&
+ mimeType.includes("javascript")
+ ),
+ click: () => this.openInDebugger(url),
+ },
+ {
+ id: "request-list-context-open-in-style-editor",
+ label: L10N.getStr("netmonitor.context.openInStyleEditor"),
+ accesskey: L10N.getStr(
+ "netmonitor.context.openInStyleEditor.accesskey"
+ ),
+ visible: !!(
+ clickedRequest &&
+ Services.prefs.getBoolPref("devtools.styleeditor.enabled") &&
+ mimeType &&
+ mimeType.includes("css")
+ ),
+ click: () => this.openInStyleEditor(url),
+ },
+ {
+ id: "request-list-context-perf",
+ label: L10N.getStr("netmonitor.context.perfTools"),
+ accesskey: L10N.getStr("netmonitor.context.perfTools.accesskey"),
+ visible: !!requests.length,
+ click: () => openStatistics(true),
+ },
+ {
+ type: "separator",
+ },
+ {
+ id: "request-list-context-use-as-fetch",
+ label: L10N.getStr("netmonitor.context.useAsFetch"),
+ accesskey: L10N.getStr("netmonitor.context.useAsFetch.accesskey"),
+ visible: !!clickedRequest,
+ click: () =>
+ this.useAsFetch(id, url, method, requestHeaders, requestPostData),
+ },
+ ];
+ }
+
+ open(event, clickedRequest, requests, blockedUrls) {
+ const menu = this.createMenu(clickedRequest, requests, blockedUrls);
+
+ showMenu(menu, {
+ screenX: event.screenX,
+ screenY: event.screenY,
+ });
+ }
+
+ /**
+ * Opens selected item in the debugger
+ */
+ openInDebugger(url) {
+ const toolbox = this.props.connector.getToolbox();
+ toolbox.viewGeneratedSourceInDebugger(url);
+ }
+
+ /**
+ * Opens selected item in the style editor
+ */
+ openInStyleEditor(url) {
+ const toolbox = this.props.connector.getToolbox();
+ toolbox.viewGeneratedSourceInStyleEditor(url);
+ }
+
+ /**
+ * Copy the request url from the currently selected item.
+ */
+ copyUrl(url) {
+ copyString(url);
+ }
+
+ /**
+ * Copy the request url query string parameters from the currently
+ * selected item.
+ */
+ copyUrlParams(url) {
+ const params = getUrlQuery(url).split("&");
+ copyString(params.join(Services.appinfo.OS === "WINNT" ? "\r\n" : "\n"));
+ }
+
+ /**
+ * Copy the request form data parameters (or raw payload) from
+ * the currently selected item.
+ */
+ async copyPostData(id, formDataSections, requestPostData) {
+ let params = [];
+ // Try to extract any form data parameters if formDataSections is already
+ // available, which is only true if RequestPanel has ever been mounted before.
+ if (formDataSections) {
+ formDataSections.forEach(section => {
+ const paramsArray = parseQueryString(section);
+ if (paramsArray) {
+ params = [...params, ...paramsArray];
+ }
+ });
+ }
+
+ let string = params
+ .map(param => param.name + (param.value ? "=" + param.value : ""))
+ .join(Services.appinfo.OS === "WINNT" ? "\r\n" : "\n");
+
+ // Fall back to raw payload.
+ if (!string) {
+ requestPostData =
+ requestPostData ||
+ (await this.props.connector.requestData(id, "requestPostData"));
+
+ string = requestPostData.postData.text;
+ if (Services.appinfo.OS !== "WINNT") {
+ string = string.replace(/\r/g, "");
+ }
+ }
+ copyString(string);
+ }
+
+ /**
+ * Copy a cURL command from the currently selected item.
+ */
+ async copyAsCurl(
+ id,
+ url,
+ method,
+ httpVersion,
+ requestHeaders,
+ requestPostData,
+ responseHeaders,
+ platform
+ ) {
+ requestHeaders =
+ requestHeaders ||
+ (await this.props.connector.requestData(id, "requestHeaders"));
+
+ requestPostData =
+ requestPostData ||
+ (await this.props.connector.requestData(id, "requestPostData"));
+
+ responseHeaders =
+ responseHeaders ||
+ (await this.props.connector.requestData(id, "responseHeaders"));
+
+ // Create a sanitized object for the Curl command generator.
+ const data = {
+ url,
+ method,
+ headers: requestHeaders.headers,
+ responseHeaders: responseHeaders.headers,
+ httpVersion,
+ postDataText: requestPostData ? requestPostData.postData.text : "",
+ };
+ copyString(Curl.generateCommand(data, platform));
+ }
+
+ async copyAsPowerShell(request) {
+ let { id, url, method, requestHeaders, requestPostData, requestCookies } =
+ request;
+
+ requestHeaders =
+ requestHeaders ||
+ (await this.props.connector.requestData(id, "requestHeaders"));
+
+ requestPostData =
+ requestPostData ||
+ (await this.props.connector.requestData(id, "requestPostData"));
+
+ requestCookies =
+ requestCookies ||
+ (await this.props.connector.requestData(id, "requestCookies"));
+
+ return copyString(
+ PowerShell.generateCommand(
+ url,
+ method,
+ requestHeaders.headers,
+ requestPostData.postData,
+ requestCookies.cookies || requestCookies
+ )
+ );
+ }
+
+ /**
+ * Generate fetch string
+ */
+ async generateFetchString(id, url, method, requestHeaders, requestPostData) {
+ requestHeaders =
+ requestHeaders ||
+ (await this.props.connector.requestData(id, "requestHeaders"));
+
+ requestPostData =
+ requestPostData ||
+ (await this.props.connector.requestData(id, "requestPostData"));
+
+ // https://fetch.spec.whatwg.org/#forbidden-header-name
+ const forbiddenHeaders = {
+ "accept-charset": 1,
+ "accept-encoding": 1,
+ "access-control-request-headers": 1,
+ "access-control-request-method": 1,
+ connection: 1,
+ "content-length": 1,
+ cookie: 1,
+ cookie2: 1,
+ date: 1,
+ dnt: 1,
+ expect: 1,
+ host: 1,
+ "keep-alive": 1,
+ origin: 1,
+ referer: 1,
+ te: 1,
+ trailer: 1,
+ "transfer-encoding": 1,
+ upgrade: 1,
+ via: 1,
+ };
+ const credentialHeaders = { cookie: 1, authorization: 1 };
+
+ const headers = {};
+ for (const { name, value } of requestHeaders.headers) {
+ if (!forbiddenHeaders[name.toLowerCase()]) {
+ headers[name] = value;
+ }
+ }
+
+ const referrerHeader = requestHeaders.headers.find(
+ ({ name }) => name.toLowerCase() === "referer"
+ );
+
+ const referrerPolicy = requestHeaders.headers.find(
+ ({ name }) => name.toLowerCase() === "referrer-policy"
+ );
+
+ const referrer = referrerHeader ? referrerHeader.value : undefined;
+ const credentials = requestHeaders.headers.some(
+ ({ name }) => credentialHeaders[name.toLowerCase()]
+ )
+ ? "include"
+ : "omit";
+
+ const fetchOptions = {
+ credentials,
+ headers,
+ referrer,
+ referrerPolicy,
+ body: requestPostData.postData.text,
+ method,
+ mode: "cors",
+ };
+
+ const options = JSON.stringify(fetchOptions, null, 4);
+ const fetchString = `await fetch("${url}", ${options});`;
+ return fetchString;
+ }
+
+ /**
+ * Copy the currently selected item as fetch request.
+ */
+ async copyAsFetch(id, url, method, requestHeaders, requestPostData) {
+ const fetchString = await this.generateFetchString(
+ id,
+ url,
+ method,
+ requestHeaders,
+ requestPostData
+ );
+ copyString(fetchString);
+ }
+
+ /**
+ * Open split console and fill it with fetch command for selected item
+ */
+ async useAsFetch(id, url, method, requestHeaders, requestPostData) {
+ const fetchString = await this.generateFetchString(
+ id,
+ url,
+ method,
+ requestHeaders,
+ requestPostData
+ );
+ const toolbox = this.props.connector.getToolbox();
+ await toolbox.openSplitConsole();
+ const { hud } = await toolbox.getPanel("webconsole");
+ hud.setInputValue(fetchString);
+ }
+
+ /**
+ * Copy the raw request headers from the currently selected item.
+ */
+ async copyRequestHeaders(
+ id,
+ { method, httpVersion, requestHeaders, urlDetails }
+ ) {
+ requestHeaders =
+ requestHeaders ||
+ (await this.props.connector.requestData(id, "requestHeaders"));
+
+ let rawHeaders = getRequestHeadersRawText(
+ method,
+ httpVersion,
+ requestHeaders,
+ urlDetails
+ );
+
+ if (Services.appinfo.OS !== "WINNT") {
+ rawHeaders = rawHeaders.replace(/\r/g, "");
+ }
+ copyString(rawHeaders);
+ }
+
+ /**
+ * Copy the raw response headers from the currently selected item.
+ */
+ async copyResponseHeaders(id, responseHeaders) {
+ responseHeaders =
+ responseHeaders ||
+ (await this.props.connector.requestData(id, "responseHeaders"));
+
+ let rawHeaders = responseHeaders.rawHeaders.trim();
+
+ if (Services.appinfo.OS !== "WINNT") {
+ rawHeaders = rawHeaders.replace(/\r/g, "");
+ }
+ copyString(rawHeaders);
+ }
+
+ /**
+ * Copy image as data uri.
+ */
+ async copyImageAsDataUri(id, mimeType, responseContent) {
+ responseContent =
+ responseContent ||
+ (await this.props.connector.requestData(id, "responseContent"));
+
+ const { encoding, text } = responseContent.content;
+ copyString(formDataURI(mimeType, encoding, text));
+ }
+
+ /**
+ * Save image as.
+ */
+ async saveImageAs(id, url, responseContent) {
+ responseContent =
+ responseContent ||
+ (await this.props.connector.requestData(id, "responseContent"));
+
+ const { encoding, text } = responseContent.content;
+ const fileName = getUrlBaseName(url);
+ let data;
+ if (encoding === "base64") {
+ const decoded = atob(text);
+ data = new Uint8Array(decoded.length);
+ for (let i = 0; i < decoded.length; ++i) {
+ data[i] = decoded.charCodeAt(i);
+ }
+ } else {
+ data = new TextEncoder().encode(text);
+ }
+ saveAs(window, data, fileName);
+ }
+
+ /**
+ * Copy response data as a string.
+ */
+ async copyResponse(id, responseContent) {
+ responseContent =
+ responseContent ||
+ (await this.props.connector.requestData(id, "responseContent"));
+
+ copyString(responseContent.content.text);
+ }
+
+ async fetchRequestHeaders(id) {
+ await this.props.connector.requestData(id, "requestHeaders");
+ }
+}
+
+module.exports = RequestListContextMenu;
diff --git a/devtools/client/netmonitor/src/widgets/RequestListHeaderContextMenu.js b/devtools/client/netmonitor/src/widgets/RequestListHeaderContextMenu.js
new file mode 100644
index 0000000000..02ee502790
--- /dev/null
+++ b/devtools/client/netmonitor/src/widgets/RequestListHeaderContextMenu.js
@@ -0,0 +1,105 @@
+/* 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 {
+ HEADERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getVisibleColumns,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+const stringMap = HEADERS.filter(header =>
+ header.hasOwnProperty("label")
+).reduce((acc, { name, label }) => Object.assign(acc, { [name]: label }), {});
+
+const subMenuMap = HEADERS.filter(header =>
+ header.hasOwnProperty("subMenu")
+).reduce(
+ (acc, { name, subMenu }) => Object.assign(acc, { [name]: subMenu }),
+ {}
+);
+
+const nonLocalizedHeaders = HEADERS.filter(header =>
+ header.hasOwnProperty("noLocalization")
+).map(header => header.name);
+
+class RequestListHeaderContextMenu {
+ constructor(props) {
+ this.props = props;
+ }
+
+ /**
+ * Handle the context menu opening.
+ */
+ open(event = {}, columns) {
+ const menu = [];
+ const subMenu = { timings: [], responseHeaders: [] };
+ const onlyOneColumn = getVisibleColumns(columns).length === 1;
+
+ for (const column in columns) {
+ const shown = columns[column];
+ const label = nonLocalizedHeaders.includes(column)
+ ? stringMap[column] || column
+ : L10N.getStr(`netmonitor.toolbar.${stringMap[column] || column}`);
+ const entry = {
+ id: `request-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,
+ };
+ subMenuMap.hasOwnProperty(column)
+ ? subMenu[subMenuMap[column]].push(entry)
+ : menu.push(entry);
+ }
+
+ menu.push({ type: "separator" });
+ menu.push({
+ label: L10N.getStr("netmonitor.toolbar.timings"),
+ submenu: subMenu.timings,
+ });
+ menu.push({
+ label: L10N.getStr("netmonitor.toolbar.responseHeaders"),
+ submenu: subMenu.responseHeaders,
+ });
+
+ menu.push({ type: "separator" });
+ menu.push({
+ id: "request-list-header-reset-columns",
+ label: L10N.getStr("netmonitor.toolbar.resetColumns"),
+ click: () => this.props.resetColumns(),
+ });
+
+ menu.push({
+ id: "request-list-header-reset-sorting",
+ label: L10N.getStr("netmonitor.toolbar.resetSorting"),
+ click: () => this.props.resetSorting(),
+ });
+
+ const columnName = event.target.getAttribute("data-name");
+
+ menu.push({
+ id: "request-list-header-resize-column-to-fit-content",
+ label: L10N.getStr("netmonitor.toolbar.resizeColumnToFitContent"),
+ click: () => this.props.resizeColumnToFitContent(columnName),
+ });
+
+ showMenu(menu, {
+ screenX: event.screenX,
+ screenY: event.screenY,
+ });
+ }
+}
+
+module.exports = RequestListHeaderContextMenu;
diff --git a/devtools/client/netmonitor/src/widgets/WaterfallBackground.js b/devtools/client/netmonitor/src/widgets/WaterfallBackground.js
new file mode 100644
index 0000000000..e2be7f5715
--- /dev/null
+++ b/devtools/client/netmonitor/src/widgets/WaterfallBackground.js
@@ -0,0 +1,163 @@
+/* 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 { getColor } = require("resource://devtools/client/shared/theme.js");
+const { colorUtils } = require("resource://devtools/shared/css/color.js");
+const {
+ REQUESTS_WATERFALL,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const HTML_NS = "http://www.w3.org/1999/xhtml";
+const STATE_KEYS = [
+ "firstRequestStartedMs",
+ "scale",
+ "timingMarkers",
+ "waterfallWidth",
+];
+
+/**
+ * Creates the background displayed on each waterfall view in this container.
+ */
+class WaterfallBackground {
+ constructor() {
+ this.canvas = document.createElementNS(HTML_NS, "canvas");
+ this.ctx = this.canvas.getContext("2d");
+ this.prevState = {};
+ }
+
+ /**
+ * Changes the element being used as the CSS background for a background
+ * with a given background element ID.
+ *
+ * The funtion wrap the Firefox only API. Waterfall Will not draw the
+ * vertical line when running on non-firefox browser.
+ * Could be fixed by Bug 1308695
+ */
+ setImageElement(imageElementId, imageElement) {
+ if (document.mozSetImageElement) {
+ document.mozSetImageElement(imageElementId, imageElement);
+ }
+ }
+
+ draw(state) {
+ // Do a shallow compare of the previous and the new state
+ const shouldUpdate = STATE_KEYS.some(
+ key => this.prevState[key] !== state[key]
+ );
+ if (!shouldUpdate) {
+ return;
+ }
+
+ this.prevState = state;
+
+ if (state.waterfallWidth === null || state.scale === null) {
+ this.setImageElement("waterfall-background", null);
+ return;
+ }
+
+ // Nuke the context.
+ const canvasWidth = (this.canvas.width = Math.max(
+ state.waterfallWidth - REQUESTS_WATERFALL.LABEL_WIDTH,
+ 1
+ ));
+ // Awww yeah, 1px, repeats on Y axis.
+ const canvasHeight = (this.canvas.height = 1);
+
+ // Start over.
+ const imageData = this.ctx.createImageData(canvasWidth, canvasHeight);
+ const pixelArray = imageData.data;
+
+ const buf = new ArrayBuffer(pixelArray.length);
+ const view8bit = new Uint8ClampedArray(buf);
+ const view32bit = new Uint32Array(buf);
+
+ // Build new millisecond tick lines...
+ let timingStep = REQUESTS_WATERFALL.BACKGROUND_TICKS_MULTIPLE;
+ let optimalTickIntervalFound = false;
+ let scaledStep;
+
+ while (!optimalTickIntervalFound) {
+ // Ignore any divisions that would end up being too close to each other.
+ scaledStep = state.scale * timingStep;
+ if (scaledStep < REQUESTS_WATERFALL.BACKGROUND_TICKS_SPACING_MIN) {
+ timingStep <<= 1;
+ continue;
+ }
+ optimalTickIntervalFound = true;
+ }
+
+ const isRTL = document.dir === "rtl";
+ const [r, g, b] = REQUESTS_WATERFALL.BACKGROUND_TICKS_COLOR_RGB;
+ let alphaComponent = REQUESTS_WATERFALL.BACKGROUND_TICKS_OPACITY_MIN;
+
+ function drawPixelAt(offset, color) {
+ const position = (isRTL ? canvasWidth - offset : offset - 1) | 0;
+ const [rc, gc, bc, ac] = color;
+ view32bit[position] = (ac << 24) | (bc << 16) | (gc << 8) | rc;
+ }
+
+ // Insert one pixel for each division on each scale.
+ for (let i = 1; i <= REQUESTS_WATERFALL.BACKGROUND_TICKS_SCALES; i++) {
+ const increment = scaledStep * Math.pow(2, i);
+ for (let x = 0; x < canvasWidth; x += increment) {
+ drawPixelAt(x, [r, g, b, alphaComponent]);
+ }
+ alphaComponent += REQUESTS_WATERFALL.BACKGROUND_TICKS_OPACITY_ADD;
+ }
+
+ function drawTimestamp(timestamp, color) {
+ if (timestamp === -1) {
+ return;
+ }
+
+ const delta = Math.floor(
+ (timestamp - state.firstRequestStartedMs) * state.scale
+ );
+ drawPixelAt(delta, color);
+ }
+
+ const { DOMCONTENTLOADED_TICKS_COLOR, LOAD_TICKS_COLOR } =
+ REQUESTS_WATERFALL;
+ drawTimestamp(
+ state.timingMarkers.firstDocumentDOMContentLoadedTimestamp,
+ this.getThemeColorAsRgba(DOMCONTENTLOADED_TICKS_COLOR, state.theme)
+ );
+
+ drawTimestamp(
+ state.timingMarkers.firstDocumentLoadTimestamp,
+ this.getThemeColorAsRgba(LOAD_TICKS_COLOR, state.theme)
+ );
+
+ // Flush the image data and cache the waterfall background.
+ pixelArray.set(view8bit);
+ this.ctx.putImageData(imageData, 0, 0);
+
+ this.setImageElement("waterfall-background", this.canvas);
+ }
+
+ /**
+ * Retrieve a color defined for the provided theme as a rgba array. The alpha channel is
+ * forced to the waterfall constant TICKS_COLOR_OPACITY.
+ *
+ * @param {String} colorName
+ * The name of the theme color
+ * @param {String} theme
+ * The name of the theme
+ * @return {Array} RGBA array for the color.
+ */
+ getThemeColorAsRgba(colorName, theme) {
+ const colorStr = getColor(colorName, theme);
+ const color = new colorUtils.CssColor(colorStr);
+ const { r, g, b } = color.getRGBATuple();
+ return [r, g, b, REQUESTS_WATERFALL.TICKS_COLOR_OPACITY];
+ }
+
+ destroy() {
+ this.setImageElement("waterfall-background", null);
+ }
+}
+
+module.exports = WaterfallBackground;
diff --git a/devtools/client/netmonitor/src/widgets/moz.build b/devtools/client/netmonitor/src/widgets/moz.build
new file mode 100644
index 0000000000..106deca935
--- /dev/null
+++ b/devtools/client/netmonitor/src/widgets/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(
+ "HeadersPanelContextMenu.js",
+ "PropertiesViewContextMenu.js",
+ "RequestBlockingContextMenu.js",
+ "RequestListContextMenu.js",
+ "RequestListHeaderContextMenu.js",
+ "WaterfallBackground.js",
+)
diff --git a/devtools/client/netmonitor/src/workers/moz.build b/devtools/client/netmonitor/src/workers/moz.build
new file mode 100644
index 0000000000..a1384c1e10
--- /dev/null
+++ b/devtools/client/netmonitor/src/workers/moz.build
@@ -0,0 +1,8 @@
+# vim: set filetype=python:
+# 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 += [
+ "search",
+]
diff --git a/devtools/client/netmonitor/src/workers/search/index.js b/devtools/client/netmonitor/src/workers/search/index.js
new file mode 100644
index 0000000000..a721454034
--- /dev/null
+++ b/devtools/client/netmonitor/src/workers/search/index.js
@@ -0,0 +1,25 @@
+/* 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 {
+ WorkerDispatcher,
+} = require("resource://devtools/client/shared/worker-utils.js");
+
+const SEARCH_WORKER_URL =
+ "resource://devtools/client/netmonitor/src/workers/search/worker.js";
+
+class SearchDispatcher extends WorkerDispatcher {
+ constructor() {
+ super(SEARCH_WORKER_URL);
+ }
+
+ // The search worker support just one task at this point,
+ // which is searching through specified resource.
+ searchInResource = this.task("searchInResource");
+}
+
+// Compared to debugger, we instantiate a singleton within the dispatcher module
+module.exports = new SearchDispatcher();
diff --git a/devtools/client/netmonitor/src/workers/search/moz.build b/devtools/client/netmonitor/src/workers/search/moz.build
new file mode 100644
index 0000000000..ee5a5dd950
--- /dev/null
+++ b/devtools/client/netmonitor/src/workers/search/moz.build
@@ -0,0 +1,10 @@
+# vim: set filetype=python:
+# 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",
+ "search.js",
+ "worker.js",
+)
diff --git a/devtools/client/netmonitor/src/workers/search/search.js b/devtools/client/netmonitor/src/workers/search/search.js
new file mode 100644
index 0000000000..880f5357b2
--- /dev/null
+++ b/devtools/client/netmonitor/src/workers/search/search.js
@@ -0,0 +1,349 @@
+/* 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/. */
+/* eslint-disable no-unused-vars */
+
+"use strict";
+
+/**
+ * Search within specified resource. Note that this function runs
+ * within a worker thread.
+ */
+function searchInResource(resource, query, modifiers) {
+ const results = [];
+
+ if (resource.url) {
+ results.push(
+ findMatches(resource, query, modifiers, {
+ key: "url",
+ label: "Url",
+ type: "url",
+ panel: "headers",
+ })
+ );
+ }
+
+ if (resource.responseHeaders) {
+ results.push(
+ findMatches(resource, query, modifiers, {
+ key: "responseHeaders.headers",
+ type: "responseHeaders",
+ panel: "headers",
+ })
+ );
+ }
+
+ if (resource.requestHeaders) {
+ results.push(
+ findMatches(resource, query, modifiers, {
+ key: "requestHeaders.headers",
+ type: "requestHeaders",
+ panel: "headers",
+ })
+ );
+ }
+
+ if (resource.requestHeadersFromUploadStream) {
+ results.push(
+ findMatches(resource, query, modifiers, {
+ key: "requestHeadersFromUploadStream.headers",
+ type: "requestHeadersFromUploadStream",
+ panel: "headers",
+ })
+ );
+ }
+
+ if (resource.responseCookies) {
+ let key = "responseCookies";
+
+ if (resource.responseCookies.cookies) {
+ key = "responseCookies.cookies";
+ }
+
+ results.push(
+ findMatches(resource, query, modifiers, {
+ key,
+ type: "responseCookies",
+ panel: "cookies",
+ })
+ );
+ }
+
+ if (resource.requestCookies) {
+ let key = "requestCookies";
+
+ if (resource.requestCookies.cookies) {
+ key = "requestCookies.cookies";
+ }
+
+ results.push(
+ findMatches(resource, query, modifiers, {
+ key,
+ type: "requestCookies",
+ panel: "cookies",
+ })
+ );
+ }
+
+ if (resource.responseContent) {
+ results.push(
+ findMatches(resource, query, modifiers, {
+ key: "responseContent.content.text",
+ type: "responseContent",
+ panel: "response",
+ })
+ );
+ }
+
+ if (resource.requestPostData) {
+ results.push(
+ findMatches(resource, query, modifiers, {
+ key: "requestPostData.postData.text",
+ type: "requestPostData",
+ panel: "request",
+ })
+ );
+ }
+
+ return getResults(results, resource);
+}
+
+/**
+ * Concatenates all results
+ * @param results
+ * @returns {*[]}
+ */
+function getResults(results, resource) {
+ const tempResults = [].concat.apply([], results);
+
+ // Generate unique result keys
+ tempResults.forEach((result, index) => {
+ result.key = index;
+ result.parentResource = resource;
+ });
+
+ return tempResults;
+}
+
+function find(query, modifiers, source) {
+ const { caseSensitive } = modifiers;
+ const value = caseSensitive ? source : source.toLowerCase();
+ const q = caseSensitive ? query : query.toLowerCase();
+
+ return value.includes(q);
+}
+
+/**
+ * Find query matches in arrays, objects and strings.
+ * @param resource
+ * @param query
+ * @param modifiers
+ * @param data
+ * @returns {*[]|[]|Array|*}
+ */
+function findMatches(resource, query, modifiers, data) {
+ if (!resource || !query || !modifiers || !data) {
+ return [];
+ }
+
+ const resourceValue = getValue(data.key, resource);
+ const resourceType = getType(resourceValue);
+
+ if (resource.hasOwnProperty("name") && resource.hasOwnProperty("value")) {
+ return searchInProperties(query, modifiers, resource, data);
+ }
+
+ switch (resourceType) {
+ case "string":
+ return searchInText(query, modifiers, resourceValue, data);
+ case "array":
+ return searchInArray(query, modifiers, resourceValue, data);
+ case "object":
+ return searchInObject(query, modifiers, resourceValue, data);
+ default:
+ return [];
+ }
+}
+
+function searchInProperties(query, modifiers, obj, data) {
+ const { name, value } = obj;
+ const match = {
+ ...data,
+ };
+
+ if (find(query, modifiers, name)) {
+ match.label = name;
+ }
+
+ if (find(query, modifiers, name) || find(query, modifiers, value)) {
+ match.value = value;
+ match.startIndex = value.indexOf(query);
+
+ return match;
+ }
+
+ return [];
+}
+
+/**
+ * Get type of resource - deals with arrays as well.
+ * @param resource
+ * @returns {*}
+ */
+function getType(resource) {
+ return Array.isArray(resource) ? "array" : typeof resource;
+}
+
+/**
+ * Function returns the value of a key, included nested keys.
+ * @param path
+ * @param obj
+ * @returns {*}
+ */
+function getValue(path, obj) {
+ const properties = Array.isArray(path) ? path : path.split(".");
+ return properties.reduce((prev, curr) => prev?.[curr], obj);
+}
+
+/**
+ * Search text for specific string and return all matches found
+ * @param query
+ * @param modifiers
+ * @param text
+ * @param data
+ * @returns {*}
+ */
+function searchInText(query, modifiers, text, data) {
+ const { type } = data;
+ const lines = text.split(/\r\n|\r|\n/);
+ const matches = [];
+
+ // iterate through each line
+ lines.forEach((curr, i) => {
+ const { caseSensitive } = modifiers;
+ const flags = caseSensitive ? "g" : "gi";
+ const regexQuery = RegExp(
+ caseSensitive ? query : query.toLowerCase(),
+ flags
+ );
+ const lineMatches = [];
+ let singleMatch;
+
+ while ((singleMatch = regexQuery.exec(lines[i])) !== null) {
+ const startIndex = regexQuery.lastIndex;
+ lineMatches.push(startIndex);
+ }
+
+ if (lineMatches.length !== 0) {
+ const line = i + 1;
+ const match = {
+ ...data,
+ label: type !== "url" ? line + "" : "Url",
+ line,
+ startIndex: lineMatches,
+ };
+
+ match.value =
+ lineMatches.length === 1
+ ? getTruncatedValue(lines[i], query, lineMatches[0])
+ : lines[i];
+
+ matches.push(match);
+ }
+ });
+
+ return matches.length === 0 ? [] : matches;
+}
+
+/**
+ * Search for query in array.
+ * Iterates through each array item and handles item based on type.
+ * @param query
+ * @param modifiers
+ * @param arr
+ * @param data
+ * @returns {*[]}
+ */
+function searchInArray(query, modifiers, arr, data) {
+ const { key, label } = data;
+ const matches = arr.map((match, i) =>
+ findMatches(match, query, modifiers, {
+ ...data,
+ label: match.hasOwnProperty("name") ? match.name : label,
+ key: key + ".[" + i + "]",
+ })
+ );
+
+ return getResults(matches);
+}
+
+/**
+ * Return query match and up to 50 characters on left and right.
+ * (50) + [matched query] + (50)
+ * @param value
+ * @param query
+ * @param startIndex
+ * @returns {*}
+ */
+function getTruncatedValue(value, query, startIndex) {
+ const valueSize = value.length;
+ const indexEnd = startIndex + query.length;
+
+ if (valueSize < 100 + query.length) {
+ return value;
+ }
+
+ const start = value.substring(startIndex, startIndex - 50);
+ const end = value.substring(indexEnd, indexEnd + 50);
+
+ return start + end;
+}
+
+/**
+ * Iterates through object, including nested objects, returns all
+ * @param query
+ * @param modifiers
+ * @param obj
+ * @param data
+ * @returns {*|[]}
+ */
+function searchInObject(query, modifiers, obj, data) {
+ const matches = data.hasOwnProperty("collector") ? data.collector : [];
+ const { caseSensitive } = modifiers;
+
+ for (const objectKey in obj) {
+ const objectKeyType = getType(obj[objectKey]);
+
+ // if the value is an object, send to search in object
+ if (objectKeyType === "object" && Object.keys(obj[objectKey].length > 1)) {
+ searchInObject(query, obj[objectKey], {
+ ...data,
+ collector: matches,
+ });
+
+ continue;
+ }
+
+ const value = !caseSensitive
+ ? obj[objectKey].toLowerCase()
+ : obj[objectKey];
+ const key = !caseSensitive ? objectKey.toLowerCase() : objectKey;
+ const q = !caseSensitive ? query.toLowerCase() : query;
+
+ if ((objectKeyType === "string" && value.includes(q)) || key.includes(q)) {
+ const match = {
+ ...data,
+ };
+
+ const startIndex = value.indexOf(q);
+
+ match.label = objectKey;
+ match.startIndex = startIndex;
+ match.value = getTruncatedValue(obj[objectKey], query, startIndex);
+
+ matches.push(match);
+ }
+ }
+
+ return matches;
+}
diff --git a/devtools/client/netmonitor/src/workers/search/worker.js b/devtools/client/netmonitor/src/workers/search/worker.js
new file mode 100644
index 0000000000..825bf34360
--- /dev/null
+++ b/devtools/client/netmonitor/src/workers/search/worker.js
@@ -0,0 +1,17 @@
+/* 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";
+
+/* eslint-env worker */
+
+/* import-globals-from search.js */
+/* import-globals-from ../../../../shared/worker-utils.js */
+importScripts(
+ "resource://devtools/client/netmonitor/src/workers/search/search.js",
+ "resource://devtools/client/shared/worker-utils.js"
+);
+
+// Implementation of search worker (runs in worker scope).
+self.onmessage = workerHandler({ searchInResource });
diff --git a/devtools/client/netmonitor/test/.eslintrc.js b/devtools/client/netmonitor/test/.eslintrc.js
new file mode 100644
index 0000000000..d6776ad3f7
--- /dev/null
+++ b/devtools/client/netmonitor/test/.eslintrc.js
@@ -0,0 +1,7 @@
+"use strict";
+
+module.exports = {
+ env: {
+ jest: true,
+ },
+};
diff --git a/devtools/client/netmonitor/test/OstrichLicense.txt b/devtools/client/netmonitor/test/OstrichLicense.txt
new file mode 100644
index 0000000000..14c043d601
--- /dev/null
+++ b/devtools/client/netmonitor/test/OstrichLicense.txt
@@ -0,0 +1,41 @@
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+
+5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file
diff --git a/devtools/client/netmonitor/test/browser.ini b/devtools/client/netmonitor/test/browser.ini
new file mode 100644
index 0000000000..6f1b9ba904
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser.ini
@@ -0,0 +1,330 @@
+[DEFAULT]
+tags = devtools
+subsuite = devtools
+skip-if = http3 # Bug 1829298
+support-files =
+ dropmarker.svg
+ file_ws_backend_wsh.py
+ head.js
+ html_cause-test-page.html
+ html_content-type-without-cache-test-page.html
+ html_brotli-test-page.html
+ html_image-tooltip-test-page.html
+ html_cache-test-page.html
+ html_cors-test-page.html
+ html_csp-frame-test-page.html
+ html_csp-resend-test-page.html
+ html_csp-test-page.html
+ html_custom-get-page.html
+ html_cyrillic-test-page.html
+ html_fonts-test-page.html
+ html_frame-test-page.html
+ html_frame-subdocument.html
+ html_filter-test-page.html
+ html_infinite-get-page.html
+ html_internal-stylesheet.html
+ html_json-b64.html
+ html_json-basic.html
+ html_json-custom-mime-test-page.html
+ html_json-empty.html
+ html_json-long-test-page.html
+ html_json-malformed-test-page.html
+ html_json-text-mime-test-page.html
+ html_json-xssi-protection.html
+ html_jsonp-test-page.html
+ html_maps-test-page.html
+ html_navigate-test-page.html
+ html_params-test-page.html
+ html_pause-test-page.html
+ html_post-data-test-page.html
+ html_post-array-data-test-page.html
+ html_post-json-test-page.html
+ html_post-raw-test-page.html
+ html_header-test-page.html
+ html_post-raw-with-headers-test-page.html
+ html_simple-test-page.html
+ html_single-get-page.html
+ html_slow-requests-test-page.html
+ html_send-beacon.html
+ html_sorting-test-page.html
+ html_statistics-edge-case-page.html
+ html_statistics-test-page.html
+ html_status-codes-test-page.html
+ html_tracking-protection.html
+ html_api-calls-test-page.html
+ html_copy-as-curl.html
+ html_curl-utils.html
+ html_open-request-in-tab.html
+ html_worker-test-page.html
+ html_websocket-test-page.html
+ html_ws-early-connection-page.html
+ html_ws-test-page.html
+ html_sse-test-page.html
+ html_ws-sse-test-page.html
+ html_image-cache.html
+ js_worker-test.js
+ js_worker-test2.js
+ js_websocket-worker-test.js
+ sjs_content-type-test-server.sjs
+ sjs_cors-test-server.sjs
+ sjs_https-redirect-test-server.sjs
+ sjs_hsts-test-server.sjs
+ sjs_json-test-server.sjs
+ sjs_long-polling-server.sjs
+ sjs_search-test-server.sjs
+ sjs_method-test-server.sjs
+ sjs_set-cookie-same-site.sjs
+ sjs_simple-test-server.sjs
+ sjs_simple-unsorted-cookies-test-server.sjs
+ sjs_slow-script-server.sjs
+ sjs_slow-test-server.sjs
+ sjs_sorting-test-server.sjs
+ sjs_sse-test-server.sjs
+ sjs_status-codes-test-server.sjs
+ sjs_timings-test-server.sjs
+ sjs_truncate-test-server.sjs
+ test-image.png
+ ostrich-regular.ttf
+ ostrich-black.ttf
+ service-workers/status-codes.html
+ service-workers/status-codes-service-worker.js
+ xhr_bundle.js
+ xhr_bundle.js.map
+ xhr_original.js
+ !/devtools/client/shared/test/shared-head.js
+ !/devtools/client/shared/test/telemetry-test-helpers.js
+ !/devtools/client/webconsole/test/browser/shared-head.js
+
+[browser_net-ws-filter-freetext.js]
+[browser_net_accessibility-01.js]
+[browser_net_accessibility-02.js]
+[browser_net_api-calls.js]
+[browser_net_autoscroll.js]
+[browser_net_background_update.js]
+[browser_net_basic-search.js]
+[browser_net_block-context.js]
+[browser_net_block-csp.js]
+[browser_net_block-draganddrop.js]
+[browser_net_block-extensions.js]
+[browser_net_block-pattern.js]
+skip-if = (os == 'linux') || debug && (os == 'win' || os == 'mac') # Bug 1603355
+[browser_net_block-serviceworker.js]
+[browser_net_block.js]
+[browser_net_brotli.js]
+[browser_net_cache_details.js]
+[browser_net_cached-status.js]
+skip-if =
+ verify
+ win10_2004 # Bug 1723573
+ win11_2009 # Bug 1797751
+[browser_net_cause_redirect.js]
+[browser_net_cause_source_map.js]
+[browser_net_charts-01.js]
+[browser_net_charts-02.js]
+[browser_net_charts-03.js]
+[browser_net_charts-04.js]
+[browser_net_charts-05.js]
+[browser_net_charts-06.js]
+[browser_net_charts-07.js]
+[browser_net_clear.js]
+[browser_net_column-resize-fit.js]
+[browser_net_column_headers_tooltips.js]
+[browser_net_column_slow-request-indicator.js]
+[browser_net_columns_last_column.js]
+[browser_net_columns_pref.js]
+[browser_net_columns_reset.js]
+[browser_net_columns_showhide.js]
+[browser_net_columns_time.js]
+skip-if =
+ win10_2004 # Bug 1723573
+ win11_2009 # Bug 1797751
+[browser_net_complex-params.js]
+skip-if =
+ (verify && !debug && (os == 'win'))
+ win10_2004 # Bug 1723573
+ win11_2009 # Bug 1797751
+[browser_net_content-type.js]
+skip-if = !debug && os == 'mac'
+[browser_net_cookies_sorted.js]
+skip-if = (verify && debug && os == 'win')
+[browser_net_copy_as_curl.js]
+[browser_net_copy_as_fetch.js]
+[browser_net_copy_as_powershell.js]
+[browser_net_copy_headers.js]
+[browser_net_copy_image_as_data_uri.js]
+[browser_net_copy_params.js]
+skip-if =
+ win10_2004 # Bug 1723573
+ win11_2009 # Bug 1797751
+ (verify && !debug && (os == 'mac')) # bug 1328915, disable linux32 debug devtools for timeouts
+[browser_net_copy_response.js]
+[browser_net_copy_svg_image_as_data_uri.js]
+[browser_net_copy_url.js]
+[browser_net_cors_requests.js]
+[browser_net_curl-utils.js]
+skip-if = win10_2004 # Bug 1723573
+[browser_net_cyrillic-01.js]
+[browser_net_cyrillic-02.js]
+[browser_net_decode-params.js]
+[browser_net_decode-url.js]
+[browser_net_details_copy.js]
+[browser_net_domain-not-found.js]
+[browser_net_edit_resend_cancel.js]
+[browser_net_edit_resend_caret.js]
+[browser_net_edit_resend_with_filtering.js]
+[browser_net_edit_resend_xhr.js]
+[browser_net_error-boundary-01.js]
+[browser_net_filter-01.js]
+[browser_net_filter-02.js]
+[browser_net_filter-03.js]
+[browser_net_filter-04.js]
+[browser_net_filter-autocomplete.js]
+[browser_net_filter-flags.js]
+[browser_net_filter-sts-search.js]
+[browser_net_filter-value-preserved.js]
+[browser_net_fission_switch_target.js]
+skip-if = verify # Bug 1607678
+[browser_net_fonts.js]
+skip-if = win10_2004 # Bug 1723573
+[browser_net_footer-summary.js]
+[browser_net_frame.js]
+skip-if = true # Bug 1479782
+[browser_net_header-docs.js]
+[browser_net_header-ref-policy.js]
+[browser_net_header-request-priority.js]
+[browser_net_headers-alignment.js]
+[browser_net_headers-link_clickable.js]
+[browser_net_headers-resize.js]
+[browser_net_headers_filter.js]
+[browser_net_headers_sorted.js]
+[browser_net_html-preview.js]
+[browser_net_image-tooltip.js]
+[browser_net_image_cache.js]
+[browser_net_initiator.js]
+[browser_net_internal-stylesheet.js]
+[browser_net_json-b64.js]
+[browser_net_json-empty.js]
+[browser_net_json-long.js]
+[browser_net_json-malformed.js]
+[browser_net_json-nogrip.js]
+[browser_net_json-null.js]
+[browser_net_json-xssi-protection.js]
+[browser_net_json_custom_mime.js]
+[browser_net_json_text_mime.js]
+[browser_net_jsonp.js]
+[browser_net_large-response.js]
+[browser_net_leak_on_tab_close.js]
+[browser_net_new_request_panel.js]
+[browser_net_new_request_panel_clear_button.js]
+[browser_net_new_request_panel_content-length.js]
+[browser_net_new_request_panel_context_menu.js]
+[browser_net_new_request_panel_persisted_content.js]
+[browser_net_new_request_panel_send_request.js]
+[browser_net_new_request_panel_sync_url_params.js]
+[browser_net_open_in_debugger.js]
+[browser_net_open_in_style_editor.js]
+[browser_net_open_request_in_tab.js]
+[browser_net_pane-collapse.js]
+[browser_net_pane-network-details.js]
+[browser_net_pane-toggle.js]
+[browser_net_params_sorted.js]
+[browser_net_pause.js]
+skip-if = (verify && debug && (os == 'win'))
+[browser_net_persistent_logs.js]
+skip-if = true #Bug 1661612
+[browser_net_post-data-json-payloads.js]
+[browser_net_post-data-raw-payloads-with-upload-stream-headers.js]
+[browser_net_post-data-raw-payloads.js]
+[browser_net_post-data.js]
+[browser_net_prefs-and-l10n.js]
+[browser_net_prefs-reload.js]
+skip-if = os == 'win' # bug 1391264
+[browser_net_raw_headers.js]
+[browser_net_reload-button.js]
+[browser_net_reload-markers.js]
+[browser_net_req-resp-bodies.js]
+[browser_net_resend.js]
+[browser_net_resend_cors.js]
+[browser_net_resend_csp.js]
+[browser_net_resend_headers.js]
+[browser_net_resend_hidden_headers.js]
+[browser_net_resend_xhr.js]
+[browser_net_response_CORS_blocked.js]
+skip-if = a11y_checks && (os == 'linux') && !debug # bug 1732635
+[browser_net_response_node-expanded.js]
+[browser_net_search-results.js]
+skip-if = (os == 'linux' && a11y_checks) # Bug 1721160
+[browser_net_security-details.js]
+[browser_net_security-error.js]
+[browser_net_security-icon-click.js]
+[browser_net_security-redirect.js]
+[browser_net_security-state.js]
+[browser_net_security-tab-deselect.js]
+[browser_net_security-tab-visibility.js]
+[browser_net_security-warnings.js]
+[browser_net_send-beacon-other-tab.js]
+[browser_net_send-beacon.js]
+[browser_net_server_timings.js]
+[browser_net_service-worker-status.js]
+skip-if = (verify && !debug && (os == 'linux'))
+[browser_net_set-cookie-same-site.js]
+[browser_net_simple-request-data.js]
+skip-if = true #Bug 1667115
+[browser_net_simple-request-details.js]
+[browser_net_simple-request.js]
+[browser_net_sort-01.js]
+[browser_net_sort-02.js]
+[browser_net_sort-reset.js]
+[browser_net_sse-basic.js]
+[browser_net_stacktraces-visibility.js]
+[browser_net_statistics-01.js]
+skip-if = true # Bug 1373558
+[browser_net_statistics-02.js]
+[browser_net_statistics-edge-case.js]
+[browser_net_status-bar-transferred-size.js]
+[browser_net_status-bar.js]
+skip-if = win10_2004 # Bug 1723573
+[browser_net_status-codes.js]
+[browser_net_streaming-response.js]
+[browser_net_tabbar_focus.js]
+[browser_net_telemetry_edit_resend.js]
+[browser_net_telemetry_filters_changed.js]
+[browser_net_telemetry_persist_toggle_changed.js]
+[browser_net_telemetry_select_ws_frame.js]
+[browser_net_telemetry_sidepanel_changed.js]
+[browser_net_telemetry_throttle_changed.js]
+[browser_net_throttle.js]
+[browser_net_throttling_profiles.js]
+[browser_net_timeline_ticks.js]
+skip-if = true # TODO: fix the test
+[browser_net_timing-division.js]
+[browser_net_tracking-resources.js]
+[browser_net_truncate-post-data.js]
+skip-if =
+ os == 'win' && os_version == '6.1' && !debug # Bug 1547150
+ socketprocess_networking # Bug 1772211
+[browser_net_truncate.js]
+[browser_net_url-preview.js]
+[browser_net_use_as_fetch.js]
+[browser_net_view-source-debugger.js]
+[browser_net_waterfall-click.js]
+[browser_net_websocket_stacks.js]
+[browser_net_worker_stacks.js]
+skip-if =
+ win10_2004 # Bug 1723573
+[browser_net_ws-basic.js]
+[browser_net_ws-clear.js]
+[browser_net_ws-connection-closed.js]
+[browser_net_ws-early-connection.js]
+[browser_net_ws-filter-dropdown.js]
+[browser_net_ws-filter-regex.js]
+[browser_net_ws-json-action-cable-payload.js]
+[browser_net_ws-json-payload.js]
+[browser_net_ws-json-stomp-payload.js]
+[browser_net_ws-keep-future-frames.js]
+[browser_net_ws-limit-frames.js]
+[browser_net_ws-limit-payload.js]
+[browser_net_ws-messages-navigation.js]
+[browser_net_ws-sockjs-stomp-payload.js]
+[browser_net_ws-sse-persist-columns.js]
+[browser_net_ws-stomp-payload.js]
diff --git a/devtools/client/netmonitor/test/browser_http3.ini b/devtools/client/netmonitor/test/browser_http3.ini
new file mode 100644
index 0000000000..82f9162b4a
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_http3.ini
@@ -0,0 +1,11 @@
+[DEFAULT]
+tags = devtools
+subsuite = devtools
+skip-if = !http3
+support-files =
+ head.js
+ !/devtools/client/shared/test/shared-head.js
+ !/devtools/client/shared/test/telemetry-test-helpers.js
+ !/devtools/client/webconsole/test/browser/shared-head.js
+
+[browser_net_http3_request_details.js]
diff --git a/devtools/client/netmonitor/test/browser_net-ws-filter-freetext.js b/devtools/client/netmonitor/test/browser_net-ws-filter-freetext.js
new file mode 100644
index 0000000000..3b17e8c8be
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net-ws-filter-freetext.js
@@ -0,0 +1,93 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WS connection is established successfully and filtering messages using freetext works correctly.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedMessages } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/messages"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connection(s) to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(3);
+ await content.wrappedJSObject.openConnection(1);
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 2, "There should be two requests");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ const wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 6
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 6, "There should be six frames");
+
+ // Fill filter input with text and check displayed messages
+ const filterInput = document.querySelector(
+ "#messages-view .devtools-filterinput"
+ );
+ filterInput.focus();
+ typeInNetmonitor("Payload 2", monitor);
+
+ // Wait till the text filter is applied.
+ await waitUntil(() => getDisplayedMessages(store.getState()).length == 2);
+
+ const filteredFrames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+ is(filteredFrames.length, 2, "There should be two frames");
+
+ // Select the second request and check that the filter input is cleared
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[1]);
+ // Wait till the text filter is applied. There should be two frames rendered
+ await waitUntil(
+ () =>
+ document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ ).length == 2
+ );
+ const secondRequestFrames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+ is(secondRequestFrames.length, 2, "There should be two frames");
+ is(filterInput.value, "", "The filter input is cleared");
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_accessibility-01.js b/devtools/client/netmonitor/test/browser_net_accessibility-01.js
new file mode 100644
index 0000000000..58ac0c91fe
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_accessibility-01.js
@@ -0,0 +1,87 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if focus modifiers work for the Side Menu.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ // It seems that this test may be slow on Ubuntu builds running on ec2.
+ requestLongerTimeout(2);
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ let count = 0;
+ function check(selectedIndex, panelVisibility) {
+ info("Performing check " + count++ + ".");
+
+ const requestItems = Array.from(
+ document.querySelectorAll(".request-list-item")
+ );
+ is(
+ requestItems.findIndex(item => item.matches(".selected")),
+ selectedIndex,
+ "The selected item in the requests menu was incorrect."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ panelVisibility,
+ "The network details panel should render correctly."
+ );
+ }
+
+ // Execute requests.
+ await performRequests(monitor, tab, 2);
+
+ check(-1, false);
+
+ store.dispatch(Actions.selectDelta(+Infinity));
+ check(1, true);
+ store.dispatch(Actions.selectDelta(-Infinity));
+ check(0, true);
+
+ store.dispatch(Actions.selectDelta(+1));
+ check(1, true);
+ store.dispatch(Actions.selectDelta(-1));
+ check(0, true);
+
+ store.dispatch(Actions.selectDelta(+10));
+ check(1, true);
+ store.dispatch(Actions.selectDelta(-10));
+ check(0, true);
+
+ // Execute requests.
+ await performRequests(monitor, tab, 18);
+
+ store.dispatch(Actions.selectDelta(+Infinity));
+ check(19, true);
+ store.dispatch(Actions.selectDelta(-Infinity));
+ check(0, true);
+
+ store.dispatch(Actions.selectDelta(+1));
+ check(1, true);
+ store.dispatch(Actions.selectDelta(-1));
+ check(0, true);
+
+ store.dispatch(Actions.selectDelta(+10));
+ check(10, true);
+ store.dispatch(Actions.selectDelta(-10));
+ check(0, true);
+
+ store.dispatch(Actions.selectDelta(+100));
+ check(19, true);
+ store.dispatch(Actions.selectDelta(-100));
+ check(0, true);
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_accessibility-02.js b/devtools/client/netmonitor/test/browser_net_accessibility-02.js
new file mode 100644
index 0000000000..003f278194
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_accessibility-02.js
@@ -0,0 +1,137 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if keyboard and mouse navigation works in the network requests menu.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ // It seems that this test may be slow on Ubuntu builds running on ec2.
+ requestLongerTimeout(2);
+
+ const { window, document, windowRequire, store } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ let count = 0;
+ function check(selectedIndex, panelVisibility) {
+ info("Performing check " + count++ + ".");
+
+ const requestItems = Array.from(
+ document.querySelectorAll(".request-list-item")
+ );
+ is(
+ requestItems.findIndex(item => item.matches(".selected")),
+ selectedIndex,
+ "The selected item in the requests menu was incorrect."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ panelVisibility,
+ "The network details panel should render correctly."
+ );
+ }
+
+ // Execute requests.
+ await performRequests(monitor, tab, 2);
+
+ document.querySelector(".requests-list-row-group").focus();
+
+ check(-1, false);
+
+ EventUtils.sendKey("DOWN", window);
+ check(0, true);
+ EventUtils.sendKey("UP", window);
+ check(0, true);
+
+ EventUtils.sendKey("PAGE_DOWN", window);
+ check(1, true);
+ EventUtils.sendKey("PAGE_UP", window);
+ check(0, true);
+
+ EventUtils.sendKey("END", window);
+ check(1, true);
+ EventUtils.sendKey("HOME", window);
+ check(0, true);
+
+ // Execute requests.
+ await performRequests(monitor, tab, 18);
+
+ EventUtils.sendKey("DOWN", window);
+ check(1, true);
+ EventUtils.sendKey("DOWN", window);
+ check(2, true);
+ EventUtils.sendKey("UP", window);
+ check(1, true);
+ EventUtils.sendKey("UP", window);
+ check(0, true);
+
+ EventUtils.sendKey("PAGE_DOWN", window);
+ check(4, true);
+ EventUtils.sendKey("PAGE_DOWN", window);
+ check(8, true);
+ EventUtils.sendKey("PAGE_UP", window);
+ check(4, true);
+ EventUtils.sendKey("PAGE_UP", window);
+ check(0, true);
+
+ EventUtils.sendKey("HOME", window);
+ check(0, true);
+ EventUtils.sendKey("HOME", window);
+ check(0, true);
+ EventUtils.sendKey("PAGE_UP", window);
+ check(0, true);
+ EventUtils.sendKey("HOME", window);
+ check(0, true);
+
+ EventUtils.sendKey("END", window);
+ check(19, true);
+ EventUtils.sendKey("END", window);
+ check(19, true);
+ EventUtils.sendKey("PAGE_DOWN", window);
+ check(19, true);
+ EventUtils.sendKey("END", window);
+ check(19, true);
+
+ EventUtils.sendKey("PAGE_UP", window);
+ check(15, true);
+ EventUtils.sendKey("PAGE_UP", window);
+ check(11, true);
+ EventUtils.sendKey("UP", window);
+ check(10, true);
+ EventUtils.sendKey("UP", window);
+ check(9, true);
+ EventUtils.sendKey("PAGE_DOWN", window);
+ check(13, true);
+ EventUtils.sendKey("PAGE_DOWN", window);
+ check(17, true);
+ EventUtils.sendKey("PAGE_DOWN", window);
+ check(19, true);
+ EventUtils.sendKey("PAGE_DOWN", window);
+ check(19, true);
+
+ EventUtils.sendKey("HOME", window);
+ check(0, true);
+ EventUtils.sendKey("DOWN", window);
+ check(1, true);
+ EventUtils.sendKey("END", window);
+ check(19, true);
+ EventUtils.sendKey("DOWN", window);
+ check(19, true);
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelector(".request-list-item")
+ );
+ check(0, true);
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_api-calls.js b/devtools/client/netmonitor/test/browser_net_api-calls.js
new file mode 100644
index 0000000000..71b178a97e
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_api-calls.js
@@ -0,0 +1,47 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests whether API call URLs (without a filename) are correctly displayed
+ * (including Unicode)
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(API_CALLS_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const REQUEST_URIS = [
+ "https://example.com/api/fileName.xml",
+ "https://example.com/api/file%E2%98%A2.xml",
+ "https://example.com/api/ascii/get/",
+ "https://example.com/api/unicode/%E2%98%A2/",
+ "https://example.com/api/search/?q=search%E2%98%A2",
+ ];
+
+ // Execute requests.
+ await performRequests(monitor, tab, 5);
+
+ REQUEST_URIS.forEach(function (uri, index) {
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[index],
+ "GET",
+ uri
+ );
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_autoscroll.js b/devtools/client/netmonitor/test/browser_net_autoscroll.js
new file mode 100644
index 0000000000..f7d379a31a
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_autoscroll.js
@@ -0,0 +1,114 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Bug 863102 - Automatically scroll down upon new network requests.
+ * edited to account for changes made to fix Bug 1360457
+ */
+add_task(async function () {
+ requestLongerTimeout(4);
+
+ const { tab, monitor } = await initNetMonitor(INFINITE_GET_URL, {
+ enableCache: true,
+ requestCount: 1,
+ });
+ const { document, windowRequire, store } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait until the first request makes the empty notice disappear
+ await waitForRequestListToAppear();
+
+ const requestsContainer = document.querySelector(".requests-list-scroll");
+ ok(requestsContainer, "Container element exists as expected.");
+
+ // (1) Check that the scroll position is maintained at the bottom
+ // when the requests overflow the vertical size of the container.
+ await waitForRequestsToOverflowContainer();
+ await waitForScroll();
+ ok(true, "Scrolled to bottom on overflow.");
+
+ // (2) Now scroll to the top and check that additional requests
+ // do not change the scroll position.
+ requestsContainer.scrollTop = 0;
+ await waitSomeTime();
+ ok(!scrolledToBottom(requestsContainer), "Not scrolled to bottom.");
+ // save for comparison later
+ const { scrollTop } = requestsContainer;
+ // As we are scrolled top, new request appended won't be fetching their event timings,
+ // so do not wait for them
+ await waitForNetworkEvents(monitor, 8, { expectedEventTimings: 0 });
+ await waitSomeTime();
+ is(requestsContainer.scrollTop, scrollTop, "Did not scroll.");
+
+ // (3) Now set the scroll position back at the bottom and check that
+ // additional requests *do* cause the container to scroll down.
+ requestsContainer.scrollTop = requestsContainer.scrollHeight;
+ ok(scrolledToBottom(requestsContainer), "Set scroll position to bottom.");
+ await waitForNetworkEvents(monitor, 8);
+ await waitForScroll();
+ ok(true, "Still scrolled to bottom.");
+
+ // (4) Now select the first item in the list
+ // and check that additional requests do not change the scroll position
+ // from just below the headers.
+ store.dispatch(Actions.selectRequestByIndex(0));
+ await waitForNetworkEvents(monitor, 8);
+ await waitSomeTime();
+ const requestsContainerHeaders = document.querySelector(
+ ".requests-list-headers"
+ );
+ const headersHeight = Math.floor(
+ requestsContainerHeaders.getBoundingClientRect().height
+ );
+ is(requestsContainer.scrollTop, headersHeight, "Did not scroll.");
+
+ // Stop doing requests.
+ await SpecialPowers.spawn(tab.linkedBrowser, [], function () {
+ content.wrappedJSObject.stopRequests();
+ });
+
+ // Done: clean up.
+ return teardown(monitor);
+
+ function waitForRequestListToAppear() {
+ info(
+ "Waiting until the empty notice disappears and is replaced with the list"
+ );
+ return waitUntil(
+ () => !!document.querySelector(".requests-list-row-group")
+ );
+ }
+
+ async function waitForRequestsToOverflowContainer() {
+ info("Waiting for enough requests to overflow the container");
+ while (true) {
+ info("Waiting for one network request");
+ await waitForNetworkEvents(monitor, 1);
+ if (
+ requestsContainer.scrollHeight >
+ requestsContainer.clientHeight + 50
+ ) {
+ info("The list is long enough, returning");
+ return;
+ }
+ }
+ }
+
+ function scrolledToBottom(element) {
+ return element.scrollTop + element.clientHeight >= element.scrollHeight;
+ }
+
+ function waitSomeTime() {
+ // Wait to make sure no scrolls happen
+ return wait(50);
+ }
+
+ function waitForScroll() {
+ info("Waiting for the list to scroll to bottom");
+ return waitUntil(() => scrolledToBottom(requestsContainer));
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_background_update.js b/devtools/client/netmonitor/test/browser_net_background_update.js
new file mode 100644
index 0000000000..e46db87a79
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_background_update.js
@@ -0,0 +1,57 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Check that network logs created when the Net panel is not visible
+ * are displayed when the user shows the panel again.
+ */
+add_task(async () => {
+ const { tab, monitor, toolbox } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute two requests
+ await performRequests(monitor, tab, 2);
+
+ // Wait for two logs
+ await waitUntil(
+ () => document.querySelectorAll(".request-list-item").length == 2
+ );
+
+ info("Select the inspector");
+ await toolbox.selectTool("inspector");
+
+ info("Wait for Net panel to be hidden");
+ await waitUntil(() => document.visibilityState == "hidden");
+
+ // Execute another two requests
+ await performRequests(monitor, tab, 2);
+
+ // The number of rendered requests should be the same since
+ // requests shouldn't be rendered while the net panel is in
+ // background
+ is(
+ document.querySelectorAll(".request-list-item").length,
+ 2,
+ "There should be expected number of requests"
+ );
+
+ info("Select the Net panel again");
+ await toolbox.selectTool("netmonitor");
+
+ // Wait for another two logs to be rendered since the panel
+ // is selected now.
+ await waitUntil(
+ () => document.querySelectorAll(".request-list-item").length == 4
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_basic-search.js b/devtools/client/netmonitor/test/browser_net_basic-search.js
new file mode 100644
index 0000000000..b7e00fdd5f
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_basic-search.js
@@ -0,0 +1,68 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test basic search functionality.
+ * Search panel is visible and number of expected results are returned.
+ */
+
+add_task(async function () {
+ await pushPref("devtools.netmonitor.features.search", true);
+
+ const { tab, monitor } = await initNetMonitor(HTTPS_CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+
+ // Action should be processed synchronously in tests.
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute two XHRs (the same URL) and wait till it's finished.
+ const URL = HTTPS_SEARCH_SJS + "?value=test";
+ const wait = waitForNetworkEvents(monitor, 2);
+
+ await SpecialPowers.spawn(tab.linkedBrowser, [URL], async function (url) {
+ content.wrappedJSObject.performRequests(2, url);
+ });
+ await wait;
+
+ // Open the Search panel
+ store.dispatch(Actions.openSearch());
+
+ // Fill Filter input with text and check displayed messages.
+ // The filter should be focused automatically.
+ typeInNetmonitor("test", monitor);
+ EventUtils.synthesizeKey("KEY_Enter");
+
+ // Wait till there are two resources rendered in the results.
+ await waitForDOMIfNeeded(
+ document,
+ ".search-panel-content .treeRow.resourceRow",
+ 2
+ );
+
+ // Click on the first resource to expand it
+ AccessibilityUtils.setEnv({
+ // Keyboard users use arrow keys to expand/collapse tree items.
+ // Accessibility is handled on the container level.
+ mustHaveAccessibleRule: false,
+ });
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".search-panel-content .treeRow .treeIcon")
+ );
+ AccessibilityUtils.resetEnv();
+
+ // Check that there is 5 matches.
+ const matches = document.querySelectorAll(
+ ".search-panel-content .treeRow.resultRow"
+ );
+ is(matches.length, 5, "There must be 5 matches");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_block-context.js b/devtools/client/netmonitor/test/browser_net_block-context.js
new file mode 100644
index 0000000000..390df67837
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_block-context.js
@@ -0,0 +1,135 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that context menus for blocked requests work
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ requestLongerTimeout(2);
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ info("Loading initial page");
+ const wait = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await wait;
+
+ info("Opening the blocked requests panel");
+ document.querySelector(".requests-list-blocking-button").click();
+
+ info("Adding sample block strings");
+ const waitForBlockingContents = waitForDOM(
+ document,
+ ".request-blocking-contents"
+ );
+ await waitForBlockingAction(store, () => Actions.addBlockedUrl("test-page"));
+ await waitForBlockingAction(store, () => Actions.addBlockedUrl("Two"));
+ await waitForBlockingContents;
+
+ is(getListitems(document), 2);
+
+ info("Reloading page, URLs should be blocked in request list");
+ await reloadPage(monitor, { isRequestBlocked: true });
+ is(checkIfRequestIsBlocked(document), true);
+
+ info("Disabling all blocked strings");
+ await openMenuAndClick(
+ monitor,
+ store,
+ document,
+ "request-blocking-disable-all"
+ );
+ is(getCheckedCheckboxes(document), 0);
+
+ info("Reloading page, URLs should not be blocked in request list");
+ await reloadPage(monitor, { isRequestBlocked: false });
+
+ is(checkIfRequestIsBlocked(document), false);
+
+ info("Enabling all blocked strings");
+ await openMenuAndClick(
+ monitor,
+ store,
+ document,
+ "request-blocking-enable-all"
+ );
+ is(getCheckedCheckboxes(document), 2);
+
+ info("Reloading page, URLs should be blocked in request list");
+ await reloadPage(monitor, { isRequestBlocked: true });
+
+ is(checkIfRequestIsBlocked(document), true);
+
+ info("Removing all blocked strings");
+ await openMenuAndClick(
+ monitor,
+ store,
+ document,
+ "request-blocking-remove-all"
+ );
+ is(getListitems(document), 0);
+
+ info("Reloading page, URLs should no longer be blocked in request list");
+ await reloadPage(monitor, { isRequestBlocked: false });
+ is(checkIfRequestIsBlocked(document), false);
+
+ return teardown(monitor);
+});
+
+async function waitForBlockingAction(store, action) {
+ const wait = waitForDispatch(store, "REQUEST_BLOCKING_UPDATE_COMPLETE");
+ store.dispatch(action());
+ await wait;
+}
+
+async function openMenuAndClick(monitor, store, document, itemSelector) {
+ info(`Right clicking on white-space in the header to get the context menu`);
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector(".request-blocking-contents")
+ );
+
+ const wait = waitForDispatch(store, "REQUEST_BLOCKING_UPDATE_COMPLETE");
+ await selectContextMenuItem(monitor, itemSelector);
+ await wait;
+}
+
+async function reloadPage(monitor, { isRequestBlocked = false } = {}) {
+ const wait = waitForNetworkEvents(monitor, 1);
+ if (isRequestBlocked) {
+ // Note: Do not use navigateTo or reloadBrowser here as the request will
+ // be blocked and no navigation happens
+ gBrowser.selectedBrowser.reload();
+ } else {
+ await reloadBrowser();
+ }
+ await wait;
+}
+
+function getCheckedCheckboxes(document) {
+ const checkboxes = [
+ ...document.querySelectorAll(".request-blocking-contents li input"),
+ ];
+ return checkboxes.filter(checkbox => checkbox.checked).length;
+}
+
+function getListitems(document) {
+ return document.querySelectorAll(".request-blocking-contents li").length;
+}
+
+function checkIfRequestIsBlocked(document) {
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+ const blockedRequestSize = firstRequest.querySelector(
+ ".requests-list-transferred"
+ ).textContent;
+ return blockedRequestSize.includes("Blocked");
+}
diff --git a/devtools/client/netmonitor/test/browser_net_block-csp.js b/devtools/client/netmonitor/test/browser_net_block-csp.js
new file mode 100644
index 0000000000..f4947cd769
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_block-csp.js
@@ -0,0 +1,111 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that CSP violations display in the netmonitor when blocked
+ */
+
+add_task(async function () {
+ info("Test requests blocked by CSP in the top level document");
+ await testRequestsBlockedByCSP(
+ HTTPS_EXAMPLE_URL,
+ HTTPS_EXAMPLE_URL + "html_csp-test-page.html"
+ );
+
+ // The html_csp-frame-test-page.html (in the .com domain) includes
+ // an iframe from the .org domain
+ info("Test requests blocked by CSP in remote frames");
+ await testRequestsBlockedByCSP(
+ HTTPS_EXAMPLE_ORG_URL,
+ HTTPS_EXAMPLE_URL + "html_csp-frame-test-page.html"
+ );
+});
+
+async function testRequestsBlockedByCSP(baseUrl, page) {
+ const { monitor } = await initNetMonitor(page, { requestCount: 3 });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ const scriptFileName = "js_websocket-worker-test.js";
+ const styleFileName = "internal-loaded.css";
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 3);
+ await reloadBrowser();
+ info("Waiting until the requests appear in netmonitor");
+ await wait;
+
+ const displayedRequests = getDisplayedRequests(store.getState());
+
+ const styleRequest = displayedRequests.find(request =>
+ request.url.includes(styleFileName)
+ );
+
+ info("Ensure the attempt to load a CSS file shows a blocked CSP error");
+
+ verifyRequestItemTarget(
+ document,
+ displayedRequests,
+ styleRequest,
+ "GET",
+ baseUrl + styleFileName,
+ {
+ transferred: "CSP",
+ cause: { type: "stylesheet" },
+ type: "",
+ }
+ );
+
+ const scriptRequest = displayedRequests.find(request =>
+ request.url.includes(scriptFileName)
+ );
+
+ info("Test that the attempt to load a JS file shows a blocked CSP error");
+
+ verifyRequestItemTarget(
+ document,
+ displayedRequests,
+ scriptRequest,
+ "GET",
+ baseUrl + scriptFileName,
+ {
+ transferred: "CSP",
+ cause: { type: "script" },
+ type: "",
+ }
+ );
+
+ info("Test that header infomation is available for blocked CSP requests");
+
+ const requestEl = document.querySelector(
+ `.requests-list-column[title*="${scriptFileName}"]`
+ ).parentNode;
+
+ const waitForHeadersPanel = waitUntil(() =>
+ document.querySelector("#headers-panel .panel-container")
+ );
+ clickElement(requestEl, monitor);
+ await waitForHeadersPanel;
+
+ ok(
+ document.querySelector(".headers-overview"),
+ "There is request overview details"
+ );
+ ok(
+ document.querySelector(".accordion #requestHeaders"),
+ "There is request header information"
+ );
+ ok(
+ !document.querySelector(".accordion #responseHeaders"),
+ "There is no response header information"
+ );
+
+ await teardown(monitor);
+}
diff --git a/devtools/client/netmonitor/test/browser_net_block-draganddrop.js b/devtools/client/netmonitor/test/browser_net_block-draganddrop.js
new file mode 100644
index 0000000000..5a1abb467c
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_block-draganddrop.js
@@ -0,0 +1,159 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test blocking and unblocking a request.
+ */
+
+add_task(async function () {
+ class DataTransfer {
+ constructor() {
+ this.BLOCKING_URL =
+ "https://example.com/browser/devtools/client/netmonitor/test/html_simple-test-page.html";
+ this.getDataTrigger = false;
+ this.setDataTrigger = false;
+ this.data = "";
+ }
+
+ setData(format, data) {
+ this.setDataTrigger = true;
+ ok(format === "text/plain", 'setData passed valid "text/plain" format');
+ ok(data === this.BLOCKING_URL, "Data matches the expected URL");
+ this.data = data;
+ }
+
+ getData(format) {
+ this.getDataTrigger = true;
+ ok(format === "text/plain", 'getData passed valid "text/plain" format');
+ return this.data;
+ }
+
+ wasGetDataTriggered() {
+ return this.getDataTrigger;
+ }
+
+ wasSetDataTriggered() {
+ return this.setDataTrigger;
+ }
+ }
+
+ const dataTransfer = new DataTransfer();
+
+ const { tab, monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Open the request blocking panel
+ store.dispatch(Actions.toggleRequestBlockingPanel());
+
+ // Reload to have one request in the list
+ let waitForEvents = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await waitForEvents;
+
+ // Capture normal request
+ let normalRequestState;
+ let normalRequestSize;
+ {
+ const requestBlockingPanel = document.querySelector(
+ ".request-blocking-panel"
+ );
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+ await waitForHeaders;
+ normalRequestState = getSelectedRequest(store.getState());
+ normalRequestSize = firstRequest.querySelector(
+ ".requests-list-transferred"
+ ).textContent;
+ info("Captured normal request");
+
+ // Drag and drop the list item
+ const createBubbledEvent = (type, props = {}) => {
+ const event = new Event(type, { bubbles: true });
+ Object.assign(event, props);
+ return event;
+ };
+
+ info('Dispatching "dragstart" event on first item of request list');
+ firstRequest.dispatchEvent(
+ createBubbledEvent("dragstart", {
+ clientX: 0,
+ clientY: 0,
+ dataTransfer,
+ })
+ );
+
+ ok(
+ dataTransfer.wasSetDataTriggered() === true,
+ 'setData() was called during the "dragstart" event'
+ );
+
+ info('Dispatching "drop" event on request blocking list');
+ requestBlockingPanel.dispatchEvent(
+ createBubbledEvent("drop", {
+ clientX: 0,
+ clientY: 1,
+ dataTransfer,
+ })
+ );
+
+ ok(
+ dataTransfer.wasGetDataTriggered() === true,
+ 'getData() was called during the "drop" event'
+ );
+
+ const onRequestBlocked = waitForDispatch(
+ store,
+ "REQUEST_BLOCKING_UPDATE_COMPLETE"
+ );
+
+ info("Wait for dropped request to be blocked");
+ await onRequestBlocked;
+ info("Dropped request is now blocked");
+ }
+
+ // Reload to have one request in the list
+ info("Reloading to check block");
+ // We can't use the normal waiting methods because a canceled request won't send all
+ // the extra update packets.
+ waitForEvents = waitForNetworkEvents(monitor, 1);
+ tab.linkedBrowser.reload();
+ await waitForEvents;
+
+ // Capture blocked request, then unblock
+ let blockedRequestState;
+ let blockedRequestSize;
+ {
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+ blockedRequestSize = firstRequest.querySelector(
+ ".requests-list-transferred"
+ ).textContent;
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+ blockedRequestState = getSelectedRequest(store.getState());
+ info("Captured blocked request");
+ }
+
+ ok(!normalRequestState.blockedReason, "Normal request is not blocked");
+ ok(!normalRequestSize.includes("Blocked"), "Normal request has a size");
+
+ ok(blockedRequestState.blockedReason, "Blocked request is blocked");
+ ok(
+ blockedRequestSize.includes("Blocked"),
+ "Blocked request shows reason as size"
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_block-extensions.js b/devtools/client/netmonitor/test/browser_net_block-extensions.js
new file mode 100644
index 0000000000..067f18d3c6
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_block-extensions.js
@@ -0,0 +1,103 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test the requests that are blocked by extenstions show correctly.
+ */
+add_task(async function () {
+ const extensionName = "Test Blocker";
+ info(`Start loading the ${extensionName} extension...`);
+ const extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ name: extensionName,
+ permissions: ["*://example.com/", "webRequest", "webRequestBlocking"],
+ },
+ useAddonManager: "temporary",
+ background() {
+ // eslint-disable-next-line no-undef
+ browser.webRequest.onBeforeRequest.addListener(
+ () => {
+ return {
+ cancel: true,
+ };
+ },
+ {
+ urls: [
+ "https://example.com/browser/devtools/client/netmonitor/test/request_0",
+ ],
+ },
+ ["blocking"]
+ );
+ // eslint-disable-next-line no-undef
+ browser.test.sendMessage("ready");
+ },
+ });
+
+ await extension.startup();
+ await extension.awaitMessage("ready");
+
+ const { tab, monitor } = await initNetMonitor(HTTPS_SINGLE_GET_URL, {
+ requestCount: 2,
+ });
+
+ const { document } = monitor.panelWin;
+
+ info("Starting test... ");
+
+ const waitForNetworkEventsToComplete = waitForNetworkEvents(monitor, 2);
+ const waitForRequestsToRender = waitForDOM(
+ document,
+ ".requests-list-row-group"
+ );
+ const waitForReload = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
+
+ await reloadBrowser();
+
+ await Promise.all([
+ waitForNetworkEventsToComplete,
+ waitForRequestsToRender,
+ waitForReload,
+ ]);
+
+ // Find the request list item that matches the blocked url
+ const request = document.querySelector(
+ "td.requests-list-url[title*=request_0]"
+ ).parentNode;
+
+ info("Assert the blocked request");
+ ok(
+ !!request.querySelector(".requests-list-status .status-code-blocked-icon"),
+ "The request blocked status icon is visible"
+ );
+
+ is(
+ request.querySelector(".requests-list-status .requests-list-status-code")
+ .title,
+ "Blocked",
+ "The request status title is 'Blocked'"
+ );
+
+ is(
+ request.querySelector(".requests-list-type").innerText,
+ "",
+ "The request shows no type"
+ );
+
+ is(
+ request.querySelector(".requests-list-transferred").innerText,
+ `Blocked By ${extensionName}`,
+ "The request shows the blocking extension name"
+ );
+
+ is(
+ request.querySelector(".requests-list-size").innerText,
+ "",
+ "The request shows no size"
+ );
+
+ await teardown(monitor);
+ info(`Unloading the ${extensionName} extension`);
+ await extension.unload();
+});
diff --git a/devtools/client/netmonitor/test/browser_net_block-pattern.js b/devtools/client/netmonitor/test/browser_net_block-pattern.js
new file mode 100644
index 0000000000..fe4962d777
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_block-pattern.js
@@ -0,0 +1,106 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test basic request blocking functionality for patterns
+ * Ensures that request blocking unblocks a relevant pattern and not just
+ * an exact URL match
+ */
+
+add_task(async function () {
+ await pushPref("devtools.netmonitor.features.requestBlocking", true);
+
+ const { tab, monitor } = await initNetMonitor(HTTPS_CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+
+ // Action should be processed synchronously in tests
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Open the request blocking panel
+ store.dispatch(Actions.toggleRequestBlockingPanel());
+
+ // Add patterns which should block some of the requests
+ await addBlockedRequest("test1", monitor);
+ await addBlockedRequest("test/*/test3", monitor);
+
+ // Close the blocking panel to ensure it's opened by the context menu later
+ store.dispatch(Actions.toggleRequestBlockingPanel());
+
+ // Execute two XHRs (the same URL) and wait till they're finished
+ const TEST_URL_1 = HTTPS_SEARCH_SJS + "?value=test1";
+ const TEST_URL_2 = HTTPS_SEARCH_SJS + "?value=test2";
+ const TEST_URL_3 = HTTPS_SEARCH_SJS + "test/something/test3";
+ const TEST_URL_4 = HTTPS_SEARCH_SJS + "test/something/test4";
+
+ let wait = waitForNetworkEvents(monitor, 4);
+ await ContentTask.spawn(tab.linkedBrowser, TEST_URL_1, async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ });
+ await ContentTask.spawn(tab.linkedBrowser, TEST_URL_2, async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ });
+ await ContentTask.spawn(tab.linkedBrowser, TEST_URL_3, async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ });
+ await ContentTask.spawn(tab.linkedBrowser, TEST_URL_4, async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ });
+ await wait;
+
+ // Wait till there are four resources rendered in the results
+ await waitForDOMIfNeeded(document, ".request-list-item", 4);
+
+ let requestItems = document.querySelectorAll(".request-list-item");
+ // Ensure that test1 item was blocked and test2 item wasn't
+ ok(
+ checkRequestListItemBlocked(requestItems[0]),
+ "The first request was blocked"
+ );
+ ok(
+ !checkRequestListItemBlocked(requestItems[1]),
+ "The second request was not blocked"
+ );
+ // Ensure that test3 item was blocked and test4 item wasn't
+ ok(
+ checkRequestListItemBlocked(requestItems[2]),
+ "The third request was blocked"
+ );
+ ok(
+ !checkRequestListItemBlocked(requestItems[3]),
+ "The fourth request was not blocked"
+ );
+
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requestItems[0]);
+ // Right-click test1, select "Unblock URL" from its context menu
+ await toggleBlockedUrl(requestItems[0], monitor, store, "unblock");
+
+ // Ensure that the request blocking panel is now open and the item is unchecked
+ ok(
+ !document.querySelector(".request-blocking-list .devtools-checkbox")
+ .checked,
+ "The blocking pattern is disabled from context menu"
+ );
+
+ // Request the unblocked URL again, ensure the URL was not blocked
+ wait = waitForNetworkEvents(monitor, 1);
+ await ContentTask.spawn(tab.linkedBrowser, TEST_URL_1, async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ });
+ await wait;
+
+ await waitForDOMIfNeeded(document, ".request-list-item", 5);
+ requestItems = document.querySelectorAll(".request-list-item");
+ ok(
+ !checkRequestListItemBlocked(requestItems[4]),
+ "The fifth request was not blocked"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_block-serviceworker.js b/devtools/client/netmonitor/test/browser_net_block-serviceworker.js
new file mode 100644
index 0000000000..cd5628fa61
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_block-serviceworker.js
@@ -0,0 +1,58 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Service workers only work on https
+const URL = EXAMPLE_URL.replace("http:", "https:");
+
+const TEST_URL = URL + "service-workers/status-codes.html";
+
+// Test that request blocking works for service worker requests.
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(TEST_URL, {
+ enableCache: true,
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Registering the service worker...");
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ await content.wrappedJSObject.registerServiceWorker();
+ });
+
+ info("Performing the service worker request");
+ await performRequests(monitor, tab, 1);
+
+ info("Open the request blocking panel and block service-workers request");
+ store.dispatch(Actions.toggleRequestBlockingPanel());
+ await addBlockedRequest("service-workers", monitor);
+
+ info("Performing the service worker request again");
+ await performRequests(monitor, tab, 1);
+
+ // Wait till there are four resources rendered in the results
+ await waitForDOMIfNeeded(document, ".request-list-item", 2);
+
+ const requestItems = document.querySelectorAll(".request-list-item");
+ ok(
+ !checkRequestListItemBlocked(requestItems[0]),
+ "The first service worker request was not blocked"
+ );
+ ok(
+ checkRequestListItemBlocked(requestItems[1]),
+ "The second service worker request was blocked"
+ );
+
+ info("Unregistering the service worker...");
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ await content.wrappedJSObject.unregisterServiceWorker();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_block.js b/devtools/client/netmonitor/test/browser_net_block.js
new file mode 100644
index 0000000000..54ba3a7526
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_block.js
@@ -0,0 +1,169 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test blocking and unblocking a request.
+ */
+
+add_task(async function () {
+ const { monitor, tab } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Reload to have one request in the list
+ let waitForEvents = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await waitForEvents;
+
+ // Capture normal request
+ let normalRequestState;
+ let normalRequestSize;
+ let normalHeadersSectionSize;
+ let normalFirstHeaderSectionTitle;
+ {
+ // Wait for the response and request header sections
+ const waitForHeaderSections = waitForDOM(
+ document,
+ "#headers-panel .accordion-item",
+ 2
+ );
+
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+
+ await waitForHeaderSections;
+
+ const headerSections = document.querySelectorAll(
+ "#headers-panel .accordion-item"
+ );
+ normalRequestState = getSelectedRequest(store.getState());
+ normalRequestSize = firstRequest.querySelector(
+ ".requests-list-transferred"
+ ).textContent;
+ normalHeadersSectionSize = headerSections.length;
+ normalFirstHeaderSectionTitle = headerSections[0].querySelector(
+ ".accordion-header-label"
+ ).textContent;
+
+ info("Captured normal request");
+
+ // Mark as blocked
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequest);
+ const onRequestBlocked = waitForDispatch(
+ store,
+ "REQUEST_BLOCKING_UPDATE_COMPLETE"
+ );
+
+ await selectContextMenuItem(monitor, "request-list-context-block-url");
+
+ info("Wait for selected request to be blocked");
+ await onRequestBlocked;
+ info("Selected request is now blocked");
+ }
+
+ // Reload to have one request in the list
+ info("Reloading to check block");
+ // We can't use the normal waiting methods because a canceled request won't send all
+ // the extra update packets.
+ waitForEvents = waitForNetworkEvents(monitor, 1);
+ tab.linkedBrowser.reload();
+ await waitForEvents;
+
+ // Capture blocked request, then unblock
+ let blockedRequestState;
+ let blockedRequestSize;
+ let blockedHeadersSectionSize;
+ let blockedFirstHeaderSectionTitle;
+ {
+ const waitForHeaderSections = waitForDOM(
+ document,
+ "#headers-panel .accordion-item",
+ 1
+ );
+
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+
+ await waitForHeaderSections;
+
+ const headerSections = document.querySelectorAll(
+ "#headers-panel .accordion-item"
+ );
+ blockedRequestSize = firstRequest.querySelector(
+ ".requests-list-transferred"
+ ).textContent;
+ blockedRequestState = getSelectedRequest(store.getState());
+ blockedHeadersSectionSize = headerSections.length;
+ blockedFirstHeaderSectionTitle = headerSections[0].querySelector(
+ ".accordion-header-label"
+ ).textContent;
+
+ info("Captured blocked request");
+
+ // Mark as unblocked
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequest);
+ const onRequestUnblocked = waitForDispatch(
+ store,
+ "REQUEST_BLOCKING_UPDATE_COMPLETE"
+ );
+
+ await selectContextMenuItem(monitor, "request-list-context-unblock-url");
+
+ info("Wait for selected request to be unblocked");
+ await onRequestUnblocked;
+ info("Selected request is now unblocked");
+ }
+
+ // Reload to have one request in the list
+ info("Reloading to check unblock");
+ waitForEvents = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await waitForEvents;
+
+ // Capture unblocked request
+ let unblockedRequestState;
+ let unblockedRequestSize;
+ {
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+ unblockedRequestSize = firstRequest.querySelector(
+ ".requests-list-transferred"
+ ).textContent;
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+ unblockedRequestState = getSelectedRequest(store.getState());
+ info("Captured unblocked request");
+ }
+
+ ok(!normalRequestState.blockedReason, "Normal request is not blocked");
+ ok(!normalRequestSize.includes("Blocked"), "Normal request has a size");
+ ok(normalHeadersSectionSize == 2, "Both header sections are showing");
+ ok(
+ normalFirstHeaderSectionTitle.includes("Response"),
+ "The response header section is visible for normal requests"
+ );
+
+ ok(blockedRequestState.blockedReason, "Blocked request is blocked");
+ ok(
+ blockedRequestSize.includes("Blocked"),
+ "Blocked request shows reason as size"
+ );
+ ok(blockedHeadersSectionSize == 1, "Only one header section is showing");
+ ok(
+ blockedFirstHeaderSectionTitle.includes("Request"),
+ "The response header section is not visible for blocked requests"
+ );
+
+ ok(!unblockedRequestState.blockedReason, "Unblocked request is not blocked");
+ ok(!unblockedRequestSize.includes("Blocked"), "Unblocked request has a size");
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_brotli.js b/devtools/client/netmonitor/test/browser_net_brotli.js
new file mode 100644
index 0000000000..84576ceca6
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_brotli.js
@@ -0,0 +1,81 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const BROTLI_URL = HTTPS_EXAMPLE_URL + "html_brotli-test-page.html";
+const BROTLI_REQUESTS = 1;
+
+/**
+ * Test brotli encoded response is handled correctly on HTTPS.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { tab, monitor } = await initNetMonitor(BROTLI_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, BROTLI_REQUESTS);
+
+ const requestItem = document.querySelector(".request-list-item");
+ // Status code title is generated on hover
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "GET",
+ HTTPS_CONTENT_TYPE_SJS + "?fmt=br",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "json",
+ fullMimeType: "text/json",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 252),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 64),
+ time: true,
+ }
+ );
+
+ const wait = waitForDOM(document, ".CodeMirror-code");
+ const onResponseContent = monitor.panelWin.api.once(
+ TEST_EVENTS.RECEIVED_RESPONSE_CONTENT
+ );
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+ await wait;
+ await onResponseContent;
+ await testResponse("br");
+ await teardown(monitor);
+
+ function testResponse(type) {
+ switch (type) {
+ case "br": {
+ is(
+ getCodeMirrorValue(monitor),
+ "X".repeat(64),
+ "The text shown in the source editor is incorrect for the brotli request."
+ );
+ break;
+ }
+ }
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_cache_details.js b/devtools/client/netmonitor/test/browser_net_cache_details.js
new file mode 100644
index 0000000000..f15ad6a90b
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_cache_details.js
@@ -0,0 +1,102 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const CACHE_TEST_URL = EXAMPLE_URL + "html_cache-test-page.html";
+
+// Test the cache details panel.
+add_task(async function () {
+ const { monitor } = await initNetMonitor(CACHE_TEST_URL, {
+ enableCache: true,
+ requestCount: 1,
+ });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ info("Create a 200 request");
+ let waitForRequest = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => {
+ content.wrappedJSObject.sendRequestWithStatus("200");
+ });
+ await waitForRequest;
+
+ info("Select the request and wait until the headers panel is displayed");
+ store.dispatch(Actions.selectRequestByIndex(0));
+ await waitFor(() => document.querySelector(".headers-overview"));
+ ok(
+ !document.querySelector("#cache-tab"),
+ "No cache panel is available for the 200 request"
+ );
+
+ info("Create a 304 request");
+ waitForRequest = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => {
+ content.wrappedJSObject.sendRequestWithStatus("304");
+ });
+ await waitForRequest;
+
+ info("Select the request and wait until the headers panel is displayed");
+ store.dispatch(Actions.selectRequestByIndex(1));
+ await waitFor(() => document.querySelector(".headers-overview"));
+ ok(
+ document.querySelector("#cache-tab"),
+ "A cache panel is available for the 304 request"
+ );
+ document.querySelector("#cache-tab").click();
+
+ info("Wait until the Cache panel content is displayed");
+ await waitFor(() => !!document.getElementById("/Cache"));
+
+ const device = getCacheDetailsValue(document, "Device");
+ is(device, "Not Available", "device information is `Not Available`");
+
+ // We cannot precisely assert the dates rendered by the cache panel because
+ // they are formatted using toLocaleDateString/toLocaleTimeString, and
+ // `new Date` might be unable to parse them. See Bug 1800448.
+
+ // For "last modified" should be the same day as the test, and we could assert
+ // that. However the cache panel is intermittently fully "Not available",
+ // except for the "Expires" field, which seems to always have a value.
+ const lastModified = getCacheDetailsValue(document, "Last Modified");
+ info("Retrieved lastModified value: " + lastModified);
+ ok(!!lastModified, "Last Modified was found in the cache panel");
+
+ // For "expires" we will only check that this is not set to `Not Available`.
+ const expires = getCacheDetailsValue(document, "Expires");
+ info("Retrieved expires value: " + expires);
+ ok(
+ !expires.includes("Not Available"),
+ "Expires is set to a value other than unavailable"
+ );
+});
+
+/**
+ * Helper to retrieve individual values from the Cache details panel.
+ * Eg, for `Expires: "11/9/2022 6:54:33 PM"`, this should return
+ * "11/9/2022 6:54:33 PM".
+ *
+ * @param {Document} doc
+ * The netmonitor document.
+ * @param {string} cacheItemId
+ * The id of the cache element to retrieve. See netmonitor.cache.* localized
+ * strings.
+ *
+ * @returns {string}
+ * The value corresponding to the provided id.
+ */
+function getCacheDetailsValue(doc, cacheItemId) {
+ const container = doc.getElementById("/Cache/" + cacheItemId);
+ ok(!!container, `Found the cache panel container for id ${cacheItemId}`);
+ const valueContainer = container.querySelector(".treeValueCell span");
+ ok(
+ !!valueContainer,
+ `Found the cache panel value container for id ${cacheItemId}`
+ );
+
+ // The values have opening and closing quotes, remove them using substring.
+ // `"some value"` -> `some value`
+ const quotedValue = valueContainer.textContent;
+ return quotedValue.substring(1, quotedValue.length - 1);
+}
diff --git a/devtools/client/netmonitor/test/browser_net_cached-status.js b/devtools/client/netmonitor/test/browser_net_cached-status.js
new file mode 100644
index 0000000000..eff6601651
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_cached-status.js
@@ -0,0 +1,130 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if cached requests have the correct status code
+ */
+
+add_task(async function () {
+ // Disable rcwn to make cache behavior deterministic.
+ await pushPref("network.http.rcwn.enabled", false);
+
+ const { tab, monitor } = await initNetMonitor(STATUS_CODES_URL, {
+ enableCache: true,
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const REQUEST_DATA = [
+ {
+ method: "GET",
+ uri: STATUS_CODES_SJS + "?sts=ok&cached",
+ details: {
+ status: 200,
+ statusText: "OK",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ uri: STATUS_CODES_SJS + "?sts=redirect&cached",
+ details: {
+ status: 301,
+ statusText: "Moved Permanently",
+ type: "html",
+ fullMimeType: "text/html; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ uri: "http://example.com/redirected",
+ details: {
+ status: 404,
+ statusText: "Not Found",
+ type: "html",
+ fullMimeType: "text/html; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ uri: STATUS_CODES_SJS + "?sts=ok&cached",
+ details: {
+ status: 200,
+ statusText: "OK (cached)",
+ displayedStatus: "cached",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ uri: STATUS_CODES_SJS + "?sts=redirect&cached",
+ details: {
+ status: 301,
+ statusText: "Moved Permanently (cached)",
+ displayedStatus: "cached",
+ type: "html",
+ fullMimeType: "text/html; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ uri: "http://example.com/redirected",
+ details: {
+ status: 404,
+ statusText: "Not Found",
+ type: "html",
+ fullMimeType: "text/html; charset=utf-8",
+ },
+ },
+ ];
+
+ info("Performing requests #1...");
+ await performRequestsAndWait();
+
+ info("Performing requests #2...");
+ await performRequestsAndWait();
+
+ let index = 0;
+ for (const request of REQUEST_DATA) {
+ const requestItem = document.querySelectorAll(".request-list-item")[index];
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+
+ info("Verifying request #" + index);
+ await verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[index],
+ request.method,
+ request.uri,
+ request.details
+ );
+
+ index++;
+ }
+
+ await teardown(monitor);
+
+ async function performRequestsAndWait() {
+ const wait = waitForNetworkEvents(monitor, 3);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.performCachedRequests();
+ });
+ await wait;
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_cause_redirect.js b/devtools/client/netmonitor/test/browser_net_cause_redirect.js
new file mode 100644
index 0000000000..d4184af158
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_cause_redirect.js
@@ -0,0 +1,80 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if request JS stack is property reported if the request is internally
+ * redirected without hitting the network (HSTS is one of such cases)
+ */
+
+add_task(async function () {
+ // This test explicitly checks http->https redirects and should not force https.
+ await pushPref("dom.security.https_first", false);
+
+ const EXPECTED_REQUESTS = [
+ // Request to HTTP URL, redirects to HTTPS
+ { status: 302 },
+ // Serves HTTPS, sets the Strict-Transport-Security header
+ // This request is the redirection caused by the first one
+ { status: 200 },
+ // Second request to HTTP redirects to HTTPS internally
+ { status: 200 },
+ ];
+
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ const { store, windowRequire, connector } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ let wait = waitForNetworkEvents(monitor, EXPECTED_REQUESTS.length);
+ await performRequests(2, HSTS_SJS);
+ await wait;
+
+ // Fetch stack-trace data from the backend and wait till
+ // all packets are received.
+ const requests = getSortedRequests(store.getState())
+ .filter(req => !req.stacktrace)
+ .map(req => connector.requestData(req.id, "stackTrace"));
+
+ await Promise.all(requests);
+
+ EXPECTED_REQUESTS.forEach(({ status }, i) => {
+ const item = getSortedRequests(store.getState())[i];
+
+ is(
+ parseInt(item.status, 10),
+ status,
+ `Request #${i} has the expected status`
+ );
+
+ const { stacktrace } = item;
+ const stackLen = stacktrace ? stacktrace.length : 0;
+
+ ok(stacktrace, `Request #${i} has a stacktrace`);
+ ok(stackLen > 0, `Request #${i} has a stacktrace with ${stackLen} items`);
+ });
+
+ // Send a request to reset the HSTS policy to state before the test
+ wait = waitForNetworkEvents(monitor, 1);
+ await performRequests(1, HSTS_SJS + "?reset");
+ await wait;
+
+ await teardown(monitor);
+
+ function performRequests(count, url) {
+ return SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [{ count, url }],
+ async function (args) {
+ content.wrappedJSObject.performRequests(args.count, args.url);
+ }
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_cause_source_map.js b/devtools/client/netmonitor/test/browser_net_cause_source_map.js
new file mode 100644
index 0000000000..740bad3767
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_cause_source_map.js
@@ -0,0 +1,60 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if request cause is reported correctly when using source maps.
+ */
+
+const CAUSE_FILE_NAME = "html_maps-test-page.html";
+const CAUSE_URL = HTTPS_EXAMPLE_URL + CAUSE_FILE_NAME;
+
+const N_EXPECTED_REQUESTS = 4;
+
+add_task(async function () {
+ // the initNetMonitor function clears the network request list after the
+ // page is loaded. That's why we first load a bogus page from SIMPLE_URL,
+ // and only then load the real thing from CAUSE_URL - we want to catch
+ // all the requests the page is making, not only the XHRs.
+ // We can't use about:blank here, because initNetMonitor checks that the
+ // page has actually made at least one request.
+ const { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+ let waitPromise = waitForNetworkEvents(monitor, N_EXPECTED_REQUESTS);
+ await navigateTo(CAUSE_URL);
+ await waitPromise;
+
+ info("Clicking item and waiting for details panel to open");
+ waitPromise = waitForDOM(document, ".network-details-bar");
+ const xhrRequestItem = document.querySelectorAll(".request-list-item")[3];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, xhrRequestItem);
+ await waitPromise;
+
+ info("Clicking stack tab and waiting for stack panel to open");
+ waitPromise = waitForDOM(document, "#stack-trace-panel");
+ clickOnSidebarTab(document, "stack-trace");
+ await waitPromise;
+
+ info("Waiting for source maps to be applied");
+ await waitUntil(() => {
+ const frames = document.querySelectorAll(".frame-link");
+ return (
+ frames &&
+ frames.length >= 2 &&
+ frames[0].textContent.includes("xhr_original") &&
+ frames[1].textContent.includes("xhr_original")
+ );
+ });
+
+ const frames = document.querySelectorAll(".frame-link");
+ is(frames.length, 3, "should have 3 stack frames");
+ is(frames[0].textContent, `reallydoxhr xhr_original.js:6`);
+ is(frames[1].textContent, `doxhr xhr_original.js:10`);
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_charts-01.js b/devtools/client/netmonitor/test/browser_net_charts-01.js
new file mode 100644
index 0000000000..7f901e158f
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_charts-01.js
@@ -0,0 +1,153 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Makes sure Pie Charts have the right internal structure.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+
+ const { document, windowRequire } = monitor.panelWin;
+ const { Chart } = windowRequire("devtools/client/shared/widgets/Chart");
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await wait;
+
+ const pie = Chart.Pie(document, {
+ width: 100,
+ height: 100,
+ data: [
+ {
+ size: 1,
+ label: "foo",
+ },
+ {
+ size: 2,
+ label: "bar",
+ },
+ {
+ size: 3,
+ label: "baz",
+ },
+ ],
+ });
+
+ const { node } = pie;
+ const slicesContainer = node.querySelectorAll(".pie-chart-slice-container");
+ const slices = node.querySelectorAll(".pie-chart-slice");
+ const labels = node.querySelectorAll(".pie-chart-label");
+
+ ok(
+ node.classList.contains("pie-chart-container") &&
+ node.classList.contains("generic-chart-container"),
+ "A pie chart container was created successfully."
+ );
+ is(
+ node.getAttribute("aria-label"),
+ "Pie chart representing the size of each type of request in proportion to each other",
+ "pie chart container has expected aria-label"
+ );
+
+ is(
+ slicesContainer.length,
+ 3,
+ "There should be 3 pie chart slices container created."
+ );
+
+ is(slices.length, 3, "There should be 3 pie chart slices created.");
+ ok(
+ slices[0]
+ .getAttribute("d")
+ .match(
+ /\s*M 50,50 L 49\.\d+,97\.\d+ A 47\.5,47\.5 0 0 1 49\.\d+,2\.5\d* Z/
+ ),
+ "The first slice has the correct data."
+ );
+ ok(
+ slices[1]
+ .getAttribute("d")
+ .match(
+ /\s*M 50,50 L 91\.\d+,26\.\d+ A 47\.5,47\.5 0 0 1 49\.\d+,97\.\d+ Z/
+ ),
+ "The second slice has the correct data."
+ );
+ ok(
+ slices[2]
+ .getAttribute("d")
+ .match(
+ /\s*M 50,50 L 50\.\d+,2\.5\d* A 47\.5,47\.5 0 0 1 91\.\d+,26\.\d+ Z/
+ ),
+ "The third slice has the correct data."
+ );
+
+ is(
+ slicesContainer[0].getAttribute("aria-label"),
+ "baz: 50%",
+ "First slice container has expected aria-label"
+ );
+ is(
+ slicesContainer[1].getAttribute("aria-label"),
+ "bar: 33.33%",
+ "Second slice container has expected aria-label"
+ );
+ is(
+ slicesContainer[2].getAttribute("aria-label"),
+ "foo: 16.67%",
+ "Third slice container has expected aria-label"
+ );
+
+ ok(
+ slices[0].hasAttribute("largest"),
+ "The first slice should be the largest one."
+ );
+ ok(
+ slices[2].hasAttribute("smallest"),
+ "The third slice should be the smallest one."
+ );
+
+ is(
+ slices[0].getAttribute("data-statistic-name"),
+ "baz",
+ "The first slice's name is correct."
+ );
+ is(
+ slices[1].getAttribute("data-statistic-name"),
+ "bar",
+ "The first slice's name is correct."
+ );
+ is(
+ slices[2].getAttribute("data-statistic-name"),
+ "foo",
+ "The first slice's name is correct."
+ );
+
+ is(labels.length, 3, "There should be 3 pie chart labels created.");
+ is(labels[0].textContent, "baz", "The first label's text is correct.");
+ is(labels[1].textContent, "bar", "The first label's text is correct.");
+ is(labels[2].textContent, "foo", "The first label's text is correct.");
+ is(
+ labels[0].getAttribute("aria-hidden"),
+ "true",
+ "The first label has aria-hidden."
+ );
+ is(
+ labels[1].getAttribute("aria-hidden"),
+ "true",
+ "The first label has aria-hidden."
+ );
+ is(
+ labels[2].getAttribute("aria-hidden"),
+ "true",
+ "The first label has aria-hidden."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_charts-02.js b/devtools/client/netmonitor/test/browser_net_charts-02.js
new file mode 100644
index 0000000000..106ec88380
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_charts-02.js
@@ -0,0 +1,72 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Makes sure Pie Charts have the right internal structure when
+ * initialized with empty data.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, windowRequire } = monitor.panelWin;
+ const { Chart } = windowRequire("devtools/client/shared/widgets/Chart");
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await wait;
+
+ const pie = Chart.Pie(document, {
+ data: null,
+ width: 100,
+ height: 100,
+ });
+
+ const { node } = pie;
+ const slices = node.querySelectorAll(".pie-chart-slice");
+ const labels = node.querySelectorAll(".pie-chart-label");
+
+ ok(
+ node.classList.contains("pie-chart-container") &&
+ node.classList.contains("generic-chart-container"),
+ "A pie chart container was created successfully."
+ );
+
+ is(slices.length, 1, "There should be 1 pie chart slice created.");
+ ok(
+ slices[0]
+ .getAttribute("d")
+ .match(
+ /\s*M 50,50 L 50\.\d+,2\.5\d* A 47\.5,47\.5 0 1 1 49\.\d+,2\.5\d* Z/
+ ),
+ "The first slice has the correct data."
+ );
+
+ ok(
+ slices[0].hasAttribute("largest"),
+ "The first slice should be the largest one."
+ );
+ ok(
+ slices[0].hasAttribute("smallest"),
+ "The first slice should also be the smallest one."
+ );
+ is(
+ slices[0].getAttribute("data-statistic-name"),
+ L10N.getStr("pieChart.loading"),
+ "The first slice's name is correct."
+ );
+
+ is(labels.length, 1, "There should be 1 pie chart label created.");
+ is(labels[0].textContent, "Loading", "The first label's text is correct.");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_charts-03.js b/devtools/client/netmonitor/test/browser_net_charts-03.js
new file mode 100644
index 0000000000..f938bb3932
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_charts-03.js
@@ -0,0 +1,195 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Makes sure Table Charts have the right internal structure.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, windowRequire } = monitor.panelWin;
+ const { Chart } = windowRequire("devtools/client/shared/widgets/Chart");
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await wait;
+
+ const table = Chart.Table(document, {
+ title: "Table title",
+ data: [
+ {
+ label1: 1,
+ label2: 11.1,
+ },
+ {
+ label1: 2,
+ label2: 12.2,
+ },
+ {
+ label1: 3,
+ label2: 13.3,
+ },
+ ],
+ strings: {
+ label2: (value, index) => value + ["foo", "bar", "baz"][index],
+ },
+ totals: {
+ label1: value => "Hello " + L10N.numberWithDecimals(value, 2),
+ label2: value => "World " + L10N.numberWithDecimals(value, 2),
+ },
+ header: {
+ label1: "label1header",
+ label2: "label2header",
+ },
+ });
+
+ const { node } = table;
+ const title = node.querySelector(".table-chart-title");
+ const grid = node.querySelector(".table-chart-grid");
+ const totals = node.querySelector(".table-chart-totals");
+ const rows = grid.querySelectorAll(".table-chart-row");
+ const sums = node.querySelectorAll(".table-chart-summary-label");
+
+ ok(
+ node.classList.contains("table-chart-container") &&
+ node.classList.contains("generic-chart-container"),
+ "A table chart container was created successfully."
+ );
+
+ ok(title, "A title node was created successfully.");
+ is(
+ title.textContent,
+ "Table title",
+ "The title node displays the correct text."
+ );
+
+ is(
+ rows.length,
+ 4,
+ "There should be 3 table chart rows and a header created."
+ );
+
+ is(
+ rows[0].querySelectorAll(".table-chart-row-label")[0].getAttribute("name"),
+ "label1",
+ "The first column of the header exists."
+ );
+ is(
+ rows[0].querySelectorAll(".table-chart-row-label")[1].getAttribute("name"),
+ "label2",
+ "The second column of the header exists."
+ );
+ is(
+ rows[0].querySelectorAll(".table-chart-row-label")[0].textContent,
+ "label1header",
+ "The first column of the header displays the correct text."
+ );
+ is(
+ rows[0].querySelectorAll(".table-chart-row-label")[1].textContent,
+ "label2header",
+ "The second column of the header displays the correct text."
+ );
+
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[0].getAttribute("name"),
+ "label1",
+ "The first column of the first row exists."
+ );
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[1].getAttribute("name"),
+ "label2",
+ "The second column of the first row exists."
+ );
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[0].textContent,
+ "1",
+ "The first column of the first row displays the correct text."
+ );
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[1].textContent,
+ "11.1foo",
+ "The second column of the first row displays the correct text."
+ );
+
+ is(
+ rows[2].querySelectorAll(".table-chart-row-label")[0].getAttribute("name"),
+ "label1",
+ "The first column of the second row exists."
+ );
+ is(
+ rows[2].querySelectorAll(".table-chart-row-label")[1].getAttribute("name"),
+ "label2",
+ "The second column of the second row exists."
+ );
+ is(
+ rows[2].querySelectorAll(".table-chart-row-label")[0].textContent,
+ "2",
+ "The first column of the second row displays the correct text."
+ );
+ is(
+ rows[2].querySelectorAll(".table-chart-row-label")[1].textContent,
+ "12.2bar",
+ "The second column of the first row displays the correct text."
+ );
+
+ is(
+ rows[3].querySelectorAll(".table-chart-row-label")[0].getAttribute("name"),
+ "label1",
+ "The first column of the third row exists."
+ );
+ is(
+ rows[3].querySelectorAll(".table-chart-row-label")[1].getAttribute("name"),
+ "label2",
+ "The second column of the third row exists."
+ );
+ is(
+ rows[3].querySelectorAll(".table-chart-row-label")[0].textContent,
+ "3",
+ "The first column of the third row displays the correct text."
+ );
+ is(
+ rows[3].querySelectorAll(".table-chart-row-label")[1].textContent,
+ "13.3baz",
+ "The second column of the third row displays the correct text."
+ );
+
+ is(sums.length, 2, "There should be 2 total summaries created.");
+
+ is(
+ totals
+ .querySelectorAll(".table-chart-summary-label")[0]
+ .getAttribute("name"),
+ "label1",
+ "The first sum's type is correct."
+ );
+ is(
+ totals.querySelectorAll(".table-chart-summary-label")[0].textContent,
+ "Hello 6",
+ "The first sum's value is correct."
+ );
+
+ is(
+ totals
+ .querySelectorAll(".table-chart-summary-label")[1]
+ .getAttribute("name"),
+ "label2",
+ "The second sum's type is correct."
+ );
+ is(
+ totals.querySelectorAll(".table-chart-summary-label")[1].textContent,
+ "World 36.60",
+ "The second sum's value is correct."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_charts-04.js b/devtools/client/netmonitor/test/browser_net_charts-04.js
new file mode 100644
index 0000000000..686608fb81
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_charts-04.js
@@ -0,0 +1,117 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Makes sure Pie Charts have the right internal structure when
+ * initialized with empty data.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, windowRequire } = monitor.panelWin;
+ const { Chart } = windowRequire("devtools/client/shared/widgets/Chart");
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await wait;
+
+ const table = Chart.Table(document, {
+ title: "Table title",
+ data: null,
+ totals: {
+ label1: value => "Hello " + L10N.numberWithDecimals(value, 2),
+ label2: value => "World " + L10N.numberWithDecimals(value, 2),
+ },
+ header: {
+ label1: "",
+ label2: "",
+ },
+ });
+
+ const { node } = table;
+ const title = node.querySelector(".table-chart-title");
+ const grid = node.querySelector(".table-chart-grid");
+ const totals = node.querySelector(".table-chart-totals");
+ const rows = grid.querySelectorAll(".table-chart-row");
+ const sums = node.querySelectorAll(".table-chart-summary-label");
+
+ ok(
+ node.classList.contains("table-chart-container") &&
+ node.classList.contains("generic-chart-container"),
+ "A table chart container was created successfully."
+ );
+
+ ok(title, "A title node was created successfully.");
+ is(
+ title.textContent,
+ "Table title",
+ "The title node displays the correct text."
+ );
+
+ is(
+ rows.length,
+ 2,
+ "There should be 1 table chart row and a 1 header created."
+ );
+
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[0].getAttribute("name"),
+ "size",
+ "The first column of the first row exists."
+ );
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[1].getAttribute("name"),
+ "label",
+ "The second column of the first row exists."
+ );
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[0].textContent,
+ "",
+ "The first column of the first row displays the correct text."
+ );
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[1].textContent,
+ L10N.getStr("tableChart.loading"),
+ "The second column of the first row displays the correct text."
+ );
+
+ is(sums.length, 2, "There should be 2 total summaries created.");
+
+ is(
+ totals
+ .querySelectorAll(".table-chart-summary-label")[0]
+ .getAttribute("name"),
+ "label1",
+ "The first sum's type is correct."
+ );
+ is(
+ totals.querySelectorAll(".table-chart-summary-label")[0].textContent,
+ "Hello 0",
+ "The first sum's value is correct."
+ );
+
+ is(
+ totals
+ .querySelectorAll(".table-chart-summary-label")[1]
+ .getAttribute("name"),
+ "label2",
+ "The second sum's type is correct."
+ );
+ is(
+ totals.querySelectorAll(".table-chart-summary-label")[1].textContent,
+ "World 0",
+ "The second sum's value is correct."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_charts-05.js b/devtools/client/netmonitor/test/browser_net_charts-05.js
new file mode 100644
index 0000000000..5a75eee610
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_charts-05.js
@@ -0,0 +1,94 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Makes sure Pie+Table Charts have the right internal structure.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, windowRequire } = monitor.panelWin;
+ const { Chart } = windowRequire("devtools/client/shared/widgets/Chart");
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await wait;
+
+ const chart = Chart.PieTable(document, {
+ title: "Table title",
+ data: [
+ {
+ size: 1,
+ label: 11.1,
+ },
+ {
+ size: 2,
+ label: 12.2,
+ },
+ {
+ size: 3,
+ label: 13.3,
+ },
+ ],
+ strings: {
+ label2: (value, index) => value + ["foo", "bar", "baz"][index],
+ },
+ totals: {
+ size: value => "Hello " + L10N.numberWithDecimals(value, 2),
+ label: value => "World " + L10N.numberWithDecimals(value, 2),
+ },
+ header: {
+ label1: "",
+ label2: "",
+ },
+ });
+
+ ok(chart.pie, "The pie chart proxy is accessible.");
+ ok(chart.table, "The table chart proxy is accessible.");
+
+ const { node } = chart;
+ const rows = node.querySelectorAll(".table-chart-row");
+ const sums = node.querySelectorAll(".table-chart-summary-label");
+
+ ok(
+ node.classList.contains("pie-table-chart-container"),
+ "A pie+table chart container was created successfully."
+ );
+
+ ok(
+ node.querySelector(".table-chart-title"),
+ "A title node was created successfully."
+ );
+ ok(
+ node.querySelector(".pie-chart-container"),
+ "A pie chart was created successfully."
+ );
+ ok(
+ node.querySelector(".table-chart-container"),
+ "A table chart was created successfully."
+ );
+
+ is(
+ rows.length,
+ 4,
+ "There should be 3 pie chart slices and 1 header created."
+ );
+ is(
+ rows.length,
+ 4,
+ "There should be 3 table chart rows and 1 header created."
+ );
+ is(sums.length, 2, "There should be 2 total summaries and 1 header created.");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_charts-06.js b/devtools/client/netmonitor/test/browser_net_charts-06.js
new file mode 100644
index 0000000000..a41e997873
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_charts-06.js
@@ -0,0 +1,62 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Makes sure Pie Charts correctly handle empty source data.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, windowRequire } = monitor.panelWin;
+ const { Chart } = windowRequire("devtools/client/shared/widgets/Chart");
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await wait;
+
+ const pie = Chart.Pie(document, {
+ data: [],
+ width: 100,
+ height: 100,
+ });
+
+ const { node } = pie;
+ const slices = node.querySelectorAll(".pie-chart-slice");
+ const labels = node.querySelectorAll(".pie-chart-label");
+
+ is(slices.length, 1, "There should be 1 pie chart slice created.");
+ ok(
+ slices[0]
+ .getAttribute("d")
+ .match(
+ /\s*M 50,50 L 50\.\d+,2\.5\d* A 47\.5,47\.5 0 1 1 49\.\d+,2\.5\d* Z/
+ ),
+ "The slice has the correct data."
+ );
+
+ ok(slices[0].hasAttribute("largest"), "The slice should be the largest one.");
+ ok(
+ slices[0].hasAttribute("smallest"),
+ "The slice should also be the smallest one."
+ );
+ is(
+ slices[0].getAttribute("data-statistic-name"),
+ L10N.getStr("pieChart.unavailable"),
+ "The slice's name is correct."
+ );
+
+ is(labels.length, 1, "There should be 1 pie chart label created.");
+ is(labels[0].textContent, "Empty", "The label's text is correct.");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_charts-07.js b/devtools/client/netmonitor/test/browser_net_charts-07.js
new file mode 100644
index 0000000000..9744c33e6d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_charts-07.js
@@ -0,0 +1,97 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Makes sure Table Charts correctly handle empty source data.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, windowRequire } = monitor.panelWin;
+ const { Chart } = windowRequire("devtools/client/shared/widgets/Chart");
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await wait;
+
+ const table = Chart.Table(document, {
+ data: [],
+ totals: {
+ label1: value => "Hello " + L10N.numberWithDecimals(value, 2),
+ label2: value => "World " + L10N.numberWithDecimals(value, 2),
+ },
+ header: {
+ label1: "",
+ label2: "",
+ },
+ });
+
+ const { node } = table;
+ const grid = node.querySelector(".table-chart-grid");
+ const totals = node.querySelector(".table-chart-totals");
+ const rows = grid.querySelectorAll(".table-chart-row");
+ const sums = node.querySelectorAll(".table-chart-summary-label");
+
+ is(rows.length, 2, "There should be 1 table chart row and 1 header created.");
+
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[0].getAttribute("name"),
+ "size",
+ "The first column of the first row exists."
+ );
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[1].getAttribute("name"),
+ "label",
+ "The second column of the first row exists."
+ );
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[0].textContent,
+ "",
+ "The first column of the first row displays the correct text."
+ );
+ is(
+ rows[1].querySelectorAll(".table-chart-row-label")[1].textContent,
+ L10N.getStr("tableChart.unavailable"),
+ "The second column of the first row displays the correct text."
+ );
+
+ is(sums.length, 2, "There should be 2 total summaries created.");
+
+ is(
+ totals
+ .querySelectorAll(".table-chart-summary-label")[0]
+ .getAttribute("name"),
+ "label1",
+ "The first sum's type is correct."
+ );
+ is(
+ totals.querySelectorAll(".table-chart-summary-label")[0].textContent,
+ "Hello 0",
+ "The first sum's value is correct."
+ );
+
+ is(
+ totals
+ .querySelectorAll(".table-chart-summary-label")[1]
+ .getAttribute("name"),
+ "label2",
+ "The second sum's type is correct."
+ );
+ is(
+ totals.querySelectorAll(".table-chart-summary-label")[1].textContent,
+ "World 0",
+ "The second sum's value is correct."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_clear.js b/devtools/client/netmonitor/test/browser_net_clear.js
new file mode 100644
index 0000000000..5a97de3e02
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_clear.js
@@ -0,0 +1,145 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/devtools/client/webconsole/test/browser/shared-head.js",
+ this
+);
+
+/**
+ * Tests if the clear button empties the request menu.
+ */
+
+add_task(async function () {
+ Services.prefs.setBoolPref("devtools.webconsole.filter.net", true);
+
+ const { monitor, toolbox } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const clearButton = document.querySelector(".requests-list-clear-button");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Make sure we start in a sane state
+ assertNoRequestState();
+
+ // Load one request and assert it shows up in the list
+ let wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ assertSingleRequestState();
+ assertNetworkEventResourceState(1);
+
+ info("Swith to the webconsole and wait for network logs");
+ const onWebConsole = monitor.toolbox.once("webconsole-selected");
+ const { hud } = await monitor.toolbox.selectTool("webconsole");
+ await onWebConsole;
+
+ info("Wait for request");
+ await waitFor(() => findMessageByType(hud, SIMPLE_URL, ".network"));
+
+ info("Switch back the the netmonitor");
+ await monitor.toolbox.selectTool("netmonitor");
+
+ // Click clear and make sure the requests are gone
+ let waitRequestListCleared = waitForEmptyRequestList(document);
+ EventUtils.sendMouseEvent({ type: "click" }, clearButton);
+ await waitRequestListCleared;
+
+ assertNoRequestState();
+ assertNetworkEventResourceState(0);
+
+ info(
+ "Swith back to the webconsole to assert that the cleared request gets disabled"
+ );
+ await monitor.toolbox.selectTool("webconsole");
+
+ info("Wait for network request to show and that its disabled");
+
+ await waitFor(() => findMessageByType(hud, SIMPLE_URL, ".network.disabled"));
+
+ // Switch back to the netmonitor.
+ await monitor.toolbox.selectTool("netmonitor");
+
+ // Load a second request and make sure they still show up
+ wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ assertSingleRequestState();
+ assertNetworkEventResourceState(1);
+
+ // Make sure we can now open the network details panel
+ store.dispatch(Actions.toggleNetworkDetails());
+ const detailsPanelToggleButton = document.querySelector(".sidebar-toggle");
+ // Wait for the details panel to finish fetching the headers information
+ await waitForRequestData(store, ["requestHeaders", "responseHeaders"]);
+
+ ok(
+ detailsPanelToggleButton &&
+ !detailsPanelToggleButton.classList.contains("pane-collapsed"),
+ "The details pane should be visible."
+ );
+
+ // Click clear and make sure the details pane closes
+ waitRequestListCleared = waitForEmptyRequestList(document);
+ EventUtils.sendMouseEvent({ type: "click" }, clearButton);
+ await waitRequestListCleared;
+
+ assertNoRequestState();
+ assertNetworkEventResourceState(0);
+
+ ok(
+ !document.querySelector(".network-details-bar"),
+ "The details pane should not be visible clicking 'clear'."
+ );
+
+ return teardown(monitor);
+
+ /**
+ * Asserts the state of the network monitor when one request has loaded
+ */
+ function assertSingleRequestState() {
+ is(
+ store.getState().requests.requests.length,
+ 1,
+ "The request menu should have one item at this point."
+ );
+ }
+
+ /**
+ * Asserts the state of the network monitor when no requests have loaded
+ */
+ function assertNoRequestState() {
+ is(
+ store.getState().requests.requests.length,
+ 0,
+ "The request menu should be empty at this point."
+ );
+ }
+
+ function assertNetworkEventResourceState(expectedNoOfNetworkEventResources) {
+ const actualNoOfNetworkEventResources =
+ toolbox.resourceCommand.getAllResources(
+ toolbox.resourceCommand.TYPES.NETWORK_EVENT
+ ).length;
+
+ is(
+ actualNoOfNetworkEventResources,
+ expectedNoOfNetworkEventResources,
+ `The expected number of network resources is correctly ${actualNoOfNetworkEventResources}`
+ );
+ }
+
+ function waitForEmptyRequestList(doc) {
+ info("Wait for request list to clear");
+ return waitFor(() => !!doc.querySelector(".request-list-empty-notice"));
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_column-resize-fit.js b/devtools/client/netmonitor/test/browser_net_column-resize-fit.js
new file mode 100644
index 0000000000..7cb60a8c38
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_column-resize-fit.js
@@ -0,0 +1,95 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests resizing of columns in NetMonitor.
+ */
+add_task(async function () {
+ // Reset visibleColumns so we only get the default ones
+ // and not all that are set in head.js
+ Services.prefs.clearUserPref("devtools.netmonitor.visibleColumns");
+ const visibleColumns = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.visibleColumns")
+ );
+ // Init network monitor
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document } = monitor.panelWin;
+
+ // Wait for network events (to have some requests in the table)
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ info("Testing column resize to fit using double-click on draggable resizer");
+ const fileHeader = document.querySelector(`#requests-list-file-header-box`);
+ const fileColumnResizer = fileHeader.querySelector(".column-resizer");
+
+ EventUtils.sendMouseEvent({ type: "dblclick" }, fileColumnResizer);
+
+ // After resize - get fresh prefs for tests.
+ let columnsData = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.columnsData")
+ );
+
+ // `File` column before resize: 25%, after resize: 11.25%
+ // `Transferred` column before resize: 10%, after resize: 10%
+ checkColumnsData(columnsData, "file", 12);
+ checkSumOfVisibleColumns(columnsData, visibleColumns);
+
+ info(
+ "Testing column resize to fit using context menu `Resize Column To Fit Content`"
+ );
+
+ // Resizing `transferred` column.
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector("#requests-list-transferred-button")
+ );
+
+ await selectContextMenuItem(
+ monitor,
+ "request-list-header-resize-column-to-fit-content"
+ );
+
+ columnsData = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.columnsData")
+ );
+
+ // `Transferred` column before resize: 10%, after resize: 2.97%
+ checkColumnsData(columnsData, "transferred", 3);
+ checkSumOfVisibleColumns(columnsData, visibleColumns);
+
+ // Done: clean up.
+ return teardown(monitor);
+});
+
+function checkColumnsData(columnsData, column, expectedWidth) {
+ const width = getWidthFromPref(columnsData, column);
+ const widthsDiff = Math.abs(width - expectedWidth);
+ ok(
+ widthsDiff < 2,
+ `Column ${column} has expected size. Got ${width}, Expected ${expectedWidth}`
+ );
+}
+
+function checkSumOfVisibleColumns(columnsData, visibleColumns) {
+ let sum = 0;
+ visibleColumns.forEach(column => {
+ sum += getWidthFromPref(columnsData, column);
+ });
+ sum = Math.round(sum);
+ is(sum, 100, "All visible columns cover 100%.");
+}
+
+function getWidthFromPref(columnsData, column) {
+ const widthInPref = columnsData.find(function (element) {
+ return element.name === column;
+ }).width;
+ return widthInPref;
+}
diff --git a/devtools/client/netmonitor/test/browser_net_column_headers_tooltips.js b/devtools/client/netmonitor/test/browser_net_column_headers_tooltips.js
new file mode 100644
index 0000000000..56a23c058d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_column_headers_tooltips.js
@@ -0,0 +1,30 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Bug 1377094 - Test that all column headers have tooltips.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ const { document } = monitor.panelWin;
+
+ const headers = document.querySelectorAll(".requests-list-header-button");
+ for (const header of headers) {
+ const buttonText = header.querySelector(".button-text").textContent;
+ const tooltip = header.getAttribute("title");
+ is(
+ buttonText,
+ tooltip,
+ "The " +
+ header.id +
+ " header has the button text in its 'title' attribute."
+ );
+ }
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_column_slow-request-indicator.js b/devtools/client/netmonitor/test/browser_net_column_slow-request-indicator.js
new file mode 100644
index 0000000000..368873c3c6
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_column_slow-request-indicator.js
@@ -0,0 +1,69 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that the slow request indicator is visible for slow requests.
+ */
+
+add_task(async function () {
+ // The script sjs_slow-script-server.sjs takes about 2s which is
+ // definately above the slow threshold set here.
+ const SLOW_THRESHOLD = 450;
+
+ Services.prefs.setIntPref("devtools.netmonitor.audits.slow", SLOW_THRESHOLD);
+
+ const { monitor } = await initNetMonitor(SLOW_REQUESTS_URL, {
+ requestCount: 2,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 2);
+ await reloadBrowser();
+ await wait;
+
+ const requestList = document.querySelectorAll(
+ ".network-monitor .request-list-item"
+ );
+
+ info("Checking the html document request");
+ is(
+ requestList[0].querySelector(".requests-list-file div:first-child")
+ .textContent,
+ "html_slow-requests-test-page.html",
+ "The html document is the first request"
+ );
+ is(
+ !!requestList[0].querySelector(".requests-list-slow-button"),
+ false,
+ "The request is not slow"
+ );
+
+ info("Checking the slow script request");
+ is(
+ requestList[1].querySelector(".requests-list-file div:first-child")
+ .textContent,
+ "sjs_slow-script-server.sjs",
+ "The slow test script is the second request"
+ );
+ is(
+ !!requestList[1].querySelector(".requests-list-slow-button"),
+ true,
+ "The request is slow"
+ );
+
+ is(
+ requestList[1]
+ .querySelector(".requests-list-slow-button")
+ .title.includes(`The recommended limit is ${SLOW_THRESHOLD} ms.`),
+ true,
+ "The tooltip text is correct"
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_columns_last_column.js b/devtools/client/netmonitor/test/browser_net_columns_last_column.js
new file mode 100644
index 0000000000..aaed0aa210
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_columns_last_column.js
@@ -0,0 +1,64 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that last visible column can't be hidden. Note that the column
+ * header is visible only if there are requests in the list.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ const initialColumns = store.getState().ui.columns;
+ for (const column in initialColumns) {
+ const shown = initialColumns[column];
+
+ const columns = store.getState().ui.columns;
+ const visibleColumns = [];
+ for (const c in columns) {
+ if (columns[c]) {
+ visibleColumns.push(c);
+ }
+ }
+
+ if (visibleColumns.length === 1) {
+ if (!shown) {
+ continue;
+ }
+ await testLastMenuItem(column);
+ break;
+ }
+
+ if (shown) {
+ await hideColumn(monitor, column);
+ }
+ }
+
+ await teardown(monitor);
+
+ async function testLastMenuItem(column) {
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector(`#requests-list-${column}-button`)
+ );
+
+ const menuItem = getContextMenuItem(
+ monitor,
+ `request-list-header-${column}-toggle`
+ );
+ ok(menuItem.disabled, "Last visible column menu item should be disabled.");
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_columns_pref.js b/devtools/client/netmonitor/test/browser_net_columns_pref.js
new file mode 100644
index 0000000000..4c64ac8f94
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_columns_pref.js
@@ -0,0 +1,59 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if visible columns are properly saved. Note that the column
+ * header is visible only if there are requests in the list.
+ */
+
+add_task(async function () {
+ Services.prefs.setCharPref(
+ "devtools.netmonitor.visibleColumns",
+ '["status", "contentSize", "waterfall"]'
+ );
+
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ ok(
+ document.querySelector("#requests-list-status-button"),
+ "Status column should be shown"
+ );
+ ok(
+ document.querySelector("#requests-list-contentSize-button"),
+ "Content size column should be shown"
+ );
+
+ await hideColumn(monitor, "status");
+ await hideColumn(monitor, "contentSize");
+
+ let visibleColumns = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.visibleColumns")
+ );
+
+ ok(!visibleColumns.includes("status"), "Pref should be synced for status");
+ ok(
+ !visibleColumns.includes("contentSize"),
+ "Pref should be synced for contentSize"
+ );
+
+ await showColumn(monitor, "status");
+
+ visibleColumns = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.visibleColumns")
+ );
+
+ ok(visibleColumns.includes("status"), "Pref should be synced for status");
+});
diff --git a/devtools/client/netmonitor/test/browser_net_columns_reset.js b/devtools/client/netmonitor/test/browser_net_columns_reset.js
new file mode 100644
index 0000000000..bdee8de75b
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_columns_reset.js
@@ -0,0 +1,43 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests reset column menu item. Note that the column
+ * header is visible only if there are requests in the list.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { Prefs } = windowRequire("devtools/client/netmonitor/src/utils/prefs");
+
+ const prefBefore = Prefs.visibleColumns;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ await hideColumn(monitor, "status");
+ await hideColumn(monitor, "waterfall");
+
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector("#requests-list-contentSize-button")
+ );
+
+ await selectContextMenuItem(monitor, "request-list-header-reset-columns");
+
+ ok(
+ JSON.stringify(prefBefore) === JSON.stringify(Prefs.visibleColumns),
+ "Reset columns item should reset columns pref"
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_columns_showhide.js b/devtools/client/netmonitor/test/browser_net_columns_showhide.js
new file mode 100644
index 0000000000..7213d2c5f7
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_columns_showhide.js
@@ -0,0 +1,181 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test showing/hiding columns.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, connector, windowRequire } = monitor.panelWin;
+ const { requestData } = connector;
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await wait;
+
+ const item = getSortedRequests(store.getState())[0];
+ ok(
+ item.responseHeadersAvailable,
+ "headers are available for lazily fetching"
+ );
+
+ if (item.responseHeadersAvailable && !item.responseHeaders) {
+ await requestData(item.id, "responseHeaders");
+ }
+
+ const requestsContainer = document.querySelector(".requests-list-row-group");
+ ok(requestsContainer, "Container element exists as expected.");
+ const headers = document.querySelector(".requests-list-headers");
+
+ let columns = store.getState().ui.columns;
+ for (const column in columns) {
+ if (columns[column]) {
+ await testVisibleColumnContextMenuItem(column, document, monitor);
+ testColumnsAlignment(headers, requestsContainer);
+ await testHiddenColumnContextMenuItem(column, document, monitor);
+ } else {
+ await testHiddenColumnContextMenuItem(column, document, monitor);
+ testColumnsAlignment(headers, requestsContainer);
+ await testVisibleColumnContextMenuItem(column, document, monitor);
+ }
+ }
+
+ columns = store.getState().ui.columns;
+ for (const column in columns) {
+ if (columns[column]) {
+ await testVisibleColumnContextMenuItem(column, document, monitor);
+ // Right click on the white-space for the context menu to appear
+ // and toggle column visibility
+ await testWhiteSpaceContextMenuItem(column, document, monitor);
+ }
+ }
+});
+
+async function testWhiteSpaceContextMenuItem(column, document, monitor) {
+ ok(
+ !document.querySelector(`#requests-list-${column}-button`),
+ `Column ${column} should be hidden`
+ );
+
+ info(`Right clicking on white-space in the header to get the context menu`);
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector(".requests-list-headers")
+ );
+
+ // Wait for next tick to do stuff async and force repaint.
+ await waitForTick();
+ await toggleAndCheckColumnVisibility(column, document, monitor);
+}
+
+async function testVisibleColumnContextMenuItem(column, document, monitor) {
+ ok(
+ document.querySelector(`#requests-list-${column}-button`),
+ `Column ${column} should be visible`
+ );
+
+ info(`Clicking context-menu item for ${column}`);
+
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector("#requests-list-status-button") ||
+ document.querySelector("#requests-list-waterfall-button")
+ );
+
+ await waitForTick();
+
+ const id = `request-list-header-${column}-toggle`;
+ const menuItem = getContextMenuItem(monitor, id);
+
+ is(
+ menuItem.getAttribute("type"),
+ "checkbox",
+ `${column} menu item should have type="checkbox" attribute`
+ );
+ is(
+ menuItem.getAttribute("checked"),
+ "true",
+ `checked state of ${column} menu item should be correct`
+ );
+ ok(
+ !menuItem.disabled,
+ `disabled state of ${column} menu item should be correct`
+ );
+
+ const onHeaderRemoved = waitForDOM(
+ document,
+ `#requests-list-${column}-button`,
+ 0
+ );
+
+ await selectContextMenuItem(monitor, id);
+
+ await onHeaderRemoved;
+ await waitForTick();
+
+ ok(
+ !document.querySelector(`#requests-list-${column}-button`),
+ `Column ${column} should be hidden`
+ );
+}
+
+async function testHiddenColumnContextMenuItem(column, document, monitor) {
+ ok(
+ !document.querySelector(`#requests-list-${column}-button`),
+ `Column ${column} should be hidden`
+ );
+
+ info(`Clicking context-menu item for ${column}`);
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector("#requests-list-status-button") ||
+ document.querySelector("#requests-list-waterfall-button")
+ );
+
+ await waitForTick();
+ await toggleAndCheckColumnVisibility(column, document, monitor);
+}
+
+async function toggleAndCheckColumnVisibility(column, document, monitor) {
+ const id = `request-list-header-${column}-toggle`;
+ const menuItem = getContextMenuItem(monitor, id);
+
+ is(
+ menuItem.getAttribute("type"),
+ "checkbox",
+ `${column} menu item should have type="checkbox" attribute`
+ );
+ ok(
+ !menuItem.getAttribute("checked"),
+ `checked state of ${column} menu item should be correct`
+ );
+ ok(
+ !menuItem.disabled,
+ `disabled state of ${column} menu item should be correct`
+ );
+
+ const onHeaderAdded = waitForDOM(
+ document,
+ `#requests-list-${column}-button`,
+ 1
+ );
+
+ await selectContextMenuItem(monitor, id);
+
+ await onHeaderAdded;
+ await waitForTick();
+
+ ok(
+ document.querySelector(`#requests-list-${column}-button`),
+ `Column ${column} should be visible`
+ );
+}
diff --git a/devtools/client/netmonitor/test/browser_net_columns_time.js b/devtools/client/netmonitor/test/browser_net_columns_time.js
new file mode 100644
index 0000000000..c2e9a9b858
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_columns_time.js
@@ -0,0 +1,61 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests for timings columns. Note that the column
+ * header is visible only if there are requests in the list.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const visibleColumns = store.getState().ui.columns;
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ // Hide the waterfall column to make sure timing data are fetched
+ // by the other timing columns ("endTime", "responseTime", "duration",
+ // "latency").
+ // Note that all these timing columns are based on the same
+ // `RequestListColumnTime` component.
+ if (visibleColumns.waterfall) {
+ await hideColumn(monitor, "waterfall");
+ }
+
+ ["endTime", "responseTime", "duration", "latency"].forEach(async column => {
+ if (!visibleColumns[column]) {
+ await showColumn(monitor, column);
+ }
+ });
+
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await onNetworkEvents;
+
+ // There should be one request in the list.
+ const requestItems = document.querySelectorAll(".request-list-item");
+ is(requestItems.length, 1, "There must be one visible item");
+
+ const item = requestItems[0];
+ const types = ["end", "response", "duration", "latency"];
+
+ for (const t of types) {
+ await waitUntil(() => {
+ const node = item.querySelector(".requests-list-" + t + "-time");
+ const value = parseInt(node.textContent, 10);
+ return value > 0;
+ });
+ }
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_complex-params.js b/devtools/client/netmonitor/test/browser_net_complex-params.js
new file mode 100644
index 0000000000..3b746fa7ac
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_complex-params.js
@@ -0,0 +1,310 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests whether complex request params and payload sent via POST are
+ * displayed correctly.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(PARAMS_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 12);
+
+ const requestListItems = document.querySelectorAll(
+ ".network-monitor .request-list-item"
+ );
+
+ // Select the Request tab.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requestListItems[0]);
+ clickOnSidebarTab(document, "request");
+
+ await testRequestWithFormattedView(
+ monitor,
+ requestListItems[0],
+ '{ "foo": "bar" }',
+ "",
+ '{ "foo": "bar" }',
+ 1
+ );
+ await testRequestWithFormattedView(
+ monitor,
+ requestListItems[1],
+ '{ "foo": "bar" }',
+ "",
+ '{ "foo": "bar" }',
+ 1
+ );
+ await testRequestWithFormattedView(
+ monitor,
+ requestListItems[2],
+ "?foo",
+ "bar",
+ "?foo=bar",
+ 1
+ );
+ await testRequestWithFormattedView(
+ monitor,
+ requestListItems[3],
+ "foo",
+ "bar",
+ '{ "foo": "bar" }',
+ 2
+ );
+ await testRequestWithFormattedView(
+ monitor,
+ requestListItems[4],
+ "foo",
+ "bar",
+ '{ "foo": "bar" }',
+ 2
+ );
+ await testRequestWithOnlyRawDataView(
+ monitor,
+ requestListItems[5],
+ "?foo=bar"
+ );
+ await testRequestWithoutRequestData(monitor, requestListItems[6]);
+ await testRequestWithFormattedView(
+ monitor,
+ requestListItems[7],
+ '{ "foo": "bar" }',
+ "",
+ '{ "foo": "bar" }',
+ 1
+ );
+ await testRequestWithFormattedView(
+ monitor,
+ requestListItems[8],
+ '{ "foo": "bar" }',
+ "",
+ '{ "foo": "bar" }',
+ 1
+ );
+
+ await teardown(monitor);
+});
+
+async function testRequestWithFormattedView(
+ monitor,
+ requestListItem,
+ paramName,
+ paramValue,
+ rawValue,
+ dataType
+) {
+ const { document, windowRequire } = monitor.panelWin;
+ const { L10N } = windowRequire("devtools/client/netmonitor/src/utils/l10n");
+
+ // Wait for header and properties view to be displayed
+ const wait = waitForDOM(document, "#request-panel .data-header");
+ let waitForContent = waitForDOM(document, "#request-panel .properties-view");
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requestListItem);
+ await Promise.all([wait, waitForContent]);
+
+ const tabpanel = document.querySelector("#request-panel");
+ let headerLabel;
+ switch (dataType) {
+ case 1:
+ headerLabel = L10N.getStr("paramsFormData");
+ break;
+
+ case 2:
+ headerLabel = L10N.getStr("jsonScopeName");
+ break;
+ }
+
+ is(
+ tabpanel.querySelectorAll(".raw-data-toggle").length,
+ 1,
+ "The raw request data toggle should be displayed in this tabpanel."
+ );
+ is(
+ tabpanel.querySelectorAll("tr.treeRow").length,
+ 1,
+ "The number of param rows displayed in this tabpanel is incorrect."
+ );
+ ok(
+ tabpanel.querySelector(".empty-notice") === null,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+
+ ok(
+ tabpanel.querySelector(".treeTable"),
+ "The request params box should be displayed."
+ );
+ ok(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ "The request post data editor should not be displayed."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ is(
+ tabpanel.querySelector(".data-label").textContent,
+ headerLabel,
+ "The form data section doesn't have the correct title."
+ );
+
+ is(
+ labels[0].textContent,
+ paramName,
+ "The first form data param name was incorrect."
+ );
+ is(
+ values[0].textContent,
+ `"${paramValue}"`,
+ "The first form data param value was incorrect."
+ );
+
+ // Toggle the raw data display. This should hide the formatted display.
+ waitForContent = waitForDOM(document, "#request-panel .CodeMirror-code");
+ let rawDataToggle = document.querySelector(
+ "#request-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(rawDataToggle, monitor);
+ await waitForContent;
+
+ const dataLabel = tabpanel.querySelector(".data-label") ?? {};
+ is(
+ dataLabel.textContent,
+ L10N.getStr("paramsPostPayload"),
+ "The label for the raw request payload is correct."
+ );
+ is(
+ tabpanel.querySelector(".raw-data-toggle-input .devtools-checkbox-toggle")
+ .checked,
+ true,
+ "The raw request toggle should be on."
+ );
+ is(
+ tabpanel.querySelector(".properties-view") === null,
+ true,
+ "The formatted display should be hidden."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") !== null,
+ true,
+ "The raw payload data display is shown."
+ );
+ is(
+ getCodeMirrorValue(monitor),
+ rawValue,
+ "The raw payload data string needs to be correct."
+ );
+ ok(
+ tabpanel.querySelector(".empty-notice") === null,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+
+ // Toggle the raw data display off again. This should show the formatted display.
+ // This is required to reset the original state
+ waitForContent = waitForDOM(document, "#request-panel .properties-view");
+ rawDataToggle = document.querySelector(
+ "#request-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(rawDataToggle, monitor);
+ await waitForContent;
+}
+
+async function testRequestWithOnlyRawDataView(
+ monitor,
+ requestListItem,
+ paramName
+) {
+ const { document, windowRequire } = monitor.panelWin;
+ const { L10N } = windowRequire("devtools/client/netmonitor/src/utils/l10n");
+
+ // Wait for header and CodeMirror editor to be displayed
+ const wait = waitForDOM(document, "#request-panel .data-header");
+ const waitForContent = waitForDOM(
+ document,
+ "#request-panel .CodeMirror-code"
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requestListItem);
+ await Promise.all([wait, waitForContent]);
+
+ const tabpanel = document.querySelector("#request-panel");
+
+ const dataLabel = tabpanel.querySelector(".data-label") ?? {};
+ is(
+ dataLabel.textContent,
+ L10N.getStr("paramsPostPayload"),
+ "The label for the raw request payload is correct."
+ );
+ is(
+ tabpanel.querySelectorAll(".raw-data-toggle").length,
+ 0,
+ "The raw request data toggle should not be displayed in this tabpanel."
+ );
+ is(
+ tabpanel.querySelector(".properties-view") === null,
+ true,
+ "The formatted display should be hidden."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") !== null,
+ true,
+ "The raw payload data display is shown."
+ );
+ is(
+ getCodeMirrorValue(monitor),
+ paramName,
+ "The raw payload data string needs to be correct."
+ );
+ ok(
+ tabpanel.querySelector(".empty-notice") === null,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+}
+
+async function testRequestWithoutRequestData(monitor, requestListItem) {
+ const { document } = monitor.panelWin;
+
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requestListItem);
+
+ const tabpanel = document.querySelector("#request-panel");
+
+ is(
+ tabpanel.querySelector(".data-label") === null,
+ true,
+ "There must be no label for the request payload."
+ );
+ is(
+ tabpanel.querySelectorAll(".raw-data-toggle").length,
+ 0,
+ "The raw request data toggle should not be displayed in this tabpanel."
+ );
+ is(
+ tabpanel.querySelector(".properties-view") === null,
+ true,
+ "The formatted display should be hidden."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ true,
+ "The raw payload data display should be hidden."
+ );
+ is(
+ tabpanel.querySelector(".empty-notice") !== null,
+ true,
+ "The empty notice should be displayed in this tabpanel."
+ );
+ is(
+ tabpanel.querySelector(".empty-notice").textContent,
+ L10N.getStr("paramsNoPayloadText"),
+ "The empty notice should be correct."
+ );
+}
diff --git a/devtools/client/netmonitor/test/browser_net_content-type.js b/devtools/client/netmonitor/test/browser_net_content-type.js
new file mode 100644
index 0000000000..df0bec0c23
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_content-type.js
@@ -0,0 +1,358 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if different response content types are handled correctly.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ CONTENT_TYPE_WITHOUT_CACHE_URL,
+ { requestCount: 1 }
+ );
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { L10N } = windowRequire("devtools/client/netmonitor/src/utils/l10n");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, CONTENT_TYPE_WITHOUT_CACHE_REQUESTS);
+
+ for (const requestItem of document.querySelectorAll(".request-list-item")) {
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ requestItem.scrollIntoView();
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+ }
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=xml",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "xml",
+ fullMimeType: "text/xml; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 42),
+ time: true,
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[1],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=css",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "css",
+ fullMimeType: "text/css; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 34),
+ time: true,
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[2],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=js",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "js",
+ fullMimeType: "application/javascript; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 34),
+ time: true,
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[3],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=json",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "json",
+ fullMimeType: "application/json; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 29),
+ time: true,
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[4],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=bogus",
+ {
+ status: 404,
+ statusText: "Not Found",
+ type: "html",
+ fullMimeType: "text/html; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 24),
+ time: true,
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[5],
+ "GET",
+ TEST_IMAGE,
+ {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "png",
+ fullMimeType: "image/png",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 580),
+ time: true,
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[6],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=gzip",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "plain",
+ fullMimeType: "text/plain",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 324),
+ size: L10N.getFormatStrWithNumbers("networkMenu.size.kB", 10.99),
+ time: true,
+ }
+ );
+
+ await selectIndexAndWaitForSourceEditor(monitor, 0);
+ await testResponseTab("xml");
+
+ await selectIndexAndWaitForSourceEditor(monitor, 1);
+ await testResponseTab("css");
+
+ await selectIndexAndWaitForSourceEditor(monitor, 2);
+ await testResponseTab("js");
+
+ await selectIndexAndWaitForJSONView(3);
+ await testResponseTab("json");
+
+ await selectIndexAndWaitForHtmlView(4);
+ await testResponseTab("html");
+
+ await selectIndexAndWaitForImageView(5);
+ await testResponseTab("png");
+
+ await selectIndexAndWaitForSourceEditor(monitor, 6);
+ await testResponseTab("gzip");
+
+ await teardown(monitor);
+
+ function testResponseTab(type) {
+ const tabpanel = document.querySelector("#response-panel");
+
+ function checkVisibility(box) {
+ is(
+ tabpanel.querySelector(".response-error-header") === null,
+ true,
+ "The response error header doesn't display"
+ );
+ const jsonView = tabpanel.querySelector(".data-label") || {};
+ is(
+ jsonView.textContent !== L10N.getStr("jsonScopeName"),
+ box != "json",
+ "The response json view doesn't display"
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ box !== "textarea",
+ "The response editor doesn't display"
+ );
+ is(
+ tabpanel.querySelector(".response-image-box") === null,
+ box != "image",
+ "The response image view doesn't display"
+ );
+ }
+
+ switch (type) {
+ case "xml": {
+ checkVisibility("textarea");
+
+ const text = getCodeMirrorValue(monitor);
+
+ is(
+ text,
+ "<label value='greeting'>Hello XML!</label>",
+ "The text shown in the source editor is incorrect for the xml request."
+ );
+ break;
+ }
+ case "css": {
+ checkVisibility("textarea");
+
+ const text = getCodeMirrorValue(monitor);
+
+ is(
+ text,
+ "body:pre { content: 'Hello CSS!' }",
+ "The text shown in the source editor is incorrect for the css request."
+ );
+ break;
+ }
+ case "js": {
+ checkVisibility("textarea");
+
+ const text = getCodeMirrorValue(monitor);
+
+ is(
+ text,
+ "function() { return 'Hello JS!'; }",
+ "The text shown in the source editor is incorrect for the js request."
+ );
+ break;
+ }
+ case "json": {
+ checkVisibility("json");
+
+ is(
+ tabpanel.querySelectorAll(".raw-data-toggle").length,
+ 1,
+ "The response payload toggle should be displayed in this tabpanel."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+
+ is(
+ tabpanel.querySelector(".data-label").textContent,
+ L10N.getStr("jsonScopeName"),
+ "The json view section doesn't have the correct title."
+ );
+
+ const labels = tabpanel.querySelectorAll(
+ "tr .treeLabelCell .treeLabel"
+ );
+ const values = tabpanel.querySelectorAll(
+ "tr .treeValueCell .objectBox"
+ );
+
+ is(
+ labels[0].textContent,
+ "greeting",
+ "The first json property name was incorrect."
+ );
+ is(
+ values[0].textContent,
+ `"Hello JSON!"`,
+ "The first json property value was incorrect."
+ );
+ break;
+ }
+ case "html": {
+ checkVisibility("html");
+
+ const text = document.querySelector(".html-preview iframe").src;
+ const expectedText =
+ "data:text/html;charset=UTF-8," +
+ encodeURIComponent("<blink>Not Found</blink>");
+
+ is(
+ text,
+ expectedText,
+ "The text shown in the iframe is incorrect for the html request."
+ );
+ break;
+ }
+ case "png": {
+ checkVisibility("image");
+
+ const [name, dimensions, mime] = tabpanel.querySelectorAll(
+ ".response-image-box .tabpanel-summary-value"
+ );
+
+ is(
+ name.textContent,
+ "test-image.png",
+ "The image name info isn't correct."
+ );
+ is(mime.textContent, "image/png", "The image mime info isn't correct.");
+ is(
+ dimensions.textContent,
+ "16" + " \u00D7 " + "16",
+ "The image dimensions info isn't correct."
+ );
+ break;
+ }
+ case "gzip": {
+ checkVisibility("textarea");
+
+ const text = getCodeMirrorValue(monitor);
+
+ is(
+ text,
+ new Array(1000).join("Hello gzip!"),
+ "The text shown in the source editor is incorrect for the gzip request."
+ );
+ break;
+ }
+ }
+ }
+
+ async function selectIndexAndWaitForHtmlView(index) {
+ const onResponseContent = monitor.panelWin.api.once(
+ TEST_EVENTS.RECEIVED_RESPONSE_CONTENT
+ );
+ const tabpanel = document.querySelector("#response-panel");
+ const waitDOM = waitForDOM(tabpanel, ".html-preview");
+ store.dispatch(Actions.selectRequestByIndex(index));
+ await waitDOM;
+ await onResponseContent;
+ }
+
+ async function selectIndexAndWaitForJSONView(index) {
+ const onResponseContent = monitor.panelWin.api.once(
+ TEST_EVENTS.RECEIVED_RESPONSE_CONTENT
+ );
+ const tabpanel = document.querySelector("#response-panel");
+ const waitDOM = waitForDOM(tabpanel, ".treeTable");
+ store.dispatch(Actions.selectRequestByIndex(index));
+ await waitDOM;
+ await onResponseContent;
+
+ // Waiting for RECEIVED_RESPONSE_CONTENT isn't enough.
+ // DOM may not be fully updated yet and checkVisibility(json) may still fail.
+ await waitForTick();
+ }
+
+ async function selectIndexAndWaitForImageView(index) {
+ const onResponseContent = monitor.panelWin.api.once(
+ TEST_EVENTS.RECEIVED_RESPONSE_CONTENT
+ );
+ const tabpanel = document.querySelector("#response-panel");
+ const waitDOM = waitForDOM(tabpanel, ".response-image");
+ store.dispatch(Actions.selectRequestByIndex(index));
+ const [imageNode] = await waitDOM;
+ await once(imageNode, "load");
+ await onResponseContent;
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_cookies_sorted.js b/devtools/client/netmonitor/test/browser_net_cookies_sorted.js
new file mode 100644
index 0000000000..f25220f650
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_cookies_sorted.js
@@ -0,0 +1,85 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if Request-Cookies and Response-Cookies are sorted in Cookies tab.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_UNSORTED_COOKIES_SJS, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ let wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ wait = waitForDOM(document, ".headers-overview");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ clickOnSidebarTab(document, "cookies");
+
+ info("Check if Request-Cookies and Response-Cookies are sorted");
+ const expectedLabelValues = [
+ "__proto__",
+ "httpOnly",
+ "value",
+ "bob",
+ "httpOnly",
+ "value",
+ "foo",
+ "httpOnly",
+ "value",
+ "tom",
+ "httpOnly",
+ "value",
+ "__proto__",
+ "bob",
+ "foo",
+ "tom",
+ ];
+
+ const labelCells = document.querySelectorAll(".treeLabelCell");
+ labelCells.forEach(function (val, index) {
+ is(
+ val.innerText,
+ expectedLabelValues[index],
+ "Actual label value " +
+ val.innerText +
+ " not equal to expected label value " +
+ expectedLabelValues[index]
+ );
+ });
+
+ const lastItem = document.querySelector(
+ "#cookies-panel .properties-view tr.treeRow:last-child"
+ );
+ lastItem.scrollIntoView();
+
+ info("Checking for unwanted scrollbars appearing in the tree view");
+ const view = document.querySelector(
+ "#cookies-panel .properties-view .treeTable"
+ );
+ is(scrolledToBottom(view), true, "The view is not scrollable");
+
+ await teardown(monitor);
+
+ function scrolledToBottom(element) {
+ return element.scrollTop + element.clientHeight >= element.scrollHeight;
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_copy_as_curl.js b/devtools/client/netmonitor/test/browser_net_copy_as_curl.js
new file mode 100644
index 0000000000..4cce679fe9
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_copy_as_curl.js
@@ -0,0 +1,242 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if Copy as cURL works.
+ */
+
+const POST_PAYLOAD = "Plaintext value as a payload";
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(HTTPS_CURL_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ // Different quote chars are used for Windows and POSIX
+ const QUOTE_WIN = '"';
+ const QUOTE_POSIX = "'";
+
+ const isWin = Services.appinfo.OS === "WINNT";
+ const testData = isWin
+ ? [
+ {
+ menuItemId: "request-list-context-copy-as-curl-win",
+ data: buildTestData(QUOTE_WIN),
+ },
+ {
+ menuItemId: "request-list-context-copy-as-curl-posix",
+ data: buildTestData(QUOTE_POSIX),
+ },
+ ]
+ : [
+ {
+ menuItemId: "request-list-context-copy-as-curl",
+ data: buildTestData(QUOTE_POSIX),
+ },
+ ];
+
+ await testForPlatform(tab, monitor, testData);
+
+ await teardown(monitor);
+});
+
+function buildTestData(QUOTE) {
+ // Quote a string, escape the quotes inside the string
+ function quote(str) {
+ return QUOTE + str.replace(new RegExp(QUOTE, "g"), `\\${QUOTE}`) + QUOTE;
+ }
+
+ // Header param is formatted as -H "Header: value" or -H 'Header: value'
+ function header(h) {
+ return "-H " + quote(h);
+ }
+
+ // Construct the expected command
+ const SIMPLE_BASE = ["curl " + quote(HTTPS_SIMPLE_SJS)];
+ const SLOW_BASE = ["curl " + quote(HTTPS_SLOW_SJS)];
+ const BASE_RESULT = [
+ "--compressed",
+ header("User-Agent: " + navigator.userAgent),
+ header("Accept: */*"),
+ header("Accept-Language: " + navigator.language),
+ header("X-Custom-Header-1: Custom value"),
+ header("X-Custom-Header-2: 8.8.8.8"),
+ header("X-Custom-Header-3: Mon, 3 Mar 2014 11:11:11 GMT"),
+ header("Referer: " + HTTPS_CURL_URL),
+ header("Connection: keep-alive"),
+ header("Pragma: no-cache"),
+ header("Cache-Control: no-cache"),
+ header("Sec-Fetch-Dest: empty"),
+ header("Sec-Fetch-Mode: cors"),
+ header("Sec-Fetch-Site: same-origin"),
+ ];
+
+ const COOKIE_PARTIAL_RESULT = [header("Cookie: bob=true; tom=cool")];
+
+ const POST_PARTIAL_RESULT = [
+ "-X",
+ "POST",
+ "--data-raw " + quote(POST_PAYLOAD),
+ header("Content-Type: text/plain;charset=UTF-8"),
+ ];
+ const ORIGIN_RESULT = [header("Origin: https://example.com")];
+
+ const HEAD_PARTIAL_RESULT = ["-I"];
+
+ return {
+ SIMPLE_BASE,
+ SLOW_BASE,
+ BASE_RESULT,
+ COOKIE_PARTIAL_RESULT,
+ POST_PAYLOAD,
+ POST_PARTIAL_RESULT,
+ ORIGIN_RESULT,
+ HEAD_PARTIAL_RESULT,
+ };
+}
+
+async function testForPlatform(tab, monitor, testData) {
+ // GET request, no cookies (first request)
+ await performRequest("GET");
+ for (const test of testData) {
+ await testClipboardContent(test.menuItemId, [
+ ...test.data.SIMPLE_BASE,
+ ...test.data.BASE_RESULT,
+ ]);
+ }
+ // Check to make sure it is still OK after we view the response (bug#1452442)
+ await selectIndexAndWaitForSourceEditor(monitor, 0);
+ for (const test of testData) {
+ await testClipboardContent(test.menuItemId, [
+ ...test.data.SIMPLE_BASE,
+ ...test.data.BASE_RESULT,
+ ]);
+ }
+
+ // GET request, cookies set by previous response
+ await performRequest("GET");
+ for (const test of testData) {
+ await testClipboardContent(test.menuItemId, [
+ ...test.data.SIMPLE_BASE,
+ ...test.data.BASE_RESULT,
+ ...test.data.COOKIE_PARTIAL_RESULT,
+ ]);
+ }
+
+ // Unfinished request (bug#1378464, bug#1420513)
+ const waitSlow = waitForNetworkEvents(monitor, 0);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [HTTPS_SLOW_SJS],
+ async function (url) {
+ content.wrappedJSObject.performRequest(url, "GET", null);
+ }
+ );
+ await waitSlow;
+ for (const test of testData) {
+ await testClipboardContent(test.menuItemId, [
+ ...test.data.SLOW_BASE,
+ ...test.data.BASE_RESULT,
+ ...test.data.COOKIE_PARTIAL_RESULT,
+ ]);
+ }
+
+ // POST request
+ await performRequest("POST", POST_PAYLOAD);
+ for (const test of testData) {
+ await testClipboardContent(test.menuItemId, [
+ ...test.data.SIMPLE_BASE,
+ ...test.data.BASE_RESULT,
+ ...test.data.COOKIE_PARTIAL_RESULT,
+ ...test.data.POST_PARTIAL_RESULT,
+ ...test.data.ORIGIN_RESULT,
+ ]);
+ }
+
+ // HEAD request
+ await performRequest("HEAD");
+ for (const test of testData) {
+ await testClipboardContent(test.menuItemId, [
+ ...test.data.SIMPLE_BASE,
+ ...test.data.BASE_RESULT,
+ ...test.data.COOKIE_PARTIAL_RESULT,
+ ...test.data.HEAD_PARTIAL_RESULT,
+ ]);
+ }
+
+ async function performRequest(method, payload) {
+ const waitRequest = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [
+ {
+ url: HTTPS_SIMPLE_SJS,
+ method_: method,
+ payload_: payload,
+ },
+ ],
+ async function ({ url, method_, payload_ }) {
+ content.wrappedJSObject.performRequest(url, method_, payload_);
+ }
+ );
+ await waitRequest;
+ }
+
+ async function testClipboardContent(menuItemId, expectedResult) {
+ const { document } = monitor.panelWin;
+
+ const items = document.querySelectorAll(".request-list-item");
+ const itemIndex = items.length - 1;
+ EventUtils.sendMouseEvent({ type: "mousedown" }, items[itemIndex]);
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ /* Ensure that the copy as cURL option is always visible */
+ is(
+ !!getContextMenuItem(monitor, menuItemId),
+ true,
+ `The "Copy as cURL" context menu item "${menuItemId}" should not be hidden.`
+ );
+
+ await waitForClipboardPromise(
+ async function setup() {
+ await selectContextMenuItem(monitor, menuItemId);
+ },
+ function validate(result) {
+ if (typeof result !== "string") {
+ return false;
+ }
+
+ // Different setups may produce the same command, but with the
+ // parameters in a different order in the commandline (which is fine).
+ // Here we confirm that the commands are the same even in that case.
+
+ // This monster regexp parses the command line into an array of arguments,
+ // recognizing quoted args with matching quotes and escaped quotes inside:
+ // [ "curl 'url'", "--standalone-arg", "-arg-with-quoted-string 'value\'s'" ]
+ const matchRe = /[-A-Za-z1-9]+(?: ([\"'])(?:\\\1|.)*?\1)?/g;
+
+ const actual = result.match(matchRe);
+ // Must begin with the same "curl 'URL'" segment
+ if (!actual || expectedResult[0] != actual[0]) {
+ return false;
+ }
+
+ // Must match each of the params in the middle (headers)
+ return (
+ expectedResult.length === actual.length &&
+ expectedResult.some(param => actual.includes(param))
+ );
+ }
+ );
+
+ info(
+ `Clipboard contains a cURL command for item ${itemIndex} by "${menuItemId}"`
+ );
+ }
+}
diff --git a/devtools/client/netmonitor/test/browser_net_copy_as_fetch.js b/devtools/client/netmonitor/test/browser_net_copy_as_fetch.js
new file mode 100644
index 0000000000..517e9e54f8
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_copy_as_fetch.js
@@ -0,0 +1,92 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if Copy as Fetch works.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(HTTPS_CURL_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ // GET request, no cookies (first request)
+ await performRequest("GET");
+ await testClipboardContent(`await fetch("https://example.com/browser/devtools/client/netmonitor/test/sjs_simple-test-server.sjs", {
+ "credentials": "omit",
+ "headers": {
+ "User-Agent": "${navigator.userAgent}",
+ "Accept": "*/*",
+ "Accept-Language": "en-US",
+ "X-Custom-Header-1": "Custom value",
+ "X-Custom-Header-2": "8.8.8.8",
+ "X-Custom-Header-3": "Mon, 3 Mar 2014 11:11:11 GMT",
+ "Sec-Fetch-Dest": "empty",
+ "Sec-Fetch-Mode": "cors",
+ "Sec-Fetch-Site": "same-origin",
+ "Pragma": "no-cache",
+ "Cache-Control": "no-cache"
+ },
+ "referrer": "https://example.com/browser/devtools/client/netmonitor/test/html_copy-as-curl.html",
+ "method": "GET",
+ "mode": "cors"
+});`);
+
+ await teardown(monitor);
+
+ async function performRequest(method, payload) {
+ const waitRequest = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [
+ {
+ url: HTTPS_SIMPLE_SJS,
+ method_: method,
+ payload_: payload,
+ },
+ ],
+ async function ({ url, method_, payload_ }) {
+ content.wrappedJSObject.performRequest(url, method_, payload_);
+ }
+ );
+ await waitRequest;
+ }
+
+ async function testClipboardContent(expectedResult) {
+ const { document } = monitor.panelWin;
+
+ const items = document.querySelectorAll(".request-list-item");
+ EventUtils.sendMouseEvent({ type: "mousedown" }, items[items.length - 1]);
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ /* Ensure that the copy as fetch option is always visible */
+ is(
+ !!getContextMenuItem(monitor, "request-list-context-copy-as-fetch"),
+ true,
+ 'The "Copy as Fetch" context menu item should not be hidden.'
+ );
+
+ await waitForClipboardPromise(
+ async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "request-list-context-copy-as-fetch"
+ );
+ },
+ function validate(result) {
+ if (typeof result !== "string") {
+ return false;
+ }
+ return expectedResult === result;
+ }
+ );
+
+ info("Clipboard contains a fetch command for item " + (items.length - 1));
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_copy_as_powershell.js b/devtools/client/netmonitor/test/browser_net_copy_as_powershell.js
new file mode 100644
index 0000000000..5785b89929
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_copy_as_powershell.js
@@ -0,0 +1,167 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test the Copy as PowerShell command
+ */
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(HTTPS_CURL_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+ info("Test powershell command for GET request without any cookies");
+ await performRequest("GET");
+ await testClipboardContentForRecentRequest(`Invoke-WebRequest -UseBasicParsing -Uri "https://example.com/browser/devtools/client/netmonitor/test/sjs_simple-test-server.sjs" \`
+-UserAgent "${navigator.userAgent}" \`
+-Headers @{
+"Accept" = "*/*"
+ "Accept-Language" = "en-US"
+ "Accept-Encoding" = "gzip, deflate, br"
+ "X-Custom-Header-1" = "Custom value"
+ "X-Custom-Header-2" = "8.8.8.8"
+ "X-Custom-Header-3" = "Mon, 3 Mar 2014 11:11:11 GMT"
+ "Referer" = "https://example.com/browser/devtools/client/netmonitor/test/html_copy-as-curl.html"
+ "Sec-Fetch-Dest" = "empty"
+ "Sec-Fetch-Mode" = "cors"
+ "Sec-Fetch-Site" = "same-origin"
+ "Pragma" = "no-cache"
+ "Cache-Control" = "no-cache"
+}`);
+
+ info("Test powershell command for GET request with cookies");
+ await performRequest("GET");
+ await testClipboardContentForRecentRequest(`$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
+$session.Cookies.Add((New-Object System.Net.Cookie("bob", "true", "/", "example.com")))
+$session.Cookies.Add((New-Object System.Net.Cookie("tom", "cool", "/", "example.com")))
+Invoke-WebRequest -UseBasicParsing -Uri "https://example.com/browser/devtools/client/netmonitor/test/sjs_simple-test-server.sjs" \`
+-WebSession $session \`
+-UserAgent "${navigator.userAgent}" \`
+-Headers @{
+"Accept" = "*/*"
+ "Accept-Language" = "en-US"
+ "Accept-Encoding" = "gzip, deflate, br"
+ "X-Custom-Header-1" = "Custom value"
+ "X-Custom-Header-2" = "8.8.8.8"
+ "X-Custom-Header-3" = "Mon, 3 Mar 2014 11:11:11 GMT"
+ "Referer" = "https://example.com/browser/devtools/client/netmonitor/test/html_copy-as-curl.html"
+ "Sec-Fetch-Dest" = "empty"
+ "Sec-Fetch-Mode" = "cors"
+ "Sec-Fetch-Site" = "same-origin"
+ "Pragma" = "no-cache"
+ "Cache-Control" = "no-cache"
+}`);
+
+ info("Test powershell command for POST request with post body");
+ await performRequest("POST", "Plaintext value as a payload");
+ await testClipboardContentForRecentRequest(`$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
+$session.Cookies.Add((New-Object System.Net.Cookie("bob", "true", "/", "example.com")))
+$session.Cookies.Add((New-Object System.Net.Cookie("tom", "cool", "/", "example.com")))
+Invoke-WebRequest -UseBasicParsing -Uri "https://example.com/browser/devtools/client/netmonitor/test/sjs_simple-test-server.sjs" \`
+-Method POST \`
+-WebSession $session \`
+-UserAgent "${navigator.userAgent}" \`
+-Headers @{
+"Accept" = "*/*"
+ "Accept-Language" = "en-US"
+ "Accept-Encoding" = "gzip, deflate, br"
+ "X-Custom-Header-1" = "Custom value"
+ "X-Custom-Header-2" = "8.8.8.8"
+ "X-Custom-Header-3" = "Mon, 3 Mar 2014 11:11:11 GMT"
+ "Origin" = "https://example.com"
+ "Referer" = "https://example.com/browser/devtools/client/netmonitor/test/html_copy-as-curl.html"
+ "Sec-Fetch-Dest" = "empty"
+ "Sec-Fetch-Mode" = "cors"
+ "Sec-Fetch-Site" = "same-origin"
+ "Pragma" = "no-cache"
+ "Cache-Control" = "no-cache"
+} \`
+-ContentType "text/plain;charset=UTF-8" \`
+-Body "Plaintext value as a payload"`);
+
+ info(
+ "Test powershell command for POST request with post body which contains ASCII non printing characters"
+ );
+ await performRequest("POST", `TAB character included in payload \t`);
+ await testClipboardContentForRecentRequest(`$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
+$session.Cookies.Add((New-Object System.Net.Cookie("bob", "true", "/", "example.com")))
+$session.Cookies.Add((New-Object System.Net.Cookie("tom", "cool", "/", "example.com")))
+Invoke-WebRequest -UseBasicParsing -Uri "https://example.com/browser/devtools/client/netmonitor/test/sjs_simple-test-server.sjs" \`
+-Method POST \`
+-WebSession $session \`
+-UserAgent "${navigator.userAgent}" \`
+-Headers @{
+"Accept" = "*/*"
+ "Accept-Language" = "en-US"
+ "Accept-Encoding" = "gzip, deflate, br"
+ "X-Custom-Header-1" = "Custom value"
+ "X-Custom-Header-2" = "8.8.8.8"
+ "X-Custom-Header-3" = "Mon, 3 Mar 2014 11:11:11 GMT"
+ "Origin" = "https://example.com"
+ "Referer" = "https://example.com/browser/devtools/client/netmonitor/test/html_copy-as-curl.html"
+ "Sec-Fetch-Dest" = "empty"
+ "Sec-Fetch-Mode" = "cors"
+ "Sec-Fetch-Site" = "same-origin"
+ "Pragma" = "no-cache"
+ "Cache-Control" = "no-cache"
+} \`
+-ContentType "text/plain;charset=UTF-8" \`
+-Body ([System.Text.Encoding]::UTF8.GetBytes("TAB character included in payload $([char]9)"))`);
+
+ async function performRequest(method, payload) {
+ const waitRequest = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [
+ {
+ url: HTTPS_SIMPLE_SJS,
+ method_: method,
+ payload_: payload,
+ },
+ ],
+ async function ({ url, method_, payload_ }) {
+ content.wrappedJSObject.performRequest(url, method_, payload_);
+ }
+ );
+ await waitRequest;
+ }
+
+ async function testClipboardContentForRecentRequest(expectedClipboardText) {
+ const { document } = monitor.panelWin;
+
+ const items = document.querySelectorAll(".request-list-item");
+ EventUtils.sendMouseEvent({ type: "mousedown" }, items[items.length - 1]);
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ /* Ensure that the copy as fetch option is always visible */
+ is(
+ !!getContextMenuItem(monitor, "request-list-context-copy-as-powershell"),
+ true,
+ 'The "Copy as PowerShell" context menu item should not be hidden on windows'
+ );
+
+ await waitForClipboardPromise(
+ async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "request-list-context-copy-as-powershell"
+ );
+ },
+ function validate(result) {
+ if (typeof result !== "string") {
+ return false;
+ }
+ return expectedClipboardText == result;
+ }
+ );
+
+ info(
+ "Clipboard contains a powershell command for item " + (items.length - 1)
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_copy_headers.js b/devtools/client/netmonitor/test/browser_net_copy_headers.js
new file mode 100644
index 0000000000..cd6499d93b
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_copy_headers.js
@@ -0,0 +1,105 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if copying a request's request/response headers works.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { getSortedRequests, getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ const requestItem = getSortedRequests(store.getState())[0];
+ const { method, httpVersion, status, statusText } = requestItem;
+
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ const selectedRequest = getSelectedRequest(store.getState());
+ is(selectedRequest, requestItem, "Proper request is selected");
+
+ const EXPECTED_REQUEST_HEADERS = [
+ `${method} ${SIMPLE_URL.split("example.com")[1]} ${httpVersion}`,
+ "Host: example.com",
+ "User-Agent: " + navigator.userAgent + "",
+ "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
+ "Accept-Language: " + navigator.languages.join(",") + ";q=0.5",
+ "Accept-Encoding: gzip, deflate",
+ "Connection: keep-alive",
+ "Upgrade-Insecure-Requests: 1",
+ "Pragma: no-cache",
+ "Cache-Control: no-cache",
+ ].join("\n");
+
+ await waitForClipboardPromise(
+ async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "request-list-context-copy-request-headers"
+ );
+ },
+ function validate(result) {
+ // Sometimes, a "Cookie" header is left over from other tests. Remove it:
+ result = String(result).replace(/Cookie: [^\n]+\n/, "");
+ return result === EXPECTED_REQUEST_HEADERS;
+ }
+ );
+ info("Clipboard contains the currently selected item's request headers.");
+
+ const EXPECTED_RESPONSE_HEADERS = [
+ `${httpVersion} ${status} ${statusText}`,
+ "last-modified: Sun, 3 May 2015 11:11:11 GMT",
+ "content-type: text/html",
+ "content-length: 465",
+ "connection: close",
+ "server: httpd.js",
+ "date: Sun, 3 May 2015 11:11:11 GMT",
+ ].join("\n");
+
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ await waitForClipboardPromise(
+ async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "response-list-context-copy-response-headers"
+ );
+ },
+ function validate(result) {
+ // Fake the "Last-Modified" and "Date" headers because they will vary:
+ result = String(result)
+ .replace(
+ /last-modified: [^\n]+ GMT/,
+ "last-modified: Sun, 3 May 2015 11:11:11 GMT"
+ )
+ .replace(/date: [^\n]+ GMT/, "date: Sun, 3 May 2015 11:11:11 GMT");
+ return result === EXPECTED_RESPONSE_HEADERS;
+ }
+ );
+ info("Clipboard contains the currently selected item's response headers.");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_copy_image_as_data_uri.js b/devtools/client/netmonitor/test/browser_net_copy_image_as_data_uri.js
new file mode 100644
index 0000000000..88c080d707
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_copy_image_as_data_uri.js
@@ -0,0 +1,41 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if copying an image as data uri works.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ CONTENT_TYPE_WITHOUT_CACHE_URL,
+ { requestCount: 1 }
+ );
+ info("Starting test... ");
+
+ const { document } = monitor.panelWin;
+
+ // Execute requests.
+ await performRequests(monitor, tab, CONTENT_TYPE_WITHOUT_CACHE_REQUESTS);
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[5]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[5]
+ );
+
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "request-list-context-copy-image-as-data-uri"
+ );
+ }, TEST_IMAGE_DATA_URI);
+
+ ok(true, "Clipboard contains the currently selected image as data uri.");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_copy_params.js b/devtools/client/netmonitor/test/browser_net_copy_params.js
new file mode 100644
index 0000000000..0d26d9cd0c
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_copy_params.js
@@ -0,0 +1,167 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests whether copying a request item's parameters works.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(PARAMS_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 7);
+
+ await testCopyUrlParamsHidden(0, false);
+ await testCopyUrlParams(0, "a");
+ await testCopyPostDataHidden(0, false);
+ await testCopyPostData(0, '{ "foo": "bar" }');
+
+ await testCopyUrlParamsHidden(1, false);
+ await testCopyUrlParams(1, "a=b");
+ await testCopyPostDataHidden(1, false);
+ await testCopyPostData(1, '{ "foo": "bar" }');
+
+ await testCopyUrlParamsHidden(2, false);
+ await testCopyUrlParams(2, "a=b");
+ await testCopyPostDataHidden(2, false);
+ await testCopyPostData(2, "foo=bar");
+
+ await testCopyUrlParamsHidden(3, false);
+ await testCopyUrlParams(3, "a");
+ await testCopyPostDataHidden(3, false);
+ await testCopyPostData(3, '{ "foo": "bar" }');
+
+ await testCopyUrlParamsHidden(4, false);
+ await testCopyUrlParams(4, "a=b");
+ await testCopyPostDataHidden(4, false);
+ await testCopyPostData(4, '{ "foo": "bar" }');
+
+ await testCopyUrlParamsHidden(5, false);
+ await testCopyUrlParams(5, "a=b");
+ await testCopyPostDataHidden(5, false);
+ await testCopyPostData(5, "?foo=bar");
+ testCopyRequestDataLabel(5, "POST");
+
+ await testCopyUrlParamsHidden(6, true);
+ await testCopyPostDataHidden(6, true);
+
+ await testCopyPostDataHidden(7, false);
+ testCopyRequestDataLabel(7, "PATCH");
+
+ await testCopyPostDataHidden(8, false);
+ testCopyRequestDataLabel(8, "PUT");
+
+ return teardown(monitor);
+
+ async function testCopyUrlParamsHidden(index, hidden) {
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+
+ is(
+ !!getContextMenuItem(monitor, "request-list-context-copy-url-params"),
+ !hidden,
+ 'The "Copy URL Parameters" context menu item should' +
+ (hidden ? " " : " not ") +
+ "be hidden."
+ );
+ }
+
+ async function testCopyUrlParams(index, queryString) {
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "request-list-context-copy-url-params"
+ );
+ }, queryString);
+ ok(true, "The url query string copied from the selected item is correct.");
+ }
+
+ async function testCopyPostDataHidden(index, hidden) {
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+ is(
+ !!getContextMenuItem(monitor, "request-list-context-copy-post-data"),
+ !hidden,
+ 'The "Copy POST Data" context menu item should' +
+ (hidden ? " " : " not ") +
+ "be hidden."
+ );
+ }
+
+ function testCopyRequestDataLabel(index, method) {
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+ const copyPostDataNode = getContextMenuItem(
+ monitor,
+ "request-list-context-copy-post-data"
+ );
+ is(
+ copyPostDataNode.attributes.label.value,
+ "Copy " + method + " Data",
+ 'The "Copy Data" context menu item should have label - Copy ' +
+ method +
+ " Data"
+ );
+ }
+
+ async function testCopyPostData(index, postData) {
+ // Wait for formDataSections and requestPostData state are ready in redux store
+ // since copyPostData API needs to read these state.
+ await waitUntil(() => {
+ const { requests } = store.getState().requests;
+ const { formDataSections, requestPostData } = requests[index];
+ return formDataSections && requestPostData;
+ });
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "request-list-context-copy-post-data"
+ );
+ }, postData);
+ ok(true, "The post data string copied from the selected item is correct.");
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_copy_response.js b/devtools/client/netmonitor/test/browser_net_copy_response.js
new file mode 100644
index 0000000000..28a09001fc
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_copy_response.js
@@ -0,0 +1,38 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if copying a request's response works.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ CONTENT_TYPE_WITHOUT_CACHE_URL,
+ { requestCount: 1 }
+ );
+ info("Starting test... ");
+
+ const EXPECTED_RESULT = '{ "greeting": "Hello JSON!" }';
+
+ const { document } = monitor.panelWin;
+
+ // Execute requests.
+ await performRequests(monitor, tab, CONTENT_TYPE_WITHOUT_CACHE_REQUESTS);
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[3]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[3]
+ );
+
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(monitor, "request-list-context-copy-response");
+ }, EXPECTED_RESULT);
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_copy_svg_image_as_data_uri.js b/devtools/client/netmonitor/test/browser_net_copy_svg_image_as_data_uri.js
new file mode 100644
index 0000000000..e01842c3db
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_copy_svg_image_as_data_uri.js
@@ -0,0 +1,48 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if copying an image as data uri works.
+ */
+
+const SVG_URL = HTTPS_EXAMPLE_URL + "dropmarker.svg";
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(HTTPS_CURL_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document } = monitor.panelWin;
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [SVG_URL], async function (url) {
+ content.wrappedJSObject.performRequest(url);
+ });
+ await wait;
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ await waitForClipboardPromise(
+ async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "request-list-context-copy-image-as-data-uri"
+ );
+ },
+ function check(text) {
+ return text.startsWith("data:") && !/undefined/.test(text);
+ }
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_copy_url.js b/devtools/client/netmonitor/test/browser_net_copy_url.js
new file mode 100644
index 0000000000..41e73877ae
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_copy_url.js
@@ -0,0 +1,50 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if copying a request's url works.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ info("Simulating CmdOrCtrl+C on a first element of the request table");
+ await waitForClipboardPromise(
+ () => synthesizeKeyShortcut("CmdOrCtrl+C"),
+ requestItem.url
+ );
+
+ emptyClipboard();
+
+ info("Simulating context click on a first element of the request table");
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(monitor, "request-list-context-copy-url");
+ }, requestItem.url);
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_cors_requests.js b/devtools/client/netmonitor/test/browser_net_cors_requests.js
new file mode 100644
index 0000000000..40668dca9a
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_cors_requests.js
@@ -0,0 +1,54 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that CORS preflight requests are displayed by network monitor
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(HTTPS_CORS_URL, {
+ requestCount: 1,
+ });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 2);
+
+ info("Performing a CORS request");
+ const requestUrl = "https://test1.example.com" + CORS_SJS_PATH;
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [requestUrl],
+ async function (url) {
+ content.wrappedJSObject.performRequests(
+ url,
+ "triggering/preflight",
+ "post-data"
+ );
+ }
+ );
+
+ info("Waiting until the requests appear in netmonitor");
+ await wait;
+
+ info("Checking the preflight and flight methods");
+ ["OPTIONS", "POST"].forEach((method, index) => {
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[index],
+ method,
+ requestUrl
+ );
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_curl-utils.js b/devtools/client/netmonitor/test/browser_net_curl-utils.js
new file mode 100644
index 0000000000..32b7aca316
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_curl-utils.js
@@ -0,0 +1,385 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests Curl Utils functionality.
+ */
+
+const {
+ Curl,
+ CurlUtils,
+} = require("resource://devtools/client/shared/curl.js");
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(HTTPS_CURL_UTILS_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { store, windowRequire, connector } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const { getLongString, requestData } = connector;
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 6);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [HTTPS_SIMPLE_SJS],
+ async function (url) {
+ content.wrappedJSObject.performRequests(url);
+ }
+ );
+ await wait;
+
+ const requests = {
+ get: getSortedRequests(store.getState())[0],
+ post: getSortedRequests(store.getState())[1],
+ postJson: getSortedRequests(store.getState())[2],
+ patch: getSortedRequests(store.getState())[3],
+ multipart: getSortedRequests(store.getState())[4],
+ multipartForm: getSortedRequests(store.getState())[5],
+ };
+
+ let data = await createCurlData(requests.get, getLongString, requestData);
+ testFindHeader(data);
+
+ data = await createCurlData(requests.post, getLongString, requestData);
+ testIsUrlEncodedRequest(data);
+ testWritePostDataTextParams(data);
+ testWriteEmptyPostDataTextParams(data);
+ testDataArgumentOnGeneratedCommand(data);
+
+ data = await createCurlData(requests.patch, getLongString, requestData);
+ testWritePostDataTextParams(data);
+ testDataArgumentOnGeneratedCommand(data);
+
+ data = await createCurlData(requests.postJson, getLongString, requestData);
+ testDataEscapeOnGeneratedCommand(data);
+
+ data = await createCurlData(requests.multipart, getLongString, requestData);
+ testIsMultipartRequest(data);
+ testGetMultipartBoundary(data);
+ testMultiPartHeaders(data);
+ testRemoveBinaryDataFromMultipartText(data);
+
+ data = await createCurlData(
+ requests.multipartForm,
+ getLongString,
+ requestData
+ );
+ testMultiPartHeaders(data);
+
+ testGetHeadersFromMultipartText({
+ postDataText: "Content-Type: text/plain\r\n\r\n",
+ });
+
+ if (Services.appinfo.OS != "WINNT") {
+ testEscapeStringPosix();
+ } else {
+ testEscapeStringWin();
+ }
+
+ await teardown(monitor);
+});
+
+function testIsUrlEncodedRequest(data) {
+ const isUrlEncoded = CurlUtils.isUrlEncodedRequest(data);
+ ok(isUrlEncoded, "Should return true for url encoded requests.");
+}
+
+function testIsMultipartRequest(data) {
+ const isMultipart = CurlUtils.isMultipartRequest(data);
+ ok(isMultipart, "Should return true for multipart/form-data requests.");
+}
+
+function testFindHeader(data) {
+ const { headers } = data;
+ const hostName = CurlUtils.findHeader(headers, "Host");
+ const requestedWithLowerCased = CurlUtils.findHeader(
+ headers,
+ "x-requested-with"
+ );
+ const doesNotExist = CurlUtils.findHeader(headers, "X-Does-Not-Exist");
+
+ is(
+ hostName,
+ "example.com",
+ "Header with name 'Host' should be found in the request array."
+ );
+ is(
+ requestedWithLowerCased,
+ "XMLHttpRequest",
+ "The search should be case insensitive."
+ );
+ is(doesNotExist, null, "Should return null when a header is not found.");
+}
+
+function testMultiPartHeaders(data) {
+ const { headers } = data;
+ const contentType = CurlUtils.findHeader(headers, "Content-Type");
+
+ ok(
+ contentType.startsWith("multipart/form-data; boundary="),
+ "Multi-part content type header is present in headers array"
+ );
+}
+
+function testWritePostDataTextParams(data) {
+ const params = CurlUtils.writePostDataTextParams(data.postDataText);
+ is(
+ params,
+ "param1=value1&param2=value2&param3=value3",
+ "Should return a serialized representation of the request parameters"
+ );
+}
+
+function testWriteEmptyPostDataTextParams(data) {
+ const params = CurlUtils.writePostDataTextParams(null);
+ is(params, "", "Should return a empty string when no parameters provided");
+}
+
+function testDataArgumentOnGeneratedCommand(data) {
+ const curlCommand = Curl.generateCommand(data);
+ ok(
+ curlCommand.includes("--data-raw"),
+ "Should return a curl command with --data-raw"
+ );
+}
+
+function testDataEscapeOnGeneratedCommand(data) {
+ const paramsWin = `--data-raw "{""param1"":""value1"",""param2"":""value2""}"`;
+ const paramsPosix = `--data-raw '{"param1":"value1","param2":"value2"}'`;
+
+ let curlCommand = Curl.generateCommand(data, "WINNT");
+ ok(
+ curlCommand.includes(paramsWin),
+ "Should return a curl command with --data-raw escaped for Windows systems"
+ );
+
+ curlCommand = Curl.generateCommand(data, "Linux");
+ ok(
+ curlCommand.includes(paramsPosix),
+ "Should return a curl command with --data-raw escaped for Posix systems"
+ );
+}
+
+function testGetMultipartBoundary(data) {
+ const boundary = CurlUtils.getMultipartBoundary(data);
+ ok(
+ /-{3,}\w+/.test(boundary),
+ "A boundary string should be found in a multipart request."
+ );
+}
+
+function testRemoveBinaryDataFromMultipartText(data) {
+ const generatedBoundary = CurlUtils.getMultipartBoundary(data);
+ const text = data.postDataText;
+ const binaryRemoved = CurlUtils.removeBinaryDataFromMultipartText(
+ text,
+ generatedBoundary
+ );
+ const boundary = "--" + generatedBoundary;
+
+ const EXPECTED_POSIX_RESULT = [
+ "$'",
+ boundary,
+ "\\r\\n",
+ 'Content-Disposition: form-data; name="param1"',
+ "\\r\\n\\r\\n",
+ "value1",
+ "\\r\\n",
+ boundary,
+ "\\r\\n",
+ 'Content-Disposition: form-data; name="file"; filename="filename.png"',
+ "\\r\\n",
+ "Content-Type: image/png",
+ "\\r\\n\\r\\n",
+ boundary + "--",
+ "\\r\\n",
+ "'",
+ ].join("");
+
+ const EXPECTED_WIN_RESULT = [
+ '"',
+ boundary,
+ '"^\u000d\u000A\u000d\u000A"',
+ 'Content-Disposition: form-data; name=""param1""',
+ '"^\u000d\u000A\u000d\u000A""^\u000d\u000A\u000d\u000A"',
+ "value1",
+ '"^\u000d\u000A\u000d\u000A"',
+ boundary,
+ '"^\u000d\u000A\u000d\u000A"',
+ 'Content-Disposition: form-data; name=""file""; filename=""filename.png""',
+ '"^\u000d\u000A\u000d\u000A"',
+ "Content-Type: image/png",
+ '"^\u000d\u000A\u000d\u000A""^\u000d\u000A\u000d\u000A"',
+ boundary + "--",
+ '"^\u000d\u000A\u000d\u000A"',
+ '"',
+ ].join("");
+
+ if (Services.appinfo.OS != "WINNT") {
+ is(
+ CurlUtils.escapeStringPosix(binaryRemoved),
+ EXPECTED_POSIX_RESULT,
+ "The mulitpart request payload should not contain binary data."
+ );
+ } else {
+ is(
+ CurlUtils.escapeStringWin(binaryRemoved),
+ EXPECTED_WIN_RESULT,
+ "WinNT: The mulitpart request payload should not contain binary data."
+ );
+ }
+}
+
+function testGetHeadersFromMultipartText(data) {
+ const headers = CurlUtils.getHeadersFromMultipartText(data.postDataText);
+
+ ok(Array.isArray(headers), "Should return an array.");
+ ok(!!headers.length, "There should exist at least one request header.");
+ is(
+ headers[0].name,
+ "Content-Type",
+ "The first header name should be 'Content-Type'."
+ );
+}
+
+function testEscapeStringPosix() {
+ const surroundedWithQuotes = "A simple string";
+ is(
+ CurlUtils.escapeStringPosix(surroundedWithQuotes),
+ "'A simple string'",
+ "The string should be surrounded with single quotes."
+ );
+
+ const singleQuotes = "It's unusual to put crickets in your coffee.";
+ is(
+ CurlUtils.escapeStringPosix(singleQuotes),
+ "$'It\\'s unusual to put crickets in your coffee.'",
+ "Single quotes should be escaped."
+ );
+
+ const escapeChar = "'!ls:q:gs|ls|;ping 8.8.8.8;|";
+ is(
+ CurlUtils.escapeStringPosix(escapeChar),
+ "$'\\'\\041ls:q:gs|ls|;ping 8.8.8.8;|'",
+ "'!' should be escaped."
+ );
+
+ const newLines = "Line 1\r\nLine 2\u000d\u000ALine3";
+ is(
+ CurlUtils.escapeStringPosix(newLines),
+ "$'Line 1\\r\\nLine 2\\r\\nLine3'",
+ "Newlines should be escaped."
+ );
+
+ const controlChars = "\u0007 \u0009 \u000C \u001B";
+ is(
+ CurlUtils.escapeStringPosix(controlChars),
+ "$'\\x07 \\x09 \\x0c \\x1b'",
+ "Control characters should be escaped."
+ );
+
+ // æ ø ü ß ö é
+ const extendedAsciiChars =
+ "\xc3\xa6 \xc3\xb8 \xc3\xbc \xc3\x9f \xc3\xb6 \xc3\xa9";
+ is(
+ CurlUtils.escapeStringPosix(extendedAsciiChars),
+ "$'\\xc3\\xa6 \\xc3\\xb8 \\xc3\\xbc \\xc3\\x9f \\xc3\\xb6 \\xc3\\xa9'",
+ "Character codes outside of the decimal range 32 - 126 should be escaped."
+ );
+}
+
+function testEscapeStringWin() {
+ const surroundedWithDoubleQuotes = "A simple string";
+ is(
+ CurlUtils.escapeStringWin(surroundedWithDoubleQuotes),
+ '"A simple string"',
+ "The string should be surrounded with double quotes."
+ );
+
+ const doubleQuotes = 'Quote: "Time is an illusion. Lunchtime doubly so."';
+ is(
+ CurlUtils.escapeStringWin(doubleQuotes),
+ '"Quote: ""Time is an illusion. Lunchtime doubly so."""',
+ "Double quotes should be escaped."
+ );
+
+ const percentSigns = "%TEMP% %@foo% %2XX% %_XX% %?XX%";
+ is(
+ CurlUtils.escapeStringWin(percentSigns),
+ '"^%^TEMP^% ^%^@foo^% ^%^2XX^% ^%^_XX^% ^%?XX^%"',
+ "Percent signs should be escaped."
+ );
+
+ const backslashes = "\\A simple string\\";
+ is(
+ CurlUtils.escapeStringWin(backslashes),
+ '"\\\\A simple string\\\\"',
+ "Backslashes should be escaped."
+ );
+
+ const newLines = "line1\r\nline2\r\rline3\n\nline4";
+ is(
+ CurlUtils.escapeStringWin(newLines),
+ '"line1"^\r\n\r\n"line2"^\r\n\r\n""^\r\n\r\n"line3"^\r\n\r\n""^\r\n\r\n"line4"',
+ "Newlines should be escaped."
+ );
+
+ const dollarSignCommand = "$(calc.exe)";
+ is(
+ CurlUtils.escapeStringWin(dollarSignCommand),
+ '"\\$(calc.exe)"',
+ "Dollar sign should be escaped."
+ );
+
+ const tickSignCommand = "`$(calc.exe)";
+ is(
+ CurlUtils.escapeStringWin(tickSignCommand),
+ '"\\`\\$(calc.exe)"',
+ "Both the tick and dollar signs should be escaped."
+ );
+
+ const evilCommand = `query=evil\r\rcmd" /c timeout /t 3 & calc.exe\r\r`;
+ is(
+ CurlUtils.escapeStringWin(evilCommand),
+ '"query=evil"^\r\n\r\n""^\r\n\r\n"cmd"" /c timeout /t 3 & calc.exe"^\r\n\r\n""^\r\n\r\n""',
+ "The evil command is escaped properly"
+ );
+}
+
+async function createCurlData(selected, getLongString, requestData) {
+ const { id, url, method, httpVersion } = selected;
+
+ // Create a sanitized object for the Curl command generator.
+ const data = {
+ url,
+ method,
+ headers: [],
+ httpVersion,
+ postDataText: null,
+ };
+
+ const requestHeaders = await requestData(id, "requestHeaders");
+ // Fetch header values.
+ for (const { name, value } of requestHeaders.headers) {
+ const text = await getLongString(value);
+ data.headers.push({ name, value: text });
+ }
+
+ const requestPostData = await requestData(id, "requestPostData");
+ // Fetch the request payload.
+ if (requestPostData) {
+ const postData = requestPostData.postData.text;
+ data.postDataText = await getLongString(postData);
+ }
+
+ return data;
+}
diff --git a/devtools/client/netmonitor/test/browser_net_cyrillic-01.js b/devtools/client/netmonitor/test/browser_net_cyrillic-01.js
new file mode 100644
index 0000000000..4b44dc34ac
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_cyrillic-01.js
@@ -0,0 +1,64 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if cyrillic text is rendered correctly in the source editor.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(CYRILLIC_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ const requestItem = document.querySelectorAll(".request-list-item")[0];
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ requestItem.scrollIntoView();
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=txt",
+ {
+ status: 200,
+ statusText: "DA DA DA",
+ }
+ );
+
+ let wait = waitForDOM(document, "#headers-panel");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+ wait = waitForDOM(document, "#response-panel .CodeMirror-code");
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ ok(
+ getCodeMirrorValue(monitor).includes(
+ "\u0411\u0440\u0430\u0442\u0430\u043d"
+ ),
+ "The text shown in the source editor is correct."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_cyrillic-02.js b/devtools/client/netmonitor/test/browser_net_cyrillic-02.js
new file mode 100644
index 0000000000..ee8f8946c9
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_cyrillic-02.js
@@ -0,0 +1,76 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if cyrillic text is rendered correctly in the source editor
+ * when loaded directly from an HTML page.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(CYRILLIC_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ let wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ const requestItem = document.querySelectorAll(".request-list-item")[0];
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ requestItem.scrollIntoView();
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "GET",
+ CYRILLIC_URL,
+ {
+ status: 200,
+ statusText: "OK",
+ }
+ );
+
+ wait = waitForDOM(document, "#headers-panel");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ wait = waitForDOM(document, "#response-panel .data-header");
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ wait = waitForDOM(document, "#response-panel .CodeMirror-code");
+ const header = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(header, monitor);
+ await wait;
+
+ // CodeMirror will only load lines currently in view to the DOM. getValue()
+ // retrieves all lines pending render after a user begins scrolling.
+ const text = document.querySelector(".CodeMirror").CodeMirror.getValue();
+
+ ok(
+ text.includes("\u0411\u0440\u0430\u0442\u0430\u043d"),
+ "The text shown in the source editor is correct."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_decode-params.js b/devtools/client/netmonitor/test/browser_net_decode-params.js
new file mode 100644
index 0000000000..45be876dec
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_decode-params.js
@@ -0,0 +1,35 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if "+" is replaces with spaces in the headers panel.
+ */
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(POST_RAW_URL_WITH_HASH, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute request.
+ await performRequests(monitor, tab, 1);
+
+ // Wait until the tab panel summary is displayed
+ const wait = waitUntil(
+ () => document.querySelectorAll(".tabpanel-summary-label")[0]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ clickOnSidebarTab(document, "request");
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_decode-url.js b/devtools/client/netmonitor/test/browser_net_decode-url.js
new file mode 100644
index 0000000000..e3a900f313
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_decode-url.js
@@ -0,0 +1,42 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if "Request URL" containing "#" in its query is correctly decoded.
+ */
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(POST_RAW_URL_WITH_HASH, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute request.
+ await performRequests(monitor, tab, 1);
+
+ // Wait until the url preview ihas loaded
+ const wait = waitUntil(() =>
+ document.querySelector("#headers-panel .url-preview")
+ );
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ await wait;
+
+ const requestURL = document.querySelector("#headers-panel .url-preview .url");
+ is(
+ requestURL.textContent.endsWith("foo # bar"),
+ true,
+ "\"Request URL\" containing '#' is correctly decoded."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_details_copy.js b/devtools/client/netmonitor/test/browser_net_details_copy.js
new file mode 100644
index 0000000000..b9c7e7db9a
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_details_copy.js
@@ -0,0 +1,295 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+/**
+ * Test that the URL Preview can be copied
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting the url preview copy test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ await waitForDOM(document, "#headers-panel .url-preview", 1);
+
+ const urlPreview = document.querySelector("#headers-panel .url-preview");
+ const urlRow = urlPreview.querySelector(".objectRow");
+
+ /* Test for copy value on the url */
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, urlRow);
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "properties-view-context-menu-copyvalue"
+ );
+ }, "http://example.com/browser/devtools/client/netmonitor/test/html_simple-test-page.html");
+
+ ok(true, "The copy value action put expected url string into clipboard");
+
+ /* Test for copy all */
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, urlRow);
+ const expected = JSON.stringify(
+ {
+ GET: {
+ scheme: "http",
+ host: "example.com",
+ filename:
+ "/browser/devtools/client/netmonitor/test/html_simple-test-page.html",
+ remote: {
+ Address: "127.0.0.1:8888",
+ },
+ },
+ },
+ null,
+ "\t"
+ );
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "properties-view-context-menu-copyall"
+ );
+ }, expected);
+
+ ok(true, "The copy all action put expected json data into clipboard");
+
+ await teardown(monitor);
+});
+
+/**
+ * Test that the Headers summary can be copied
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting the headers summary copy test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ await waitForDOM(document, "#headers-panel .summary", 1);
+
+ const headersSummary = document.querySelector("#headers-panel .summary");
+ const httpSummaryValue = headersSummary.querySelectorAll(
+ ".tabpanel-summary-value"
+ )[1];
+
+ /* Test for copy value */
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, httpSummaryValue);
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "headers-panel-context-menu-copyvalue"
+ );
+ }, "HTTP/1.1");
+
+ ok(true, "The copy value action put expected text into clipboard");
+
+ /* Test for copy all */
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, httpSummaryValue);
+ const expected = JSON.stringify(
+ {
+ Status: "200OK",
+ Version: "HTTP/1.1",
+ Transferred: "650 B (465 B size)",
+ "Request Priority": "Highest",
+ },
+ null,
+ "\t"
+ );
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(monitor, "headers-panel-context-menu-copyall");
+ }, expected);
+
+ ok(true, "The copy all action put expected json into clipboard");
+
+ await teardown(monitor);
+});
+
+/**
+ * Test if response JSON in PropertiesView can be copied
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ JSON_BASIC_URL + "?name=nogrip",
+ { requestCount: 1 }
+ );
+ info("Starting the json in properties view copy test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ await performRequests(monitor, tab, 1);
+
+ const onResponsePanelReady = waitForDOM(
+ document,
+ "#response-panel .treeTable"
+ );
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+ await onResponsePanelReady;
+
+ const responsePanel = document.querySelector("#response-panel");
+
+ const objectRow = responsePanel.querySelectorAll(".objectRow")[0];
+
+ // Open the node to get the string
+ const waitOpenNode = waitForDOM(document, ".stringRow");
+ const toggleButton = objectRow.querySelector("td span.treeIcon");
+ toggleButton.click();
+ await waitOpenNode;
+ const stringRow = responsePanel.querySelectorAll(".stringRow")[0];
+
+ /* Test for copy value on an object */
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, objectRow);
+ const expected = JSON.stringify({ obj: { type: "string" } }, null, "\t");
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "properties-view-context-menu-copyvalue"
+ );
+ }, expected);
+
+ ok(true, "The copy value action put expected json into clipboard");
+
+ /* Test for copy all */
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, objectRow);
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "properties-view-context-menu-copyall"
+ );
+ }, expected);
+
+ ok(true, "The copy all action put expected json into clipboard");
+
+ /* Test for copy value of a single row */
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, stringRow);
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "properties-view-context-menu-copyvalue"
+ );
+ }, "string");
+
+ ok(true, "The copy value action put expected text into clipboard");
+
+ await teardown(monitor);
+});
+
+/**
+ * Test if response/request Cookies in PropertiesView can be copied
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_UNSORTED_COOKIES_SJS, {
+ requestCount: 1,
+ });
+ info(
+ "Starting the request/response cookies in properties view copy test... "
+ );
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ let wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ wait = waitForDOM(document, ".headers-overview");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ clickOnSidebarTab(document, "cookies");
+
+ const cookiesPanel = document.querySelector("#cookies-panel");
+
+ const objectRows = cookiesPanel.querySelectorAll(".objectRow");
+ const stringRows = cookiesPanel.querySelectorAll(".stringRow");
+
+ const expectedResponseCookies = [
+ `{
+ "__proto__": {
+ "httpOnly": true,
+ "value": "2"
+ }
+}`,
+ `{
+ "bob": {
+ "httpOnly": true,
+ "value": "true"
+ }
+}`,
+ `{
+ "foo": {
+ "httpOnly": true,
+ "value": "bar"
+ }
+}`,
+ `{
+ "tom": {
+ "httpOnly": true,
+ "value": "cool"
+ }
+}`,
+ ];
+ for (let i = 0; i < objectRows.length; i++) {
+ const cur = objectRows[i];
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, cur);
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "properties-view-context-menu-copyvalue"
+ );
+ }, expectedResponseCookies[i]);
+ }
+
+ const expectedRequestCookies = ["2", "true", "bar", "cool"];
+ for (let i = 0; i < expectedRequestCookies.length; i++) {
+ const cur = stringRows[objectRows.length + i];
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, cur);
+ await waitForClipboardPromise(async function setup() {
+ await selectContextMenuItem(
+ monitor,
+ "properties-view-context-menu-copyvalue"
+ );
+ }, expectedRequestCookies[i]);
+ }
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_domain-not-found.js b/devtools/client/netmonitor/test/browser_net_domain-not-found.js
new file mode 100644
index 0000000000..d4e3e9eaab
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_domain-not-found.js
@@ -0,0 +1,41 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that the request for a domain that is not found shows
+ * correctly.
+ */
+add_task(async function () {
+ const URL = "https://not-existed.com/";
+ const { monitor } = await initNetMonitor(URL, {
+ requestCount: 1,
+ waitForLoad: false,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ reloadBrowser({ waitForLoad: false });
+ await wait;
+
+ const firstItem = document.querySelectorAll(".request-list-item")[0];
+
+ is(
+ firstItem.querySelector(".requests-list-url").innerText,
+ URL,
+ "The url in the displayed request is correct"
+ );
+ is(
+ firstItem.querySelector(".requests-list-transferred").innerText,
+ "NS_ERROR_UNKNOWN_HOST",
+ "The error in the displayed request is correct"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_edit_resend_cancel.js b/devtools/client/netmonitor/test/browser_net_edit_resend_cancel.js
new file mode 100644
index 0000000000..e0958c3497
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_edit_resend_cancel.js
@@ -0,0 +1,68 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if original request's header panel is visible when custom request is cancelled.
+ */
+
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ ok(
+ true,
+ "Skip this test when pref is true, because this panel won't be default when that is the case."
+ );
+ return;
+ }
+
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Reload to have one request in the list
+ const waitForEvents = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await waitForEvents;
+
+ // Context Menu > "Edit & Resend"
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+ await waitForHeaders;
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequest);
+ const firstRequestState = getSelectedRequest(store.getState());
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+
+ // Waits for "Edit & Resend" panel to appear > New request "Cancel"
+ await waitUntil(() => document.querySelector(".custom-request-panel"));
+ document.querySelector("#custom-request-close-button").click();
+ const finalRequestState = getSelectedRequest(store.getState());
+
+ ok(
+ firstRequestState.id === finalRequestState.id,
+ "Original request is selected after cancel button is clicked"
+ );
+
+ ok(
+ document.querySelector(".headers-overview") !== null,
+ "Request is selected and headers panel is visible"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_edit_resend_caret.js b/devtools/client/netmonitor/test/browser_net_edit_resend_caret.js
new file mode 100644
index 0000000000..4c73f7fa0a
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_edit_resend_caret.js
@@ -0,0 +1,102 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if position of caret does not change (resets to the end) after setting
+ * header's value to empty string. Also make sure the "method" field stays empty
+ * after removing it and resets to its original value when it looses focus.
+ */
+
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ ok(
+ true,
+ "Skip this test when pref is true, because this panel won't be default when that is the case."
+ );
+ return;
+ }
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Reload to have one request in the list.
+ const waitForEvents = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await waitForEvents;
+
+ // Open context menu and execute "Edit & Resend".
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+ await waitForHeaders;
+ await waitForRequestData(store, ["requestHeaders"]);
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequest);
+
+ // Open "New Request" form
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+ await waitUntil(() => document.querySelector("#custom-headers-value"));
+ const headersTextarea = document.querySelector("#custom-headers-value");
+ await waitUntil(() => document.querySelector("#custom-method-value"));
+ const methodField = document.querySelector("#custom-method-value");
+ const originalMethodValue = methodField.value;
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const request = getSelectedRequest(store.getState());
+ const hostHeader = request.requestHeaders.headers[0];
+
+ // Close the open context menu, otherwise sendString will not work
+ EventUtils.synthesizeKey("VK_ESCAPE", {});
+ headersTextarea.focus();
+
+ // Clean value of host header
+ const headersContent = headersTextarea.value;
+ const start = "Host: ".length;
+ const end = headersContent.indexOf("\n");
+ headersTextarea.setSelectionRange(start, end);
+ EventUtils.synthesizeKey("VK_DELETE", {});
+
+ methodField.focus();
+ methodField.select();
+ EventUtils.synthesizeKey("VK_DELETE", {});
+
+ ok(
+ getSelectedRequest(store.getState()).requestHeaders.headers[0] !==
+ hostHeader,
+ "Value of Host header was edited and should change"
+ );
+
+ ok(
+ headersTextarea.selectionStart === start &&
+ headersTextarea.selectionEnd === start,
+ "Position of caret should not change"
+ );
+
+ ok(
+ getSelectedRequest(store.getState()).method === "",
+ "Value of method header was deleted and should be empty"
+ );
+
+ headersTextarea.focus();
+
+ ok(
+ getSelectedRequest(store.getState()).method === originalMethodValue,
+ "Value of method header should reset to its original value"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_edit_resend_with_filtering.js b/devtools/client/netmonitor/test/browser_net_edit_resend_with_filtering.js
new file mode 100644
index 0000000000..197e752a05
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_edit_resend_with_filtering.js
@@ -0,0 +1,153 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if resending a XHR request while filtering XHR displays
+ * the correct requests
+ */
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ ok(
+ true,
+ "Skip this test when pref is true, because this panel won't be default when that is the case."
+ );
+ return;
+ }
+
+ const { tab, monitor } = await initNetMonitor(POST_RAW_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute XHR request and filter by XHR
+ await performRequests(monitor, tab, 1);
+ document.querySelector(".requests-list-filter-xhr-button").click();
+
+ // Confirm XHR request and click it
+ const xhrRequestItem = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, xhrRequestItem);
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ await waitForHeaders;
+ const firstRequest = getSelectedRequest(store.getState());
+
+ // Open context menu and execute "Edit & Resend".
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, xhrRequestItem);
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+
+ // Wait for "Edit & Resend" panel to appear
+ await waitUntil(() => document.querySelector("#custom-request-send-button"));
+
+ // Select the temporary clone-request and check its ID
+ // it should be calculated from the original request
+ // by appending '-clone' suffix.
+ document.querySelectorAll(".request-list-item")[1].click();
+ const cloneRequest = getSelectedRequest(store.getState());
+
+ ok(
+ cloneRequest.id.replace(/-clone$/, "") == firstRequest.id,
+ "The second XHR request is a clone of the first"
+ );
+
+ // Click the "Send" button and wait till the new request appears in the list
+ document.querySelector("#custom-request-send-button").click();
+ await waitForNetworkEvents(monitor, 1);
+
+ // Filtering by "other" so the resent request is visible after completion
+ document.querySelector(".requests-list-filter-other-button").click();
+
+ // Select the new (cloned) request
+ document.querySelectorAll(".request-list-item")[0].click();
+ const resendRequest = getSelectedRequest(store.getState());
+
+ ok(
+ resendRequest.id !== firstRequest.id,
+ "The second XHR request was made and is unique"
+ );
+
+ await teardown(monitor);
+});
+
+/**
+ * Tests if resending an XHR request while XHR filtering is on, displays
+ * the correct requests
+ */
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ const { tab, monitor } = await initNetMonitor(POST_RAW_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const Actions = windowRequire(
+ "devtools/client/netmonitor/src/actions/index"
+ );
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute XHR request and filter by XHR
+ await performRequests(monitor, tab, 1);
+ document.querySelector(".requests-list-filter-xhr-button").click();
+
+ // Confirm XHR request and click it
+ const xhrRequestItem = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, xhrRequestItem);
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ await waitForHeaders;
+ const firstRequest = getSelectedRequest(store.getState());
+
+ // Open context menu and execute "Edit & Resend".
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, xhrRequestItem);
+
+ info("Opening the new request panel");
+ const waitForPanels = waitUntil(
+ () =>
+ document.querySelector(".http-custom-request-panel") &&
+ document.querySelector("#http-custom-request-send-button").disabled ===
+ false
+ );
+
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+ await waitForPanels;
+
+ // Click the "Send" button and wait till the new request appears in the list
+ document.querySelector("#http-custom-request-send-button").click();
+ await waitForNetworkEvents(monitor, 1);
+
+ // Filtering by "other" so the resent request is visible after completion
+ document.querySelector(".requests-list-filter-other-button").click();
+
+ // Select new request
+ const newRequest = document.querySelectorAll(".request-list-item")[1];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, newRequest);
+ const resendRequest = getSelectedRequest(store.getState());
+
+ ok(
+ resendRequest.id !== firstRequest.id,
+ "The second XHR request was made and is unique"
+ );
+
+ await teardown(monitor);
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_edit_resend_xhr.js b/devtools/client/netmonitor/test/browser_net_edit_resend_xhr.js
new file mode 100644
index 0000000000..4820e16993
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_edit_resend_xhr.js
@@ -0,0 +1,135 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if editing and resending a XHR request works and the
+ * cloned request retains the same cause type.
+ */
+
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ ok(
+ true,
+ "Skip this test when pref is true, because this panel won't be default when that is the case."
+ );
+ return;
+ }
+
+ const { tab, monitor } = await initNetMonitor(POST_RAW_URL, {
+ requestCount: 1,
+ });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Executes 1 XHR request
+ await performRequests(monitor, tab, 1);
+
+ // Selects 1st XHR request
+ const xhrRequest = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, xhrRequest);
+
+ // Stores original request for comparison of values later
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const original = getSelectedRequest(store.getState());
+
+ // Context Menu > "Edit & Resend"
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, xhrRequest);
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+
+ // 1) Wait for "Edit & Resend" panel to appear
+ // 2) Click the "Send" button
+ // 3) Wait till the new request appears in the list
+ await waitUntil(() => document.querySelector(".custom-request-panel"));
+ document.querySelector("#custom-request-send-button").click();
+ await waitForNetworkEvents(monitor, 1);
+
+ // Selects cloned request
+ const clonedRequest = document.querySelectorAll(".request-list-item")[1];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, clonedRequest);
+ const cloned = getSelectedRequest(store.getState());
+
+ // Compares if the requests have the same cause type (XHR)
+ ok(
+ original.cause.type === cloned.cause.type,
+ "Both requests retain the same cause type"
+ );
+
+ await teardown(monitor);
+});
+
+/**
+ * Tests if editing and resending a XHR request works and the
+ * new request retains the same cause type.
+ */
+
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ const { tab, monitor } = await initNetMonitor(POST_RAW_URL, {
+ requestCount: 1,
+ });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire(
+ "devtools/client/netmonitor/src/actions/index"
+ );
+ store.dispatch(Actions.batchEnable(false));
+
+ // Executes 1 XHR request
+ await performRequests(monitor, tab, 1);
+
+ // Selects 1st XHR request
+ const xhrRequest = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, xhrRequest);
+
+ // Stores original request for comparison of values later
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const original = getSelectedRequest(store.getState());
+
+ // Context Menu > "Edit & Resend"
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, xhrRequest);
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+
+ // 1) Wait for "Edit & Resend" panel to appear
+ // 2) Wait for the Send button to be enabled (i.e all the data is loaded)
+ // 2) Click the "Send" button
+ // 3) Wait till the new request appears in the list
+ await waitUntil(
+ () =>
+ document.querySelector(".http-custom-request-panel") &&
+ document.querySelector("#http-custom-request-send-button").disabled ===
+ false
+ );
+ document.querySelector("#http-custom-request-send-button").click();
+ await waitForNetworkEvents(monitor, 1);
+
+ // Selects new request
+ const newRequest = document.querySelectorAll(".request-list-item")[1];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, newRequest);
+ const request = getSelectedRequest(store.getState());
+
+ ok(
+ original.cause.type === request.cause.type,
+ "Both requests retain the same cause type"
+ );
+
+ await teardown(monitor);
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_error-boundary-01.js b/devtools/client/netmonitor/test/browser_net_error-boundary-01.js
new file mode 100644
index 0000000000..cb27428d3f
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_error-boundary-01.js
@@ -0,0 +1,31 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+/**
+ * Test that top-level net monitor error boundary catches child errors.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+
+ const { store, windowRequire, document } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Intentionally damage the store to cause a child component error
+ const state = store.getState();
+ state.ui.columns = null;
+
+ await reloadBrowser();
+
+ // Wait for the panel to fall back to the error UI
+ const errorPanel = await waitUntil(() =>
+ document.querySelector(".app-error-panel")
+ );
+
+ is(errorPanel, !undefined);
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_filter-01.js b/devtools/client/netmonitor/test/browser_net_filter-01.js
new file mode 100644
index 0000000000..f72fb4d8c5
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_filter-01.js
@@ -0,0 +1,558 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Used to test filtering a unicode URI component
+const UNICODE_IN_URI_COMPONENT = "\u6e2c";
+const ENCODED_CHARS_IN_URI_COMP = encodeURIComponent(UNICODE_IN_URI_COMPONENT);
+
+// Used to test filtering an international domain name with Unicode
+const IDN = "xn--hxajbheg2az3al.xn--jxalpdlp";
+const UNICODE_IN_IDN = "\u03c0\u03b1";
+
+/**
+ * Test if filtering items in the network table works correctly.
+ */
+const BASIC_REQUESTS = [
+ {
+ url: getSjsURLInUnicodeIdn() + "?fmt=html&res=undefined&text=Sample&cors=1",
+ },
+ { url: "sjs_content-type-test-server.sjs?fmt=css&text=sample" },
+ { url: "sjs_content-type-test-server.sjs?fmt=js&text=sample" },
+ {
+ url: `sjs_content-type-test-server.sjs?fmt=html&text=${ENCODED_CHARS_IN_URI_COMP}`,
+ },
+ {
+ url: `sjs_content-type-test-server.sjs?fmt=css&text=${ENCODED_CHARS_IN_URI_COMP}`,
+ },
+ {
+ url: `sjs_content-type-test-server.sjs?fmt=js&text=${ENCODED_CHARS_IN_URI_COMP}`,
+ },
+];
+
+const REQUESTS_WITH_MEDIA = BASIC_REQUESTS.concat([
+ { url: getSjsURLInUnicodeIdn() + "?fmt=font&cors=1" },
+ { url: "sjs_content-type-test-server.sjs?fmt=image" },
+ { url: "sjs_content-type-test-server.sjs?fmt=audio" },
+ { url: "sjs_content-type-test-server.sjs?fmt=application-ogg" },
+ { url: "sjs_content-type-test-server.sjs?fmt=video" },
+ { url: "sjs_content-type-test-server.sjs?fmt=hls-m3u8" },
+ { url: "sjs_content-type-test-server.sjs?fmt=hls-m3u8-alt-mime-type" },
+]);
+
+const REQUESTS_WITH_MEDIA_AND_FLASH = REQUESTS_WITH_MEDIA.concat([
+ { url: "sjs_content-type-test-server.sjs?fmt=flash" },
+]);
+
+const REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS =
+ REQUESTS_WITH_MEDIA_AND_FLASH.concat([
+ /* Use new WebSocket() to mock native websocket request, then "Upgrade" will be added */
+ { url: WS_URL + "sjs_content-type-test-server.sjs?fmt=ws", ws: true },
+ ]);
+
+const EXPECTED_REQUESTS = [
+ {
+ method: "GET",
+ url: getSjsURLInUnicodeIdn() + "?fmt=html&res=undefined&text=Sample&cors=1",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "html",
+ fullMimeType: "text/html; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=css&text=sample",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "css",
+ fullMimeType: "text/css; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=js&text=sample",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "js",
+ fullMimeType: "application/javascript; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + `?fmt=html&text=${ENCODED_CHARS_IN_URI_COMP}`,
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "html",
+ fullMimeType: "text/html; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + `?fmt=css&text=${ENCODED_CHARS_IN_URI_COMP}`,
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "css",
+ fullMimeType: "text/css; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + `?fmt=js&text=${ENCODED_CHARS_IN_URI_COMP}`,
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "js",
+ fullMimeType: "application/javascript; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: getSjsURLInUnicodeIdn() + "?fmt=font&cors=1",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "woff",
+ fullMimeType: "font/woff",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=image",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "png",
+ fullMimeType: "image/png",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=audio",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "ogg",
+ fullMimeType: "audio/ogg",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=application-ogg",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "ogg",
+ fullMimeType: "application/ogg",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=video",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "webm",
+ fullMimeType: "video/webm",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=hls-m3u8",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "x-mpegurl",
+ fullMimeType: "application/x-mpegurl",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=hls-m3u8-alt-mime-type",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "vnd.apple.mpegurl",
+ fullMimeType: "application/vnd.apple.mpegurl",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=flash",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "x-shockwave-flash",
+ fullMimeType: "application/x-shockwave-flash",
+ },
+ },
+ {
+ method: "GET",
+ url: WS_WS_CONTENT_TYPE_SJS + "?fmt=ws",
+ data: {
+ fuzzyUrl: true,
+ status: 101,
+ statusText: "Switching Protocols",
+ },
+ },
+];
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(FILTERING_URL, { requestCount: 1 });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSelectedRequest, getSortedRequests } =
+ windowRequire("devtools/client/netmonitor/src/selectors/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ function setFreetextFilter(value) {
+ store.dispatch(Actions.setRequestFilterText(value));
+ }
+
+ info("Starting test... ");
+
+ const wait = waitForNetworkEvents(
+ monitor,
+ REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS.length
+ );
+ await performRequestsInContent(REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS);
+ await wait;
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ isnot(
+ getSelectedRequest(store.getState()),
+ null,
+ "There should be a selected item in the requests menu."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ 0,
+ "The first item should be selected in the requests menu."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should render correctly."
+ );
+
+ // First test with single filters...
+ testFilterButtons(monitor, "all");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-html-button")
+ );
+ testFilterButtons(monitor, "html");
+ await testContents([1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ // Reset filters
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-css-button")
+ );
+ testFilterButtons(monitor, "css");
+ await testContents([0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-js-button")
+ );
+ testFilterButtons(monitor, "js");
+ await testContents([0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-xhr-button")
+ );
+ testFilterButtons(monitor, "xhr");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-fonts-button")
+ );
+ testFilterButtons(monitor, "fonts");
+ await testContents([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-images-button")
+ );
+ testFilterButtons(monitor, "images");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-media-button")
+ );
+ testFilterButtons(monitor, "media");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-ws-button")
+ );
+ testFilterButtons(monitor, "ws");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+
+ testFilterButtons(monitor, "all");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ // Text in filter box that matches nothing should hide all.
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ setFreetextFilter("foobar");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ // ASCII text in filter box that matches should filter out everything else.
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ setFreetextFilter("sample");
+ await testContents([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ // ASCII text in filter box that matches should filter out everything else.
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ setFreetextFilter("SAMPLE");
+ await testContents([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ // Test negative filtering ASCII text(only show unmatched items)
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ setFreetextFilter("-sample");
+ await testContents([0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ // Unicode text in filter box that matches should filter out everything else.
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ setFreetextFilter(UNICODE_IN_URI_COMPONENT);
+ await testContents([0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ // Ditto, except the above is for a Unicode URI component, and this one is for
+ // a Unicode domain name.
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ setFreetextFilter(UNICODE_IN_IDN);
+ await testContents([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ // Test negative filtering Unicode text(only show unmatched items)
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ setFreetextFilter(`-${UNICODE_IN_URI_COMPONENT}`);
+ await testContents([1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ // Ditto, except the above is for a Unicode URI component, and this one is for
+ // a Unicode domain name.
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ setFreetextFilter(`-${UNICODE_IN_IDN}`);
+ await testContents([0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ // ...then combine multiple filters together.
+
+ // Enable filtering for html and css; should show request of both type.
+ setFreetextFilter("");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-html-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-css-button")
+ );
+ testFilterButtonsCustom(monitor, [0, 1, 1, 0, 0, 0, 0, 0, 0, 0]);
+ await testContents([1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ // Html and css filter enabled and text filter should show just the html and css match.
+ // Should not show both the items matching the button plus the items matching the text.
+ setFreetextFilter("sample");
+ await testContents([1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+ setFreetextFilter(UNICODE_IN_URI_COMPONENT);
+ await testContents([0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+ setFreetextFilter("");
+ testFilterButtonsCustom(monitor, [0, 1, 1, 0, 0, 0, 0, 0, 0, 0]);
+ await testContents([1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ // Disable some filters. Only one left active.
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-css-button")
+ );
+ testFilterButtons(monitor, "html");
+ await testContents([1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ // Disable last active filter. Should toggle to all.
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-html-button")
+ );
+ testFilterButtons(monitor, "all");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ // Enable few filters and click on all. Only "all" should be checked.
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-html-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-css-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-ws-button")
+ );
+ testFilterButtonsCustom(monitor, [0, 1, 1, 0, 0, 0, 0, 0, 1, 0]);
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ testFilterButtons(monitor, "all");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ await teardown(monitor);
+
+ function getSelectedIndex(state) {
+ if (!state.requests.selectedId) {
+ return -1;
+ }
+ return getSortedRequests(state).findIndex(
+ r => r.id === state.requests.selectedId
+ );
+ }
+
+ async function testContents(visibility) {
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ }
+
+ const items = getSortedRequests(store.getState());
+ let visibleItems;
+
+ // Filter results will be updated asynchronously, so we should wait until
+ // displayed requests reach final state.
+ await waitUntil(() => {
+ visibleItems = getDisplayedRequests(store.getState());
+ return visibleItems.length === visibility.filter(e => e).length;
+ });
+
+ is(
+ items.length,
+ visibility.length,
+ "There should be a specific amount of items in the requests menu."
+ );
+ is(
+ visibleItems.length,
+ visibility.filter(e => e).length,
+ "There should be a specific amount of visible items in the requests menu."
+ );
+
+ for (let i = 0; i < visibility.length; i++) {
+ const itemId = items[i].id;
+ const shouldBeVisible = !!visibility[i];
+ const isThere = visibleItems.some(r => r.id == itemId);
+
+ is(
+ isThere,
+ shouldBeVisible,
+ `The item at index ${i} has visibility=${shouldBeVisible}`
+ );
+
+ if (shouldBeVisible) {
+ const { method, url, data } = EXPECTED_REQUESTS[i];
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[i],
+ method,
+ url,
+ data
+ );
+ }
+ }
+ }
+});
+
+function getSjsURLInUnicodeIdn() {
+ const { hostname } = new URL(CONTENT_TYPE_SJS);
+ return CONTENT_TYPE_SJS.replace(hostname, IDN);
+}
diff --git a/devtools/client/netmonitor/test/browser_net_filter-02.js b/devtools/client/netmonitor/test/browser_net_filter-02.js
new file mode 100644
index 0000000000..2e2b7752da
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_filter-02.js
@@ -0,0 +1,307 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if filtering items in the network table works correctly with new requests.
+ */
+
+const BASIC_REQUESTS = [
+ { url: "sjs_content-type-test-server.sjs?fmt=html&res=undefined" },
+ { url: "sjs_content-type-test-server.sjs?fmt=xhtml" },
+ { url: "sjs_content-type-test-server.sjs?fmt=css" },
+ { url: "sjs_content-type-test-server.sjs?fmt=js" },
+];
+
+const REQUESTS_WITH_MEDIA = BASIC_REQUESTS.concat([
+ { url: "sjs_content-type-test-server.sjs?fmt=font" },
+ { url: "sjs_content-type-test-server.sjs?fmt=image" },
+ { url: "sjs_content-type-test-server.sjs?fmt=audio" },
+ { url: "sjs_content-type-test-server.sjs?fmt=video" },
+]);
+
+const REQUESTS_WITH_MEDIA_AND_FLASH = REQUESTS_WITH_MEDIA.concat([
+ { url: "sjs_content-type-test-server.sjs?fmt=flash" },
+]);
+
+const REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS =
+ REQUESTS_WITH_MEDIA_AND_FLASH.concat([
+ /* "Upgrade" is a reserved header and can not be set on XMLHttpRequest */
+ { url: "sjs_content-type-test-server.sjs?fmt=ws" },
+ ]);
+
+const EXPECTED_REQUESTS = [
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=html",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "html",
+ fullMimeType: "text/html; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=xhtml",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "xhtml",
+ fullMimeType: "application/xhtml+xml; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=css",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "css",
+ fullMimeType: "text/css; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=js",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "js",
+ fullMimeType: "application/javascript; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=font",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "woff",
+ fullMimeType: "font/woff",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=image",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "png",
+ fullMimeType: "image/png",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=audio",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "ogg",
+ fullMimeType: "audio/ogg",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=video",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "webm",
+ fullMimeType: "video/webm",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=flash",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "x-shockwave-flash",
+ fullMimeType: "application/x-shockwave-flash",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=ws",
+ data: {
+ fuzzyUrl: true,
+ status: 101,
+ statusText: "Switching Protocols",
+ },
+ },
+];
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(FILTERING_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ // It seems that this test may be slow on Ubuntu builds running on ec2.
+ requestLongerTimeout(2);
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSelectedRequest, getSortedRequests } =
+ windowRequire("devtools/client/netmonitor/src/selectors/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ let wait = waitForNetworkEvents(monitor, 10);
+ await performRequestsInContent(REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS);
+ await wait;
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ isnot(
+ getSelectedRequest(store.getState()),
+ null,
+ "There should be a selected item in the requests menu."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ 0,
+ "The first item should be selected in the requests menu."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should be visible after toggle button was pressed."
+ );
+
+ testFilterButtons(monitor, "all");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ info("Testing html filtering.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-html-button")
+ );
+ testFilterButtons(monitor, "html");
+ await testContents([1, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info("Performing more requests.");
+ // As the view is filtered and there is only one request for which we fetch event timings
+ wait = waitForNetworkEvents(monitor, 10, { expectedEventTimings: 1 });
+ await performRequestsInContent(REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS);
+ await wait;
+
+ info("Testing html filtering again.");
+ testFilterButtons(monitor, "html");
+ await testContents([
+ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
+ ]);
+
+ info("Performing more requests.");
+ wait = waitForNetworkEvents(monitor, 10, { expectedEventTimings: 1 });
+ await performRequestsInContent(REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS);
+ await wait;
+
+ info("Testing html filtering again.");
+ testFilterButtons(monitor, "html");
+ await testContents([
+ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0,
+ 0, 0, 0, 0, 0,
+ ]);
+
+ info("Resetting filters.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ testFilterButtons(monitor, "all");
+ await testContents([
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1,
+ ]);
+
+ await teardown(monitor);
+
+ function getSelectedIndex(state) {
+ if (!state.requests.selectedId) {
+ return -1;
+ }
+ return getSortedRequests(state).findIndex(
+ r => r.id === state.requests.selectedId
+ );
+ }
+
+ async function testContents(visibility) {
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ }
+
+ isnot(
+ getSelectedRequest(store.getState()),
+ null,
+ "There should still be a selected item after filtering."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ 0,
+ "The first item should be still selected after filtering."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should still be visible after filtering."
+ );
+
+ const items = getSortedRequests(store.getState());
+ const visibleItems = getDisplayedRequests(store.getState());
+
+ is(
+ items.length,
+ visibility.length,
+ "There should be a specific amount of items in the requests menu."
+ );
+ is(
+ visibleItems.length,
+ visibility.filter(e => e).length,
+ "There should be a specific amount of visible items in the requests menu."
+ );
+
+ for (let i = 0; i < visibility.length; i++) {
+ const itemId = items[i].id;
+ const shouldBeVisible = !!visibility[i];
+ const isThere = visibleItems.some(r => r.id == itemId);
+ is(
+ isThere,
+ shouldBeVisible,
+ `The item at index ${i} has visibility=${shouldBeVisible}`
+ );
+ }
+
+ for (let i = 0; i < EXPECTED_REQUESTS.length; i++) {
+ const { method, url, data } = EXPECTED_REQUESTS[i];
+ for (let j = i; j < visibility.length; j += EXPECTED_REQUESTS.length) {
+ if (visibility[j]) {
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[i],
+ method,
+ url,
+ data
+ );
+ }
+ }
+ }
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_filter-03.js b/devtools/client/netmonitor/test/browser_net_filter-03.js
new file mode 100644
index 0000000000..b7ce43871e
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_filter-03.js
@@ -0,0 +1,163 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if filtering items in the network table works correctly with new requests
+ * and while sorting is enabled.
+ */
+const BASIC_REQUESTS = [
+ { url: "sjs_content-type-test-server.sjs?fmt=html&res=undefined" },
+ { url: "sjs_content-type-test-server.sjs?fmt=css" },
+ { url: "sjs_content-type-test-server.sjs?fmt=js" },
+];
+
+const REQUESTS_WITH_MEDIA = BASIC_REQUESTS.concat([
+ { url: "sjs_content-type-test-server.sjs?fmt=font" },
+ { url: "sjs_content-type-test-server.sjs?fmt=image" },
+ { url: "sjs_content-type-test-server.sjs?fmt=audio" },
+ { url: "sjs_content-type-test-server.sjs?fmt=video" },
+]);
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(FILTERING_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ // It seems that this test may be slow on Ubuntu builds running on ec2.
+ requestLongerTimeout(2);
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSelectedRequest, getSortedRequests } =
+ windowRequire("devtools/client/netmonitor/src/selectors/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // The test assumes that the first HTML request here has a longer response
+ // body than the other HTML requests performed later during the test.
+ const requests = Cu.cloneInto(REQUESTS_WITH_MEDIA, {});
+ const newres = "res=<p>" + new Array(10).join(Math.random(10)) + "</p>";
+ requests[0].url = requests[0].url.replace("res=undefined", newres);
+
+ let wait = waitForNetworkEvents(monitor, 7);
+ await performRequestsInContent(requests);
+ await wait;
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ isnot(
+ getSelectedRequest(store.getState()),
+ null,
+ "There should be a selected item in the requests menu."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ 0,
+ "The first item should be selected in the requests menu."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should be visible after toggle button was pressed."
+ );
+
+ testFilterButtons(monitor, "all");
+ testContents([0, 1, 2, 3, 4, 5, 6], 7, 0);
+
+ info("Sorting by size, ascending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-contentSize-button")
+ );
+ testFilterButtons(monitor, "all");
+ testContents([6, 4, 5, 0, 1, 2, 3], 7, 6);
+
+ info("Testing html filtering.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-html-button")
+ );
+ testFilterButtons(monitor, "html");
+ testContents([6, 4, 5, 0, 1, 2, 3], 1, 6);
+
+ info("Performing more requests.");
+ // As the view is filtered and there is only one request for which we fetch event timings
+ wait = waitForNetworkEvents(monitor, 7, { expectedEventTimings: 1 });
+ performRequestsInContent(REQUESTS_WITH_MEDIA);
+ await wait;
+
+ info("Testing html filtering again.");
+ resetSorting();
+ testFilterButtons(monitor, "html");
+ testContents([8, 13, 9, 11, 10, 12, 0, 4, 1, 5, 2, 6, 3, 7], 2, 13);
+
+ info("Performing more requests.");
+ // As the view is filtered and there is only one request for which we fetch event timings
+ wait = waitForNetworkEvents(monitor, 7, { expectedEventTimings: 1 });
+ performRequestsInContent(REQUESTS_WITH_MEDIA);
+ await wait;
+
+ info("Testing html filtering again.");
+ resetSorting();
+ testFilterButtons(monitor, "html");
+ testContents(
+ [12, 13, 20, 14, 16, 18, 15, 17, 19, 0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11],
+ 3,
+ 20
+ );
+
+ await teardown(monitor);
+
+ function resetSorting() {
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-initiator-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-contentSize-button")
+ );
+ }
+
+ function getSelectedIndex(state) {
+ if (!state.requests.selectedId) {
+ return -1;
+ }
+ return getSortedRequests(state).findIndex(
+ r => r.id === state.requests.selectedId
+ );
+ }
+
+ function testContents(order, visible, selection) {
+ isnot(
+ getSelectedRequest(store.getState()),
+ null,
+ "There should still be a selected item after filtering."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ selection,
+ "The first item should be still selected after filtering."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should still be visible after filtering."
+ );
+
+ is(
+ getSortedRequests(store.getState()).length,
+ order.length,
+ "There should be a specific amount of items in the requests menu."
+ );
+ is(
+ getDisplayedRequests(store.getState()).length,
+ visible,
+ "There should be a specific amount of visible items in the requests menu."
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_filter-04.js b/devtools/client/netmonitor/test/browser_net_filter-04.js
new file mode 100644
index 0000000000..d690813285
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_filter-04.js
@@ -0,0 +1,80 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if invalid filter types are sanitized when loaded from the preferences.
+ */
+
+const BASIC_REQUESTS = [
+ { url: "sjs_content-type-test-server.sjs?fmt=html&res=undefined" },
+ { url: "sjs_content-type-test-server.sjs?fmt=css" },
+ { url: "sjs_content-type-test-server.sjs?fmt=js" },
+];
+
+const REQUESTS_WITH_MEDIA = BASIC_REQUESTS.concat([
+ { url: "sjs_content-type-test-server.sjs?fmt=font" },
+ { url: "sjs_content-type-test-server.sjs?fmt=image" },
+ { url: "sjs_content-type-test-server.sjs?fmt=audio" },
+ { url: "sjs_content-type-test-server.sjs?fmt=video" },
+]);
+
+const REQUESTS_WITH_MEDIA_AND_FLASH = REQUESTS_WITH_MEDIA.concat([
+ { url: "sjs_content-type-test-server.sjs?fmt=flash" },
+]);
+
+const REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS =
+ REQUESTS_WITH_MEDIA_AND_FLASH.concat([
+ /* "Upgrade" is a reserved header and can not be set on XMLHttpRequest */
+ { url: "sjs_content-type-test-server.sjs?fmt=ws" },
+ ]);
+
+add_task(async function () {
+ Services.prefs.setCharPref(
+ "devtools.netmonitor.filters",
+ '["bogus", "js", "alsobogus"]'
+ );
+
+ const { monitor } = await initNetMonitor(FILTERING_URL, {
+ requestCount: 1,
+ expectedEventTimings: 0,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { Prefs } = windowRequire("devtools/client/netmonitor/src/utils/prefs");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ is(Prefs.filters.length, 3, "All the filter types should be loaded.");
+ is(
+ Prefs.filters[0],
+ "bogus",
+ "The first filter type is invalid, but loaded anyway."
+ );
+
+ // As the view is filtered and there is only one request for which we fetch event timings
+ const wait = waitForNetworkEvents(monitor, 9, { expectedEventTimings: 1 });
+ await performRequestsInContent(REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS);
+ await wait;
+
+ testFilterButtons(monitor, "js");
+ ok(true, "Only the correct filter type was taken into consideration.");
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-html-button")
+ );
+
+ const filters = Services.prefs.getCharPref("devtools.netmonitor.filters");
+ is(
+ filters,
+ '["html","js"]',
+ "The filters preferences were saved directly after the click and only" +
+ " with the valid."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_filter-autocomplete.js b/devtools/client/netmonitor/test/browser_net_filter-autocomplete.js
new file mode 100644
index 0000000000..974c18a4f2
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_filter-autocomplete.js
@@ -0,0 +1,207 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test autocomplete based on filtering flags and requests
+ */
+const REQUESTS = [
+ {
+ url: "sjs_content-type-test-server.sjs?fmt=html&res=undefined&text=Sample",
+ },
+ {
+ url:
+ "sjs_content-type-test-server.sjs?fmt=html&res=undefined&text=Sample" +
+ "&cookies=1",
+ },
+ { url: "sjs_content-type-test-server.sjs?fmt=css&text=sample" },
+ { url: "sjs_content-type-test-server.sjs?fmt=js&text=sample" },
+ { url: "sjs_content-type-test-server.sjs?fmt=font" },
+ { url: "sjs_content-type-test-server.sjs?fmt=image" },
+ { url: "sjs_content-type-test-server.sjs?fmt=audio" },
+ { url: "sjs_content-type-test-server.sjs?fmt=video" },
+ { url: "sjs_content-type-test-server.sjs?fmt=gzip" },
+ { url: "sjs_status-codes-test-server.sjs?sts=304" },
+];
+
+function testAutocompleteContents(expected, document) {
+ expected.forEach(function (item, i) {
+ is(
+ document.querySelector(
+ `.devtools-autocomplete-listbox .autocomplete-item:nth-child(${i + 1})`
+ ).textContent,
+ item,
+ `${expected[i]} found`
+ );
+ });
+}
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(FILTERING_URL, { requestCount: 1 });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Starting test... ");
+
+ // Let the requests load completely before the autocomplete tests begin
+ // as autocomplete values also rely on the network requests.
+ const waitNetwork = waitForNetworkEvents(monitor, REQUESTS.length);
+ await performRequestsInContent(REQUESTS);
+ await waitNetwork;
+
+ EventUtils.synthesizeMouseAtCenter(
+ document.querySelector(".devtools-filterinput"),
+ {},
+ document.defaultView
+ );
+ // Empty Mouse click should keep autocomplete hidden
+ ok(
+ !document.querySelector(".devtools-autocomplete-popup"),
+ "Autocomplete Popup still hidden"
+ );
+
+ document.querySelector(".devtools-filterinput").focus();
+
+ // Typing numbers that corresponds to status codes should invoke an autocomplete
+ EventUtils.sendString("2");
+ ok(
+ document.querySelector(".devtools-autocomplete-popup"),
+ "Autocomplete Popup Created"
+ );
+ testAutocompleteContents(
+ [
+ "status-code:200",
+ "status-code:201",
+ "status-code:202",
+ "status-code:203",
+ "status-code:204",
+ "status-code:205",
+ "status-code:206",
+ ],
+ document
+ );
+ EventUtils.synthesizeKey("KEY_Enter");
+ is(
+ document.querySelector(".devtools-filterinput").value,
+ "status-code:200",
+ "Value correctly set after Enter"
+ );
+ ok(
+ !document.querySelector(".devtools-autocomplete-popup"),
+ "Autocomplete Popup hidden after keyboard Enter key"
+ );
+
+ // Space separated tokens
+ // The last token where autocomplete is available shall generate the popup
+ EventUtils.sendString(" s");
+ ok(
+ document.querySelector(".devtools-autocomplete-popup"),
+ "Autocomplete Popup Created"
+ );
+ testAutocompleteContents(
+ [
+ "scheme:",
+ "set-cookie-domain:",
+ "set-cookie-name:",
+ "set-cookie-value:",
+ "size:",
+ "status-code:",
+ ],
+ document
+ );
+
+ EventUtils.sendString("c");
+ testAutocompleteContents(["scheme:"], document);
+ EventUtils.synthesizeKey("KEY_Tab");
+ // Tab selection should hide autocomplete
+ ok(
+ document.querySelector(".devtools-autocomplete-popup"),
+ "Autocomplete Popup alive with content values"
+ );
+ testAutocompleteContents(["scheme:http"], document);
+
+ EventUtils.synthesizeKey("KEY_Enter");
+ is(
+ document.querySelector(".devtools-filterinput").value,
+ "status-code:200 scheme:http",
+ "Value correctly set after Enter"
+ );
+ ok(
+ !document.querySelector(".devtools-autocomplete-popup"),
+ "Autocomplete Popup hidden after keyboard Enter key"
+ );
+
+ // Space separated tokens
+ // The last token where autocomplete is available shall generate the popup
+ EventUtils.sendString(" pro");
+ testAutocompleteContents(["protocol:"], document);
+
+ // The new value of the text box should be previousTokens + latest value selected
+ // First return selects "protocol:"
+ EventUtils.synthesizeKey("KEY_Enter");
+ // Second return selects "protocol:HTTP/1.1"
+ EventUtils.synthesizeKey("KEY_Enter");
+ is(
+ document.querySelector(".devtools-filterinput").value,
+ "status-code:200 scheme:http protocol:HTTP/1.1",
+ "Tokenized click generates correct value in input box"
+ );
+
+ // Explicitly type in `flag:` renders autocomplete with values
+ EventUtils.sendString(" status-code:");
+ testAutocompleteContents(["status-code:200", "status-code:304"], document);
+
+ // Typing the exact value closes autocomplete
+ EventUtils.sendString("304");
+ ok(
+ !document.querySelector(".devtools-autocomplete-popup"),
+ "Typing the exact value closes autocomplete"
+ );
+
+ // Check if mime-type has been correctly parsed out and values also get autocomplete
+ EventUtils.sendString(" mime-type:text");
+ testAutocompleteContents(
+ ["mime-type:text/css", "mime-type:text/html", "mime-type:text/plain"],
+ document
+ );
+
+ // The negative filter flags
+ EventUtils.sendString(" -");
+ testAutocompleteContents(
+ [
+ "-cause:",
+ "-domain:",
+ "-has-response-header:",
+ "-initiator:",
+ "-is:",
+ "-larger-than:",
+ "-method:",
+ "-mime-type:",
+ "-priority:",
+ "-protocol:",
+ "-regexp:",
+ "-remote-ip:",
+ "-scheme:",
+ "-set-cookie-domain:",
+ "-set-cookie-name:",
+ "-set-cookie-value:",
+ "-size:",
+ "-status-code:",
+ "-transferred-larger-than:",
+ "-transferred:",
+ ],
+ document
+ );
+
+ // Autocomplete for negative filtering
+ EventUtils.sendString("is:");
+ testAutocompleteContents(
+ ["-is:cached", "-is:from-cache", "-is:running"],
+ document
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_filter-flags.js b/devtools/client/netmonitor/test/browser_net_filter-flags.js
new file mode 100644
index 0000000000..15260a0e75
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_filter-flags.js
@@ -0,0 +1,435 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+requestLongerTimeout(2);
+
+/**
+ * Test different text filtering flags
+ */
+const REQUESTS = [
+ {
+ url: "sjs_content-type-test-server.sjs?fmt=html&res=undefined&text=Sample",
+ },
+ {
+ url:
+ "sjs_content-type-test-server.sjs?fmt=html&res=undefined&text=Sample" +
+ "&cookies=1",
+ },
+ { url: "sjs_content-type-test-server.sjs?fmt=css&text=sample" },
+ { url: "sjs_content-type-test-server.sjs?fmt=js&text=sample" },
+ { url: "sjs_content-type-test-server.sjs?fmt=font" },
+ { url: "sjs_content-type-test-server.sjs?fmt=image" },
+ { url: "sjs_content-type-test-server.sjs?fmt=audio" },
+ { url: "sjs_content-type-test-server.sjs?fmt=video" },
+ { url: "sjs_content-type-test-server.sjs?fmt=gzip" },
+ { url: "sjs_status-codes-test-server.sjs?sts=304" },
+];
+
+const EXPECTED_REQUESTS = [
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=html",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "html",
+ fullMimeType: "text/html; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=html",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "html",
+ fullMimeType: "text/html; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=css",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "css",
+ fullMimeType: "text/css; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=js",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "js",
+ fullMimeType: "application/javascript; charset=utf-8",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=font",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "woff",
+ fullMimeType: "font/woff",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=image",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "png",
+ fullMimeType: "image/png",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=audio",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "ogg",
+ fullMimeType: "audio/ogg",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=video",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ type: "webm",
+ fullMimeType: "video/webm",
+ },
+ },
+ {
+ method: "GET",
+ url: CONTENT_TYPE_SJS + "?fmt=gzip",
+ data: {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "OK",
+ displayedStatus: "200",
+ type: "plain",
+ fullMimeType: "text/plain",
+ },
+ },
+ {
+ method: "GET",
+ url: STATUS_CODES_SJS + "?sts=304",
+ data: {
+ status: 304,
+ statusText: "Not Modified",
+ displayedStatus: "304",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ },
+ },
+];
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(FILTERING_URL, { requestCount: 1 });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Filtering network request will start fetching data lazily
+ // (fetching requestHeaders & responseHeaders for filtering WS & XHR)
+ // Lazy fetching will be executed when user focuses on filter box.
+ function setFreetextFilter(value) {
+ const filterBox = document.querySelector(".devtools-filterinput");
+ filterBox.focus();
+ filterBox.value = "";
+ typeInNetmonitor(value, monitor);
+ }
+
+ info("Starting test... ");
+
+ const waitNetwork = waitForNetworkEvents(monitor, REQUESTS.length);
+ await performRequestsInContent(REQUESTS);
+ await waitNetwork;
+
+ info(" > Test running flag once requests finish running");
+ setFreetextFilter("is:running");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test cached flag");
+ setFreetextFilter("is:from-cache");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
+
+ setFreetextFilter("is:cached");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
+
+ info(" > Test negative cached flag");
+ setFreetextFilter("-is:from-cache");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 0]);
+
+ setFreetextFilter("-is:cached");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 0]);
+
+ info(" > Test status-code flag");
+ setFreetextFilter("status-code:200");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 0]);
+
+ info(" > Test status-code negative flag");
+ setFreetextFilter("-status-code:200");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
+
+ info(" > Test mime-type flag");
+ setFreetextFilter("mime-type:HtmL");
+ await testContents([1, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test mime-type negative flag");
+ setFreetextFilter("-mime-type:HtmL");
+ await testContents([0, 0, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ info(" > Test method flag");
+ setFreetextFilter("method:get");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ info(" > Test unmatched method flag");
+ setFreetextFilter("method:post");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test scheme flag (all requests are http)");
+ setFreetextFilter("scheme:http");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ setFreetextFilter("scheme:https");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test regex filter");
+ setFreetextFilter("regexp:content.*?Sam");
+ await testContents([1, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test set-cookie-name flag");
+ setFreetextFilter("set-cookie-name:name2");
+ await testContents([0, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ setFreetextFilter("set-cookie-name:not-existing");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test set-cookie-value flag");
+ setFreetextFilter("set-cookie-value:value2");
+ await testContents([0, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ setFreetextFilter("set-cookie-value:not-existing");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test set-cookie-domain flag");
+ setFreetextFilter("set-cookie-domain:.example.com");
+ await testContents([0, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ setFreetextFilter("set-cookie-domain:.foo.example.com");
+ await testContents([0, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ setFreetextFilter("set-cookie-domain:.not-existing.example.com");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test size");
+ setFreetextFilter("size:-1");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ setFreetextFilter("size:0");
+ await testContents([0, 0, 0, 0, 1, 1, 1, 1, 0, 1]);
+
+ setFreetextFilter("size:34");
+ await testContents([0, 0, 1, 1, 0, 0, 0, 0, 0, 0]);
+
+ setFreetextFilter("size:0kb");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Testing the lower bound");
+ setFreetextFilter("size:9.659k");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Testing the actual value");
+ setFreetextFilter("size:10989");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 1, 0]);
+
+ info(" > Testing the upper bound");
+ setFreetextFilter("size:11.804k");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 1, 0]);
+
+ info(" > Test transferred");
+ setFreetextFilter("transferred:200");
+ await testContents([0, 0, 0, 0, 1, 1, 1, 1, 0, 0]);
+
+ setFreetextFilter("transferred:234");
+ await testContents([1, 0, 1, 0, 0, 0, 0, 0, 0, 1]);
+
+ setFreetextFilter("transferred:248");
+ await testContents([0, 0, 1, 1, 0, 0, 0, 0, 0, 1]);
+
+ setFreetextFilter("transferred:0kb");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test larger-than");
+ setFreetextFilter("larger-than:-1");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ setFreetextFilter("larger-than:0");
+ await testContents([1, 1, 1, 1, 0, 0, 0, 0, 1, 0]);
+
+ setFreetextFilter("larger-than:33");
+ await testContents([0, 0, 1, 1, 0, 0, 0, 0, 1, 0]);
+
+ setFreetextFilter("larger-than:34");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 1, 0]);
+
+ setFreetextFilter("larger-than:10.73k");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 1, 0]);
+
+ setFreetextFilter("larger-than:10.732k");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 1, 0]);
+
+ setFreetextFilter("larger-than:0kb");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test transferred-larger-than");
+ setFreetextFilter("transferred-larger-than:-1");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ setFreetextFilter("transferred-larger-than:214");
+ await testContents([1, 1, 1, 1, 0, 0, 0, 0, 1, 1]);
+
+ setFreetextFilter("transferred-larger-than:247");
+ await testContents([0, 1, 1, 1, 0, 0, 0, 0, 1, 0]);
+
+ setFreetextFilter("transferred-larger-than:248");
+ await testContents([0, 1, 0, 1, 0, 0, 0, 0, 1, 0]);
+
+ setFreetextFilter("transferred-larger-than:10.73k");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ setFreetextFilter("transferred-larger-than:0kb");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test cause");
+ setFreetextFilter("cause:xhr");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ setFreetextFilter("cause:script");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test has-response-header");
+ setFreetextFilter("has-response-header:Content-Type");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ setFreetextFilter("has-response-header:Last-Modified");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test remote-ip");
+ setFreetextFilter("remote-ip:127.0.0.1");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ setFreetextFilter("remote-ip:192.168.1.2");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test domain");
+ setFreetextFilter("domain:example.com");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ setFreetextFilter("domain:wrongexample.com");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test protocol");
+ setFreetextFilter("protocol:http/1");
+ await testContents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
+
+ setFreetextFilter("protocol:http/2");
+ await testContents([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+ info(" > Test mixing flags");
+ setFreetextFilter("-mime-type:HtmL status-code:200");
+ await testContents([0, 0, 1, 1, 1, 1, 1, 1, 1, 0]);
+
+ await teardown(monitor);
+
+ async function testContents(visibility) {
+ const items = getSortedRequests(store.getState());
+ let visibleItems = getDisplayedRequests(store.getState());
+
+ // Filter results will be updated asynchronously, so we should wait until
+ // displayed requests reach final state.
+ await waitUntil(() => {
+ visibleItems = getDisplayedRequests(store.getState());
+ return visibleItems.length === visibility.filter(e => e).length;
+ });
+
+ is(
+ items.length,
+ visibility.length,
+ "There should be a specific amount of items in the requests menu."
+ );
+ is(
+ visibleItems.length,
+ visibility.filter(e => e).length,
+ "There should be a specific amount of visible items in the requests menu."
+ );
+
+ for (let i = 0; i < visibility.length; i++) {
+ const itemId = items[i].id;
+ const shouldBeVisible = !!visibility[i];
+ let isThere = visibleItems.some(r => r.id == itemId);
+
+ // Filter results will be updated asynchronously, so we should wait until
+ // displayed requests reach final state.
+ await waitUntil(() => {
+ visibleItems = getDisplayedRequests(store.getState());
+ isThere = visibleItems.some(r => r.id == itemId);
+ return isThere === shouldBeVisible;
+ });
+
+ is(
+ isThere,
+ shouldBeVisible,
+ `The item at index ${i} has visibility=${shouldBeVisible}`
+ );
+ }
+
+ // Fake mouse over the status column only after the list is fully updated
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+ }
+
+ for (let i = 0; i < visibility.length; i++) {
+ const shouldBeVisible = !!visibility[i];
+
+ if (shouldBeVisible) {
+ const { method, url, data } = EXPECTED_REQUESTS[i];
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[i],
+ method,
+ url,
+ data
+ );
+ }
+ }
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_filter-sts-search.js b/devtools/client/netmonitor/test/browser_net_filter-sts-search.js
new file mode 100644
index 0000000000..d8de156cb6
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_filter-sts-search.js
@@ -0,0 +1,59 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test incomplete status-code search
+ */
+const REQUESTS = [
+ { url: "sjs_status-codes-test-server.sjs?sts=400" },
+ { url: "sjs_status-codes-test-server.sjs?sts=300" },
+ { url: "sjs_status-codes-test-server.sjs?sts=304" },
+];
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(FILTERING_URL, { requestCount: 1 });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ const { getDisplayedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Starting test... ");
+
+ // Let the requests load completely before the incomplete search tests begin
+ // because we are searching for the status code in these requests.
+ const waitNetwork = waitForNetworkEvents(monitor, REQUESTS.length);
+ await performRequestsInContent(REQUESTS);
+ await waitNetwork;
+
+ document.querySelector(".devtools-filterinput").focus();
+
+ EventUtils.sendString("status-code:3");
+
+ let visibleItems = getDisplayedRequests(store.getState());
+
+ // Results will be updated asynchronously, so we should wait until
+ // displayed requests reach final state.
+ await waitUntil(() => {
+ visibleItems = getDisplayedRequests(store.getState());
+ return visibleItems.length === 2;
+ });
+
+ is(
+ Number(visibleItems[0].status),
+ 303,
+ "First visible item has expected status"
+ );
+ is(
+ Number(visibleItems[1].status),
+ 304,
+ "Second visible item has expected status"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_filter-value-preserved.js b/devtools/client/netmonitor/test/browser_net_filter-value-preserved.js
new file mode 100644
index 0000000000..59eccc25f7
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_filter-value-preserved.js
@@ -0,0 +1,55 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that filter input keeps its value when host or panel changes
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(FILTERING_URL, { requestCount: 1 });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Starting test... ");
+
+ const toolbars = document.querySelector("#netmonitor-toolbar-container");
+ let input = toolbars.querySelector(".devtools-filterinput");
+ input.value = "hello";
+
+ await monitor.toolbox.switchHost("right");
+ await waitForTick();
+
+ is(
+ toolbars.querySelectorAll(".devtools-toolbar").length,
+ 2,
+ "Should be in 2 toolbar mode"
+ );
+
+ input = toolbars.querySelector(".devtools-filterinput");
+ is(
+ input.value,
+ "hello",
+ "Value should be preserved after switching to right host"
+ );
+
+ await monitor.toolbox.switchHost("bottom");
+
+ input = toolbars.querySelector(".devtools-filterinput");
+ is(
+ input.value,
+ "hello",
+ "Value should be preserved after switching to bottom host"
+ );
+
+ await monitor.toolbox.selectTool("inspector");
+ await monitor.toolbox.selectTool("netmonitor");
+
+ input = toolbars.querySelector(".devtools-filterinput");
+ is(input.value, "hello", "Value should be preserved after switching tools");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_fission_switch_target.js b/devtools/client/netmonitor/test/browser_net_fission_switch_target.js
new file mode 100644
index 0000000000..a34e17c02e
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_fission_switch_target.js
@@ -0,0 +1,54 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Test switching for the top-level target.
+
+const EXAMPLE_COM_URL = "https://example.com/document-builder.sjs?html=testcom";
+const EXAMPLE_NET_URL = "https://example.net/document-builder.sjs?html=testnet";
+const REQUEST_URL = HTTPS_SEARCH_SJS + "?value=test";
+const PARENT_PROCESS_URL = "about:blank";
+
+add_task(async function () {
+ info("Open a page that runs on the content process and the netmonitor");
+ const { monitor } = await initNetMonitor(EXAMPLE_COM_URL, {
+ requestCount: 1,
+ });
+ await assertRequest(monitor, REQUEST_URL);
+
+ info("Navigate to a page that runs in another content process (if fission)");
+ await waitForUpdatesAndNavigateTo(EXAMPLE_NET_URL);
+ await assertRequest(monitor, REQUEST_URL);
+
+ info("Navigate to a parent process page");
+ await waitForUpdatesAndNavigateTo(PARENT_PROCESS_URL);
+ await assertRequest(monitor, REQUEST_URL);
+
+ info("Navigate back to the example.com content page");
+ await waitForUpdatesAndNavigateTo(EXAMPLE_COM_URL);
+ await assertRequest(monitor, REQUEST_URL);
+
+ await teardown(monitor);
+});
+
+async function waitForUpdatesAndNavigateTo(url) {
+ await waitForAllNetworkUpdateEvents();
+ await navigateTo(url);
+}
+
+async function assertRequest(monitor, url) {
+ const waitForRequests = waitForNetworkEvents(monitor, 1);
+ info("Create a request in the target page for the URL: " + url);
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [url], async _url => {
+ // Note: we are not reusing performRequests available in some netmonitor
+ // test pages because we also need to run this helper against an about:
+ // page, which won't have the helper defined.
+ // Therefore, we use a simplified performRequest implementation here.
+ const xhr = new content.wrappedJSObject.XMLHttpRequest();
+ xhr.open("GET", _url, true);
+ xhr.send(null);
+ });
+ info("Wait for the request to be received by the netmonitor UI");
+ return waitForRequests;
+}
diff --git a/devtools/client/netmonitor/test/browser_net_fonts.js b/devtools/client/netmonitor/test/browser_net_fonts.js
new file mode 100644
index 0000000000..6667ca7962
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_fonts.js
@@ -0,0 +1,84 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if font preview is generated correctly
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(FONTS_URL + "?name=fonts", {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Reload the page to get the font request
+ const waitForRequests = waitForNetworkEvents(monitor, 3);
+ await reloadBrowser();
+ await waitForRequests;
+
+ const wait = waitForDOMIfNeeded(
+ document,
+ "#response-panel .response-font[src^='data:']"
+ );
+
+ const requests = document.querySelectorAll(
+ ".request-list-item .requests-list-status"
+ );
+
+ // Check first font request
+ clickElement(requests[1], monitor);
+ clickOnSidebarTab(document, "response");
+
+ await wait;
+
+ ok(true, "Font preview is shown");
+
+ const tabpanel = document.querySelector("#response-panel");
+ let image = tabpanel.querySelector(".response-font");
+ await once(image, "load");
+
+ ok(
+ image.complete && image.naturalHeight !== 0,
+ "Font preview got generated correctly"
+ );
+
+ let fontData = document.querySelectorAll(".tabpanel-summary-value");
+ is(fontData[0].textContent, "Ostrich Sans Medium", "Font name is correct");
+ // "font/ttf" is returned on Linux, which is the expected MIME type, though
+ // "application/octet-stream" is also accepted which is returned on Windows and MacOS.
+ ok(
+ ["font/ttf", "application/octet-stream"].includes(fontData[1].textContent),
+ "MIME type is correct"
+ );
+
+ // Check second font request
+ clickElement(requests[2], monitor);
+
+ await waitForDOM(document, "#response-panel .response-font[src^='data:']");
+
+ image = tabpanel.querySelector(".response-font");
+ await once(image, "load");
+
+ ok(
+ image.complete && image.naturalHeight !== 0,
+ "Font preview got generated correctly"
+ );
+
+ fontData = document.querySelectorAll(".tabpanel-summary-value");
+ is(fontData[0].textContent, "Ostrich Sans Black", "Font name is correct");
+ // Actually expected is "font/ttf", though "application/octet-stream" is
+ // ok as well and obviously returned when running the test locally.
+ ok(
+ ["font/ttf", "application/octet-stream"].includes(fontData[1].textContent),
+ "MIME type is correct"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_footer-summary.js b/devtools/client/netmonitor/test/browser_net_footer-summary.js
new file mode 100644
index 0000000000..e0b12bcf77
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_footer-summary.js
@@ -0,0 +1,114 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if the summary text displayed in the network requests menu footer is correct.
+ */
+
+add_task(async function () {
+ const {
+ getFormattedSize,
+ getFormattedTime,
+ } = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+ requestLongerTimeout(2);
+
+ const { tab, monitor } = await initNetMonitor(FILTERING_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequestsSummary } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const { L10N } = windowRequire("devtools/client/netmonitor/src/utils/l10n");
+ const { PluralForm } = windowRequire("devtools/shared/plural-form");
+
+ store.dispatch(Actions.batchEnable(false));
+ testStatus();
+
+ for (let i = 0; i < 2; i++) {
+ info(`Performing requests in batch #${i}`);
+ const wait = waitForNetworkEvents(monitor, 8);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.performRequests(
+ '{ "getMedia": true, "getFlash": true }'
+ );
+ });
+ await wait;
+
+ testStatus();
+
+ const buttons = ["html", "css", "js", "xhr", "fonts", "images", "media"];
+ for (const button of buttons) {
+ const buttonEl = document.querySelector(
+ `.requests-list-filter-${button}-button`
+ );
+ EventUtils.sendMouseEvent({ type: "click" }, buttonEl);
+ testStatus();
+ }
+ }
+
+ await teardown(monitor);
+
+ function testStatus() {
+ const state = store.getState();
+ const totalRequestsCount = state.requests.requests.length;
+ const requestsSummary = getDisplayedRequestsSummary(state);
+ info(
+ `Current requests: ${requestsSummary.count} of ${totalRequestsCount}.`
+ );
+
+ const valueCount = document.querySelector(
+ ".requests-list-network-summary-count"
+ ).textContent;
+ info("Current summary count: " + valueCount);
+ const expectedCount = PluralForm.get(
+ requestsSummary.count,
+ L10N.getStr("networkMenu.summary.requestsCount2")
+ ).replace("#1", requestsSummary.count);
+
+ if (!totalRequestsCount || !requestsSummary.count) {
+ is(
+ valueCount,
+ L10N.getStr("networkMenu.summary.requestsCountEmpty"),
+ "The current summary text is incorrect, expected an 'empty' label."
+ );
+ return;
+ }
+
+ const valueTransfer = document.querySelector(
+ ".requests-list-network-summary-transfer"
+ ).textContent;
+ info("Current summary transfer: " + valueTransfer);
+ const expectedTransfer = L10N.getFormatStrWithNumbers(
+ "networkMenu.summary.transferred",
+ getFormattedSize(requestsSummary.contentSize),
+ getFormattedSize(requestsSummary.transferredSize)
+ );
+
+ const valueFinish = document.querySelector(
+ ".requests-list-network-summary-finish"
+ ).textContent;
+ info("Current summary finish: " + valueFinish);
+ const expectedFinish = L10N.getFormatStrWithNumbers(
+ "networkMenu.summary.finish",
+ getFormattedTime(requestsSummary.ms)
+ );
+
+ info(`Computed total bytes: ${requestsSummary.bytes}`);
+ info(`Computed total ms: ${requestsSummary.ms}`);
+
+ is(valueCount, expectedCount, "The current summary count is correct.");
+ is(
+ valueTransfer,
+ expectedTransfer,
+ "The current summary transfer is correct."
+ );
+ is(valueFinish, expectedFinish, "The current summary finish is correct.");
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_frame.js b/devtools/client/netmonitor/test/browser_net_frame.js
new file mode 100644
index 0000000000..4827a8fbc4
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_frame.js
@@ -0,0 +1,272 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests for all expected requests when an iframe is loading a subdocument.
+ */
+
+const TOP_FILE_NAME = "html_frame-test-page.html";
+const SUB_FILE_NAME = "html_frame-subdocument.html";
+const TOP_URL = EXAMPLE_URL + TOP_FILE_NAME;
+const SUB_URL = EXAMPLE_URL + SUB_FILE_NAME;
+
+const EXPECTED_REQUESTS_TOP = [
+ {
+ method: "GET",
+ url: TOP_URL,
+ causeType: "document",
+ causeUri: null,
+ stack: true,
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "stylesheet_request",
+ causeType: "stylesheet",
+ causeUri: TOP_URL,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "img_request",
+ causeType: "img",
+ causeUri: TOP_URL,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "xhr_request",
+ causeType: "xhr",
+ causeUri: TOP_URL,
+ stack: [{ fn: "performXhrRequest", file: TOP_FILE_NAME, line: 25 }],
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "fetch_request",
+ causeType: "fetch",
+ causeUri: TOP_URL,
+ stack: [{ fn: "performFetchRequest", file: TOP_FILE_NAME, line: 29 }],
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "promise_fetch_request",
+ causeType: "fetch",
+ causeUri: TOP_URL,
+ stack: [
+ { fn: "performPromiseFetchRequest", file: TOP_FILE_NAME, line: 41 },
+ {
+ fn: null,
+ file: TOP_FILE_NAME,
+ line: 40,
+ asyncCause: "promise callback",
+ },
+ ],
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "timeout_fetch_request",
+ causeType: "fetch",
+ causeUri: TOP_URL,
+ stack: [
+ { fn: "performTimeoutFetchRequest", file: TOP_FILE_NAME, line: 43 },
+ {
+ fn: "performPromiseFetchRequest",
+ file: TOP_FILE_NAME,
+ line: 42,
+ asyncCause: "setTimeout handler",
+ },
+ ],
+ },
+ {
+ method: "POST",
+ url: EXAMPLE_URL + "beacon_request",
+ causeType: "beacon",
+ causeUri: TOP_URL,
+ stack: [{ fn: "performBeaconRequest", file: TOP_FILE_NAME, line: 33 }],
+ },
+];
+
+const EXPECTED_REQUESTS_SUB = [
+ {
+ method: "GET",
+ url: SUB_URL,
+ causeType: "subdocument",
+ causeUri: TOP_URL,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "stylesheet_request",
+ causeType: "stylesheet",
+ causeUri: SUB_URL,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "img_request",
+ causeType: "img",
+ causeUri: SUB_URL,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "xhr_request",
+ causeType: "xhr",
+ causeUri: SUB_URL,
+ stack: [{ fn: "performXhrRequest", file: SUB_FILE_NAME, line: 24 }],
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "fetch_request",
+ causeType: "fetch",
+ causeUri: SUB_URL,
+ stack: [{ fn: "performFetchRequest", file: SUB_FILE_NAME, line: 28 }],
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "promise_fetch_request",
+ causeType: "fetch",
+ causeUri: SUB_URL,
+ stack: [
+ { fn: "performPromiseFetchRequest", file: SUB_FILE_NAME, line: 40 },
+ {
+ fn: null,
+ file: SUB_FILE_NAME,
+ line: 39,
+ asyncCause: "promise callback",
+ },
+ ],
+ },
+ {
+ method: "GET",
+ url: EXAMPLE_URL + "timeout_fetch_request",
+ causeType: "fetch",
+ causeUri: SUB_URL,
+ stack: [
+ { fn: "performTimeoutFetchRequest", file: SUB_FILE_NAME, line: 42 },
+ {
+ fn: "performPromiseFetchRequest",
+ file: SUB_FILE_NAME,
+ line: 41,
+ asyncCause: "setTimeout handler",
+ },
+ ],
+ },
+ {
+ method: "POST",
+ url: EXAMPLE_URL + "beacon_request",
+ causeType: "beacon",
+ causeUri: SUB_URL,
+ stack: [{ fn: "performBeaconRequest", file: SUB_FILE_NAME, line: 32 }],
+ },
+];
+
+const REQUEST_COUNT =
+ EXPECTED_REQUESTS_TOP.length + EXPECTED_REQUESTS_SUB.length;
+
+add_task(async function () {
+ // the initNetMonitor function clears the network request list after the
+ // page is loaded. That's why we first load a bogus page from SIMPLE_URL,
+ // and only then load the real thing from TOP_URL - we want to catch
+ // all the requests the page is making, not only the XHRs.
+ // We can't use about:blank here, because initNetMonitor checks that the
+ // page has actually made at least one request.
+ const { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+
+ const { document, store, windowRequire, connector } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ await navigateTo(TOP_URL);
+
+ await waitForNetworkEvents(monitor, REQUEST_COUNT);
+
+ is(
+ store.getState().requests.requests.length,
+ REQUEST_COUNT,
+ "All the page events should be recorded."
+ );
+
+ // Fetch stack-trace data from the backend and wait till
+ // all packets are received.
+ const requests = getSortedRequests(store.getState());
+ await Promise.all(
+ requests.map(requestItem =>
+ connector.requestData(requestItem.id, "stackTrace")
+ )
+ );
+
+ // While there is a defined order for requests in each document separately, the requests
+ // from different documents may interleave in various ways that change per test run, so
+ // there is not a single order when considering all the requests together.
+ let currentTop = 0;
+ let currentSub = 0;
+ for (let i = 0; i < REQUEST_COUNT; i++) {
+ const requestItem = getSortedRequests(store.getState())[i];
+
+ const itemUrl = requestItem.url;
+ const itemCauseUri = requestItem.cause.loadingDocumentUri;
+ let spec;
+ if (itemUrl == SUB_URL || itemCauseUri == SUB_URL) {
+ spec = EXPECTED_REQUESTS_SUB[currentSub++];
+ } else {
+ spec = EXPECTED_REQUESTS_TOP[currentTop++];
+ }
+ const { method, url, causeType, causeUri, stack } = spec;
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ method,
+ url,
+ { cause: { type: causeType, loadingDocumentUri: causeUri } }
+ );
+
+ const { stacktrace } = requestItem;
+ const stackLen = stacktrace ? stacktrace.length : 0;
+
+ if (stack) {
+ ok(stacktrace, `Request #${i} has a stacktrace`);
+ ok(
+ stackLen > 0,
+ `Request #${i} (${causeType}) has a stacktrace with ${stackLen} items`
+ );
+
+ // if "stack" is array, check the details about the top stack frames
+ if (Array.isArray(stack)) {
+ stack.forEach((frame, j) => {
+ is(
+ stacktrace[j].functionName,
+ frame.fn,
+ `Request #${i} has the correct function on JS stack frame #${j}`
+ );
+ is(
+ stacktrace[j].filename.split("/").pop(),
+ frame.file,
+ `Request #${i} has the correct file on JS stack frame #${j}`
+ );
+ is(
+ stacktrace[j].lineNumber,
+ frame.line,
+ `Request #${i} has the correct line number on JS stack frame #${j}`
+ );
+ is(
+ stacktrace[j].asyncCause,
+ frame.asyncCause,
+ `Request #${i} has the correct async cause on JS stack frame #${j}`
+ );
+ });
+ }
+ } else {
+ is(stackLen, 0, `Request #${i} (${causeType}) has an empty stacktrace`);
+ }
+ }
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_header-docs.js b/devtools/client/netmonitor/test/browser_net_header-docs.js
new file mode 100644
index 0000000000..bdb6c61693
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_header-docs.js
@@ -0,0 +1,74 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if "Learn More" links are correctly displayed
+ * next to headers.
+ */
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(POST_DATA_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const {
+ getHeadersURL,
+ } = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 2);
+
+ AccessibilityUtils.setEnv({
+ // Keyboard users will will see the sidebar when the request row is
+ // selected. Accessibility is handled on the container level.
+ actionCountRule: false,
+ interactiveRule: false,
+ labelRule: false,
+ });
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ AccessibilityUtils.resetEnv();
+
+ testShowLearnMore(getSortedRequests(store.getState())[0]);
+
+ return teardown(monitor);
+
+ /*
+ * Tests that a "Learn More" button is only shown if
+ * and only if a header is documented in MDN.
+ */
+ function testShowLearnMore(data) {
+ const selector = ".properties-view .treeRow.stringRow";
+ document.querySelectorAll(selector).forEach((rowEl, index) => {
+ const headerName = rowEl.querySelectorAll(".treeLabelCell .treeLabel")[0]
+ .textContent;
+ const headerDocURL = getHeadersURL(headerName);
+ const learnMoreEl = rowEl.querySelectorAll(
+ ".treeValueCell .learn-more-link"
+ );
+
+ if (headerDocURL === null) {
+ ok(
+ learnMoreEl.length === 0,
+ 'undocumented header does not include a "Learn More" button'
+ );
+ } else {
+ ok(
+ learnMoreEl[0].getAttribute("title") === headerDocURL,
+ 'documented header includes a "Learn More" button with a link to MDN'
+ );
+ }
+ });
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_header-ref-policy.js b/devtools/client/netmonitor/test/browser_net_header-ref-policy.js
new file mode 100644
index 0000000000..18e9578bb5
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_header-ref-policy.js
@@ -0,0 +1,62 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if "Referrer Policy" is displayed in the header panel.
+ */
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(POST_RAW_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute request.
+ await performRequests(monitor, tab, 1);
+
+ // Wait until the tab panel summary is displayed
+ const wait = waitUntil(
+ () => document.querySelectorAll(".tabpanel-summary-label")[0]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ const referrerPolicyIndex = 3;
+ const referrerPolicyHeader = document.querySelectorAll(
+ ".tabpanel-summary-label"
+ )[referrerPolicyIndex];
+ const referrerPolicyValue = document.querySelectorAll(
+ ".tabpanel-summary-value"
+ )[referrerPolicyIndex];
+
+ is(
+ referrerPolicyHeader.textContent === "Referrer Policy",
+ true,
+ '"Referrer Policy" header is displayed in the header panel.'
+ );
+
+ const defaultPolicy = Services.prefs.getIntPref(
+ "network.http.referer.defaultPolicy"
+ );
+ const stringMap = {
+ 0: "no-referrer",
+ 1: "same-origin",
+ 2: "strict-origin-when-cross-origin",
+ 3: "no-referrer-when-downgrade",
+ };
+ is(
+ referrerPolicyValue.textContent === stringMap[defaultPolicy],
+ true,
+ "The referrer policy value is reflected correctly."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_header-request-priority.js b/devtools/client/netmonitor/test/browser_net_header-request-priority.js
new file mode 100644
index 0000000000..196116a98d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_header-request-priority.js
@@ -0,0 +1,43 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if "Request Priority" is displayed in the header panel.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(POST_RAW_URL, {
+ requestCount: 1,
+ });
+
+ const { document } = monitor.panelWin;
+
+ const waitReq = waitForNetworkEvents(monitor, 1);
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-reload-notice-button")
+ );
+ await waitReq;
+
+ // Wait until the tab panel summary is displayed
+ const wait = waitUntil(
+ () => document.querySelectorAll(".tabpanel-summary-label")[0]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ const requestPriorityHeaderExists = Array.from(
+ document.querySelectorAll(".tabpanel-summary-label")
+ ).some(header => header.textContent === "Request Priority");
+ is(
+ requestPriorityHeaderExists,
+ true,
+ '"Request Priority" header is displayed in the header panel.'
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_headers-alignment.js b/devtools/client/netmonitor/test/browser_net_headers-alignment.js
new file mode 100644
index 0000000000..b6eaca9308
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_headers-alignment.js
@@ -0,0 +1,65 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Bug 1360457 - Mis-alignment between headers and columns on overflow
+ */
+
+add_task(async function () {
+ requestLongerTimeout(4);
+
+ const { tab, monitor } = await initNetMonitor(INFINITE_GET_URL, {
+ enableCache: true,
+ requestCount: 1,
+ });
+ const { document, windowRequire, store } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait until the first request makes the empty notice disappear
+ await waitForRequestListToAppear();
+
+ const requestsContainerScroll = document.querySelector(
+ ".requests-list-scroll"
+ );
+ ok(requestsContainerScroll, "Container element exists as expected.");
+ const requestsContainer = document.querySelector(".requests-list-row-group");
+ const headers = document.querySelector(".requests-list-headers");
+ ok(headers, "Headers element exists as expected.");
+
+ await waitForRequestsToOverflowContainer(monitor, requestsContainerScroll);
+
+ testColumnsAlignment(headers, requestsContainer);
+
+ // Stop doing requests.
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.stopRequests();
+ });
+
+ // Done: clean up.
+ return teardown(monitor);
+
+ function waitForRequestListToAppear() {
+ info(
+ "Waiting until the empty notice disappears and is replaced with the list"
+ );
+ return waitUntil(
+ () => !!document.querySelector(".requests-list-row-group")
+ );
+ }
+});
+
+async function waitForRequestsToOverflowContainer(monitor, requestList) {
+ info("Waiting for enough requests to overflow the container");
+ while (true) {
+ info("Waiting for one network request");
+ await waitForNetworkEvents(monitor, 1);
+ if (requestList.scrollHeight > requestList.clientHeight + 50) {
+ info("The list is long enough, returning");
+ return;
+ }
+ }
+}
diff --git a/devtools/client/netmonitor/test/browser_net_headers-link_clickable.js b/devtools/client/netmonitor/test/browser_net_headers-link_clickable.js
new file mode 100644
index 0000000000..9f59e7fe12
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_headers-link_clickable.js
@@ -0,0 +1,44 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if links in headers panel are clickable.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(JSON_LONG_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ await performRequests(monitor, tab, 1);
+
+ info("Selecting first request");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ info("Waiting for request and response headers");
+ await waitForRequestData(store, ["requestHeaders", "responseHeaders"]);
+
+ const headerLink = document.querySelector(".objectBox-string .url");
+ const expectedURL =
+ "http://example.com/browser/devtools/client/netmonitor/test/html_json-long-test-page.html";
+ const onTabOpen = BrowserTestUtils.waitForNewTab(gBrowser, expectedURL, true);
+
+ info("Click on a first link in Headers panel");
+ headerLink.click();
+ await onTabOpen;
+
+ ok(onTabOpen, "New tab opened from link");
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_headers-resize.js b/devtools/client/netmonitor/test/browser_net_headers-resize.js
new file mode 100644
index 0000000000..dc1aadb470
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_headers-resize.js
@@ -0,0 +1,279 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests resizing of columns in NetMonitor.
+ */
+add_task(async function () {
+ await testForGivenDir("ltr");
+
+ await testForGivenDir("rtl");
+});
+
+async function testForGivenDir(dir) {
+ if (dir === "rtl") {
+ await pushPref("intl.l10n.pseudo", "bidi");
+ } else {
+ await pushPref("intl.l10n.pseudo", "");
+ }
+
+ // Reset visibleColumns so we only get the default ones
+ // and not all that are set in head.js
+ Services.prefs.clearUserPref("devtools.netmonitor.visibleColumns");
+ const initialColumnData = Services.prefs.getCharPref(
+ "devtools.netmonitor.columnsData"
+ );
+ let visibleColumns = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.visibleColumns")
+ );
+
+ // Init network monitor
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, windowRequire, store } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for network events (to have some requests in the table)
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ const headers = document.querySelector(".requests-list-headers");
+ const parentWidth = headers.getBoundingClientRect().width;
+
+ // 1. Change File column from 25% (default) to 20%
+ // Size column should then change from 5% (default) to 10%
+ // When File width changes, contentSize should compensate the change.
+ info("Resize file & check changed prefs...");
+ const fileHeader = document.querySelector(`#requests-list-file-header-box`);
+
+ resizeColumn(fileHeader, 20, parentWidth, dir);
+
+ // after resize - get fresh prefs for tests
+ let columnsData = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.columnsData")
+ );
+ checkColumnsData(columnsData, "file", 20);
+ checkColumnsData(columnsData, "contentSize", 10);
+ checkSumOfVisibleColumns(columnsData, visibleColumns);
+
+ // 2. Change Waterfall column width and check that the size
+ // of waterfall changed correctly and all the other columns changed size.
+ info("Resize waterfall & check changed prefs...");
+ const waterfallHeader = document.querySelector(
+ `#requests-list-waterfall-header-box`
+ );
+ // before resizing waterfall -> save old columnsData for later testing
+ const oldColumnsData = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.columnsData")
+ );
+ resizeWaterfallColumn(waterfallHeader, 30, parentWidth, dir); // 30 fails currently!
+
+ // after resize - get fresh prefs for tests
+ columnsData = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.columnsData")
+ );
+
+ checkColumnsData(columnsData, "waterfall", 30);
+ checkSumOfVisibleColumns(columnsData, visibleColumns);
+ checkAllColumnsChanged(columnsData, oldColumnsData, visibleColumns);
+
+ // 3. Check that all rows have the right column sizes.
+ info("Checking alignment of columns and headers...");
+ const requestsContainer = document.querySelector(".requests-list-row-group");
+ testColumnsAlignment(headers, requestsContainer);
+
+ // 4. Hide all columns but size and waterfall
+ // and check that they resize correctly. Then resize
+ // waterfall to 50% => size should take up 50%
+ info("Hide all but 2 columns - size & waterfall and check resizing...");
+ await hideMoreColumns(monitor, [
+ "status",
+ "method",
+ "domain",
+ "file",
+ "initiator",
+ "type",
+ "transferred",
+ ]);
+
+ resizeWaterfallColumn(waterfallHeader, 50, parentWidth, dir);
+ // after resize - get fresh prefs for tests
+ columnsData = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.columnsData")
+ );
+ visibleColumns = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.visibleColumns")
+ );
+
+ checkColumnsData(columnsData, "contentSize", 50);
+ checkColumnsData(columnsData, "waterfall", 50);
+ checkSumOfVisibleColumns(columnsData, visibleColumns);
+
+ // 5. Hide all columns but domain and file
+ // and resize domain to 50% => file should be 50%
+ info("Hide all but 2 columns - domain & file and check resizing...");
+ await showMoreColumns(monitor, ["domain", "file"]);
+ await hideMoreColumns(monitor, ["contentSize", "waterfall"]);
+
+ const domainHeader = document.querySelector(
+ `#requests-list-domain-header-box`
+ );
+ resizeColumn(domainHeader, 50, parentWidth, dir);
+
+ // after resize - get fresh prefs for tests
+ columnsData = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.columnsData")
+ );
+
+ visibleColumns = JSON.parse(
+ Services.prefs.getCharPref("devtools.netmonitor.visibleColumns")
+ );
+
+ checkColumnsData(columnsData, "domain", 50);
+ checkColumnsData(columnsData, "file", 50);
+ checkSumOfVisibleColumns(columnsData, visibleColumns);
+
+ // Done: clean up.
+ Services.prefs.setCharPref(
+ "devtools.netmonitor.columnsData",
+ initialColumnData
+ );
+ return teardown(monitor);
+}
+
+async function hideMoreColumns(monitor, arr) {
+ for (let i = 0; i < arr.length; i++) {
+ await hideColumn(monitor, arr[i]);
+ }
+}
+
+async function showMoreColumns(monitor, arr) {
+ for (let i = 0; i < arr.length; i++) {
+ await showColumn(monitor, arr[i]);
+ }
+}
+
+function resizeColumn(columnHeader, newPercent, parentWidth, dir) {
+ const newWidthInPixels = (newPercent * parentWidth) / 100;
+ const win = columnHeader.ownerDocument.defaultView;
+ const currentWidth = columnHeader.getBoundingClientRect().width;
+ const mouseDown = dir === "rtl" ? 0 : currentWidth;
+ const mouseMove =
+ dir === "rtl" ? currentWidth - newWidthInPixels : newWidthInPixels;
+
+ EventUtils.synthesizeMouse(
+ columnHeader,
+ mouseDown,
+ 1,
+ { type: "mousedown" },
+ win
+ );
+ EventUtils.synthesizeMouse(
+ columnHeader,
+ mouseMove,
+ 1,
+ { type: "mousemove" },
+ win
+ );
+ EventUtils.synthesizeMouse(
+ columnHeader,
+ mouseMove,
+ 1,
+ { type: "mouseup" },
+ win
+ );
+}
+
+function resizeWaterfallColumn(columnHeader, newPercent, parentWidth, dir) {
+ const newWidthInPixels = (newPercent * parentWidth) / 100;
+ const win = columnHeader.ownerDocument.defaultView;
+ const mouseDown =
+ dir === "rtl"
+ ? columnHeader.getBoundingClientRect().right
+ : columnHeader.getBoundingClientRect().left;
+ const mouseMove =
+ dir === "rtl"
+ ? mouseDown +
+ (newWidthInPixels - columnHeader.getBoundingClientRect().width)
+ : mouseDown +
+ (columnHeader.getBoundingClientRect().width - newWidthInPixels);
+
+ EventUtils.synthesizeMouse(
+ columnHeader.parentElement,
+ mouseDown,
+ 1,
+ { type: "mousedown" },
+ win
+ );
+ EventUtils.synthesizeMouse(
+ columnHeader.parentElement,
+ mouseMove,
+ 1,
+ { type: "mousemove" },
+ win
+ );
+ EventUtils.synthesizeMouse(
+ columnHeader.parentElement,
+ mouseMove,
+ 1,
+ { type: "mouseup" },
+ win
+ );
+}
+
+function checkColumnsData(columnsData, column, expectedWidth) {
+ const widthInPref = Math.round(getWidthFromPref(columnsData, column));
+ is(widthInPref, expectedWidth, "Column " + column + " has expected size.");
+}
+
+function checkSumOfVisibleColumns(columnsData, visibleColumns) {
+ let sum = 0;
+ visibleColumns.forEach(column => {
+ sum += getWidthFromPref(columnsData, column);
+ });
+ sum = Math.round(sum);
+ is(sum, 100, "All visible columns cover 100%.");
+}
+
+function getWidthFromPref(columnsData, column) {
+ const widthInPref = columnsData.find(function (element) {
+ return element.name === column;
+ }).width;
+ return widthInPref;
+}
+
+function checkAllColumnsChanged(columnsData, oldColumnsData, visibleColumns) {
+ const oldWaterfallWidth = getWidthFromPref(oldColumnsData, "waterfall");
+ const newWaterfallWidth = getWidthFromPref(columnsData, "waterfall");
+ visibleColumns.forEach(column => {
+ // do not test waterfall against waterfall
+ if (column !== "waterfall") {
+ const oldWidth = getWidthFromPref(oldColumnsData, column);
+ const newWidth = getWidthFromPref(columnsData, column);
+
+ // Test that if waterfall is smaller all other columns are bigger
+ if (oldWaterfallWidth > newWaterfallWidth) {
+ is(
+ oldWidth < newWidth,
+ true,
+ "Column " + column + " has changed width correctly."
+ );
+ }
+ // Test that if waterfall is bigger all other columns are smaller
+ if (oldWaterfallWidth < newWaterfallWidth) {
+ is(
+ oldWidth > newWidth,
+ true,
+ "Column " + column + " has changed width correctly."
+ );
+ }
+ }
+ });
+}
diff --git a/devtools/client/netmonitor/test/browser_net_headers_filter.js b/devtools/client/netmonitor/test/browser_net_headers_filter.js
new file mode 100644
index 0000000000..6256adb08d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_headers_filter.js
@@ -0,0 +1,80 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if Request-Headers and Response-Headers are correctly filtered in Headers tab.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_SJS, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ let wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ wait = waitUntil(() => document.querySelector(".headers-overview"));
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ await waitForRequestData(store, ["requestHeaders", "responseHeaders"]);
+
+ document.querySelectorAll(".devtools-filterinput")[1].focus();
+ EventUtils.synthesizeKey("con", {});
+ await waitUntil(() => document.querySelector(".treeRow.hidden"));
+
+ info("Check if Headers are filtered correctly");
+
+ const expectedResponseHeaders = [
+ "cache-control",
+ "connection",
+ "content-length",
+ "content-type",
+ ];
+ const expectedRequestHeaders = ["Cache-Control", "Connection"];
+
+ const responseLabelCells = document.querySelectorAll(
+ "#responseHeaders .treeLabelCell"
+ );
+ const requestLabelCells = document.querySelectorAll(
+ "#requestHeaders .treeLabelCell"
+ );
+ const filteredResponseHeaders = [];
+ const filteredRequestHeaders = [];
+
+ for (let i = 0; i < responseLabelCells.length; i++) {
+ if (responseLabelCells[i].offsetHeight > 0) {
+ filteredResponseHeaders.push(responseLabelCells[i].innerText);
+ }
+ }
+
+ for (let i = 0; i < requestLabelCells.length; i++) {
+ if (requestLabelCells[i].offsetHeight > 0) {
+ filteredRequestHeaders.push(requestLabelCells[i].innerText);
+ }
+ }
+
+ is(
+ filteredResponseHeaders.toString(),
+ expectedResponseHeaders.toString(),
+ "Response Headers are filtered"
+ );
+ is(
+ filteredRequestHeaders.toString(),
+ expectedRequestHeaders.toString(),
+ "Request Headers are filtered"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_headers_sorted.js b/devtools/client/netmonitor/test/browser_net_headers_sorted.js
new file mode 100644
index 0000000000..2965ea8d3c
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_headers_sorted.js
@@ -0,0 +1,194 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if Request-Headers and Response-Headers are sorted in Headers tab.
+ * The test also verifies that headers with the same name and headers
+ * with an empty value are also displayed.
+ *
+ * The test also checks that raw headers are displayed in the original
+ * order and not sorted.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_SJS, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ // Verify request and response headers.
+ await verifyHeaders(monitor);
+ await verifyRawHeaders(monitor);
+
+ // Clean up
+ await teardown(monitor);
+});
+
+async function verifyHeaders(monitor) {
+ const { document, store } = monitor.panelWin;
+
+ info("Check if Request-Headers and Response-Headers are sorted");
+
+ const wait = waitForDOM(document, ".headers-overview");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ await waitForRequestData(store, ["requestHeaders", "responseHeaders"]);
+
+ const expectedResponseHeaders = [
+ "cache-control",
+ "connection",
+ "content-length",
+ "content-type",
+ "date",
+ "expires",
+ "foo-bar",
+ "foo-bar",
+ "foo-bar",
+ "pragma",
+ "server",
+ "set-cookie",
+ "set-cookie",
+ ];
+ const expectedRequestHeaders = [
+ "Accept",
+ "Accept-Encoding",
+ "Accept-Language",
+ "Cache-Control",
+ "Connection",
+ "Cookie",
+ "Host",
+ "Pragma",
+ "Sec-Fetch-Dest",
+ "Sec-Fetch-Mode",
+ "Sec-Fetch-Site",
+ "Upgrade-Insecure-Requests",
+ "User-Agent",
+ ];
+
+ const responseLabelCells = document.querySelectorAll(
+ "#responseHeaders .treeLabelCell"
+ );
+ const requestLabelCells = document.querySelectorAll(
+ "#requestHeaders .treeLabelCell"
+ );
+ const actualResponseHeaders = [];
+ const actualRequestHeaders = [];
+
+ for (let i = 0; i < responseLabelCells.length; i++) {
+ actualResponseHeaders.push(responseLabelCells[i].innerText);
+ }
+
+ for (let i = 0; i < requestLabelCells.length; i++) {
+ actualRequestHeaders.push(requestLabelCells[i].innerText);
+ }
+
+ is(
+ actualResponseHeaders.toString(),
+ expectedResponseHeaders.toString(),
+ "Response Headers are sorted"
+ );
+
+ is(
+ actualRequestHeaders.toString(),
+ expectedRequestHeaders.toString(),
+ "Request Headers are sorted"
+ );
+}
+
+async function verifyRawHeaders(monitor) {
+ const { document } = monitor.panelWin;
+
+ info("Check if raw Request-Headers and raw Response-Headers are not sorted");
+
+ const actualResponseHeaders = [];
+ const actualRequestHeaders = [];
+
+ const expectedResponseHeaders = [
+ "cache-control",
+ "pragma",
+ "expires",
+ "set-cookie",
+ "set-cookie",
+ "content-type",
+ "foo-bar",
+ "foo-bar",
+ "foo-bar",
+ "connection",
+ "server",
+ "date",
+ "content-length",
+ ];
+
+ const expectedRequestHeaders = [
+ "Host",
+ "User-Agent",
+ "Accept",
+ "Accept-Language",
+ "Accept-Encoding",
+ "Connection",
+ "Cookie",
+ "Upgrade-Insecure-Requests",
+ "Sec-Fetch-Dest",
+ "Sec-Fetch-Mode",
+ "Sec-Fetch-Site",
+ "Pragma",
+ "Cache-Control",
+ ];
+
+ // Click the 'Raw headers' toggle to show original headers source.
+ for (const rawToggleInput of document.querySelectorAll(
+ ".devtools-checkbox-toggle"
+ )) {
+ rawToggleInput.click();
+ }
+
+ // Wait till raw headers are available.
+ let rawArr;
+ await waitUntil(() => {
+ rawArr = document.querySelectorAll("textarea.raw-headers");
+ // Both raw headers must be present
+ return rawArr.length > 1;
+ });
+
+ // Request headers are rendered first, so it is element with index 1
+ const requestHeadersText = rawArr[1].textContent;
+ // Response headers are rendered first, so it is element with index 0
+ const responseHeadersText = rawArr[0].textContent;
+
+ const rawRequestHeadersArray = requestHeadersText.split("\n");
+ for (let i = 1; i < rawRequestHeadersArray.length; i++) {
+ const header = rawRequestHeadersArray[i];
+ actualRequestHeaders.push(header.split(":")[0]);
+ }
+
+ const rawResponseHeadersArray = responseHeadersText.split("\n");
+ for (let i = 1; i < rawResponseHeadersArray.length; i++) {
+ const header = rawResponseHeadersArray[i];
+ actualResponseHeaders.push(header.split(":")[0]);
+ }
+
+ is(
+ actualResponseHeaders.toString(),
+ expectedResponseHeaders.toString(),
+ "Raw Response Headers are not sorted"
+ );
+
+ is(
+ actualRequestHeaders.toString(),
+ expectedRequestHeaders.toString(),
+ "Raw Request Headers are not sorted"
+ );
+}
diff --git a/devtools/client/netmonitor/test/browser_net_html-preview.js b/devtools/client/netmonitor/test/browser_net_html-preview.js
new file mode 100644
index 0000000000..873c712105
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_html-preview.js
@@ -0,0 +1,176 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if different response content types are handled correctly.
+ */
+
+const httpServer = createTestHTTPServer();
+httpServer.registerContentType("html", "text/html");
+
+const BASE_URL = `http://localhost:${httpServer.identity.primaryPort}/`;
+
+const REDIRECT_URL = BASE_URL + "redirect.html";
+
+// In all content previewed as HTML we ensure using proper html, head and body in order to
+// prevent having them added by the <browser> when loaded as a preview.
+function addBaseHtmlElements(body) {
+ return `<html><head></head><body>${body}</body></html>`;
+}
+
+// This first page asserts we can redirect to another URL, even if JS happen to be executed
+const FETCH_CONTENT_1 = addBaseHtmlElements(
+ `Fetch 1<script>window.parent.location.href = "${REDIRECT_URL}";</script>`
+);
+// This second page asserts that JS is disabled
+const FETCH_CONTENT_2 = addBaseHtmlElements(
+ `Fetch 2<script>document.write("JS activated")</script>`
+);
+// This third page asserts that links and forms are disabled
+const FETCH_CONTENT_3 = addBaseHtmlElements(
+ `Fetch 3<a href="${REDIRECT_URL}">link</a> -- <form action="${REDIRECT_URL}"><input type="submit"></form>`
+);
+// This fourth page asserts responses with line breaks
+const FETCH_CONTENT_4 = addBaseHtmlElements(`
+ <a href="#" id="link1">link1</a>
+ <a href="#" id="link2">link2</a>
+`);
+
+// Use fetch in order to prevent actually running this code in the test page
+const TEST_HTML = addBaseHtmlElements(`<div id="to-copy">HTML</div><script>
+ fetch("${BASE_URL}fetch-1.html");
+ fetch("${BASE_URL}fetch-2.html");
+ fetch("${BASE_URL}fetch-3.html");
+ fetch("${BASE_URL}fetch-4.html");
+</script>`);
+const TEST_URL = BASE_URL + "doc-html-preview.html";
+
+httpServer.registerPathHandler(
+ "/doc-html-preview.html",
+ (request, response) => {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.write(TEST_HTML);
+ }
+);
+httpServer.registerPathHandler("/fetch-1.html", (request, response) => {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.write(FETCH_CONTENT_1);
+});
+httpServer.registerPathHandler("/fetch-2.html", (request, response) => {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.write(FETCH_CONTENT_2);
+});
+httpServer.registerPathHandler("/fetch-3.html", (request, response) => {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.write(FETCH_CONTENT_3);
+});
+httpServer.registerPathHandler("/fetch-4.html", (request, response) => {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.write(FETCH_CONTENT_4);
+});
+httpServer.registerPathHandler("/redirect.html", (request, response) => {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.write("Redirected!");
+});
+
+add_task(async function () {
+ // Enable async events so that clicks on preview iframe's links are correctly
+ // going through the parent process which is meant to cancel any mousedown.
+ await pushPref("test.events.async.enabled", true);
+
+ const { monitor } = await initNetMonitor(TEST_URL, { requestCount: 3 });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const onNetworkEvent = waitForNetworkEvents(monitor, 3);
+ await reloadBrowser();
+ await onNetworkEvent;
+
+ // The new lines are stripped when using outerHTML to retrieve HTML content of the preview iframe
+ await selectIndexAndWaitForHtmlView(0, TEST_HTML);
+ await selectIndexAndWaitForHtmlView(1, FETCH_CONTENT_1);
+ await selectIndexAndWaitForHtmlView(2, FETCH_CONTENT_2);
+ await selectIndexAndWaitForHtmlView(3, FETCH_CONTENT_3);
+ await selectIndexAndWaitForHtmlView(4, FETCH_CONTENT_4);
+
+ await teardown(monitor);
+
+ async function selectIndexAndWaitForHtmlView(index, expectedHtmlPreview) {
+ info(`Select the request #${index}`);
+ const onResponseContent = monitor.panelWin.api.once(
+ TEST_EVENTS.RECEIVED_RESPONSE_CONTENT
+ );
+ store.dispatch(Actions.selectRequestByIndex(index));
+
+ info("Open the Response tab");
+ document.querySelector("#response-tab").click();
+
+ const [iframe] = await waitForDOM(
+ document,
+ "#response-panel .html-preview iframe"
+ );
+
+ // <xul:iframe type=content remote=true> don't emit "load" event.
+ // And SpecialPowsers.spawn throws if kept running during a page load.
+ // So poll for the end of the iframe load...
+ await waitFor(async () => {
+ // Note that if spawn executes early, the iframe may not yet be loading
+ // and would throw for the reason mentioned in previous comment.
+ try {
+ const rv = await SpecialPowers.spawn(iframe.browsingContext, [], () => {
+ return content.document.readyState == "complete";
+ });
+ return rv;
+ } catch (e) {
+ return false;
+ }
+ });
+
+ info("Wait for response content to be loaded");
+ await onResponseContent;
+
+ is(
+ iframe.browsingContext.currentWindowGlobal.isInProcess,
+ false,
+ "The preview is loaded in a content process"
+ );
+
+ await SpecialPowers.spawn(
+ iframe.browsingContext,
+ [expectedHtmlPreview],
+ async function (expectedHtml) {
+ is(
+ content.document.documentElement.outerHTML,
+ expectedHtml,
+ "The text shown in the iframe is incorrect for the html request."
+ );
+ }
+ );
+
+ // Only assert copy to clipboard on the first test page
+ if (expectedHtmlPreview == TEST_HTML) {
+ await waitForClipboardPromise(async function () {
+ await SpecialPowers.spawn(
+ iframe.browsingContext,
+ [],
+ async function () {
+ const elt = content.document.getElementById("to-copy");
+ EventUtils.synthesizeMouseAtCenter(elt, { clickCount: 2 }, content);
+ await new Promise(r =>
+ elt.addEventListener("dblclick", r, { once: true })
+ );
+ EventUtils.synthesizeKey("c", { accelKey: true }, content);
+ }
+ );
+ }, "HTML");
+ }
+
+ return iframe;
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_http3_request_details.js b/devtools/client/netmonitor/test/browser_net_http3_request_details.js
new file mode 100644
index 0000000000..8ec7aa1b03
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_http3_request_details.js
@@ -0,0 +1,153 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests request details with HTTP/3
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_SJS, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ const waitForHeaders = waitForDOM(document, ".headers-overview");
+ store.dispatch(Actions.toggleNetworkDetails());
+ await waitForHeaders;
+
+ info("Assert the content of the headers");
+
+ const tabpanel = document.querySelector("#headers-panel");
+ // Request URL
+ is(
+ tabpanel.querySelector(".url-preview .url").innerText,
+ HTTPS_SIMPLE_SJS,
+ "The url summary value is incorrect."
+ );
+
+ // Request method
+ is(
+ tabpanel.querySelectorAll(".treeLabel")[0].innerText,
+ "GET",
+ "The method summary value is incorrect."
+ );
+ // Status code
+ is(
+ tabpanel.querySelector(".requests-list-status-code").innerText,
+ "200",
+ "The status summary code is incorrect."
+ );
+ is(
+ tabpanel.querySelector(".status").childNodes[1].textContent,
+ "OK",
+ "The status summary value is incorrect."
+ );
+ // Version
+ is(
+ tabpanel.querySelectorAll(".tabpanel-summary-value")[1].innerText,
+ "HTTP/3",
+ "The HTTP version is incorrect."
+ );
+
+ await waitForRequestData(store, ["requestHeaders", "responseHeaders"]);
+
+ is(
+ tabpanel.querySelectorAll(".accordion-item").length,
+ 2,
+ "There should be 2 header scopes displayed in this tabpanel."
+ );
+
+ const headers = [...tabpanel.querySelectorAll(".accordion .treeLabelCell")];
+
+ is(
+ // The Text-Encoding header is not consistently displayed, exclude it from
+ // the assertion. See Bug 1830053.
+ headers.filter(cell => cell.textContent != "TE").length,
+ 25,
+ "There should be 25 header values displayed in this tabpanel."
+ );
+
+ const headersTable = tabpanel.querySelector(".accordion");
+ const responseHeaders = headersTable.querySelectorAll(
+ "tr[id^='/Response Headers']"
+ );
+
+ const expectedHeaders = [
+ {
+ name: "cache-control",
+ value: "no-cache, no-store, must-revalidate",
+ index: 0,
+ },
+ {
+ name: "content-length",
+ value: "12",
+ index: 1,
+ },
+ {
+ name: "content-type",
+ value: "text/plain; charset=utf-8",
+ index: 2,
+ },
+ {
+ name: "foo-bar",
+ value: "baz",
+ index: 6,
+ },
+ ];
+ expectedHeaders.forEach(header => {
+ is(
+ responseHeaders[header.index].querySelector(".treeLabel").innerHTML,
+ header.name,
+ `The response header at index ${header.index} name was incorrect.`
+ );
+ is(
+ responseHeaders[header.index].querySelector(".objectBox").innerHTML,
+ `${header.value}`,
+ `The response header at index ${header.index} value was incorrect.`
+ );
+ });
+
+ info("Assert the content of the raw headers");
+
+ // Click the 'Raw headers' toggle to show original headers source.
+ document.querySelector("#raw-request-checkbox").click();
+ document.querySelector("#raw-response-checkbox").click();
+
+ let rawHeadersElements;
+ await waitUntil(() => {
+ rawHeadersElements = document.querySelectorAll("textarea.raw-headers");
+ // Both raw headers must be present
+ return rawHeadersElements.length > 1;
+ });
+ const requestHeadersText = rawHeadersElements[1].textContent;
+ const rawRequestHeaderFirstLine = requestHeadersText.split(/\r\n|\n|\r/)[0];
+ is(
+ rawRequestHeaderFirstLine,
+ "GET /browser/devtools/client/netmonitor/test/sjs_simple-test-server.sjs HTTP/3"
+ );
+
+ const responseHeadersText = rawHeadersElements[0].textContent;
+ const rawResponseHeaderFirstLine = responseHeadersText.split(/\r\n|\n|\r/)[0];
+ is(rawResponseHeaderFirstLine, "HTTP/3 200 OK");
+
+ info("Assert the content of the protocol column");
+ const target = document.querySelectorAll(".request-list-item")[0];
+ is(
+ target.querySelector(".requests-list-protocol").textContent,
+ "HTTP/3",
+ "The displayed protocol is correct."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_image-tooltip.js b/devtools/client/netmonitor/test/browser_net_image-tooltip.js
new file mode 100644
index 0000000000..c0b08708e8
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_image-tooltip.js
@@ -0,0 +1,117 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const IMAGE_TOOLTIP_URL = EXAMPLE_URL + "html_image-tooltip-test-page.html";
+const IMAGE_TOOLTIP_REQUESTS = 1;
+
+/**
+ * Tests if image responses show a popup in the requests menu when hovered.
+ */
+add_task(async function test() {
+ const { tab, monitor } = await initNetMonitor(IMAGE_TOOLTIP_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire, connector } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { triggerActivity } = connector;
+ const { ACTIVITY_TYPE } = windowRequire(
+ "devtools/client/netmonitor/src/constants"
+ );
+ const toolboxDoc = monitor.panelWin.parent.document;
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, IMAGE_TOOLTIP_REQUESTS);
+
+ info("Checking the image thumbnail after a few requests were made...");
+ await showTooltipAndVerify(
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ // Hide tooltip before next test, to avoid the situation that tooltip covers
+ // the icon for the request of the next test.
+ info("Checking the image thumbnail gets hidden...");
+ await hideTooltipAndVerify(
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ // +1 extra document reload
+ const onEvents = waitForNetworkEvents(monitor, IMAGE_TOOLTIP_REQUESTS + 1);
+
+ info("Reloading the debuggee and performing all requests again...");
+ await triggerActivity(ACTIVITY_TYPE.RELOAD.WITH_CACHE_ENABLED);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.performRequests();
+ });
+ await onEvents;
+
+ info("Checking the image thumbnail after a reload.");
+ await showTooltipAndVerify(
+ document.querySelectorAll(".request-list-item")[1]
+ );
+
+ info(
+ "Checking if the image thumbnail is hidden when mouse leaves the menu widget"
+ );
+ const requestsListContents = document.querySelector(
+ ".requests-list-row-group"
+ );
+ EventUtils.synthesizeMouse(
+ requestsListContents,
+ 0,
+ 0,
+ { type: "mousemove" },
+ monitor.panelWin
+ );
+ await waitUntil(
+ () => !toolboxDoc.querySelector(".tooltip-container.tooltip-visible")
+ );
+
+ await teardown(monitor);
+
+ /**
+ * Show a tooltip on the {target} and verify that it was displayed
+ * with the expected content.
+ */
+ async function showTooltipAndVerify(target) {
+ const anchor = target.querySelector(".requests-list-file");
+ await showTooltipOn(anchor);
+
+ info("Tooltip was successfully opened for the image request.");
+ is(
+ toolboxDoc.querySelector(".tooltip-panel img").src,
+ TEST_IMAGE_DATA_URI,
+ "The tooltip's image content is displayed correctly."
+ );
+ }
+
+ /**
+ * Trigger a tooltip over an element by sending mousemove event.
+ * @return a promise that resolves when the tooltip is shown
+ */
+ async function showTooltipOn(element) {
+ const win = element.ownerDocument.defaultView;
+ EventUtils.synthesizeMouseAtCenter(element, { type: "mousemove" }, win);
+ await waitUntil(() => toolboxDoc.querySelector(".tooltip-panel img"));
+ }
+
+ /**
+ * Hide a tooltip on the {target} and verify that it was closed.
+ */
+ async function hideTooltipAndVerify(target) {
+ // Hovering over the "method" column hides the tooltip.
+ const anchor = target.querySelector(".requests-list-method");
+ const win = anchor.ownerDocument.defaultView;
+ EventUtils.synthesizeMouseAtCenter(anchor, { type: "mousemove" }, win);
+
+ await waitUntil(
+ () => !toolboxDoc.querySelector(".tooltip-container.tooltip-visible")
+ );
+ info("Tooltip was successfully closed.");
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_image_cache.js b/devtools/client/netmonitor/test/browser_net_image_cache.js
new file mode 100644
index 0000000000..4720ef70f0
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_image_cache.js
@@ -0,0 +1,76 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests image caches can be displayed in the network monitor
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(IMAGE_CACHE_URL, {
+ enableCache: true,
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const waitForEvents = waitForNetworkEvents(monitor, 2, {
+ expectedEventTimings: 0,
+ expectedPayloadReady: 1,
+ });
+
+ // Using `BrowserTestUtils.loadURI` instead of `navigateTo` because
+ // `navigateTo` would use `gBrowser.reloadTab` to reload the tab
+ // when the current uri is the same as the one that is going to navigate.
+ // And the issue is that with `gBrowser.reloadTab`, `VALIDATE_ALWAYS`
+ // flag will be applied to the loadgroup, such that the sub resources
+ // are forced to be revalidated. So we use `BrowserTestUtils.loadURI` to
+ // avoid having `VALIDATE_ALWAYS` applied.
+ BrowserTestUtils.loadURIString(gBrowser.selectedBrowser, IMAGE_CACHE_URL);
+ await waitForEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+
+ // Though there are 3 test-image.png images on the page, only 1 request
+ // representing the images from the cache should be shown. Therefore we
+ // expect 2 requests all together (1 for html_image-cache.html and 1 for
+ // test-image.png)
+ is(requests.length, 2, "There should be 2 requests");
+
+ const requestData = {
+ uri: HTTPS_EXAMPLE_URL + "test-image.png",
+ details: {
+ status: 200,
+ statusText: "OK (cached)",
+ displayedStatus: "cached",
+ type: "png",
+ fullMimeType: "image/png",
+ },
+ };
+
+ for (let i = 1; i < requests.length; ++i) {
+ const request = requests[i];
+
+ // mouseover is needed for tooltips to show up.
+ const requestsListStatus = request.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+
+ await verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[i],
+ "GET",
+ requestData.uri,
+ requestData.details
+ );
+ }
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_initiator.js b/devtools/client/netmonitor/test/browser_net_initiator.js
new file mode 100644
index 0000000000..4082db6fa2
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_initiator.js
@@ -0,0 +1,291 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+const {
+ getUrlBaseName,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+/**
+ * Tests if request initiator is reported correctly.
+ */
+
+const INITIATOR_FILE_NAME = "html_cause-test-page.html";
+const INITIATOR_URL = HTTPS_EXAMPLE_URL + INITIATOR_FILE_NAME;
+
+const EXPECTED_REQUESTS = [
+ {
+ method: "GET",
+ url: INITIATOR_URL,
+ causeType: "document",
+ causeUri: null,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "stylesheet_request",
+ causeType: "stylesheet",
+ causeUri: INITIATOR_URL,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "img_request",
+ causeType: "img",
+ causeUri: INITIATOR_URL,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "img_srcset_request",
+ causeType: "imageset",
+ causeUri: INITIATOR_URL,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "xhr_request",
+ causeType: "xhr",
+ causeUri: INITIATOR_URL,
+ stack: [{ fn: "performXhrRequestCallback", file: INITIATOR_URL, line: 32 }],
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "fetch_request",
+ causeType: "fetch",
+ causeUri: INITIATOR_URL,
+ stack: [{ fn: "performFetchRequest", file: INITIATOR_URL, line: 37 }],
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "promise_fetch_request",
+ causeType: "fetch",
+ causeUri: INITIATOR_URL,
+ stack: [
+ {
+ fn: "performPromiseFetchRequestCallback",
+ file: INITIATOR_URL,
+ line: 43,
+ },
+ {
+ fn: "performPromiseFetchRequest",
+ file: INITIATOR_URL,
+ line: 42,
+ asyncCause: "promise callback",
+ },
+ ],
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "timeout_fetch_request",
+ causeType: "fetch",
+ causeUri: INITIATOR_URL,
+ stack: [
+ {
+ fn: "performTimeoutFetchRequestCallback2",
+ file: INITIATOR_URL,
+ line: 50,
+ },
+ {
+ fn: "performTimeoutFetchRequestCallback1",
+ file: INITIATOR_URL,
+ line: 49,
+ asyncCause: "setTimeout handler",
+ },
+ ],
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "favicon_request",
+ causeType: "img",
+ causeUri: INITIATOR_URL,
+ // the favicon request is triggered in FaviconLoader.jsm module, it should
+ // NOT be shown in the stack (bug 1280266). For now we intentionally
+ // specify the file and the line number to be properly sorted.
+ // NOTE: The line number can be an arbitrary number greater than 0.
+ stack: [
+ {
+ file: "resource:///modules/FaviconLoader.jsm",
+ line: Number.MAX_SAFE_INTEGER,
+ },
+ ],
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "lazy_img_request",
+ causeType: "lazy-img",
+ causeUri: INITIATOR_URL,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "lazy_img_srcset_request",
+ causeType: "lazy-imageset",
+ causeUri: INITIATOR_URL,
+ stack: false,
+ },
+ {
+ method: "POST",
+ url: HTTPS_EXAMPLE_URL + "beacon_request",
+ causeType: "beacon",
+ causeUri: INITIATOR_URL,
+ stack: [{ fn: "performBeaconRequest", file: INITIATOR_URL, line: 82 }],
+ },
+];
+
+add_task(async function () {
+ // the initNetMonitor function clears the network request list after the
+ // page is loaded. That's why we first load a bogus page from SIMPLE_URL,
+ // and only then load the real thing from INITIATOR_URL - we want to catch
+ // all the requests the page is making, not only the XHRs.
+ // We can't use about:blank here, because initNetMonitor checks that the
+ // page has actually made at least one request.
+ const { tab, monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, EXPECTED_REQUESTS.length);
+ BrowserTestUtils.loadURIString(tab.linkedBrowser, INITIATOR_URL);
+
+ registerFaviconNotifier(tab.linkedBrowser);
+
+ await wait;
+
+ // For all expected requests
+ for (const [index, { stack }] of EXPECTED_REQUESTS.entries()) {
+ if (!stack) {
+ continue;
+ }
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(
+ ".request-list-item .requests-list-initiator-lastframe"
+ )[index]
+ );
+
+ // Clicking on the initiator column should open the Stack Trace panel
+ const onStackTraceRendered = waitUntil(() =>
+ document.querySelector("#stack-trace-panel .stack-trace .frame-link")
+ );
+ await onStackTraceRendered;
+ }
+
+ is(
+ store.getState().requests.requests.length,
+ EXPECTED_REQUESTS.length,
+ "All the page events should be recorded."
+ );
+
+ validateRequests(EXPECTED_REQUESTS, monitor);
+
+ // Sort the requests by initiator and check the order
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-initiator-button")
+ );
+
+ const expectedOrder = EXPECTED_REQUESTS.sort(initiatorSortPredicate).map(
+ r => {
+ let isChromeFrames = false;
+ const lastFrameExists = !!r.stack;
+ let initiator = "";
+ let lineNumber = "";
+ if (lastFrameExists) {
+ const { file, line: _lineNumber } = r.stack[0];
+ initiator = getUrlBaseName(file);
+ lineNumber = ":" + _lineNumber;
+ isChromeFrames = file.startsWith("resource:///");
+ }
+ const causeStr = lastFrameExists ? " (" + r.causeType + ")" : r.causeType;
+ return {
+ initiatorStr: initiator + lineNumber + causeStr,
+ isChromeFrames,
+ };
+ }
+ );
+
+ expectedOrder.forEach((expectedInitiator, i) => {
+ const request = getSortedRequests(store.getState())[i];
+ let initiator;
+ // In cases of chrome frames, we shouldn't have stack.
+ if (
+ request.cause.stacktraceAvailable &&
+ !expectedInitiator.isChromeFrames
+ ) {
+ const { filename, lineNumber } = request.cause.lastFrame;
+ initiator =
+ getUrlBaseName(filename) +
+ ":" +
+ lineNumber +
+ " (" +
+ request.cause.type +
+ ")";
+ } else {
+ initiator = request.cause.type;
+ }
+
+ if (expectedInitiator.isChromeFrames) {
+ todo_is(
+ initiator,
+ expectedInitiator.initiatorStr,
+ `The request #${i} has the expected initiator after sorting`
+ );
+ } else {
+ is(
+ initiator,
+ expectedInitiator.initiatorStr,
+ `The request #${i} has the expected initiator after sorting`
+ );
+ }
+ });
+
+ await teardown(monitor);
+});
+
+// derived from devtools/client/netmonitor/src/utils/sort-predicates.js
+function initiatorSortPredicate(first, second) {
+ const firstLastFrame = first.stack ? first.stack[0] : null;
+ const secondLastFrame = second.stack ? second.stack[0] : null;
+
+ let firstInitiator = "";
+ let firstInitiatorLineNumber = 0;
+
+ if (firstLastFrame) {
+ firstInitiator = getUrlBaseName(firstLastFrame.file);
+ firstInitiatorLineNumber = firstLastFrame.line;
+ }
+
+ let secondInitiator = "";
+ let secondInitiatorLineNumber = 0;
+
+ if (secondLastFrame) {
+ secondInitiator = getUrlBaseName(secondLastFrame.file);
+ secondInitiatorLineNumber = secondLastFrame.line;
+ }
+
+ let result;
+ // if both initiators don't have a stack trace, compare their causes
+ if (!firstInitiator && !secondInitiator) {
+ result = compareValues(first.causeType, second.causeType);
+ } else if (!firstInitiator || !secondInitiator) {
+ // if one initiator doesn't have a stack trace but the other does, former should precede the latter
+ result = compareValues(firstInitiatorLineNumber, secondInitiatorLineNumber);
+ } else {
+ result = compareValues(firstInitiator, secondInitiator);
+ if (result === 0) {
+ result = compareValues(
+ firstInitiatorLineNumber,
+ secondInitiatorLineNumber
+ );
+ }
+ }
+ return result;
+}
diff --git a/devtools/client/netmonitor/test/browser_net_internal-stylesheet.js b/devtools/client/netmonitor/test/browser_net_internal-stylesheet.js
new file mode 100644
index 0000000000..098f2803aa
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_internal-stylesheet.js
@@ -0,0 +1,37 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_URL = EXAMPLE_URL + "html_internal-stylesheet.html";
+
+/**
+ * Test for the stylesheet which is loaded as internal.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(TEST_URL, {
+ requestCount: 2,
+ });
+
+ const wait = waitForNetworkEvents(monitor, 2);
+ await reloadBrowser();
+ await wait;
+
+ const { store } = monitor.panelWin;
+ const requests = store.getState().requests.requests;
+ is(
+ requests.length,
+ 2,
+ "The number of requests state in the store is correct"
+ );
+
+ const styleSheetRequest = requests.find(
+ r => r.urlDetails.baseNameWithQuery === "internal-loaded.css"
+ );
+ ok(
+ styleSheetRequest,
+ "The stylesheet which is loaded as internal is in the request"
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_json-b64.js b/devtools/client/netmonitor/test/browser_net_json-b64.js
new file mode 100644
index 0000000000..82679d15ef
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_json-b64.js
@@ -0,0 +1,103 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if JSON responses encoded in base64 are handled correctly.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+ const { tab, monitor } = await initNetMonitor(JSON_B64_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ let wait = waitForDOM(document, "#response-panel .data-header");
+ const waitForPropsView = waitForDOM(
+ document,
+ "#response-panel .properties-view",
+ 1
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ clickOnSidebarTab(document, "response");
+
+ await Promise.all([wait, waitForPropsView]);
+
+ const tabpanel = document.querySelector("#response-panel");
+ is(
+ tabpanel.querySelectorAll(".treeRow").length,
+ 1,
+ "There should be 1 json properties displayed in this tabpanel."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ is(
+ labels[0].textContent,
+ "greeting",
+ "The first json property name was incorrect."
+ );
+ is(
+ values[0].textContent,
+ `"This is a base 64 string."`,
+ "The first json property value was incorrect."
+ );
+
+ // Open the response payload section, it should hide the json section
+ wait = waitForDOM(document, "#response-panel .CodeMirror-code");
+ const header = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(header, monitor);
+ await wait;
+
+ is(
+ tabpanel.querySelector(".response-error-header") === null,
+ true,
+ "The response error header doesn't have the intended visibility."
+ );
+ const jsonView = tabpanel.querySelector(".data-label") || {};
+ is(
+ jsonView.textContent === L10N.getStr("jsonScopeName"),
+ true,
+ "The response json view has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".raw-data-toggle-input .devtools-checkbox-toggle")
+ .checked,
+ true,
+ "The raw response toggle should be on."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ false,
+ "The response editor has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".response-image-box") === null,
+ true,
+ "The response image box doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_json-empty.js b/devtools/client/netmonitor/test/browser_net_json-empty.js
new file mode 100644
index 0000000000..0179a97d49
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_json-empty.js
@@ -0,0 +1,79 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if empty JSON responses are properly displayed.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ JSON_EMPTY_URL + "?name=empty",
+ { requestCount: 1 }
+ );
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { L10N } = windowRequire("devtools/client/netmonitor/src/utils/l10n");
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ const onResponsePanelReady = waitForDOM(
+ document,
+ "#response-panel .data-header"
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+
+ await onResponsePanelReady;
+
+ const codeMirrorReady = waitForDOM(
+ document,
+ "#response-panel .CodeMirror-code"
+ );
+
+ const header = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(header, monitor);
+
+ await codeMirrorReady;
+
+ const tabpanel = document.querySelector("#response-panel");
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+
+ is(
+ tabpanel.querySelector(".response-error-header") === null,
+ true,
+ "The response error header doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ false,
+ "The response editor has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".response-image-box") === null,
+ true,
+ "The response image box doesn't have the intended visibility."
+ );
+
+ const jsonView = tabpanel.querySelector(".data-label") || {};
+ is(
+ jsonView.textContent === L10N.getStr("jsonScopeName"),
+ true,
+ "The response json view has the intended visibility."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_json-long.js b/devtools/client/netmonitor/test/browser_net_json-long.js
new file mode 100644
index 0000000000..4884e55b83
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_json-long.js
@@ -0,0 +1,174 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if very long JSON responses are handled correctly.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { tab, monitor } = await initNetMonitor(JSON_LONG_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ // This is receiving over 80 KB of json and will populate over 6000 items
+ // in a variables view instance. Debug builds are slow.
+ requestLongerTimeout(4);
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ const requestItem = document.querySelector(".request-list-item");
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=json-long",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "json",
+ fullMimeType: "text/json; charset=utf-8",
+ size: L10N.getFormatStr(
+ "networkMenu.size.kB",
+ L10N.numberWithDecimals(85975 / 1000, 2)
+ ),
+ time: true,
+ }
+ );
+
+ let wait = waitForDOM(document, "#response-panel .data-header");
+ const waitForPropsView = waitForDOM(
+ document,
+ "#response-panel .properties-view",
+ 1
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ clickOnSidebarTab(document, "response");
+
+ await Promise.all([wait, waitForPropsView]);
+
+ // Scroll the properties view to the bottom
+ const lastItem = document.querySelector(
+ "#response-panel .properties-view tr.treeRow:last-child"
+ );
+ lastItem.scrollIntoView();
+
+ testJsonInResposeTab();
+
+ wait = waitForDOM(document, "#response-panel .CodeMirror-code");
+ const rawResponseToggle = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(rawResponseToggle, monitor);
+ await wait;
+
+ testResponseTab();
+
+ await teardown(monitor);
+
+ function testJsonInResposeTab() {
+ const tabpanel = document.querySelector("#response-panel");
+ is(
+ tabpanel.querySelectorAll(".treeRow").length,
+ 2047,
+ "There should be 2047 json properties displayed in this tabpanel."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ is(
+ labels[0].textContent,
+ "0",
+ "The first json property name was incorrect."
+ );
+ is(
+ values[0].textContent,
+ 'Object { greeting: "Hello long string JSON!" }',
+ "The first json property value was incorrect."
+ );
+
+ is(
+ labels[1].textContent,
+ "1",
+ "The second json property name was incorrect."
+ );
+ is(
+ values[1].textContent,
+ '"Hello long string JSON!"',
+ "The second json property value was incorrect."
+ );
+
+ const view = tabpanel.querySelector(".properties-view .treeTable");
+ is(scrolledToBottom(view), true, "The view is not scrollable");
+ }
+
+ function testResponseTab() {
+ const tabpanel = document.querySelector("#response-panel");
+
+ is(
+ tabpanel.querySelector(".response-error-header") === null,
+ true,
+ "The response error header doesn't have the intended visibility."
+ );
+ const jsonView = tabpanel.querySelector(".data-label") || {};
+ is(
+ jsonView.textContent === L10N.getStr("jsonScopeName"),
+ true,
+ "The response json view has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".source-editor-mount").clientHeight !== 0,
+ true,
+ "The source editor container has visible height."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ false,
+ "The response editor has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".response-image-box") === null,
+ true,
+ "The response image box doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+
+ is(
+ tabpanel.querySelector(".data-label").textContent,
+ L10N.getStr("jsonScopeName"),
+ "The json view section doesn't have the correct title."
+ );
+ }
+
+ function scrolledToBottom(element) {
+ return element.scrollTop + element.clientHeight >= element.scrollHeight;
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_json-malformed.js b/devtools/client/netmonitor/test/browser_net_json-malformed.js
new file mode 100644
index 0000000000..0e29e07e9d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_json-malformed.js
@@ -0,0 +1,97 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if malformed JSON responses are handled correctly.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+ const { tab, monitor } = await initNetMonitor(JSON_MALFORMED_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ const requestItem = document.querySelector(".request-list-item");
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=json-malformed",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "json",
+ fullMimeType: "text/json; charset=utf-8",
+ }
+ );
+
+ const wait = waitForDOM(document, "#response-panel .CodeMirror-code");
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ const tabpanel = document.querySelector("#response-panel");
+ is(
+ tabpanel.querySelector(".response-error-header") === null,
+ false,
+ "The response error header doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".response-error-header").textContent,
+ "SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data" +
+ " at line 1 column 40 of the JSON data",
+ "The response error header doesn't have the intended text content."
+ );
+ is(
+ tabpanel.querySelector(".response-error-header").getAttribute("title"),
+ "SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data" +
+ " at line 1 column 40 of the JSON data",
+ "The response error header doesn't have the intended tooltiptext attribute."
+ );
+ const jsonView = tabpanel.querySelector(".tree-section .treeLabel") || {};
+ is(
+ jsonView.textContent === L10N.getStr("jsonScopeName"),
+ false,
+ "The response json view doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ false,
+ "The response editor has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".response-image-box") === null,
+ true,
+ "The response image box doesn't have the intended visibility."
+ );
+
+ is(
+ getCodeMirrorValue(monitor),
+ '{ "greeting": "Hello malformed JSON!" },',
+ "The text shown in the source editor is incorrect."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_json-nogrip.js b/devtools/client/netmonitor/test/browser_net_json-nogrip.js
new file mode 100644
index 0000000000..6b00829f2f
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_json-nogrip.js
@@ -0,0 +1,51 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if JSON responses with property 'type' are correctly rendered.
+ * (Reps rendering JSON responses should use `noGrip=true`).
+ */
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ JSON_BASIC_URL + "?name=nogrip",
+ { requestCount: 1 }
+ );
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ await performRequests(monitor, tab, 1);
+
+ const onResponsePanelReady = waitForDOM(
+ document,
+ "#response-panel .data-header"
+ );
+
+ const onPropsViewReady = waitForDOM(
+ document,
+ "#response-panel .properties-view",
+ 1
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+ await Promise.all([onResponsePanelReady, onPropsViewReady]);
+
+ const tabpanel = document.querySelector("#response-panel");
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ is(labels[0].textContent, "obj", "The first json property name is correct.");
+ is(
+ values[0].textContent,
+ 'Object { type: "string" }',
+ "The first json property value is correct."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_json-null.js b/devtools/client/netmonitor/test/browser_net_json-null.js
new file mode 100644
index 0000000000..ec040aaca1
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_json-null.js
@@ -0,0 +1,114 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if JSON responses containing null values are properly displayed.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(JSON_BASIC_URL + "?name=null", {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const { L10N } = windowRequire("devtools/client/netmonitor/src/utils/l10n");
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ const onResponsePanelReady = waitForDOM(
+ document,
+ "#response-panel .data-header"
+ );
+
+ const onPropsViewReady = waitForDOM(
+ document,
+ "#response-panel .properties-view",
+ 1
+ );
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+ await Promise.all([onResponsePanelReady, onPropsViewReady]);
+
+ const tabpanel = document.querySelector("#response-panel");
+ is(
+ tabpanel.querySelectorAll(".raw-data-toggle").length,
+ 1,
+ "There should be 1 raw response toggle."
+ );
+ is(
+ tabpanel.querySelectorAll(".treeRow").length,
+ 1,
+ "There should be 1 json properties displayed in this tabpanel."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ is(
+ labels[0].textContent,
+ "greeting",
+ "The first json property name was incorrect."
+ );
+ is(
+ values[0].textContent,
+ "null",
+ "The first json property value was incorrect."
+ );
+
+ const onCodeMirrorReady = waitForDOM(
+ document,
+ "#response-panel .CodeMirror-code"
+ );
+
+ const rawResponseToggle = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(rawResponseToggle, monitor);
+
+ await onCodeMirrorReady;
+
+ checkResponsePanelDisplaysJSON();
+
+ await teardown(monitor);
+
+ /**
+ * Helper to assert that the response panel found in the provided document is currently
+ * showing a preview of a JSON object.
+ */
+ function checkResponsePanelDisplaysJSON() {
+ const panel = document.querySelector("#response-panel");
+ is(
+ panel.querySelector(".response-error-header") === null,
+ true,
+ "The response error header doesn't have the intended visibility."
+ );
+ const jsonView = panel.querySelector(".data-label") || {};
+ is(
+ jsonView.textContent === L10N.getStr("jsonScopeName"),
+ true,
+ "The response json view has the intended visibility."
+ );
+ is(
+ panel.querySelector(".CodeMirror-code") === null,
+ false,
+ "The response editor has the intended visibility."
+ );
+ is(
+ panel.querySelector(".response-image-box") === null,
+ true,
+ "The response image box doesn't have the intended visibility."
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_json-xssi-protection.js b/devtools/client/netmonitor/test/browser_net_json-xssi-protection.js
new file mode 100644
index 0000000000..6120e4e3bf
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_json-xssi-protection.js
@@ -0,0 +1,96 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if JSON responses and requests with XSSI protection sequences
+ * are handled correctly.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(JSON_XSSI_PROTECTION_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ const wait = waitForDOM(document, "#response-panel .data-header");
+ const waitForRawView = waitForDOM(
+ document,
+ "#response-panel .CodeMirror-code",
+ 1
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+ info("Opening response panel");
+ clickOnSidebarTab(document, "response");
+
+ await Promise.all([wait, waitForRawView]);
+
+ info(
+ "making sure response panel defaults to raw view and correctly displays payload"
+ );
+ const codeLines = document.querySelector("#response-panel .CodeMirror-code");
+ const firstLine = codeLines.firstChild;
+ const firstLineText = firstLine.querySelector("pre.CodeMirror-line span");
+ is(
+ firstLineText.textContent,
+ ")]}'",
+ "XSSI protection sequence should be visibly in raw view"
+ );
+ info("making sure XSSI notification box is not present in raw view");
+ let notification = document.querySelector(
+ '.network-monitor #response-panel .notification[data-key="xssi-string-removed-info-box"]'
+ );
+ ok(!notification, "notification should not be present in raw view");
+
+ const waitForPropsView = waitForDOM(
+ document,
+ "#response-panel .properties-view",
+ 1
+ );
+
+ info("switching to props view");
+ const tabpanel = document.querySelector("#response-panel");
+ const rawResponseToggle = tabpanel.querySelector("#raw-response-checkbox");
+ clickElement(rawResponseToggle, monitor);
+ await waitForPropsView;
+
+ is(
+ tabpanel.querySelectorAll(".treeRow").length,
+ 1,
+ "There should be 1 json property displayed in the response."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+ info("Checking content of displayed json response");
+ is(labels[0].textContent, "greeting", "The first key should be correct");
+ is(
+ values[0].textContent,
+ `"Hello good XSSI protection"`,
+ "The first property should be correct"
+ );
+
+ info("making sure notification box is present and correct in props view");
+
+ notification = document.querySelector(
+ '.network-monitor #response-panel .notification[data-key="xssi-string-removed-info-box"] .notificationInner .messageText'
+ );
+
+ is(
+ notification.textContent,
+ "The string “)]}'\n” was removed from the beginning of the JSON shown below",
+ "The notification message is correct"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_json_custom_mime.js b/devtools/client/netmonitor/test/browser_net_json_custom_mime.js
new file mode 100644
index 0000000000..1b8a0196cf
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_json_custom_mime.js
@@ -0,0 +1,133 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if JSON responses with unusal/custom MIME types are handled correctly.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(JSON_CUSTOM_MIME_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { L10N } = windowRequire("devtools/client/netmonitor/src/utils/l10n");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ const requestItem = document.querySelector(".request-list-item");
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=json-custom-mime",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "x-bigcorp-json",
+ fullMimeType: "text/x-bigcorp-json; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 41),
+ time: true,
+ }
+ );
+
+ let wait = waitForDOM(document, "#response-panel .data-header");
+ const waitForPropsView = waitForDOM(
+ document,
+ "#response-panel .properties-view",
+ 1
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+ await Promise.all([wait, waitForPropsView]);
+
+ testJsonSectionInResponseTab();
+
+ wait = waitForDOM(document, "#response-panel .CodeMirror-code");
+ const rawResponseToggle = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(rawResponseToggle, monitor);
+ await wait;
+
+ testResponseTab();
+
+ await teardown(monitor);
+
+ function testJsonSectionInResponseTab() {
+ const tabpanel = document.querySelector("#response-panel");
+ is(
+ tabpanel.querySelectorAll(".treeRow").length,
+ 1,
+ "There should be 1 json properties displayed in this tabpanel."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ is(
+ labels[0].textContent,
+ "greeting",
+ "The first json property name was incorrect."
+ );
+ is(
+ values[0].textContent,
+ `"Hello oddly-named JSON!"`,
+ "The first json property value was incorrect."
+ );
+ }
+
+ function testResponseTab() {
+ const tabpanel = document.querySelector("#response-panel");
+
+ is(
+ tabpanel.querySelector(".response-error-header") === null,
+ true,
+ "The response error header doesn't have the intended visibility."
+ );
+ const jsonView = tabpanel.querySelector(".data-label") || {};
+ is(
+ jsonView.textContent === L10N.getStr("jsonScopeName"),
+ true,
+ "The response json view has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".raw-data-toggle-input .devtools-checkbox-toggle")
+ .checked,
+ true,
+ "The raw response toggle should be on."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ false,
+ "The response editor has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".response-image-box") === null,
+ true,
+ "The response image box doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_json_text_mime.js b/devtools/client/netmonitor/test/browser_net_json_text_mime.js
new file mode 100644
index 0000000000..86fd4709d6
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_json_text_mime.js
@@ -0,0 +1,136 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if JSON responses with unusal/custom MIME types are handled correctly.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { tab, monitor } = await initNetMonitor(JSON_TEXT_MIME_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ const requestItem = document.querySelector(".request-list-item");
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=json-text-mime",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 41),
+ time: true,
+ }
+ );
+
+ let wait = waitForDOM(document, "#response-panel .data-header");
+ const waitForPropsView = waitForDOM(
+ document,
+ "#response-panel .properties-view",
+ 1
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+ await Promise.all([wait, waitForPropsView]);
+
+ testJsonSectionInResponseTab();
+
+ wait = waitForDOM(document, "#response-panel .CodeMirror-code");
+ const rawResponseToggle = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(rawResponseToggle, monitor);
+ await wait;
+
+ testResponseTab();
+
+ await teardown(monitor);
+
+ function testJsonSectionInResponseTab() {
+ const tabpanel = document.querySelector("#response-panel");
+ is(
+ tabpanel.querySelectorAll(".treeRow").length,
+ 1,
+ "There should be 1 json properties displayed in this tabpanel."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ is(
+ labels[0].textContent,
+ "greeting",
+ "The first json property name was incorrect."
+ );
+ is(
+ values[0].textContent,
+ `"Hello third-party JSON!"`,
+ "The first json property value was incorrect."
+ );
+ }
+
+ function testResponseTab() {
+ const tabpanel = document.querySelector("#response-panel");
+
+ is(
+ tabpanel.querySelector(".response-error-header") === null,
+ true,
+ "The response error header doesn't have the intended visibility."
+ );
+ const jsonView = tabpanel.querySelector(".data-label") || {};
+ is(
+ jsonView.textContent === L10N.getStr("jsonScopeName"),
+ true,
+ "The response json view has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ false,
+ "The response editor has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".raw-data-toggle-input .devtools-checkbox-toggle")
+ .checked,
+ true,
+ "The raw response toggle should be on."
+ );
+ is(
+ tabpanel.querySelector(".response-image-box") === null,
+ true,
+ "The response image box doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_jsonp.js b/devtools/client/netmonitor/test/browser_net_jsonp.js
new file mode 100644
index 0000000000..887e7c5bf3
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_jsonp.js
@@ -0,0 +1,179 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if JSONP responses are handled correctly.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { tab, monitor } = await initNetMonitor(JSONP_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 2);
+
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+ }
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=jsonp&jsonp=$_0123Fun",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "json",
+ fullMimeType: "text/json; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 41),
+ time: true,
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[1],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=jsonp2&jsonp=$_4567Sad",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "json",
+ fullMimeType: "text/json; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 54),
+ time: true,
+ }
+ );
+
+ info("Testing first request");
+ let wait = waitForDOM(document, "#response-panel .data-header");
+ let waitForPropsView = waitForDOM(
+ document,
+ "#response-panel .properties-view",
+ 1
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+ await Promise.all([wait, waitForPropsView]);
+
+ testJsonSectionInResponseTab(`"Hello JSONP!"`);
+
+ wait = waitForDOM(document, "#response-panel .CodeMirror-code");
+ let rawResponseToggle = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(rawResponseToggle, monitor);
+ await wait;
+
+ testResponseTab("$_0123Fun");
+
+ info("Testing second request");
+
+ wait = waitForDOM(document, "#response-panel .data-header");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[1]
+ );
+
+ await wait;
+
+ waitForPropsView = waitForDOM(
+ document,
+ "#response-panel .properties-view",
+ 1
+ );
+ rawResponseToggle = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(rawResponseToggle, monitor);
+
+ await waitForPropsView;
+
+ testJsonSectionInResponseTab(`"Hello weird JSONP!"`);
+
+ wait = waitForDOM(document, "#response-panel .CodeMirror-code");
+ rawResponseToggle = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(rawResponseToggle, monitor);
+ await wait;
+
+ testResponseTab("$_4567Sad");
+
+ await teardown(monitor);
+
+ function testJsonSectionInResponseTab(greeting) {
+ const tabpanel = document.querySelector("#response-panel");
+ is(
+ tabpanel.querySelectorAll(".treeRow").length,
+ 1,
+ "There should be 1 json properties displayed in this tabpanel."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ is(
+ labels[0].textContent,
+ "greeting",
+ "The first json property name was incorrect."
+ );
+ is(
+ values[0].textContent,
+ greeting,
+ "The first json property value was incorrect."
+ );
+ }
+
+ function testResponseTab(func) {
+ const tabpanel = document.querySelector("#response-panel");
+
+ is(
+ tabpanel.querySelector(".response-error-header") === null,
+ true,
+ "The response error header doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".data-label").textContent,
+ L10N.getFormatStr("jsonpScopeName", func),
+ "The response json view has the intened visibility and correct title."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ false,
+ "The response editor has the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".responseImageBox") === null,
+ true,
+ "The response image box doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_large-response.js b/devtools/client/netmonitor/test/browser_net_large-response.js
new file mode 100644
index 0000000000..b72536199a
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_large-response.js
@@ -0,0 +1,92 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if very large response contents are just displayed as plain text.
+ */
+
+const HTML_LONG_URL = CONTENT_TYPE_SJS + "?fmt=html-long";
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ // This test could potentially be slow because over 100 KB of stuff
+ // is going to be requested and displayed in the source editor.
+ requestLongerTimeout(2);
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ let wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [HTML_LONG_URL],
+ async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ }
+ );
+ await wait;
+
+ const requestItem = document.querySelector(".request-list-item");
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=html-long",
+ {
+ status: 200,
+ statusText: "OK",
+ }
+ );
+
+ wait = waitForDOM(document, "#response-panel .data-header");
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ wait = waitForDOM(document, "#response-panel .CodeMirror-code");
+ const payloadHeader = document.querySelector(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(payloadHeader, monitor);
+ await wait;
+
+ ok(
+ getCodeMirrorValue(monitor).match(/^<p>/),
+ "The text shown in the source editor is incorrect."
+ );
+
+ info("Check that search input can be displayed");
+ document.querySelector(".CodeMirror").CodeMirror.focus();
+ synthesizeKeyShortcut("CmdOrCtrl+F");
+ const searchInput = await waitFor(() =>
+ document.querySelector(".CodeMirror input[type=search]")
+ );
+ ok(
+ searchInput.ownerDocument.activeElement == searchInput,
+ "search input is focused"
+ );
+
+ await teardown(monitor);
+
+ // This test uses a lot of memory, so force a GC to help fragmentation.
+ info("Forcing GC after netmonitor test.");
+ Cu.forceGC();
+});
diff --git a/devtools/client/netmonitor/test/browser_net_leak_on_tab_close.js b/devtools/client/netmonitor/test/browser_net_leak_on_tab_close.js
new file mode 100644
index 0000000000..318a644d5c
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_leak_on_tab_close.js
@@ -0,0 +1,20 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that netmonitor doesn't leak windows on parent-side pages (bug 1285638)
+ */
+
+add_task(async function () {
+ // Tell initNetMonitor to enable cache. Otherwise it will assert that there were more
+ // than zero network requests during the page load. But when loading about:config,
+ // there are none.
+ const { monitor } = await initNetMonitor("about:config", {
+ enableCache: true,
+ requestCount: 1,
+ });
+ ok(monitor, "The network monitor was opened");
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_new_request_panel.js b/devtools/client/netmonitor/test/browser_net_new_request_panel.js
new file mode 100644
index 0000000000..dff66b2cdd
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_new_request_panel.js
@@ -0,0 +1,98 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const asyncStorage = require("resource://devtools/shared/async-storage.js");
+
+/**
+ * Test if the New Request panel shows up as a expected when opened from the toolbar
+ */
+
+add_task(async function () {
+ // Turn on the pref
+ await pushPref("devtools.netmonitor.features.newEditAndResend", true);
+ // Reset the storage for the persisted custom request
+ await asyncStorage.removeItem("devtools.netmonitor.customRequest");
+
+ const { monitor } = await initNetMonitor(HTTPS_CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+
+ // Action should be processed synchronously in tests.
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Open the HTTP Custom Panel through the toolbar button");
+ let HTTPCustomRequestButton = document.querySelector(
+ "#netmonitor-toolbar-container .devtools-http-custom-request-icon"
+ );
+ ok(HTTPCustomRequestButton, "The Toolbar button should be visible.");
+ const waitForPanels = waitForDOM(
+ document,
+ ".monitor-panel .network-action-bar"
+ );
+ HTTPCustomRequestButton.click();
+ await waitForPanels;
+
+ is(
+ !!document.querySelector("#network-action-bar-HTTP-custom-request-panel"),
+ true,
+ "The 'New Request' header should be visible when the pref is true."
+ );
+ is(
+ !!document.querySelector(
+ ".devtools-button.devtools-http-custom-request-icon.checked"
+ ),
+ true,
+ "The toolbar button should be highlighted"
+ );
+
+ info("if the default state is empty");
+ is(
+ document.querySelector(".http-custom-method-value").value,
+ "GET",
+ "The method input should be 'GET' by default"
+ );
+ is(
+ document.querySelector(".http-custom-url-value").textContent,
+ "",
+ "The URL input should be empty"
+ );
+ const urlParametersValue = document.querySelectorAll(
+ "#http-custom-query .tabpanel-summary-container.http-custom-input"
+ );
+ is(urlParametersValue.length, 0, "The URL Parameters input should be empty");
+ const headersValue = document.querySelectorAll(
+ "#http-custom-headers .tabpanel-summary-container.http-custom-input"
+ );
+ is(headersValue.length, 0, "The Headers input should be empty");
+ is(
+ document.querySelector("#http-custom-postdata-value").textContent,
+ "",
+ "The Post body input should be empty"
+ );
+
+ // Turn off the pref
+ await pushPref("devtools.netmonitor.features.newEditAndResend", false);
+ info("Close the panel to update the interface after changing the pref");
+ const closePanel = document.querySelector(
+ ".network-action-bar .tabs-navigation .sidebar-toggle"
+ );
+ closePanel.click();
+
+ info("Check if the toolbar button is hidden when the pref is false");
+ HTTPCustomRequestButton = document.querySelector(
+ "#netmonitor-toolbar-container .devtools-http-custom-request-icon"
+ );
+ is(
+ !!HTTPCustomRequestButton,
+ false,
+ "The toolbar button should be hidden when the pref is false."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_new_request_panel_clear_button.js b/devtools/client/netmonitor/test/browser_net_new_request_panel_clear_button.js
new file mode 100644
index 0000000000..78f4f8624d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_new_request_panel_clear_button.js
@@ -0,0 +1,87 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const asyncStorage = require("resource://devtools/shared/async-storage.js");
+
+/**
+ * Test cleaning a custom request.
+ */
+add_task(async function () {
+ // Turn on the pref
+ await pushPref("devtools.netmonitor.features.newEditAndResend", true);
+ // Reset the storage for the persisted custom request
+ await asyncStorage.removeItem("devtools.netmonitor.customRequest");
+
+ const { monitor, tab } = await initNetMonitor(HTTPS_CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+
+ // Action should be processed synchronously in tests.
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ await performRequests(monitor, tab, 1);
+
+ info("selecting first request");
+ const firstRequestItem = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequestItem);
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequestItem);
+
+ info("Opening the new request panel");
+ const waitForPanels = waitUntil(
+ () =>
+ document.querySelector(".http-custom-request-panel") &&
+ document.querySelector("#http-custom-request-send-button").disabled ===
+ false
+ );
+
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+ await waitForPanels;
+
+ const request = getSelectedRequest(store.getState());
+
+ // Check if the panel is updated with the content by the request clicked
+ const urlValue = document.querySelector(".http-custom-url-value");
+ is(
+ urlValue.textContent,
+ request.url,
+ "The URL in the form should match the request we clicked"
+ );
+
+ info("Clicking on the clear button");
+ document.querySelector("#http-custom-request-clear-button").click();
+ is(
+ document.querySelector(".http-custom-method-value").value,
+ "GET",
+ "The method input should be 'GET' by default"
+ );
+ is(
+ document.querySelector(".http-custom-url-value").textContent,
+ "",
+ "The URL input should be empty"
+ );
+ const urlParametersValue = document.querySelectorAll(
+ "#http-custom-query .tabpanel-summary-container.http-custom-input"
+ );
+ is(urlParametersValue.length, 0, "The URL Parameters input should be empty");
+ const headersValue = document.querySelectorAll(
+ "#http-custom-headers .tabpanel-summary-container.http-custom-input"
+ );
+ is(headersValue.length, 0, "The Headers input should be empty");
+ is(
+ document.querySelector("#http-custom-postdata-value").textContent,
+ "",
+ "The Post body input should be empty"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_new_request_panel_content-length.js b/devtools/client/netmonitor/test/browser_net_new_request_panel_content-length.js
new file mode 100644
index 0000000000..7d0bbc42c7
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_new_request_panel_content-length.js
@@ -0,0 +1,94 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that the content length field is always updated when
+ * the message body changes.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(POST_RAW_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+
+ const { window, document, store, windowRequire } = monitor.panelWin;
+
+ // Action should be processed synchronously in tests.
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ await performRequests(monitor, tab, 1);
+
+ info("Select the first request");
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+ await waitForHeaders;
+
+ info("Open the first request in the request panel to resend");
+ const waitForPanels = waitUntil(
+ () =>
+ document.querySelector(".http-custom-request-panel") &&
+ document.querySelector("#http-custom-request-send-button").disabled ===
+ false
+ );
+
+ // Open the context menu and select resend menu item
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequest);
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+
+ await waitForPanels;
+
+ const contentLengthField = document.querySelector(
+ "#http-custom-content-length .http-custom-input-value"
+ );
+
+ is(contentLengthField.value, "15", "The content length is correct");
+
+ const messageBody = document.querySelector("#http-custom-postdata-value");
+ messageBody.focus();
+ EventUtils.sendString("bla=333&", window);
+
+ await waitUntil(() => {
+ return contentLengthField.value == "23";
+ });
+ ok(true, "The content length is still correct");
+
+ const prevRequest = getSelectedRequest(store.getState());
+
+ info("Send the request");
+ const waitUntilEventsDisplayed = waitForNetworkEvents(monitor, 1);
+ document.querySelector("#http-custom-request-send-button").click();
+ await waitUntilEventsDisplayed;
+
+ // Also make sure the selected request has switched to the new resent request
+ await waitUntil(() => getSelectedRequest(store.getState()) !== prevRequest);
+
+ const newRequest = getSelectedRequest(store.getState());
+
+ // Wait for request headers to be available
+ await waitUntil(() => newRequest.requestHeaders?.headers.length);
+
+ const contentLengthHeader = newRequest.requestHeaders.headers.find(
+ header => header.name == "Content-Length"
+ );
+
+ is(
+ contentLengthHeader.value,
+ "23",
+ "The content length of the resent request is correct"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_new_request_panel_context_menu.js b/devtools/client/netmonitor/test/browser_net_new_request_panel_context_menu.js
new file mode 100644
index 0000000000..e4bc765c96
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_new_request_panel_context_menu.js
@@ -0,0 +1,208 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const asyncStorage = require("resource://devtools/shared/async-storage.js");
+
+/**
+ * Test if the New Request Panel shows up as a expected
+ * when opened from an existing request
+ */
+
+add_task(async function () {
+ // Turn true the pref
+ await pushPref("devtools.netmonitor.features.newEditAndResend", true);
+ // Reset the storage for the persisted custom request
+ await asyncStorage.removeItem("devtools.netmonitor.customRequest");
+
+ const { tab, monitor } = await initNetMonitor(POST_DATA_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire, connector } = monitor.panelWin;
+
+ // Action should be processed synchronously in tests.
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ await performRequests(monitor, tab, 2);
+
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ const expectedURLQueryParams = [
+ {
+ name: "foo",
+ value: "bar",
+ },
+ { name: "baz", value: "42" },
+ { name: "type", value: "urlencoded" },
+ ];
+
+ info("selecting first request");
+ const firstRequestItem = document.querySelectorAll(".request-list-item")[0];
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequestItem);
+ await waitForHeaders;
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequestItem);
+
+ ok(
+ getContextMenuItem(monitor, "request-list-context-resend-only"),
+ "The 'Resend' item is visible when there is a clicked request"
+ );
+
+ info("Opening the new request panel");
+ const waitForPanels = waitUntil(
+ () =>
+ document.querySelector(".http-custom-request-panel") &&
+ document.querySelector("#http-custom-request-send-button").disabled ===
+ false
+ );
+
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+ await waitForPanels;
+
+ is(
+ !!document.querySelector(
+ ".devtools-button.devtools-http-custom-request-icon.checked"
+ ),
+ true,
+ "The toolbar button should be highlighted"
+ );
+
+ const request = getSelectedRequest(store.getState());
+
+ // Verify if the default state contains the data from the request
+ const methodValue = document.querySelector(".http-custom-method-value");
+ is(
+ methodValue.value,
+ request.method,
+ "The method in the form should match the request we clicked"
+ );
+
+ const urlValue = document.querySelector(".http-custom-url-value");
+ is(
+ urlValue.textContent,
+ request.url,
+ "The URL in the form should match the request we clicked"
+ );
+
+ const urlParametersValues = document.querySelectorAll(
+ "#http-custom-query .tabpanel-summary-container.http-custom-input"
+ );
+ is(
+ urlParametersValues.length,
+ 3,
+ "The URL Parameters length in the form should match the request we clicked"
+ );
+
+ for (let i = 0; i < urlParametersValues.length; i++) {
+ const { name, value } = expectedURLQueryParams[i];
+ const [formName, formValue] =
+ urlParametersValues[i].querySelectorAll("textarea");
+ is(
+ name,
+ formName.value,
+ "The query param name in the form should match the request we clicked"
+ );
+ is(
+ value,
+ formValue.value,
+ "The query param value in the form should match the request we clicked"
+ );
+ }
+
+ const headersValues = document.querySelectorAll(
+ "#http-custom-headers .tabpanel-summary-container.http-custom-input"
+ );
+ ok(
+ headersValues.length >= 6,
+ "The headers length in the form should match the request we clicked"
+ );
+
+ for (const { name, value } of request.requestHeaders.headers) {
+ const found = Array.from(headersValues).find(item => {
+ const [formName, formValue] = item.querySelectorAll("textarea");
+ if (formName.value === name && formValue.value === value) {
+ return true;
+ }
+ return false;
+ });
+
+ ok(found, "The header was found in the form");
+ }
+
+ // Wait to the post body because it is only updated in the componentWillMount
+ const postValue = document.querySelector("#http-custom-postdata-value");
+ await waitUntil(() => postValue.textContent !== "");
+ is(
+ postValue.value,
+ request.requestPostData.postData.text,
+ "The Post body input value in the form should match the request we clicked"
+ );
+
+ info(
+ "Uncheck the header an make sure the header is removed from the new request"
+ );
+ const headers = document.querySelectorAll(
+ "#http-custom-headers .tabpanel-summary-container.http-custom-input"
+ );
+
+ const lastHeader = Array.from(headers).pop();
+ const checkbox = lastHeader.querySelector("input");
+ checkbox.click();
+
+ info("Click on the button to send a new request");
+ const waitUntilEventsDisplayed = waitForNetworkEvents(monitor, 1);
+ const buttonSend = document.querySelector("#http-custom-request-send-button");
+ buttonSend.click();
+ await waitUntilEventsDisplayed;
+
+ const newRequestSelectedId = getSelectedRequest(store.getState()).id;
+ await connector.requestData(newRequestSelectedId, "requestHeaders");
+ const updatedSelectedRequest = getSelectedRequest(store.getState());
+
+ let found = updatedSelectedRequest.requestHeaders.headers.some(
+ item => item.name == "My-header-2" && item.value == "my-value-2"
+ );
+
+ is(
+ found,
+ false,
+ "The header unchecked should not be found on the headers list"
+ );
+
+ info(
+ "Delete the header and make sure the header is removed in the custom request panel"
+ );
+ const buttonDelete = lastHeader.querySelector("button");
+ buttonDelete.click();
+
+ const headersValue = document.querySelectorAll(
+ "#http-custom-headers .tabpanel-summary-container.http-custom-input textarea"
+ );
+ found = Array.from(headersValue).some(
+ item => item.name == "My-header-2" && item.value == "my-value-2"
+ );
+ is(found, false, "The header delete should not be found on the headers form");
+
+ info(
+ "Change the request selected to make sure the request in the custom request panel does not change"
+ );
+ const previousRequest = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, previousRequest);
+
+ const urlValueChanged = document.querySelector(".http-custom-url-value");
+ is(
+ urlValue.textContent,
+ urlValueChanged.textContent,
+ "The url should not change when click on a new request"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_new_request_panel_persisted_content.js b/devtools/client/netmonitor/test/browser_net_new_request_panel_persisted_content.js
new file mode 100644
index 0000000000..509bbc0000
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_new_request_panel_persisted_content.js
@@ -0,0 +1,149 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const asyncStorage = require("resource://devtools/shared/async-storage.js");
+
+/**
+ * Test if content is still persisted after the panel is closed
+ */
+
+add_task(async function () {
+ // Turn true the pref
+ await pushPref("devtools.netmonitor.features.newEditAndResend", true);
+ // Reset the storage for the persisted custom request
+ await asyncStorage.removeItem("devtools.netmonitor.customRequest");
+
+ const { monitor } = await initNetMonitor(HTTPS_CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+
+ // Action should be processed synchronously in tests.
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ info("open the left panel");
+ let waitForPanels = waitForDOM(
+ document,
+ ".monitor-panel .network-action-bar"
+ );
+
+ let HTTPCustomRequestButton = document.querySelector(
+ "#netmonitor-toolbar-container .devtools-http-custom-request-icon"
+ );
+ HTTPCustomRequestButton.click();
+ await waitForPanels;
+
+ info("Check if the panel is empty");
+ is(
+ document.querySelector(".http-custom-url-value").value,
+ "",
+ "The URL input should be empty"
+ );
+
+ info("Add some content on the panel");
+ const methodValue = document.querySelector("#http-custom-method-value");
+ methodValue.value = "POST";
+ methodValue.dispatchEvent(new Event("change", { bubbles: true }));
+
+ const url = document.querySelector(".http-custom-url-value");
+ url.focus();
+ EventUtils.sendString("https://www.example.com");
+
+ info("Adding new parameters");
+ const newParameterName = document.querySelector(
+ "#http-custom-query .map-add-new-inputs .http-custom-input-name"
+ );
+ newParameterName.focus();
+ EventUtils.sendString("My-param");
+
+ info("Adding new headers");
+ const newHeaderName = document.querySelector(
+ "#http-custom-headers .map-add-new-inputs .http-custom-input-name"
+ );
+ newHeaderName.focus();
+ EventUtils.sendString("My-header");
+
+ const newHeaderValue = Array.from(
+ document.querySelectorAll(
+ "#http-custom-headers .http-custom-input .http-custom-input-value"
+ )
+ ).pop();
+ newHeaderValue.focus();
+ EventUtils.sendString("my-value");
+
+ const postValue = document.querySelector("#http-custom-postdata-value");
+ postValue.focus();
+ EventUtils.sendString("{'Name': 'Value'}");
+
+ // Close the panel
+ const closePanel = document.querySelector(
+ ".network-action-bar .tabs-navigation .sidebar-toggle"
+ );
+ closePanel.click();
+
+ // Open the panel again to see if the content is still there
+ waitForPanels = waitUntil(
+ () =>
+ document.querySelector(".http-custom-request-panel") &&
+ document.querySelector("#http-custom-request-send-button").disabled ===
+ false
+ );
+
+ HTTPCustomRequestButton = document.querySelector(
+ "#netmonitor-toolbar-container .devtools-http-custom-request-icon"
+ );
+ HTTPCustomRequestButton.click();
+ await waitForPanels;
+
+ is(
+ methodValue.value,
+ "POST",
+ "The content should still be there after the user close the panel and re-opened"
+ );
+
+ is(
+ url.value,
+ "https://www.example.com?My-param=",
+ "The url should still be there after the user close the panel and re-opened"
+ );
+
+ const [nameParam] = Array.from(
+ document.querySelectorAll(
+ "#http-custom-query .tabpanel-summary-container.http-custom-input textarea"
+ )
+ );
+ is(
+ nameParam.value,
+ "My-param",
+ "The Parameter name should still be there after the user close the panel and re-opened"
+ );
+
+ const [name, value] = Array.from(
+ document.querySelectorAll(
+ "#http-custom-headers .tabpanel-summary-container.http-custom-input textarea"
+ )
+ );
+ is(
+ name.value,
+ "My-header",
+ "The header name should still be there after the user close the panel and re-opened"
+ );
+ is(
+ value.value,
+ "my-value",
+ "The header value should still be there after the user close the panel and re-opened"
+ );
+
+ is(
+ postValue.value,
+ "{'Name': 'Value'}",
+ "The content should still be there after the user close the panel and re-opened"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_new_request_panel_send_request.js b/devtools/client/netmonitor/test/browser_net_new_request_panel_send_request.js
new file mode 100644
index 0000000000..656488de36
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_new_request_panel_send_request.js
@@ -0,0 +1,166 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const asyncStorage = require("resource://devtools/shared/async-storage.js");
+
+/**
+ * Test sending a custom request.
+ */
+add_task(async function () {
+ // Turn on the pref
+ await pushPref("devtools.netmonitor.features.newEditAndResend", true);
+ // Reset the storage for the persisted custom request
+ await asyncStorage.removeItem("devtools.netmonitor.customRequest");
+
+ const { monitor } = await initNetMonitor(CORS_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire, connector } = monitor.panelWin;
+ // Action should be processed synchronously in tests.
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ // Build request with known information so that we can check later
+ const request = {
+ url: "https://test1.example.com" + CORS_SJS_PATH,
+ method: "POST",
+ headers: [
+ { name: "Host", value: "fakehost.example.com" },
+ { name: "User-Agent", value: "Testzilla" },
+ { name: "Referer", value: "http://example.com/referrer" },
+ { name: "Accept", value: "application/jarda" },
+ { name: "Accept-Encoding", value: "compress, identity, funcoding" },
+ { name: "Accept-Language", value: "cs-CZ" },
+ ],
+ body: "Hello",
+ cause: {
+ loadingDocumentUri: "http://example.com",
+ stacktraceAvailable: true,
+ type: "xhr",
+ },
+ };
+ const waitUntilRequestDisplayed = waitForNetworkEvents(monitor, 1);
+ connector.networkCommand.sendHTTPRequest(request);
+ await waitUntilRequestDisplayed;
+
+ info("selecting first request");
+ const firstRequestItem = document.querySelectorAll(".request-list-item")[0];
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequestItem);
+ await waitForHeaders;
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequestItem);
+
+ info("Opening the new request panel");
+ const waitForPanels = waitUntil(
+ () =>
+ document.querySelector(".http-custom-request-panel") &&
+ document.querySelector("#http-custom-request-send-button").disabled ===
+ false
+ );
+
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+ await waitForPanels;
+
+ info(
+ "Change the request method to send a new custom request with a different method"
+ );
+ const methodValue = document.querySelector("#http-custom-method-value");
+ methodValue.value = "PUT";
+ methodValue.dispatchEvent(new Event("change", { bubbles: true }));
+
+ info("Change the URL to send a custom request with a different URL");
+ const urlValue = document.querySelector(".http-custom-url-value");
+ urlValue.focus();
+ urlValue.value = "";
+ EventUtils.sendString(`${request.url}?hello=world`);
+
+ info("Check if the parameter section was updated");
+ is(
+ document.querySelectorAll(
+ "#http-custom-query .tabpanel-summary-container.http-custom-input"
+ ).length,
+ 1,
+ "The parameter section should be updated"
+ );
+
+ info("Adding new headers");
+ const newHeaderName = document.querySelector(
+ "#http-custom-headers .map-add-new-inputs .http-custom-input-name"
+ );
+ newHeaderName.focus();
+ EventUtils.sendString("My-header");
+
+ const newHeaderValue = Array.from(
+ document.querySelectorAll(
+ "#http-custom-headers .http-custom-input .http-custom-input-value"
+ )
+ ).pop();
+ newHeaderValue.focus();
+ EventUtils.sendString("my-value");
+
+ const postValue = document.querySelector("#http-custom-postdata-value");
+ postValue.focus();
+ postValue.value = "";
+ EventUtils.sendString("{'name': 'value'}");
+
+ // Close the details panel to see if after sending a new request
+ // this request will be selected by default and
+ // if the deitails panel will be open automatically.
+ const waitForDetailsPanelToClose = waitUntil(
+ () => !document.querySelector(".monitor-panel .network-details-bar")
+ );
+ store.dispatch(Actions.toggleNetworkDetails());
+ await waitForDetailsPanelToClose;
+
+ info("Click on the button to send a new request");
+ const waitUntilEventsDisplayed = waitForNetworkEvents(monitor, 1);
+ const buttonSend = document.querySelector("#http-custom-request-send-button");
+ buttonSend.click();
+ await waitUntilEventsDisplayed;
+
+ const newRequestSelectedId = getSelectedRequest(store.getState()).id;
+ await connector.requestData(newRequestSelectedId, "requestPostData");
+ const updatedSelectedRequest = getSelectedRequest(store.getState());
+ is(updatedSelectedRequest.method, "PUT", "The request has the right method");
+ is(
+ updatedSelectedRequest.url,
+ urlValue.value,
+ "The request has the right URL"
+ );
+
+ const found = updatedSelectedRequest.requestHeaders.headers.some(
+ item => item.name === "My-header" && item.value === "my-value"
+ );
+
+ is(found, true, "The header was found in the form");
+
+ is(
+ updatedSelectedRequest.requestPostData.postData.text,
+ "{'name': 'value'}",
+ "The request has the right post body"
+ );
+
+ info("Check that all growing textareas provide a title tooltip");
+ const textareas = [
+ ...document.querySelectorAll("#http-custom-headers .auto-growing-textarea"),
+ ];
+ for (const textarea of textareas) {
+ is(
+ textarea.title,
+ textarea.dataset.replicatedValue,
+ "Title tooltip is set to the expected value"
+ );
+ }
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_new_request_panel_sync_url_params.js b/devtools/client/netmonitor/test/browser_net_new_request_panel_sync_url_params.js
new file mode 100644
index 0000000000..1d7b51f3d4
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_new_request_panel_sync_url_params.js
@@ -0,0 +1,194 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const asyncStorage = require("resource://devtools/shared/async-storage.js");
+
+/**
+ * Test to check the sync between URL parameters and the parameters section
+ */
+
+add_task(async function () {
+ // Turn on the pref
+ await pushPref("devtools.netmonitor.features.newEditAndResend", true);
+ // Reset the storage for the persisted custom request
+ await asyncStorage.removeItem("devtools.netmonitor.customRequest");
+
+ const { tab, monitor } = await initNetMonitor(HTTPS_CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+
+ // Action should be processed synchronously in tests.
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ await performRequests(monitor, tab, 1);
+
+ info("selecting first request");
+ const firstRequestItem = document.querySelectorAll(".request-list-item")[0];
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequestItem);
+ await waitForHeaders;
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequestItem);
+
+ info("Opening the new request panel");
+ const waitForPanels = waitForDOM(
+ document,
+ ".monitor-panel .network-action-bar"
+ );
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+ await waitForPanels;
+
+ const queryScenarios = [
+ {
+ queryString: "",
+ expectedParametersSize: 0,
+ expectedParameters: [],
+ },
+ {
+ queryString: "?",
+ expectedParametersSize: 0,
+ expectedParameters: [],
+ },
+ {
+ queryString: "?a",
+ expectedParametersSize: 1,
+ expectedParameters: [{ name: "a", value: "" }],
+ },
+ {
+ queryString: "?a=",
+ expectedParametersSize: 1,
+ expectedParameters: [{ name: "a", value: "" }],
+ },
+ {
+ queryString: "?a=3",
+ expectedParametersSize: 1,
+ expectedParameters: [{ name: "a", value: "3" }],
+ },
+ {
+ queryString: "?a=3&",
+ expectedParametersSize: 2,
+ expectedParameters: [
+ { name: "a", value: "3" },
+ { name: "", value: "" },
+ ],
+ },
+ {
+ queryString: "?a=3&b=4",
+ expectedParametersSize: 2,
+ expectedParameters: [
+ { name: "a", value: "3" },
+ { name: "b", value: "4" },
+ ],
+ },
+ ];
+
+ for (const sceanario of queryScenarios) {
+ assertQueryScenario(document, sceanario);
+ }
+
+ info("Adding new parameters by query parameters section");
+ const newParameterName = document.querySelector(
+ "#http-custom-query .map-add-new-inputs .http-custom-input-name"
+ );
+ newParameterName.focus();
+ EventUtils.sendString("My-param");
+
+ is(
+ document.querySelector("#http-custom-url-value").value,
+ `${HTTPS_CUSTOM_GET_URL}?a=3&b=4&My-param=`,
+ "The URL should be updated"
+ );
+
+ const newParameterValue = Array.from(
+ document.querySelectorAll(
+ "#http-custom-query .http-custom-input .http-custom-input-value"
+ )
+ ).pop();
+ newParameterValue.focus();
+ EventUtils.sendString("my-value");
+
+ // Check if the url is updated
+ is(
+ document.querySelector("#http-custom-url-value").value,
+ `${HTTPS_CUSTOM_GET_URL}?a=3&b=4&My-param=my-value`,
+ "The URL should be updated"
+ );
+
+ info("Adding new parameters by query parameters section");
+ is(
+ document.querySelectorAll(
+ "#http-custom-query .tabpanel-summary-container.http-custom-input"
+ ).length,
+ 3,
+ "The parameter section should be have 3 elements"
+ );
+
+ info(
+ "Uncheck the parameter an make sure the parameter is removed from the new url"
+ );
+ const params = document.querySelectorAll(
+ "#http-custom-query .tabpanel-summary-container.http-custom-input"
+ );
+
+ const lastParam = Array.from(params).pop();
+ const checkbox = lastParam.querySelector("input");
+ checkbox.click();
+
+ // Check if the url is updated after uncheck one parameter through the parameter section
+ is(
+ document.querySelector("#http-custom-url-value").value,
+ `${HTTPS_CUSTOM_GET_URL}?a=3&b=4`,
+ "The URL should be updated"
+ );
+
+ await teardown(monitor);
+});
+
+function assertQueryScenario(
+ document,
+ { queryString, expectedParametersSize, expectedParameters }
+) {
+ info(`Assert that "${queryString}" shows in the list properly`);
+ const urlValue = document.querySelector(".http-custom-url-value");
+ urlValue.focus();
+ urlValue.value = "";
+
+ const newURL = HTTPS_CUSTOM_GET_URL + queryString;
+ EventUtils.sendString(newURL);
+
+ is(
+ document.querySelectorAll(
+ "#http-custom-query .tabpanel-summary-container.http-custom-input"
+ ).length,
+ expectedParametersSize,
+ `The parameter section should have ${expectedParametersSize} elements`
+ );
+
+ // Check if the parameter name and value are what we expect
+ const parameterNames = document.querySelectorAll(
+ "#http-custom-query .http-custom-input-and-map-form .http-custom-input-name"
+ );
+ const parameterValues = document.querySelectorAll(
+ "#http-custom-query .http-custom-input-and-map-form .http-custom-input-value"
+ );
+
+ for (let i = 0; i < expectedParameters.length; i++) {
+ is(
+ parameterNames[i].value,
+ expectedParameters[i].name,
+ "The query param name in the form should match on the URL"
+ );
+ is(
+ parameterValues[i].value,
+ expectedParameters[i].value,
+ "The query param value in the form should match on the URL"
+ );
+ }
+}
diff --git a/devtools/client/netmonitor/test/browser_net_open_in_debugger.js b/devtools/client/netmonitor/test/browser_net_open_in_debugger.js
new file mode 100644
index 0000000000..0ca96ffaa8
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_open_in_debugger.js
@@ -0,0 +1,40 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test the 'Open in debugger' feature
+ */
+
+add_task(async function () {
+ const { tab, monitor, toolbox } = await initNetMonitor(
+ CONTENT_TYPE_WITHOUT_CACHE_URL,
+ { requestCount: 1 }
+ );
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ // Avoid async processing
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, CONTENT_TYPE_WITHOUT_CACHE_REQUESTS);
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[2]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[2]
+ );
+ const onDebuggerReady = toolbox.once("jsdebugger-ready");
+ await selectContextMenuItem(monitor, "request-list-context-open-in-debugger");
+ await onDebuggerReady;
+
+ ok(true, "Debugger has been open");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_open_in_style_editor.js b/devtools/client/netmonitor/test/browser_net_open_in_style_editor.js
new file mode 100644
index 0000000000..9592c74851
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_open_in_style_editor.js
@@ -0,0 +1,44 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test the 'Open in debugger' feature
+ */
+
+add_task(async function () {
+ const { tab, monitor, toolbox } = await initNetMonitor(
+ CONTENT_TYPE_WITHOUT_CACHE_URL,
+ { requestCount: 1 }
+ );
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ // Avoid async processing
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, CONTENT_TYPE_WITHOUT_CACHE_REQUESTS);
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[1]
+ );
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[1]
+ );
+
+ const onStyleEditorReady = toolbox.once("styleeditor-ready");
+ await selectContextMenuItem(
+ monitor,
+ "request-list-context-open-in-style-editor"
+ );
+ await onStyleEditorReady;
+
+ ok(true, "Style Editor has been open");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_open_request_in_tab.js b/devtools/client/netmonitor/test/browser_net_open_request_in_tab.js
new file mode 100644
index 0000000000..db96c350ca
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_open_request_in_tab.js
@@ -0,0 +1,264 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if Open in new tab works by ContextMenu.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(OPEN_REQUEST_IN_TAB_URL, {
+ requestCount: 1,
+ });
+ info("Starting test...");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ let newTab;
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Post data may be fetched by the Header panel,
+ // so set the Timings panel as the new default.
+ store.getState().ui.detailsPanelSelectedTab = "timings";
+
+ // Open GET request in new tab
+ await performRequest(monitor, tab, "GET");
+ newTab = await openLastRequestInTab();
+ await checkTabResponse(newTab, "GET");
+ gBrowser.removeCurrentTab();
+
+ // Open POST request in new tab
+ await performRequest(
+ monitor,
+ tab,
+ "POST",
+ "application/x-www-form-urlencoded",
+ "foo=bar&baz=42"
+ );
+ newTab = await openLastRequestInTab();
+ await checkTabResponse(
+ newTab,
+ "POST",
+ "application/x-www-form-urlencoded",
+ "foo=bar&amp;baz=42"
+ );
+ gBrowser.removeCurrentTab();
+
+ // Open POST application/json request in new tab
+ await performRequest(
+ monitor,
+ tab,
+ "POST",
+ "application/json",
+ '{"foo":"bar"}'
+ );
+ newTab = await openLastRequestInTab();
+ await checkTabResponse(newTab, "POST", "application/json", '{"foo":"bar"}');
+ gBrowser.removeCurrentTab();
+
+ await teardown(monitor);
+
+ // OpenLastRequestInTab by ContextMenu
+ async function openLastRequestInTab() {
+ const requestItems = document.querySelectorAll(".request-list-item");
+ const lastRequest = requestItems[requestItems.length - 1];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, lastRequest);
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, lastRequest);
+
+ const onTabOpen = once(gBrowser.tabContainer, "TabOpen", false);
+ await selectContextMenuItem(monitor, "request-list-context-newtab");
+ await onTabOpen;
+ info("A new tab has been opened");
+
+ const awaitedTab = gBrowser.selectedTab;
+ await BrowserTestUtils.browserLoaded(awaitedTab.linkedBrowser);
+ info("The tab load completed");
+
+ return awaitedTab;
+ }
+});
+
+/**
+ * Tests if Open in new tab works by DoubleClick RequestItem.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(OPEN_REQUEST_IN_TAB_URL, {
+ requestCount: 1,
+ });
+ info("Starting test...");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ let newTab;
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Post data may be fetched by the Header panel,
+ // so set the Timings panel as the new default.
+ store.getState().ui.detailsPanelSelectedTab = "timings";
+
+ // Open GET request in new tab
+ await performRequest(monitor, tab, "GET");
+ newTab = await openLastRequestInTab();
+ await checkTabResponse(newTab, "GET");
+ gBrowser.removeCurrentTab();
+
+ // Open POST request in new tab
+ await performRequest(
+ monitor,
+ tab,
+ "POST",
+ "application/x-www-form-urlencoded",
+ "foo=bar&baz=42"
+ );
+ newTab = await openLastRequestInTab();
+ await checkTabResponse(
+ newTab,
+ "POST",
+ "application/x-www-form-urlencoded",
+ "foo=bar&amp;baz=42"
+ );
+ gBrowser.removeCurrentTab();
+
+ // Open POST application/json request in new tab
+ await performRequest(
+ monitor,
+ tab,
+ "POST",
+ "application/json",
+ '{"foo":"bar"}'
+ );
+ newTab = await openLastRequestInTab();
+ await checkTabResponse(newTab, "POST", "application/json", '{"foo":"bar"}');
+ gBrowser.removeCurrentTab();
+
+ await teardown(monitor);
+
+ // OpenLastRequestInTab by DoubleClick
+ async function openLastRequestInTab() {
+ const requestItems = document.querySelectorAll(".request-list-item");
+ const lastRequest = requestItems[requestItems.length - 1];
+
+ const onTabOpen = once(gBrowser.tabContainer, "TabOpen", false);
+ EventUtils.sendMouseEvent({ type: "dblclick" }, lastRequest);
+ await onTabOpen;
+ info("A new tab has been opened");
+
+ const awaitedTab = gBrowser.selectedTab;
+ await BrowserTestUtils.browserLoaded(awaitedTab.linkedBrowser);
+ info("The tab load completed");
+
+ return awaitedTab;
+ }
+});
+
+/**
+ * Tests if Open in new tab works by middle click RequestItem.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(OPEN_REQUEST_IN_TAB_URL, {
+ requestCount: 1,
+ });
+ const MIDDLE_MOUSE_BUTTON = 1;
+ info("Starting test...");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ let newTab;
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Post data may be fetched by the Header panel,
+ // so set the Timings panel as the new default.
+ store.getState().ui.detailsPanelSelectedTab = "timings";
+
+ // Open GET request in new tab
+ await performRequest(monitor, tab, "GET");
+ newTab = await openLastRequestInTab();
+ await checkTabResponse(newTab, "GET");
+ gBrowser.removeCurrentTab();
+
+ // Open POST request in new tab
+ await performRequest(
+ monitor,
+ tab,
+ "POST",
+ "application/x-www-form-urlencoded",
+ "foo=bar&baz=42"
+ );
+ newTab = await openLastRequestInTab();
+ await checkTabResponse(
+ newTab,
+ "POST",
+ "application/x-www-form-urlencoded",
+ "foo=bar&amp;baz=42"
+ );
+ gBrowser.removeCurrentTab();
+
+ // Open POST application/json request in new tab
+ await performRequest(
+ monitor,
+ tab,
+ "POST",
+ "application/json",
+ '{"foo":"bar"}'
+ );
+ newTab = await openLastRequestInTab();
+ await checkTabResponse(newTab, "POST", "application/json", '{"foo":"bar"}');
+ gBrowser.removeCurrentTab();
+
+ await teardown(monitor);
+
+ // OpenLastRequestInTab by middle click
+ async function openLastRequestInTab() {
+ const requestItems = document.querySelectorAll(".request-list-item");
+ const lastRequest = requestItems[requestItems.length - 1];
+
+ const onTabOpen = once(gBrowser.tabContainer, "TabOpen", false);
+ EventUtils.sendMouseEvent(
+ { type: "mousedown", button: MIDDLE_MOUSE_BUTTON },
+ lastRequest
+ );
+ await onTabOpen;
+ info("A new tab has been opened");
+
+ const awaitedTab = gBrowser.selectedTab;
+ await BrowserTestUtils.browserLoaded(awaitedTab.linkedBrowser);
+ info("The tab load completed");
+
+ return awaitedTab;
+ }
+});
+
+async function performRequest(monitor, tab, method, contentType, payload) {
+ const wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [[method, contentType, payload]],
+ async function ([method_, contentType_, payload_]) {
+ content.wrappedJSObject.performRequest(method_, contentType_, payload_);
+ }
+ );
+ await wait;
+ info("Performed request to test server");
+}
+
+async function checkTabResponse(checkedTab, method, contentType, payload) {
+ await SpecialPowers.spawn(
+ checkedTab.linkedBrowser,
+ [[method, contentType, payload]],
+ async function ([method_, contentType_, payload_]) {
+ const { body } = content.wrappedJSObject.document;
+ const expected = [method_, contentType_, payload_].join("\n");
+ info("Response from the server:" + body.innerHTML.replace(/\n/g, "\\n"));
+ ok(
+ body.innerHTML.includes(expected),
+ "Tab method and data match original request"
+ );
+ }
+ );
+}
diff --git a/devtools/client/netmonitor/test/browser_net_pane-collapse.js b/devtools/client/netmonitor/test/browser_net_pane-collapse.js
new file mode 100644
index 0000000000..465b4740ac
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_pane-collapse.js
@@ -0,0 +1,68 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the network monitor panes collapse properly.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { Prefs } = windowRequire("devtools/client/netmonitor/src/utils/prefs");
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ ok(
+ !document.querySelector(".network-details-bar") &&
+ !document.querySelector(".sidebar-toggle"),
+ "The details panel should initially be hidden."
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ is(
+ ~~document.querySelector(".network-details-bar").clientWidth,
+ Prefs.networkDetailsWidth,
+ "The details panel has an incorrect width."
+ );
+ ok(
+ document.querySelector(".network-details-bar") &&
+ document.querySelector(".sidebar-toggle"),
+ "The details panel should at this point be visible."
+ );
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".sidebar-toggle")
+ );
+
+ ok(
+ !document.querySelector(".network-details-bar") &&
+ !document.querySelector(".sidebar-toggle"),
+ "The details panel should not be visible after collapsing."
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ is(
+ ~~document.querySelector(".network-details-bar").clientWidth,
+ Prefs.networkDetailsWidth,
+ "The details panel has an incorrect width after uncollapsing."
+ );
+ ok(
+ document.querySelector(".network-details-bar") &&
+ document.querySelector(".sidebar-toggle"),
+ "The details panel should be visible again after uncollapsing."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_pane-network-details.js b/devtools/client/netmonitor/test/browser_net_pane-network-details.js
new file mode 100644
index 0000000000..f5a11f9b4d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_pane-network-details.js
@@ -0,0 +1,149 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test the action of request details panel when filters are applied.
+ * If there are any visible requests, the first request from the
+ * list of visible requests should be displayed in the network
+ * details panel
+ * If there are no visible requests the panel should remain closed
+ */
+
+const REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS = [
+ {
+ url: "sjs_content-type-test-server.sjs?fmt=html&res=undefined&text=Sample",
+ },
+ { url: "sjs_content-type-test-server.sjs?fmt=css&text=sample" },
+ { url: "sjs_content-type-test-server.sjs?fmt=js&text=sample" },
+ { url: "sjs_content-type-test-server.sjs?fmt=font" },
+ { url: "sjs_content-type-test-server.sjs?fmt=image" },
+ { url: "sjs_content-type-test-server.sjs?fmt=audio" },
+ { url: "sjs_content-type-test-server.sjs?fmt=video" },
+ { url: "sjs_content-type-test-server.sjs?fmt=flash" },
+ { url: "sjs_content-type-test-server.sjs?fmt=ws" },
+];
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(FILTERING_URL, { requestCount: 1 });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSelectedRequest, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ function setFreetextFilter(value) {
+ store.dispatch(Actions.setRequestFilterText(value));
+ }
+
+ info("Starting test... ");
+
+ const wait = waitForNetworkEvents(monitor, 9);
+ await performRequestsInContent(REQUESTS_WITH_MEDIA_AND_FLASH_AND_WS);
+ await wait;
+
+ info("Test with the first request in the list visible");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ testDetailsPanel(true, 0);
+
+ info("Test with first request in the list not visible");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-js-button")
+ );
+ testFilterButtons(monitor, "js");
+ testDetailsPanel(true, 2);
+
+ info(
+ "Test with no request in the list visible i.e. no request match the filters"
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-all-button")
+ );
+ setFreetextFilter("foobar");
+ // The network details panel should not open as there are no available requests visible
+ testDetailsPanel(false);
+
+ await teardown(monitor);
+
+ function getSelectedIndex(state) {
+ if (!state.requests.selectedId) {
+ return -1;
+ }
+ return getSortedRequests(state).findIndex(
+ r => r.id === state.requests.selectedId
+ );
+ }
+
+ function testDetailsPanel(shouldPanelOpen, selectedItemIndex = 0) {
+ // Expected default state should be panel closed
+ ok(
+ !document.querySelector(".sidebar-toggle"),
+ "The pane toggle button should not be visible."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The details pane should still be hidden."
+ );
+ is(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should still be no selected item in the requests menu."
+ );
+
+ // Trigger the details panel toggle action
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ const toggleButton = document.querySelector(".sidebar-toggle");
+
+ if (shouldPanelOpen) {
+ is(
+ toggleButton.classList.contains("pane-collapsed"),
+ false,
+ "The pane toggle button should now indicate that the details pane is " +
+ "not collapsed anymore after being pressed."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The details pane should not be hidden after toggle button was pressed."
+ );
+ isnot(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should be a selected item in the requests menu."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ selectedItemIndex,
+ `The item index ${selectedItemIndex} should be selected in the requests menu.`
+ );
+ // Close the panel
+ EventUtils.sendMouseEvent({ type: "click" }, toggleButton);
+ } else {
+ ok(!toggleButton, "The pane toggle button should be not visible.");
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The details pane should still be hidden."
+ );
+ is(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should still be no selected item in the requests menu."
+ );
+ }
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_pane-toggle.js b/devtools/client/netmonitor/test/browser_net_pane-toggle.js
new file mode 100644
index 0000000000..ab6cb63740
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_pane-toggle.js
@@ -0,0 +1,107 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if toggling the details pane works as expected.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSelectedRequest, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ ok(
+ !document.querySelector(".sidebar-toggle"),
+ "The pane toggle button should not be visible."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The details pane should be hidden when the frontend is opened."
+ );
+ is(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should be no selected item in the requests menu."
+ );
+
+ const networkEvent = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await networkEvent;
+
+ ok(
+ !document.querySelector(".sidebar-toggle"),
+ "The pane toggle button should not be visible after the first request."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The details pane should still be hidden after the first request."
+ );
+ is(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should still be no selected item in the requests menu."
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ const toggleButton = document.querySelector(".sidebar-toggle");
+
+ is(
+ toggleButton.classList.contains("pane-collapsed"),
+ false,
+ "The pane toggle button should now indicate that the details pane is " +
+ "not collapsed anymore."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The details pane should not be hidden after toggle button was pressed."
+ );
+ isnot(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should be a selected item in the requests menu."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ 0,
+ "The first item should be selected in the requests menu."
+ );
+
+ EventUtils.sendMouseEvent({ type: "click" }, toggleButton);
+
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The details pane should now be hidden after the toggle button was pressed again."
+ );
+ is(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should now be no selected item in the requests menu."
+ );
+
+ await teardown(monitor);
+
+ function getSelectedIndex(state) {
+ if (!state.requests.selectedId) {
+ return -1;
+ }
+ return getSortedRequests(state).findIndex(
+ r => r.id === state.requests.selectedId
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_params_sorted.js b/devtools/client/netmonitor/test/browser_net_params_sorted.js
new file mode 100644
index 0000000000..6008909889
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_params_sorted.js
@@ -0,0 +1,83 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests whether keys in Params panel are sorted.
+ */
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(POST_ARRAY_DATA_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ const wait = waitForDOM(document, ".headers-overview");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ clickOnSidebarTab(document, "request");
+
+ // The Params panel should render the following
+ // POSTed JSON data structure:
+ //
+ // ▼ JSON
+ // ▼ watches: […]
+ // 0: hello
+ // 1: how
+ // 2: are
+ // 3: you
+ // ▼ 4: {…}
+ // a: 10
+ // ▼ b: […]
+ // 0: "a"
+ // 1: "c"
+ // 2: "b"
+ // c: 15
+ const expectedKeys = [
+ "watches\t[…]",
+ `0\t"hello"`,
+ `1\t"how"`,
+ `2\t"are"`,
+ `3\t"you"`,
+ "4\t{…}",
+ "a\t10",
+ "b\t[…]",
+ `0\t"a"`,
+ `1\t"c"`,
+ `2\t"b"`,
+ "c\t15",
+ ];
+
+ const waitForTreeRow = waitForDOM(
+ document,
+ ".treeTable .treeRow",
+ expectedKeys.length
+ );
+ await waitForTreeRow;
+ const actualKeys = document.querySelectorAll(".treeTable .treeRow");
+
+ for (let i = 0; i < actualKeys.length; i++) {
+ const text = actualKeys[i].innerText.trim();
+ is(
+ text,
+ expectedKeys[i],
+ "Actual value " +
+ text +
+ " is equal to the " +
+ "expected value " +
+ expectedKeys[i]
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_pause.js b/devtools/client/netmonitor/test/browser_net_pause.js
new file mode 100644
index 0000000000..6ed01efe27
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_pause.js
@@ -0,0 +1,151 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the pause/resume button works.
+ */
+add_task(async function () {
+ const { tab, monitor, toolbox } = await initNetMonitor(PAUSE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const pauseButton = document.querySelector(".requests-list-pause-button");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Make sure we start in a sane state.
+ assertRequestCount(store, 0);
+
+ // Load one request and assert it shows up in the list.
+ await performRequestAndWait(tab, monitor, SIMPLE_URL + "?id=1");
+ assertRequestCount(store, 1);
+
+ let noRequest = true;
+ monitor.panelWin.api.once(TEST_EVENTS.NETWORK_EVENT, () => {
+ noRequest = false;
+ });
+
+ monitor.panelWin.api.once(TEST_EVENTS.NETWORK_EVENT_UPDATED, () => {
+ noRequest = false;
+ });
+
+ // Click pause, load second request and make sure they don't show up.
+ EventUtils.sendMouseEvent({ type: "click" }, pauseButton);
+ await waitForPauseButtonToChange(document, true);
+
+ await performPausedRequest(tab, monitor, toolbox);
+
+ ok(noRequest, "There should be no activity when paused.");
+ assertRequestCount(store, 1);
+
+ // Click pause again to resume monitoring. Load a third request
+ // and make sure they will show up.
+ EventUtils.sendMouseEvent({ type: "click" }, pauseButton);
+ await waitForPauseButtonToChange(document, false);
+
+ await performRequestAndWait(tab, monitor, SIMPLE_URL + "?id=2");
+
+ ok(!noRequest, "There should be activity when resumed.");
+ assertRequestCount(store, 2);
+
+ // Click pause, reload the page and check that there are
+ // some requests.
+ EventUtils.sendMouseEvent({ type: "click" }, pauseButton);
+ await waitForPauseButtonToChange(document, true);
+
+ await waitForAllNetworkUpdateEvents();
+ // Page reload should auto-resume
+ await reloadBrowser();
+ await waitForPauseButtonToChange(document, false);
+ await performRequestAndWait(tab, monitor, SIMPLE_URL + "?id=3");
+
+ ok(!noRequest, "There should be activity when resumed.");
+
+ return teardown(monitor);
+});
+
+/**
+ * Wait until a request is visible in the request list
+ */
+function waitForRequest(doc, url) {
+ return waitUntil(() =>
+ [...doc.querySelectorAll(".request-list-item .requests-list-file")].some(
+ columns => columns.title.includes(url)
+ )
+ );
+}
+
+/**
+ * Waits for the state of the paused/resume button to change.
+ */
+async function waitForPauseButtonToChange(doc, isPaused) {
+ await waitUntil(
+ () =>
+ !!doc.querySelector(
+ `.requests-list-pause-button.devtools-${
+ isPaused ? "play" : "pause"
+ }-icon`
+ )
+ );
+ ok(
+ true,
+ `The pause button is correctly in the ${
+ isPaused ? "paused" : "resumed"
+ } state`
+ );
+}
+
+/**
+ * Asserts the number of requests in the network monitor.
+ */
+function assertRequestCount(store, count) {
+ is(
+ store.getState().requests.requests.length,
+ count,
+ "There should be correct number of requests"
+ );
+}
+
+/**
+ * Execute simple GET request and wait till it's done.
+ */
+async function performRequestAndWait(tab, monitor, requestURL) {
+ const wait = waitForRequest(monitor.panelWin.document, requestURL);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [requestURL],
+ async function (url) {
+ await content.wrappedJSObject.performRequests(url);
+ }
+ );
+ await wait;
+}
+
+/**
+ * Execute simple GET request, and uses a one time listener to
+ * know when the resource is available.
+ */
+async function performPausedRequest(tab, monitor, toolbox) {
+ const { onResource: waitForEventWhenPaused } =
+ await toolbox.resourceCommand.waitForNextResource(
+ toolbox.resourceCommand.TYPES.NETWORK_EVENT,
+ {
+ ignoreExistingResources: true,
+ }
+ );
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [SIMPLE_URL],
+ async function (url) {
+ await content.wrappedJSObject.performRequests(url);
+ }
+ );
+ // Wait for NETWORK_EVENT resources to be fetched, in order to ensure
+ // that there is no pending request related to their processing.
+ await waitForEventWhenPaused;
+}
diff --git a/devtools/client/netmonitor/test/browser_net_persistent_logs.js b/devtools/client/netmonitor/test/browser_net_persistent_logs.js
new file mode 100644
index 0000000000..ed44f8dfd1
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_persistent_logs.js
@@ -0,0 +1,77 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the network monitor leaks on initialization and sudden destruction.
+ * You can also use this initialization format as a template for other tests.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SINGLE_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ Services.prefs.setBoolPref("devtools.netmonitor.persistlog", false);
+
+ await reloadAndWait();
+
+ // Using waitUntil in the test is necessary to ensure all requests are added correctly.
+ // Because reloadAndWait call may catch early uncaught requests from initNetMonitor, so
+ // the actual number of requests after reloadAndWait could be wrong since all requests
+ // haven't finished.
+ await waitUntil(
+ () => document.querySelectorAll(".request-list-item").length === 2
+ );
+ is(
+ document.querySelectorAll(".request-list-item").length,
+ 2,
+ "The request list should have two items at this point."
+ );
+
+ await reloadAndWait();
+
+ await waitUntil(
+ () => document.querySelectorAll(".request-list-item").length === 2
+ );
+ // Since the reload clears the log, we still expect two requests in the log
+ is(
+ document.querySelectorAll(".request-list-item").length,
+ 2,
+ "The request list should still have two items at this point."
+ );
+
+ // Now we toggle the persistence logs on
+ Services.prefs.setBoolPref("devtools.netmonitor.persistlog", true);
+
+ await reloadAndWait();
+
+ await waitUntil(
+ () => document.querySelectorAll(".request-list-item").length === 4
+ );
+ // Since we togged the persistence logs, we expect four items after the reload
+ is(
+ document.querySelectorAll(".request-list-item").length,
+ 4,
+ "The request list should now have four items at this point."
+ );
+
+ Services.prefs.setBoolPref("devtools.netmonitor.persistlog", false);
+ return teardown(monitor);
+
+ /**
+ * Reload the page and wait for 2 GET requests.
+ */
+ async function reloadAndWait() {
+ const wait = waitForNetworkEvents(monitor, 2);
+ await reloadBrowser();
+ return wait;
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_post-data-json-payloads.js b/devtools/client/netmonitor/test/browser_net_post-data-json-payloads.js
new file mode 100644
index 0000000000..9befb3ce49
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_post-data-json-payloads.js
@@ -0,0 +1,105 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the POST requests display the correct information in the UI,
+ * for JSON payloads.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { tab, monitor } = await initNetMonitor(POST_JSON_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ // Wait for header and properties view to be displayed
+ const wait = waitForDOM(document, "#request-panel .data-header");
+ let waitForContent = waitForDOM(document, "#request-panel .properties-view");
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "request");
+ await Promise.all([wait, waitForContent]);
+
+ const tabpanel = document.querySelector("#request-panel");
+
+ ok(
+ tabpanel.querySelector(".treeTable"),
+ "The request params doesn't have the indended visibility."
+ );
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ true,
+ "The request post data doesn't have the indended visibility."
+ );
+ is(
+ tabpanel.querySelectorAll(".raw-data-toggle") !== null,
+ true,
+ "The raw request data toggle should be displayed in this tabpanel."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+
+ is(
+ tabpanel.querySelector(".data-label").textContent,
+ L10N.getStr("jsonScopeName"),
+ "The post section doesn't have the correct title."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ is(labels[0].textContent, "a", "The JSON var name was incorrect.");
+ is(values[0].textContent, "1", "The JSON var value was incorrect.");
+
+ // Toggle the raw data display. This should hide the formatted display.
+ waitForContent = waitForDOM(document, "#request-panel .CodeMirror-code");
+ const rawDataToggle = document.querySelector(
+ "#request-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ clickElement(rawDataToggle, monitor);
+ await waitForContent;
+
+ is(
+ tabpanel.querySelector(".data-label").textContent,
+ L10N.getStr("paramsPostPayload"),
+ "The post section doesn't have the correct title."
+ );
+ is(
+ tabpanel.querySelector(".raw-data-toggle-input .devtools-checkbox-toggle")
+ .checked,
+ true,
+ "The raw request toggle should be on."
+ );
+ is(
+ tabpanel.querySelector(".properties-view") === null,
+ true,
+ "The formatted display should be hidden."
+ );
+ // Bug 1514750 - Show JSON request in plain text view also
+ ok(
+ tabpanel.querySelector(".CodeMirror-code"),
+ "The request post data doesn't have the indended visibility."
+ );
+ ok(
+ getCodeMirrorValue(monitor).includes('{"a":1}'),
+ "The text shown in the source editor is incorrect."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_post-data-raw-payloads-with-upload-stream-headers.js b/devtools/client/netmonitor/test/browser_net_post-data-raw-payloads-with-upload-stream-headers.js
new file mode 100644
index 0000000000..403aa48906
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_post-data-raw-payloads-with-upload-stream-headers.js
@@ -0,0 +1,202 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the POST requests display the correct information in the UI,
+ * for raw payloads with content-type headers attached to the upload stream.
+ */
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { tab, monitor } = await initNetMonitor(POST_RAW_WITH_HEADERS_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 3);
+
+ const expectedRequestsContent = [
+ {
+ headersFromUploadSectionTitle:
+ "Request headers from upload stream (47 B)",
+ uploadSectionHeaders: [
+ { label: "content-type", value: "application/x-www-form-urlencoded" },
+ ],
+ uploadSectionRawText: "content-type: application/x-www-form-urlencoded",
+ requestPanelFormData: [
+ { label: "foo", value: '"bar"' },
+ { label: "baz", value: '"123"' },
+ ],
+ requestPanelPayload: [
+ "content-type: application/x-www-form-urlencoded",
+ "foo=bar&baz=123",
+ ],
+ },
+ {
+ headersFromUploadSectionTitle:
+ "Request headers from upload stream (47 B)",
+ uploadSectionHeaders: [
+ { label: "content-type", value: "application/x-www-form-urlencoded" },
+ ],
+ uploadSectionRawText: "content-type: application/x-www-form-urlencoded",
+ requestPanelPayload: ["content-type: application/x-www-form-urlencoded"],
+ },
+ {
+ headersFromUploadSectionTitle:
+ "Request headers from upload stream (74 B)",
+ uploadSectionHeaders: [
+ { label: "content-type", value: "application/x-www-form-urlencoded" },
+ { label: "custom-header", value: "hello world!" },
+ ],
+ uploadSectionRawText:
+ "content-type: application/x-www-form-urlencoded\r\ncustom-header: hello world!",
+ requestPanelFormData: [
+ { label: "foo", value: '"bar"' },
+ { label: "baz", value: '"123"' },
+ ],
+ requestPanelPayload: [
+ "content-type: application/x-www-form-urlencoded",
+ "custom-header: hello world!",
+ "foo=bar&baz=123",
+ ],
+ },
+ ];
+
+ const requests = document.querySelectorAll(".request-list-item");
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ for (let i = 0; i < expectedRequestsContent.length; i++) {
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[i]);
+ await assertRequestContentInHeaderAndRequestSidePanels(
+ expectedRequestsContent[i]
+ );
+ }
+
+ async function assertRequestContentInHeaderAndRequestSidePanels(expected) {
+ // Wait for all 3 headers sections to load (Response Headers, Request Headers, Request headers from upload stream)
+ let wait = waitForDOM(document, "#headers-panel .accordion-item", 3);
+ clickOnSidebarTab(document, "headers");
+ await wait;
+
+ let tabpanel = document.querySelector("#headers-panel");
+ is(
+ tabpanel.querySelectorAll(".accordion-item").length,
+ 3,
+ "There should be 3 header sections displayed in this tabpanel."
+ );
+
+ info("Check that the Headers in the upload stream section are correct.");
+ is(
+ tabpanel.querySelectorAll(".accordion-item .accordion-header-label")[2]
+ .textContent,
+ expected.headersFromUploadSectionTitle,
+ "The request headers from upload section doesn't have the correct title."
+ );
+
+ let labels = tabpanel.querySelectorAll(
+ ".accordion-item:last-child .accordion-content tr .treeLabelCell .treeLabel"
+ );
+ let values = tabpanel.querySelectorAll(
+ ".accordion-item:last-child .accordion-content tr .treeValueCell .objectBox"
+ );
+
+ for (let i = 0; i < labels.length; i++) {
+ is(
+ labels[i].textContent,
+ expected.uploadSectionHeaders[i].label,
+ "The request header name was incorrect."
+ );
+ is(
+ values[i].textContent,
+ expected.uploadSectionHeaders[i].value,
+ "The request header value was incorrect."
+ );
+ }
+
+ info(
+ "Toggle to open the raw view for the request headers from upload stream"
+ );
+
+ wait = waitForDOM(
+ tabpanel,
+ ".accordion-item:last-child .accordion-content .raw-headers-container"
+ );
+ tabpanel.querySelector("#raw-upload-checkbox").click();
+ await wait;
+
+ const rawTextArea = tabpanel.querySelector(
+ ".accordion-item:last-child .accordion-content .raw-headers"
+ );
+ is(
+ rawTextArea.textContent,
+ expected.uploadSectionRawText,
+ "The raw text for the request headers from upload section is correct"
+ );
+
+ info("Switch to the Request panel");
+
+ wait = waitForDOM(document, "#request-panel .panel-container");
+ clickOnSidebarTab(document, "request");
+ await wait;
+
+ tabpanel = document.querySelector("#request-panel");
+ if (expected.requestPanelFormData) {
+ await waitUntil(
+ () =>
+ tabpanel.querySelector(".data-label").textContent ==
+ L10N.getStr("paramsFormData")
+ );
+
+ labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ for (let i = 0; i < labels.length; i++) {
+ is(
+ labels[i].textContent,
+ expected.requestPanelFormData[i].label,
+ "The form data param name was incorrect."
+ );
+ is(
+ values[i].textContent,
+ expected.requestPanelFormData[i].value,
+ "The form data param value was incorrect."
+ );
+ }
+
+ info("Toggle open the the request payload raw view");
+
+ tabpanel.querySelector("#raw-request-checkbox").click();
+ }
+ await waitUntil(
+ () =>
+ tabpanel.querySelector(".data-label").textContent ==
+ L10N.getStr("paramsPostPayload") &&
+ tabpanel.querySelector(
+ ".panel-container .editor-row-container .CodeMirror-code"
+ )
+ );
+
+ // Check that the expected header lines are included in the codemirror
+ // text.
+ const actualText = tabpanel.querySelector(
+ ".panel-container .editor-row-container .CodeMirror-code"
+ ).textContent;
+ const requestPayloadIsCorrect = expected.requestPanelPayload.every(
+ content => actualText.includes(content)
+ );
+
+ is(requestPayloadIsCorrect, true, "The request payload is not correct");
+ }
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_post-data-raw-payloads.js b/devtools/client/netmonitor/test/browser_net_post-data-raw-payloads.js
new file mode 100644
index 0000000000..505b6840b3
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_post-data-raw-payloads.js
@@ -0,0 +1,89 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the POST requests display the correct information in the UI,
+ * for raw payloads with attached content-type headers.
+ */
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { tab, monitor } = await initNetMonitor(POST_RAW_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ // Wait for raw data toggle to be displayed
+ const wait = waitForDOM(
+ document,
+ "#request-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ clickOnSidebarTab(document, "request");
+ await wait;
+
+ const tabpanel = document.querySelector("#request-panel");
+
+ ok(
+ tabpanel.querySelector(".treeTable"),
+ "The request params doesn't have the intended visibility."
+ );
+ ok(
+ tabpanel.querySelector(".editor-mount") === null,
+ "The request post data doesn't have the indented visibility."
+ );
+
+ is(
+ tabpanel.querySelectorAll(".raw-data-toggle") !== null,
+ true,
+ "The raw request data toggle should be displayed in this tabpanel."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+
+ is(
+ tabpanel.querySelector(".data-label").textContent,
+ L10N.getStr("paramsFormData"),
+ "The post section doesn't have the correct title."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ is(labels[0].textContent, "foo", "The first query param name was incorrect.");
+ is(
+ values[0].textContent,
+ `"bar"`,
+ "The first query param value was incorrect."
+ );
+ is(
+ labels[1].textContent,
+ "baz",
+ "The second query param name was incorrect."
+ );
+ is(
+ values[1].textContent,
+ `"123"`,
+ "The second query param value was incorrect."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_post-data.js b/devtools/client/netmonitor/test/browser_net_post-data.js
new file mode 100644
index 0000000000..a2b54b8d62
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_post-data.js
@@ -0,0 +1,195 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the POST requests display the correct information in the UI.
+ */
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ // Set a higher panel height in order to get full CodeMirror content
+ Services.prefs.setIntPref("devtools.toolbox.footer.height", 600);
+
+ const { tab, monitor } = await initNetMonitor(POST_DATA_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 2);
+
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ }
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[0],
+ "POST",
+ SIMPLE_SJS + "?foo=bar&baz=42&type=urlencoded",
+ {
+ status: 200,
+ statusText: "Och Aye",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 12),
+ time: true,
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[1],
+ "POST",
+ SIMPLE_SJS + "?foo=bar&baz=42&type=multipart",
+ {
+ status: 200,
+ statusText: "Och Aye",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 12),
+ time: true,
+ }
+ );
+
+ // Wait for raw data toggle to be displayed
+ const wait = waitForDOM(
+ document,
+ "#request-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ );
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ clickOnSidebarTab(document, "request");
+ await wait;
+ await testParamsTab("urlencoded");
+
+ // Wait for header and CodeMirror editor to be displayed
+ const waitForHeader = waitForDOM(document, "#request-panel .data-header");
+ const waitForSourceEditor = waitForDOM(
+ document,
+ "#request-panel .CodeMirror-code"
+ );
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[1]
+ );
+ await Promise.all([waitForHeader, waitForSourceEditor]);
+ await testParamsTab("multipart");
+
+ return teardown(monitor);
+
+ async function testParamsTab(type) {
+ const tabpanel = document.querySelector("#request-panel");
+
+ function checkVisibility(box) {
+ is(
+ tabpanel.querySelector(".CodeMirror-code") === null,
+ !box.includes("editor"),
+ "The request post data doesn't have the intended visibility."
+ );
+ }
+
+ is(
+ tabpanel.querySelectorAll(".raw-data-toggle").length,
+ type == "urlencoded" ? 1 : 0,
+ "The display of the raw request data toggle must be correct."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 0,
+ "The empty notice should not be displayed in this tabpanel."
+ );
+
+ is(
+ tabpanel.querySelector(".data-label").textContent,
+ L10N.getStr(
+ type == "urlencoded" ? "paramsFormData" : "paramsPostPayload"
+ ),
+ "The post section doesn't have the correct title."
+ );
+
+ const labels = tabpanel.querySelectorAll("tr .treeLabelCell .treeLabel");
+ const values = tabpanel.querySelectorAll("tr .treeValueCell .objectBox");
+
+ if (type == "urlencoded") {
+ checkVisibility("request");
+ is(
+ labels.length,
+ 2,
+ "There should be 2 param values displayed in this tabpanel."
+ );
+ is(
+ labels[0].textContent,
+ "foo",
+ "The first post param name was incorrect."
+ );
+ is(
+ values[0].textContent,
+ `"bar"`,
+ "The first post param value was incorrect."
+ );
+ is(
+ labels[1].textContent,
+ "baz",
+ "The second post param name was incorrect."
+ );
+ is(
+ values[1].textContent,
+ `"123"`,
+ "The second post param value was incorrect."
+ );
+ } else {
+ checkVisibility("request editor");
+
+ const text = getCodeMirrorValue(monitor);
+
+ ok(
+ text.includes('Content-Disposition: form-data; name="text"'),
+ "The text shown in the source editor is incorrect (1.1)."
+ );
+ ok(
+ text.includes('Content-Disposition: form-data; name="email"'),
+ "The text shown in the source editor is incorrect (2.1)."
+ );
+ ok(
+ text.includes('Content-Disposition: form-data; name="range"'),
+ "The text shown in the source editor is incorrect (3.1)."
+ );
+ ok(
+ text.includes('Content-Disposition: form-data; name="Custom field"'),
+ "The text shown in the source editor is incorrect (4.1)."
+ );
+ ok(
+ text.includes("Some text..."),
+ "The text shown in the source editor is incorrect (2.2)."
+ );
+ ok(
+ text.includes("42"),
+ "The text shown in the source editor is incorrect (3.2)."
+ );
+ ok(
+ text.includes("Extra data"),
+ "The text shown in the source editor is incorrect (4.2)."
+ );
+ }
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_prefs-and-l10n.js b/devtools/client/netmonitor/test/browser_net_prefs-and-l10n.js
new file mode 100644
index 0000000000..aa5c3cac46
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_prefs-and-l10n.js
@@ -0,0 +1,78 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the preferences and localization objects work correctly.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ const { windowRequire } = monitor.panelWin;
+ const { Prefs } = windowRequire("devtools/client/netmonitor/src/utils/prefs");
+
+ testL10N();
+ testPrefs();
+
+ return teardown(monitor);
+
+ function testL10N() {
+ is(
+ typeof L10N.getStr("netmonitor.security.enabled"),
+ "string",
+ "The getStr() method didn't return a valid string."
+ );
+ is(
+ typeof L10N.getFormatStr("networkMenu.totalMS2", "foo"),
+ "string",
+ "The getFormatStr() method didn't return a valid string."
+ );
+ }
+
+ function testPrefs() {
+ is(
+ Prefs.networkDetailsWidth,
+ Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-network-details-width"
+ ),
+ "Getting a pref should work correctly."
+ );
+
+ const previousValue = Prefs.networkDetailsWidth;
+ const bogusValue = ~~(Math.random() * 100);
+ Prefs.networkDetailsWidth = bogusValue;
+ is(
+ Prefs.networkDetailsWidth,
+ Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-network-details-width"
+ ),
+ "Getting a pref after it has been modified should work correctly."
+ );
+ is(
+ Prefs.networkDetailsWidth,
+ bogusValue,
+ "The pref wasn't updated correctly in the preferences object."
+ );
+
+ Prefs.networkDetailsWidth = previousValue;
+ is(
+ Prefs.networkDetailsWidth,
+ Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-network-details-width"
+ ),
+ "Getting a pref after it has been modified again should work correctly."
+ );
+ is(
+ Prefs.networkDetailsWidth,
+ previousValue,
+ "The pref wasn't updated correctly again in the preferences object."
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_prefs-reload.js b/devtools/client/netmonitor/test/browser_net_prefs-reload.js
new file mode 100644
index 0000000000..523c4dc805
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_prefs-reload.js
@@ -0,0 +1,327 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the prefs that should survive across tool reloads work.
+ */
+
+add_task(async function () {
+ let { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+ const Actions = monitor.panelWin.windowRequire(
+ "devtools/client/netmonitor/src/actions/index"
+ );
+ info("Starting test... ");
+
+ // This test reopens the network monitor a bunch of times, for different
+ // hosts (bottom, side, window). This seems to be slow on debug builds.
+ requestLongerTimeout(3);
+
+ // Use these getters instead of caching instances inside the panel win,
+ // since the tool is reopened a bunch of times during this test
+ // and the instances will differ.
+ const getDoc = () => monitor.panelWin.document;
+ const getPrefs = () =>
+ monitor.panelWin.windowRequire("devtools/client/netmonitor/src/utils/prefs")
+ .Prefs;
+ const getStore = () => monitor.panelWin.store;
+ const getState = () => getStore().getState();
+
+ const prefsToCheck = {
+ filters: {
+ // A custom new value to be used for the verified preference.
+ newValue: ["html", "css"],
+ // Getter used to retrieve the current value from the frontend, in order
+ // to verify that the pref was applied properly.
+ validateValue: () =>
+ Object.entries(getState().filters.requestFilterTypes)
+ .filter(([type, check]) => check)
+ .map(([type, check]) => type),
+ // Predicate used to modify the frontend when setting the new pref value,
+ // before trying to validate the changes.
+ modifyFrontend: value =>
+ value.forEach(e =>
+ getStore().dispatch(Actions.toggleRequestFilterType(e))
+ ),
+ },
+ networkDetailsWidth: {
+ newValue: ~~(Math.random() * 200 + 100),
+ validateValue: () =>
+ getDoc().querySelector(".monitor-panel .split-box .controlled")
+ .clientWidth,
+ modifyFrontend(value) {
+ getDoc().querySelector(
+ ".monitor-panel .split-box .controlled"
+ ).style.width = `${value}px`;
+ },
+ },
+ networkDetailsHeight: {
+ newValue: ~~(Math.random() * 300 + 100),
+ validateValue: () =>
+ getDoc().querySelector(".monitor-panel .split-box .controlled")
+ .clientHeight,
+ modifyFrontend(value) {
+ getDoc().querySelector(
+ ".monitor-panel .split-box .controlled"
+ ).style.height = `${value}px`;
+ },
+ },
+ /* add more prefs here... */
+ };
+
+ await testBottom();
+ await testSide();
+ await testWindow();
+
+ info("Moving toolbox back to the bottom...");
+ await monitor.toolbox.switchHost("bottom");
+ return teardown(monitor);
+
+ function storeFirstPrefValues() {
+ info("Caching initial pref values.");
+
+ for (const name in prefsToCheck) {
+ const currentValue = getPrefs()[name];
+ prefsToCheck[name].firstValue = currentValue;
+ }
+ }
+
+ function validateFirstPrefValues(isVerticalSplitter) {
+ info("Validating current pref values to the UI elements.");
+
+ for (const name in prefsToCheck) {
+ if (
+ (isVerticalSplitter && name === "networkDetailsHeight") ||
+ (!isVerticalSplitter && name === "networkDetailsWidth")
+ ) {
+ continue;
+ }
+
+ const currentValue = getPrefs()[name];
+ const { firstValue, validateValue } = prefsToCheck[name];
+
+ is(
+ firstValue.toString(),
+ currentValue.toString(),
+ "Pref " + name + " should be equal to first value: " + currentValue
+ );
+ is(
+ validateValue().toString(),
+ currentValue.toString(),
+ "Pref " + name + " should validate: " + currentValue
+ );
+ }
+ }
+
+ function modifyFrontend(isVerticalSplitter) {
+ info("Modifying UI elements to the specified new values.");
+
+ for (const name in prefsToCheck) {
+ if (
+ (isVerticalSplitter && name === "networkDetailsHeight") ||
+ (!isVerticalSplitter && name === "networkDetailsWidth")
+ ) {
+ continue;
+ }
+
+ const currentValue = getPrefs()[name];
+ const { firstValue, newValue, validateValue } = prefsToCheck[name];
+ const modFrontend = prefsToCheck[name].modifyFrontend;
+
+ modFrontend(newValue);
+ info("Modified UI element affecting " + name + " to: " + newValue);
+
+ is(
+ firstValue.toString(),
+ currentValue.toString(),
+ "Pref " +
+ name +
+ " should still be equal to first value: " +
+ currentValue
+ );
+ isnot(
+ newValue.toString(),
+ currentValue.toString(),
+ "Pref " +
+ name +
+ " should't yet be equal to second value: " +
+ currentValue
+ );
+ is(
+ validateValue().toString(),
+ newValue.toString(),
+ "The UI element affecting " + name + " should validate: " + newValue
+ );
+ }
+ }
+
+ function validateNewPrefValues(isVerticalSplitter) {
+ info("Invalidating old pref values to the modified UI elements.");
+
+ for (const name in prefsToCheck) {
+ if (
+ (isVerticalSplitter && name === "networkDetailsHeight") ||
+ (!isVerticalSplitter && name === "networkDetailsWidth")
+ ) {
+ continue;
+ }
+
+ const currentValue = getPrefs()[name];
+ const { firstValue, newValue, validateValue } = prefsToCheck[name];
+
+ isnot(
+ firstValue.toString(),
+ currentValue.toString(),
+ "Pref " + name + " should't be equal to first value: " + currentValue
+ );
+ is(
+ newValue.toString(),
+ currentValue.toString(),
+ "Pref " + name + " should now be equal to second value: " + currentValue
+ );
+ is(
+ validateValue().toString(),
+ newValue.toString(),
+ "The UI element affecting " + name + " should validate: " + newValue
+ );
+ }
+ }
+
+ function resetFrontend(isVerticalSplitter) {
+ info("Resetting UI elements to the cached initial pref values.");
+
+ for (const name in prefsToCheck) {
+ if (
+ (isVerticalSplitter && name === "networkDetailsHeight") ||
+ (!isVerticalSplitter && name === "networkDetailsWidth")
+ ) {
+ continue;
+ }
+
+ const currentValue = getPrefs()[name];
+ const { firstValue, newValue, validateValue } = prefsToCheck[name];
+ const modFrontend = prefsToCheck[name].modifyFrontend;
+
+ modFrontend(firstValue);
+ info("Modified UI element affecting " + name + " to: " + firstValue);
+
+ isnot(
+ firstValue.toString(),
+ currentValue.toString(),
+ "Pref " +
+ name +
+ " should't yet be equal to first value: " +
+ currentValue
+ );
+ is(
+ newValue.toString(),
+ currentValue.toString(),
+ "Pref " +
+ name +
+ " should still be equal to second value: " +
+ currentValue
+ );
+ is(
+ validateValue().toString(),
+ firstValue.toString(),
+ "The UI element affecting " + name + " should validate: " + firstValue
+ );
+ }
+ }
+
+ async function restartNetMonitorAndSetupEnv() {
+ const newMonitor = await restartNetMonitor(monitor, { requestCount: 1 });
+ monitor = newMonitor.monitor;
+
+ const networkEvent = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await networkEvent;
+
+ const wait = waitForDOM(getDoc(), ".network-details-bar");
+ getStore().dispatch(Actions.toggleNetworkDetails());
+ await wait;
+ }
+
+ async function testBottom() {
+ await restartNetMonitorAndSetupEnv();
+
+ info("Testing prefs reload for a bottom host.");
+ storeFirstPrefValues();
+
+ // Validate and modify while toolbox is on the bottom.
+ validateFirstPrefValues(true);
+ modifyFrontend(true);
+
+ await restartNetMonitorAndSetupEnv();
+
+ // Revalidate and reset frontend while toolbox is on the bottom.
+ validateNewPrefValues(true);
+ resetFrontend(true);
+
+ await restartNetMonitorAndSetupEnv();
+
+ // Revalidate.
+ validateFirstPrefValues(true);
+ }
+
+ async function testSide() {
+ await restartNetMonitorAndSetupEnv();
+
+ info("Moving toolbox to the right...");
+
+ await monitor.toolbox.switchHost("right");
+
+ // Switching hosts is not correctly waiting when DevTools run in content frame
+ // See Bug 1571421.
+ await wait(1000);
+
+ info("Testing prefs reload for a right host.");
+ storeFirstPrefValues();
+
+ // Validate and modify frontend while toolbox is on the side.
+ validateFirstPrefValues(false);
+ modifyFrontend(false);
+
+ await restartNetMonitorAndSetupEnv();
+
+ // Revalidate and reset frontend while toolbox is on the side.
+ validateNewPrefValues(false);
+ resetFrontend(false);
+
+ await restartNetMonitorAndSetupEnv();
+
+ // Revalidate.
+ validateFirstPrefValues(false);
+ }
+
+ async function testWindow() {
+ await restartNetMonitorAndSetupEnv();
+
+ info("Moving toolbox into a window...");
+
+ await monitor.toolbox.switchHost("window");
+
+ // Switching hosts is not correctly waiting when DevTools run in content frame
+ // See Bug 1571421.
+ await wait(1000);
+
+ info("Testing prefs reload for a window host.");
+ storeFirstPrefValues();
+
+ // Validate and modify frontend while toolbox is in a window.
+ validateFirstPrefValues(true);
+ modifyFrontend(true);
+
+ await restartNetMonitorAndSetupEnv();
+
+ // Revalidate and reset frontend while toolbox is in a window.
+ validateNewPrefValues(true);
+ resetFrontend(true);
+
+ await restartNetMonitorAndSetupEnv();
+
+ // Revalidate.
+ validateFirstPrefValues(true);
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_raw_headers.js b/devtools/client/netmonitor/test/browser_net_raw_headers.js
new file mode 100644
index 0000000000..51c6ed7f11
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_raw_headers.js
@@ -0,0 +1,132 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if showing raw headers works.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(POST_DATA_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 2);
+
+ let wait = waitForDOM(document, "#headers-panel .accordion-item", 2);
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ wait = waitForDOM(document, "#responseHeaders textarea.raw-headers", 1);
+ EventUtils.sendMouseEvent({ type: "click" }, getRawHeadersToggle("RESPONSE"));
+ await wait;
+
+ wait = waitForDOM(document, "#requestHeaders textarea.raw-headers", 1);
+ EventUtils.sendMouseEvent({ type: "click" }, getRawHeadersToggle("REQUEST"));
+ await wait;
+
+ testRawHeaderToggleStyle(true);
+ testShowRawHeaders(getSortedRequests(store.getState())[0]);
+
+ EventUtils.sendMouseEvent({ type: "click" }, getRawHeadersToggle("RESPONSE"));
+ EventUtils.sendMouseEvent({ type: "click" }, getRawHeadersToggle("REQUEST"));
+
+ testRawHeaderToggleStyle(false);
+ testHideRawHeaders(document);
+
+ return teardown(monitor);
+
+ /**
+ * Tests that checked is applied correctly
+ *
+ * @param checked
+ * flag indicating whether toggle is checked or not
+ */
+ function testRawHeaderToggleStyle(checked) {
+ const rawHeadersRequestToggle = getRawHeadersToggle("REQUEST");
+ const rawHeadersResponseToggle = getRawHeadersToggle("RESPONSE");
+
+ if (checked) {
+ is(
+ rawHeadersRequestToggle.checked,
+ true,
+ "The 'Raw Request Headers' toggle should be 'checked'"
+ );
+ is(
+ rawHeadersResponseToggle.checked,
+ true,
+ "The 'Raw Response Headers' toggle should be 'checked'"
+ );
+ } else {
+ is(
+ rawHeadersRequestToggle.checked,
+ false,
+ "The 'Raw Request Headers' toggle should NOT be 'checked'"
+ );
+ is(
+ rawHeadersResponseToggle.checked,
+ false,
+ "The 'Raw Response Headers' toggle should NOT be 'checked'"
+ );
+ }
+ }
+
+ /*
+ * Tests that raw headers were displayed correctly
+ */
+ function testShowRawHeaders(data) {
+ // Request headers are rendered first, so it is element with index 1
+ const requestHeaders = document.querySelectorAll("textarea.raw-headers")[1]
+ .value;
+ for (const header of data.requestHeaders.headers) {
+ ok(
+ requestHeaders.includes(header.name + ": " + header.value),
+ "textarea contains request headers"
+ );
+ }
+ // Response headers are rendered first, so it is element with index 0
+ const responseHeaders = document.querySelectorAll("textarea.raw-headers")[0]
+ .value;
+ for (const header of data.responseHeaders.headers) {
+ ok(
+ responseHeaders.includes(header.name + ": " + header.value),
+ "textarea contains response headers"
+ );
+ }
+ }
+
+ /*
+ * Tests that raw headers textareas are hidden
+ */
+ function testHideRawHeaders() {
+ ok(
+ !document.querySelector(".raw-headers-container"),
+ "raw request headers textarea is empty"
+ );
+ }
+
+ /**
+ * Returns the 'Raw Headers' button
+ */
+ function getRawHeadersToggle(rawHeaderType) {
+ if (rawHeaderType === "RESPONSE") {
+ // Response header is first displayed
+ return document.querySelectorAll(".devtools-checkbox-toggle")[0];
+ }
+ return document.querySelectorAll(".devtools-checkbox-toggle")[1];
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_reload-button.js b/devtools/client/netmonitor/test/browser_net_reload-button.js
new file mode 100644
index 0000000000..0111f7e4d3
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_reload-button.js
@@ -0,0 +1,30 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the empty-requests reload button works.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ const { document } = monitor.panelWin;
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-reload-notice-button")
+ );
+ await wait;
+
+ is(
+ document.querySelectorAll(".request-list-item").length,
+ 1,
+ "The request list should have one item after reloading"
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_reload-markers.js b/devtools/client/netmonitor/test/browser_net_reload-markers.js
new file mode 100644
index 0000000000..93b8353ed4
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_reload-markers.js
@@ -0,0 +1,34 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the empty-requests reload button works.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ const { document } = monitor.panelWin;
+
+ const markersDone = waitForTimelineMarkers(monitor);
+
+ const button = document.querySelector(".requests-list-reload-notice-button");
+ button.click();
+
+ await waitForNetworkEvents(monitor, 1);
+ const markers = await markersDone;
+
+ ok(true, "Reloading finished");
+
+ is(
+ markers[0].name,
+ "dom-interactive",
+ "The first received marker is correct."
+ );
+ is(markers[1].name, "dom-complete", "The second received marker is correct.");
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_req-resp-bodies.js b/devtools/client/netmonitor/test/browser_net_req-resp-bodies.js
new file mode 100644
index 0000000000..49d9bbd2b2
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_req-resp-bodies.js
@@ -0,0 +1,83 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if request and response body logging stays on after opening the console.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { tab, monitor } = await initNetMonitor(JSON_LONG_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Perform first batch of requests.
+ await performRequests(monitor, tab, 1);
+
+ await verifyRequest(0);
+
+ // Switch to the webconsole.
+ const onWebConsole = monitor.toolbox.once("webconsole-selected");
+ monitor.toolbox.selectTool("webconsole");
+ await onWebConsole;
+
+ // Switch back to the netmonitor.
+ const onNetMonitor = monitor.toolbox.once("netmonitor-selected");
+ monitor.toolbox.selectTool("netmonitor");
+ await onNetMonitor;
+
+ // Reload debugee.
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ // Perform another batch of requests.
+ await performRequests(monitor, tab, 1);
+
+ await verifyRequest(1);
+
+ return teardown(monitor);
+
+ async function verifyRequest(index) {
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+ }
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[index],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=json-long",
+ {
+ status: 200,
+ statusText: "OK",
+ type: "json",
+ fullMimeType: "text/json; charset=utf-8",
+ size: L10N.getFormatStr(
+ "networkMenu.size.kB",
+ L10N.numberWithDecimals(85975 / 1000, 2)
+ ),
+ time: true,
+ }
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_resend.js b/devtools/client/netmonitor/test/browser_net_resend.js
new file mode 100644
index 0000000000..01940195f7
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_resend.js
@@ -0,0 +1,385 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if resending a request works.
+ */
+
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ await testResendRequest();
+ } else {
+ await testOldEditAndResendPanel();
+ }
+});
+
+// This tests resending a request without editing using
+// the resend context menu item. This particularly covering
+// the new resend functionality.
+async function testResendRequest() {
+ const { tab, monitor } = await initNetMonitor(POST_DATA_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+
+ // Action should be processed synchronously in tests.
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ await performRequests(monitor, tab, 2);
+
+ is(
+ document.querySelectorAll(".request-list-item").length,
+ 2,
+ "There are currently two requests"
+ );
+
+ const firstResend = await resendRequestAndWaitForNewRequest(
+ monitor,
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ ok(
+ firstResend.originalResource.resourceId !==
+ firstResend.newResource.resourceId,
+ "The resent request is different resource from the first request"
+ );
+
+ is(
+ firstResend.originalResource.url,
+ firstResend.newResource.url,
+ "The resent request has the same url and query parameters and the first request"
+ );
+
+ is(
+ firstResend.originalResource.requestHeaders.headers.length,
+ firstResend.newResource.requestHeaders.headers.length,
+ "The no of headers are the same"
+ );
+
+ firstResend.originalResource.requestHeaders.headers.forEach(
+ ({ name, value }) => {
+ const foundHeader = firstResend.newResource.requestHeaders.headers.find(
+ header => header.name == name
+ );
+ is(
+ value,
+ foundHeader.value,
+ `The '${name}' header for the request and the resent request match`
+ );
+ }
+ );
+
+ info("Check that the custom headers and form data are resent correctly");
+ const secondResend = await resendRequestAndWaitForNewRequest(
+ monitor,
+ document.querySelectorAll(".request-list-item")[1]
+ );
+
+ ok(
+ secondResend.originalResource.resourceId !==
+ secondResend.newResource.resourceId,
+ "The resent request is different resource from the second request"
+ );
+
+ const customHeader =
+ secondResend.originalResource.requestHeaders.headers.find(
+ header => header.name == "custom-header-xxx"
+ );
+
+ const customHeaderInResentRequest =
+ secondResend.newResource.requestHeaders.headers.find(
+ header => header.name == "custom-header-xxx"
+ );
+
+ is(
+ customHeader.value,
+ customHeaderInResentRequest.value,
+ "The custom header in the resent request is the same as the second request"
+ );
+
+ is(
+ customHeaderInResentRequest.value,
+ "custom-value-xxx",
+ "The custom header in the resent request is correct"
+ );
+
+ is(
+ secondResend.originalResource.requestPostData.postData.text,
+ secondResend.newResource.requestPostData.postData.text,
+ "The form data in the resent is the same as the second request"
+ );
+}
+
+async function resendRequestAndWaitForNewRequest(monitor, originalRequestItem) {
+ const { document, store, windowRequire, connector } = monitor.panelWin;
+ const { getSelectedRequest, getDisplayedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ info("Select the request to resend");
+ const expectedNoOfRequestsAfterResend =
+ getDisplayedRequests(store.getState()).length + 1;
+
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, originalRequestItem);
+ await waitForHeaders;
+
+ const originalResourceId = getSelectedRequest(store.getState()).id;
+
+ const waitForNewRequest = waitUntil(
+ () =>
+ getDisplayedRequests(store.getState()).length ==
+ expectedNoOfRequestsAfterResend &&
+ getSelectedRequest(store.getState()).id !== originalResourceId
+ );
+
+ info("Open the context menu and select the resend for the request");
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, originalRequestItem);
+ await selectContextMenuItem(monitor, "request-list-context-resend-only");
+ await waitForNewRequest;
+
+ const newResourceId = getSelectedRequest(store.getState()).id;
+
+ // Make sure we fetch the request headers and post data for the
+ // new request so we can assert them.
+ await connector.requestData(newResourceId, "requestHeaders");
+ await connector.requestData(newResourceId, "requestPostData");
+
+ return {
+ originalResource: getRequestById(store.getState(), originalResourceId),
+ newResource: getRequestById(store.getState(), newResourceId),
+ };
+}
+
+// This is a basic test for the old edit and resend panel
+// This should be removed soon in Bug 1745416 when we remove
+// the old panel functionality.
+async function testOldEditAndResendPanel() {
+ const ADD_QUERY = "t1=t2";
+ const ADD_HEADER = "Test-header: true";
+ const ADD_UA_HEADER = "User-Agent: Custom-Agent";
+ const ADD_POSTDATA = "&t3=t4";
+
+ const { tab, monitor } = await initNetMonitor(POST_DATA_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSelectedRequest, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 2);
+
+ const origItemId = getSortedRequests(store.getState())[0].id;
+
+ store.dispatch(Actions.selectRequest(origItemId));
+ await waitForRequestData(
+ store,
+ ["requestHeaders", "requestPostData"],
+ origItemId
+ );
+
+ let origItem = getSortedRequests(store.getState())[0];
+
+ // add a new custom request cloned from selected request
+
+ store.dispatch(Actions.cloneSelectedRequest());
+ await testCustomForm(origItem);
+
+ let customItem = getSelectedRequest(store.getState());
+ testCustomItem(customItem, origItem);
+
+ // edit the custom request
+ await editCustomForm();
+
+ // FIXME: reread the customItem, it's been replaced by a new object (immutable!)
+ customItem = getSelectedRequest(store.getState());
+ testCustomItemChanged(customItem, origItem);
+
+ // send the new request
+ const wait = waitForNetworkEvents(monitor, 1);
+ store.dispatch(Actions.sendCustomRequest());
+ await wait;
+
+ let sentItem;
+ // Testing sent request will require updated requestHeaders and requestPostData,
+ // we must wait for both properties get updated before starting test.
+ await waitUntil(() => {
+ sentItem = getSelectedRequest(store.getState());
+ origItem = getSortedRequests(store.getState())[0];
+ return (
+ sentItem &&
+ sentItem.requestHeaders &&
+ sentItem.requestPostData &&
+ origItem &&
+ origItem.requestHeaders &&
+ origItem.requestPostData
+ );
+ });
+
+ await testSentRequest(sentItem, origItem);
+
+ // Ensure the UI shows the new request, selected, and that the detail panel was closed.
+ is(
+ getSortedRequests(store.getState()).length,
+ 3,
+ "There are 3 requests shown"
+ );
+ is(
+ document
+ .querySelector(".request-list-item.selected")
+ .getAttribute("data-id"),
+ sentItem.id,
+ "The sent request is selected"
+ );
+ is(
+ document.querySelector(".network-details-bar"),
+ null,
+ "The detail panel is hidden"
+ );
+
+ await teardown(monitor);
+
+ function testCustomItem(item, orig) {
+ is(
+ item.method,
+ orig.method,
+ "item is showing the same method as original request"
+ );
+ is(item.url, orig.url, "item is showing the same URL as original request");
+ }
+
+ function testCustomItemChanged(item, orig) {
+ const { url } = item;
+ const expectedUrl = orig.url + "&" + ADD_QUERY;
+
+ is(url, expectedUrl, "menu item is updated to reflect url entered in form");
+ }
+
+ /*
+ * Test that the New Request form was populated correctly
+ */
+ async function testCustomForm(data) {
+ await waitUntil(() => document.querySelector(".custom-request-panel"));
+ is(
+ document.getElementById("custom-method-value").value,
+ data.method,
+ "new request form showing correct method"
+ );
+
+ is(
+ document.getElementById("custom-url-value").value,
+ data.url,
+ "new request form showing correct url"
+ );
+
+ const query = document.getElementById("custom-query-value");
+ is(
+ query.value,
+ "foo=bar\nbaz=42\ntype=urlencoded",
+ "new request form showing correct query string"
+ );
+
+ const headers = document
+ .getElementById("custom-headers-value")
+ .value.split("\n");
+ for (const { name, value } of data.requestHeaders.headers) {
+ ok(
+ headers.includes(name + ": " + value),
+ "form contains header from request"
+ );
+ }
+
+ const postData = document.getElementById("custom-postdata-value");
+ is(
+ postData.value,
+ data.requestPostData.postData.text,
+ "new request form showing correct post data"
+ );
+ }
+
+ /*
+ * Add some params and headers to the request form
+ */
+ async function editCustomForm() {
+ monitor.panelWin.focus();
+
+ const query = document.getElementById("custom-query-value");
+ const queryFocus = once(query, "focus", false);
+ // Bug 1195825: Due to some unexplained dark-matter with promise,
+ // focus only works if delayed by one tick.
+ query.setSelectionRange(query.value.length, query.value.length);
+ executeSoon(() => query.focus());
+ await queryFocus;
+
+ // add params to url query string field
+ typeInNetmonitor(["VK_RETURN"], monitor);
+ typeInNetmonitor(ADD_QUERY, monitor);
+
+ const headers = document.getElementById("custom-headers-value");
+ const headersFocus = once(headers, "focus", false);
+ headers.setSelectionRange(headers.value.length, headers.value.length);
+ headers.focus();
+ await headersFocus;
+
+ // add a header
+ typeInNetmonitor(["VK_RETURN"], monitor);
+ typeInNetmonitor(ADD_HEADER, monitor);
+
+ // add a User-Agent header, to check if default headers can be modified
+ // (there will be two of them, first gets overwritten by the second)
+ typeInNetmonitor(["VK_RETURN"], monitor);
+ typeInNetmonitor(ADD_UA_HEADER, monitor);
+
+ const postData = document.getElementById("custom-postdata-value");
+ const postFocus = once(postData, "focus", false);
+ postData.setSelectionRange(postData.value.length, postData.value.length);
+ postData.focus();
+ await postFocus;
+
+ // add to POST data once textarea has updated
+ await waitUntil(() => postData.textContent !== "");
+ typeInNetmonitor(ADD_POSTDATA, monitor);
+ }
+
+ /*
+ * Make sure newly created event matches expected request
+ */
+ async function testSentRequest(data, origData) {
+ is(data.method, origData.method, "correct method in sent request");
+ is(data.url, origData.url + "&" + ADD_QUERY, "correct url in sent request");
+
+ const { headers } = data.requestHeaders;
+ const hasHeader = headers.some(h => `${h.name}: ${h.value}` == ADD_HEADER);
+ ok(hasHeader, "new header added to sent request");
+
+ const hasUAHeader = headers.some(
+ h => `${h.name}: ${h.value}` == ADD_UA_HEADER
+ );
+ ok(hasUAHeader, "User-Agent header added to sent request");
+
+ is(
+ data.requestPostData.postData.text,
+ origData.requestPostData.postData.text + ADD_POSTDATA,
+ "post data added to sent request"
+ );
+ }
+}
diff --git a/devtools/client/netmonitor/test/browser_net_resend_cors.js b/devtools/client/netmonitor/test/browser_net_resend_cors.js
new file mode 100644
index 0000000000..6d9b42f8e8
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_resend_cors.js
@@ -0,0 +1,132 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if resending a CORS request avoids the security checks and doesn't send
+ * a preflight OPTIONS request (bug 1270096 and friends)
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(HTTPS_CORS_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { store, windowRequire, connector } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getRequestById, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const requestUrl = "https://test1.example.com" + CORS_SJS_PATH;
+
+ info("Waiting for OPTIONS, then POST");
+ const wait = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [requestUrl],
+ async function (url) {
+ content.wrappedJSObject.performRequests(
+ url,
+ "triggering/preflight",
+ "post-data"
+ );
+ }
+ );
+ await wait;
+
+ const METHODS = ["OPTIONS", "POST"];
+ const ITEMS = METHODS.map((val, i) => getSortedRequests(store.getState())[i]);
+
+ // Check the requests that were sent
+ ITEMS.forEach((item, i) => {
+ is(
+ item.method,
+ METHODS[i],
+ `The ${item.method} request has the right method`
+ );
+ is(item.url, requestUrl, `The ${item.method} request has the right URL`);
+ });
+
+ // Resend both requests without modification. Wait for resent OPTIONS, then POST.
+ // POST is supposed to have no preflight OPTIONS request this time (CORS is disabled)
+ const onRequests = waitForNetworkEvents(monitor, 1);
+ for (let item of ITEMS) {
+ info(`Selecting the ${item.method} request`);
+ store.dispatch(Actions.selectRequest(item.id));
+
+ // Wait for requestHeaders and responseHeaders are required when fetching data
+ // from back-end.
+ await waitUntil(() => {
+ item = getRequestById(store.getState(), item.id);
+ return item.requestHeaders && item.responseHeaders;
+ });
+
+ const { length } = getSortedRequests(store.getState());
+
+ info(`Cloning the ${item.method} request into a custom clone`);
+ store.dispatch(Actions.cloneRequest(item.id));
+
+ info("Sending the cloned request (without change)");
+ store.dispatch(Actions.sendCustomRequest(item.id));
+
+ await waitUntil(
+ () => getSortedRequests(store.getState()).length === length + 1
+ );
+ }
+
+ info("Waiting for both resent requests");
+ await onRequests;
+
+ // Check the resent requests
+ for (let i = 0; i < ITEMS.length; i++) {
+ let item = ITEMS[i];
+ is(
+ item.method,
+ METHODS[i],
+ `The ${item.method} request has the right method`
+ );
+ is(item.url, requestUrl, `The ${item.method} request has the right URL`);
+ is(item.status, "200", `The ${item.method} response has the right status`);
+
+ if (item.method === "POST") {
+ is(
+ item.method,
+ "POST",
+ `The ${item.method} request has the right method`
+ );
+
+ // Trigger responseContent update requires to wait until
+ // responseContentAvailable set true
+ await waitUntil(() => {
+ item = getRequestById(store.getState(), item.id);
+ return item.responseContentAvailable;
+ });
+ await connector.requestData(item.id, "responseContent");
+
+ // Wait for both requestPostData & responseContent payloads arrived.
+ await waitUntil(() => {
+ item = getRequestById(store.getState(), item.id);
+ return item.responseContent && item.requestPostData;
+ });
+
+ is(
+ item.requestPostData.postData.text,
+ "post-data",
+ "The POST request has the right POST data"
+ );
+ is(
+ item.responseContent.content.text,
+ "Access-Control-Allow-Origin: *",
+ "The POST response has the right content"
+ );
+ }
+ }
+
+ info("Finishing the test");
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_resend_csp.js b/devtools/client/netmonitor/test/browser_net_resend_csp.js
new file mode 100644
index 0000000000..2b2482b348
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_resend_csp.js
@@ -0,0 +1,153 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if resending an image request uses the same content type
+ * and hence is not blocked by the CSP of the page.
+ */
+
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ ok(
+ true,
+ "Skip this test when pref is true, because this panel won't be default when that is the case."
+ );
+ return;
+ }
+ const { tab, monitor } = await initNetMonitor(CSP_RESEND_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Executes 1 request
+ await performRequests(monitor, tab, 1);
+
+ // Select the image request
+ const imgRequest = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, imgRequest);
+
+ // Stores original request for comparison of values later
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const origReq = getSelectedRequest(store.getState());
+
+ // Context Menu > "Resend"
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, imgRequest);
+
+ const waitForResentRequest = waitForNetworkEvents(monitor, 1);
+ await selectContextMenuItem(monitor, "request-list-context-resend-only");
+ await waitForResentRequest;
+
+ // Selects request that was resent
+ const selReq = getSelectedRequest(store.getState());
+
+ // Finally, some sanity checks
+ ok(selReq.url.endsWith("test-image.png"), "Correct request selected");
+ ok(origReq.url === selReq.url, "Orig and Sel url match");
+
+ ok(selReq.cause.type === "img", "Correct type of selected");
+ ok(origReq.cause.type === selReq.cause.type, "Orig and Sel type match");
+
+ const cspOBJ = await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ return JSON.parse(content.document.cspJSON);
+ });
+
+ const policies = cspOBJ["csp-policies"];
+ is(policies.length, 1, "CSP: should be one policy");
+ const policy = policies[0];
+ is(`${policy["img-src"]}`, "*", "CSP: img-src should be *");
+
+ await teardown(monitor);
+});
+
+/**
+ * Tests if resending an image request uses the same content type
+ * and hence is not blocked by the CSP of the page.
+ */
+
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ const { tab, monitor } = await initNetMonitor(CSP_RESEND_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire(
+ "devtools/client/netmonitor/src/actions/index"
+ );
+ store.dispatch(Actions.batchEnable(false));
+
+ // Executes 1 request
+ await performRequests(monitor, tab, 1);
+
+ // Select the image request
+ const imgRequest = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, imgRequest);
+
+ // Stores original request for comparison of values later
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const origReq = getSelectedRequest(store.getState());
+
+ // Context Menu > "Resend"
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, imgRequest);
+
+ info("Opening the new request panel");
+ const waitForPanels = waitUntil(
+ () =>
+ document.querySelector(".http-custom-request-panel") &&
+ document.querySelector("#http-custom-request-send-button").disabled ===
+ false
+ );
+
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+ await waitForPanels;
+
+ const waitForResentRequest = waitForNetworkEvents(monitor, 1);
+ const buttonSend = document.querySelector(
+ "#http-custom-request-send-button"
+ );
+ buttonSend.click();
+ await waitForResentRequest;
+
+ // Selects request that was resent
+ const selReq = getSelectedRequest(store.getState());
+
+ // Finally, some sanity checks
+ ok(selReq.url.endsWith("test-image.png"), "Correct request selected");
+ ok(origReq.url === selReq.url, "Orig and Sel url match");
+
+ ok(selReq.cause.type === "img", "Correct type of selected");
+ ok(origReq.cause.type === selReq.cause.type, "Orig and Sel type match");
+
+ const cspOBJ = await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [],
+ async () => {
+ return JSON.parse(content.document.cspJSON);
+ }
+ );
+
+ const policies = cspOBJ["csp-policies"];
+ is(policies.length, 1, "CSP: should be one policy");
+ const policy = policies[0];
+ is(`${policy["img-src"]}`, "*", "CSP: img-src should be *");
+
+ await teardown(monitor);
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_resend_headers.js b/devtools/client/netmonitor/test/browser_net_resend_headers.js
new file mode 100644
index 0000000000..3096bcb727
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_resend_headers.js
@@ -0,0 +1,89 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if custom request headers are not ignored (bug 1270096 and friends)
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_SJS, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { store, windowRequire, connector } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { requestData } = connector;
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const requestUrl = HTTPS_SIMPLE_SJS;
+ const requestHeaders = [
+ { name: "Host", value: "fakehost.example.com" },
+ { name: "User-Agent", value: "Testzilla" },
+ { name: "Referer", value: "http://example.com/referrer" },
+ { name: "Accept", value: "application/jarda" },
+ { name: "Accept-Encoding", value: "compress, identity, funcoding" },
+ { name: "Accept-Language", value: "cs-CZ" },
+ ];
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ connector.networkCommand.sendHTTPRequest({
+ url: requestUrl,
+ method: "POST",
+ headers: requestHeaders,
+ body: "Hello",
+ cause: {
+ loadingDocumentUri: "http://example.com",
+ stacktraceAvailable: true,
+ type: "xhr",
+ },
+ });
+ await wait;
+
+ let item = getSortedRequests(store.getState())[0];
+
+ ok(item.requestHeadersAvailable, "headers are available for lazily fetching");
+
+ if (item.requestHeadersAvailable && !item.requestHeaders) {
+ requestData(item.id, "requestHeaders");
+ }
+
+ // Wait until requestHeaders packet gets updated.
+ await waitForRequestData(store, ["requestHeaders"]);
+
+ item = getSortedRequests(store.getState())[0];
+ is(item.method, "POST", "The request has the right method");
+ is(item.url, requestUrl, "The request has the right URL");
+
+ for (const { name, value } of item.requestHeaders.headers) {
+ info(`Request header: ${name}: ${value}`);
+ }
+
+ function hasRequestHeader(name, value) {
+ const { headers } = item.requestHeaders;
+ return headers.some(h => h.name === name && h.value === value);
+ }
+
+ function hasNotRequestHeader(name) {
+ const { headers } = item.requestHeaders;
+ return headers.every(h => h.name !== name);
+ }
+
+ for (const { name, value } of requestHeaders) {
+ ok(hasRequestHeader(name, value), `The ${name} header has the right value`);
+ }
+
+ // Check that the Cookie header was not added silently (i.e., that the request is
+ // anonymous.
+ for (const name of ["Cookie"]) {
+ ok(hasNotRequestHeader(name), `The ${name} header is not present`);
+ }
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_resend_hidden_headers.js b/devtools/client/netmonitor/test/browser_net_resend_hidden_headers.js
new file mode 100644
index 0000000000..ea5ca7b36c
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_resend_hidden_headers.js
@@ -0,0 +1,88 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that custom request headers are sent even without clicking on the original request (bug 1583397)
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { store, windowRequire, connector } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const requestUrl = HTTPS_SIMPLE_SJS;
+ const requestHeaders = [
+ { name: "Accept", value: "application/vnd.example+json" },
+ ];
+
+ const originalRequest = waitForNetworkEvents(monitor, 1);
+ connector.networkCommand.sendHTTPRequest({
+ url: requestUrl,
+ method: "GET",
+ headers: requestHeaders,
+ cause: {
+ loadingDocumentUri: "http://example.com",
+ stacktraceAvailable: true,
+ type: "xhr",
+ },
+ });
+ await originalRequest;
+
+ info("Sent original request");
+
+ const originalItem = getSortedRequests(store.getState())[0];
+
+ store.dispatch(Actions.cloneRequest(originalItem.id));
+
+ const clonedRequest = waitForNetworkEvents(monitor, 1);
+
+ store.dispatch(Actions.sendCustomRequest(originalItem.id));
+
+ await clonedRequest;
+
+ info("Resent request");
+
+ let clonedItem = getSortedRequests(store.getState())[1];
+
+ await waitForRequestData(store, ["requestHeaders"], clonedItem.id);
+
+ clonedItem = getSortedRequests(store.getState())[1];
+
+ for (const { name, value } of clonedItem.requestHeaders.headers) {
+ info(`Request header: ${name}: ${value}`);
+ }
+
+ function hasRequestHeader(name, value) {
+ const { headers } = clonedItem.requestHeaders;
+ return headers.some(h => h.name === name && h.value === value);
+ }
+
+ function hasNotRequestHeader(name) {
+ const { headers } = clonedItem.requestHeaders;
+ return headers.every(h => h.name !== name);
+ }
+
+ for (const { name, value } of requestHeaders) {
+ ok(hasRequestHeader(name, value), `The ${name} header has the right value`);
+ }
+
+ // Check that the Cookie header was not added silently (i.e., that the request is
+ // anonymous.
+ for (const name of ["Cookie"]) {
+ ok(hasNotRequestHeader(name), `The ${name} header is not present`);
+ }
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_resend_xhr.js b/devtools/client/netmonitor/test/browser_net_resend_xhr.js
new file mode 100644
index 0000000000..8de15f071a
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_resend_xhr.js
@@ -0,0 +1,57 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if resending a request works.
+ */
+
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ ok(
+ true,
+ "Skip this test when pref is true, because this panel won't be default when that is the case."
+ );
+ return;
+ }
+ const { tab, monitor } = await initNetMonitor(POST_RAW_URL, {
+ requestCount: 1,
+ });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Executes 1 request
+ await performRequests(monitor, tab, 1);
+
+ // Selects 1st request
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+
+ // Stores original request for comparison of values later
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const originalRequest = getSelectedRequest(store.getState());
+
+ const waitForResentRequestEvent = waitForNetworkEvents(monitor, 1);
+ // Context Menu > "Resend"
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequest);
+ await selectContextMenuItem(monitor, "request-list-context-resend-only");
+ await waitForResentRequestEvent;
+
+ // Selects request that was resent
+ const selectedRequest = getSelectedRequest(store.getState());
+
+ // Compares if the requests are the same.
+ ok(originalRequest.url === selectedRequest.url, "Both requests are the same");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_response_CORS_blocked.js b/devtools/client/netmonitor/test/browser_net_response_CORS_blocked.js
new file mode 100644
index 0000000000..d3dd72e6f7
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_response_CORS_blocked.js
@@ -0,0 +1,117 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that requests blocked by CORS have a notification in the response panel
+ * and that it is not present when requests are not blocked
+ */
+
+add_task(async function testCORSNotificationPresent() {
+ info("Test that CORS notification is present");
+
+ const { tab, monitor } = await initNetMonitor(HTTPS_CORS_URL, {
+ requestCount: 1,
+ });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+
+ info("making request to a origin that doesn't allow cross origin");
+ const requestUrl = HTTPS_EXAMPLE_ORG_URL + "sjs_simple-test-server.sjs";
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [requestUrl],
+ async function (url) {
+ content.wrappedJSObject.performRequests(
+ url,
+ "triggering/preflight",
+ "post-data"
+ );
+ }
+ );
+
+ info("Waiting until the requests appear in netmonitor");
+ await wait;
+
+ info("selecting first request");
+ const firstItem = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstItem);
+
+ const waitForRespPanel = waitForDOM(
+ document,
+ "#response-panel .notification"
+ );
+
+ info("switching to response panel");
+ const respPanelButton = document.querySelector("#response-tab");
+ EventUtils.sendMouseEvent({ type: "click" }, respPanelButton);
+ await waitForRespPanel;
+
+ info("selecting CORS notification");
+ const CORSNotification = document.querySelector(
+ '#response-panel .notification[data-key="CORS-error"] .messageText'
+ );
+ ok(CORSNotification, "CORS Notification Present");
+ is(
+ CORSNotification?.innerText,
+ "Response body is not available to scripts (Reason: CORS Missing Allow Origin)",
+ "Notification text is correct"
+ );
+
+ await teardown(monitor);
+});
+
+add_task(async function testCORSNotificationNotPresent() {
+ info("Test that CORS notification is not present");
+ const { tab, monitor } = await initNetMonitor(CORS_URL, {
+ requestCount: 1,
+ });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+
+ info("Making request to a origin that allows cross origin");
+ const requestUrl = "https://test1.example.com" + CORS_SJS_PATH;
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [requestUrl],
+ async function (url) {
+ content.wrappedJSObject.performRequests(
+ url,
+ "triggering/preflight",
+ "post-data"
+ );
+ }
+ );
+ info("waiting for requests to appear in netmonitor");
+ await wait;
+
+ info("selecting first request");
+ const firstItem = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstItem);
+
+ const waitForRespPanel = waitForDOM(document, "#response-panel");
+
+ info("switching to response panel");
+ const respPanelButton = document.querySelector("#response-tab");
+ EventUtils.sendMouseEvent({ type: "click" }, respPanelButton);
+ await waitForRespPanel;
+
+ info("try to select CORS notification");
+ const CORSNotification = document.querySelector(
+ '#response-panel .notification[data-key="CORS-error"] .messageText'
+ );
+ ok(!CORSNotification, "CORS notification not present");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_response_node-expanded.js b/devtools/client/netmonitor/test/browser_net_response_node-expanded.js
new file mode 100644
index 0000000000..734b84d3bc
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_response_node-expanded.js
@@ -0,0 +1,57 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the node that was expanded is still expanded when we are filtering
+ * in the Response Panel.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(JSON_LONG_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ await performRequests(monitor, tab, 1);
+
+ info("selecting first request");
+ const firstRequestItem = document.querySelectorAll(".request-list-item")[0];
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequestItem);
+
+ info("switching to response panel");
+ const waitForRespPanel = waitForDOM(
+ document,
+ "#response-panel .properties-view"
+ );
+ const respPanelButton = document.querySelector("#response-tab");
+ respPanelButton.click();
+ await waitForRespPanel;
+
+ const firstRow = document.querySelector(
+ "#response-panel tr.treeRow.objectRow"
+ );
+ const waitOpenNode = waitForDOM(document, "tr#\\/0\\/greeting");
+ const toggleButton = firstRow.querySelector("td span.treeIcon");
+
+ toggleButton.click();
+ await waitOpenNode;
+
+ is(firstRow.classList.contains("opened"), true, "the node is open");
+
+ document.querySelector("#response-panel .devtools-filterinput").focus();
+ EventUtils.sendString("greeting");
+
+ // Wait till there are 2048 resources rendered in the results.
+ await waitForDOMIfNeeded(document, "#response-panel tr.treeRow", 2048);
+
+ is(firstRow.classList.contains("opened"), true, "the node remains open");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_search-results.js b/devtools/client/netmonitor/test/browser_net_search-results.js
new file mode 100644
index 0000000000..b3fd21ec98
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_search-results.js
@@ -0,0 +1,233 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test search match functionality.
+ * Search panel is visible and clicking matches shows them in the request details.
+ */
+
+add_task(async function () {
+ await pushPref("devtools.netmonitor.features.search", true);
+
+ const { tab, monitor } = await initNetMonitor(HTTPS_CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+
+ // Action should be processed synchronously in tests.
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const SEARCH_STRING = "test";
+ // Execute two XHRs and wait until they are finished.
+ const URLS = [
+ HTTPS_SEARCH_SJS + "?value=test1",
+ HTTPS_SEARCH_SJS + "?value=test2",
+ ];
+
+ const wait = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(tab.linkedBrowser, [URLS], makeRequests);
+ await wait;
+
+ // Open the Search panel
+ await store.dispatch(Actions.openSearch());
+
+ // Fill Filter input with text and check displayed messages.
+ // The filter should be focused automatically.
+ typeInNetmonitor(SEARCH_STRING, monitor);
+ EventUtils.synthesizeKey("KEY_Enter");
+
+ // Wait until there are two resources rendered in the results
+ await waitForDOMIfNeeded(
+ document,
+ ".search-panel-content .treeRow.resourceRow",
+ 2
+ );
+
+ const searchMatchContents = document.querySelectorAll(
+ ".search-panel-content .treeRow .treeIcon"
+ );
+
+ for (let i = searchMatchContents.length - 1; i >= 0; i--) {
+ clickElement(searchMatchContents[i], monitor);
+ }
+
+ // Wait until there are two resources rendered in the results
+ await waitForDOMIfNeeded(
+ document,
+ ".search-panel-content .treeRow.resultRow",
+ 12
+ );
+
+ // Check the matches
+ const matches = document.querySelectorAll(
+ ".search-panel-content .treeRow.resultRow"
+ );
+
+ await checkSearchResult(
+ monitor,
+ matches[0],
+ "#headers-panel",
+ ".url-preview .properties-view",
+ ".treeRow",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[1],
+ "#headers-panel",
+ "#responseHeaders .properties-view",
+ ".treeRow.selected",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[2],
+ "#headers-panel",
+ "#requestHeaders .properties-view",
+ ".treeRow.selected",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[3],
+ "#cookies-panel",
+ "#responseCookies .properties-view",
+ ".treeRow.selected",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[4],
+ "#response-panel",
+ ".CodeMirror-code",
+ ".CodeMirror-activeline",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[5],
+ "#headers-panel",
+ ".url-preview .properties-view",
+ ".treeRow",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[6],
+ "#headers-panel",
+ "#responseHeaders .properties-view",
+ ".treeRow.selected",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[7],
+ "#headers-panel",
+ "#requestHeaders .properties-view",
+ ".treeRow.selected",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[8],
+ "#headers-panel",
+ "#requestHeaders .properties-view",
+ ".treeRow.selected",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[9],
+ "#cookies-panel",
+ "#responseCookies .properties-view",
+ ".treeRow.selected",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[10],
+ "#cookies-panel",
+ "#requestCookies .properties-view",
+ ".treeRow.selected",
+ [SEARCH_STRING]
+ );
+ await checkSearchResult(
+ monitor,
+ matches[11],
+ "#response-panel",
+ ".CodeMirror-code",
+ ".CodeMirror-activeline",
+ [SEARCH_STRING]
+ );
+
+ await teardown(monitor);
+});
+
+async function makeRequests(urls) {
+ await content.wrappedJSObject.get(urls[0]);
+ await content.wrappedJSObject.get(urls[1]);
+ info("XHR Requests executed");
+}
+
+/**
+ * Check whether the search result is correctly linked with the related information
+ */
+async function checkSearchResult(
+ monitor,
+ match,
+ panelSelector,
+ panelContentSelector,
+ panelDetailSelector,
+ expected
+) {
+ const { document } = monitor.panelWin;
+
+ // Scroll the match into view so that it's clickable
+ match.scrollIntoView();
+
+ // Click on the match to show it
+ clickElement(match, monitor);
+
+ console.log(`${panelSelector} ${panelContentSelector}`);
+ await waitFor(() =>
+ document.querySelector(`${panelSelector} ${panelContentSelector}`)
+ );
+
+ const tabpanel = document.querySelector(panelSelector);
+ const content = tabpanel.querySelectorAll(
+ `${panelContentSelector} ${panelDetailSelector}`
+ );
+
+ is(
+ content.length,
+ expected.length,
+ `There should be ${expected.length} item${
+ expected.length === 1 ? "" : "s"
+ } displayed in this tabpanel`
+ );
+
+ // Make sure only 1 item is selected
+ if (panelDetailSelector === ".treeRow.selected") {
+ const selectedElements = tabpanel.querySelectorAll(panelDetailSelector);
+ is(
+ selectedElements.length,
+ 1,
+ `There should be only 1 item selected, found ${selectedElements.length} items selected`
+ );
+ }
+
+ if (content.length === expected.length) {
+ for (let i = 0; i < expected.length; i++) {
+ is(
+ content[i].textContent.includes(expected[i]),
+ true,
+ `Content must include ${expected[i]}`
+ );
+ }
+ }
+}
diff --git a/devtools/client/netmonitor/test/browser_net_security-details.js b/devtools/client/netmonitor/test/browser_net_security-details.js
new file mode 100644
index 0000000000..0dda9badf1
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_security-details.js
@@ -0,0 +1,116 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that Security details tab contains the expected data.
+ */
+
+add_task(async function () {
+ await pushPref("security.pki.certificate_transparency.mode", 1);
+
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Performing a secure request.");
+ const REQUESTS_URL = "https://example.com" + CORS_SJS_PATH;
+ const wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [REQUESTS_URL],
+ async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ }
+ );
+ await wait;
+
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "security");
+ await waitUntil(() =>
+ document.querySelector("#security-panel .security-info-value")
+ );
+
+ const tabpanel = document.querySelector("#security-panel");
+ const textboxes = tabpanel.querySelectorAll(".security-info-value");
+
+ // Connection
+ // The protocol will be TLS but the exact version depends on which protocol
+ // the test server example.com supports.
+ const protocol = textboxes[0].textContent;
+ ok(protocol.startsWith('"TLS'), "The protocol " + protocol + " seems valid.");
+
+ // The cipher suite used by the test server example.com might change at any
+ // moment but all of them should start with "TLS_".
+ // http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml
+ const suite = textboxes[1].textContent;
+ ok(suite.startsWith('"TLS_'), "The suite " + suite + " seems valid.");
+
+ // Host
+ is(
+ tabpanel.querySelectorAll(".treeLabel.objectLabel")[1].textContent,
+ "Host example.com:",
+ "Label has the expected value."
+ );
+ // These two values can change. So only check they're not empty.
+ ok(textboxes[2].textContent !== "", "Label value is not empty.");
+ ok(textboxes[3].textContent !== "", "Label value is not empty.");
+ is(textboxes[4].textContent, '"Disabled"', "Label has the expected value.");
+ is(textboxes[5].textContent, '"Disabled"', "Label has the expected value.");
+
+ // Cert
+ is(
+ textboxes[6].textContent,
+ '"example.com"',
+ "Label has the expected value."
+ );
+ is(
+ textboxes[7].textContent,
+ '"<Not Available>"',
+ "Label has the expected value."
+ );
+ is(
+ textboxes[8].textContent,
+ '"<Not Available>"',
+ "Label has the expected value."
+ );
+
+ is(
+ textboxes[9].textContent,
+ '"Temporary Certificate Authority"',
+ "Label has the expected value."
+ );
+ is(
+ textboxes[10].textContent,
+ '"Mozilla Testing"',
+ "Label has the expected value."
+ );
+ is(
+ textboxes[11].textContent,
+ '"Profile Guided Optimization"',
+ "Label has the expected value."
+ );
+
+ // Locale sensitive and varies between timezones. Can't compare equality or
+ // the test fails depending on which part of the world the test is executed.
+
+ // cert validity begins
+ isnot(textboxes[12].textContent, "", "Label was not empty.");
+ // cert validity expires
+ isnot(textboxes[13].textContent, "", "Label was not empty.");
+
+ // cert sha1 fingerprint
+ isnot(textboxes[14].textContent, "", "Label was not empty.");
+ // cert sha256 fingerprint
+ isnot(textboxes[15].textContent, "", "Label was not empty.");
+
+ // Certificate transparency
+ isnot(textboxes[16].textContent, "", "Label was not empty.");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_security-error.js b/devtools/client/netmonitor/test/browser_net_security-error.js
new file mode 100644
index 0000000000..19959d7671
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_security-error.js
@@ -0,0 +1,38 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that Security details tab shows an error message with broken connections.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Requesting a resource that has a certificate problem.");
+
+ const requestsDone = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.performRequests(1, "https://nocert.example.com");
+ });
+ await requestsDone;
+
+ const securityInfoLoaded = waitForDOM(document, ".security-info-value");
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ await waitUntil(() => document.querySelector("#security-tab"));
+ clickOnSidebarTab(document, "security");
+ await securityInfoLoaded;
+
+ const errormsg = document.querySelector(".security-info-value");
+ isnot(errormsg.textContent, "", "Error message is not empty.");
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_security-icon-click.js b/devtools/client/netmonitor/test/browser_net_security-icon-click.js
new file mode 100644
index 0000000000..a51638e68d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_security-icon-click.js
@@ -0,0 +1,75 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that clicking on the security indicator opens the security details tab.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Requesting a resource over HTTPS.");
+ await performRequestAndWait(
+ "https://example.com" + CORS_SJS_PATH + "?request_2"
+ );
+ await performRequestAndWait(
+ "https://example.com" + CORS_SJS_PATH + "?request_1"
+ );
+
+ is(store.getState().requests.requests.length, 2, "Two events event logged.");
+
+ await clickAndTestSecurityIcon();
+
+ info("Selecting headers panel again.");
+ clickOnSidebarTab(document, "headers");
+
+ info("Sorting the items by filename.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-file-button")
+ );
+
+ info(
+ "Testing that security icon can be clicked after the items were sorted."
+ );
+
+ await clickAndTestSecurityIcon();
+
+ return teardown(monitor);
+
+ async function performRequestAndWait(url) {
+ const wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [{ url }],
+ async function (args) {
+ content.wrappedJSObject.performRequests(1, args.url);
+ }
+ );
+ return wait;
+ }
+
+ async function clickAndTestSecurityIcon() {
+ const icon = document.querySelector(".requests-security-state-icon");
+ info(
+ "Clicking security icon of the first request and waiting for panel update."
+ );
+ EventUtils.synthesizeMouseAtCenter(icon, {}, monitor.panelWin);
+ await waitUntil(() =>
+ document.querySelector("#security-panel .security-info-value")
+ );
+
+ ok(
+ document.querySelector("#security-tab[aria-selected=true]"),
+ "Security tab is selected."
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_security-redirect.js b/devtools/client/netmonitor/test/browser_net_security-redirect.js
new file mode 100644
index 0000000000..3ab7211fe4
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_security-redirect.js
@@ -0,0 +1,67 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test a http -> https redirect shows secure icon only for redirected https
+ * request.
+ */
+
+add_task(async function () {
+ // This test explicitly asserts http -> https redirects.
+ await pushPref("dom.security.https_first", false);
+
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [HTTPS_REDIRECT_SJS],
+ async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ }
+ );
+ await wait;
+
+ is(
+ store.getState().requests.requests.length,
+ 2,
+ "There were two requests due to redirect."
+ );
+
+ const [
+ initialDomainSecurityIcon,
+ initialUrlSecurityIcon,
+ redirectDomainSecurityIcon,
+ redirectUrlSecurityIcon,
+ ] = document.querySelectorAll(".requests-security-state-icon");
+
+ ok(
+ initialDomainSecurityIcon.classList.contains("security-state-insecure"),
+ "Initial request was marked insecure for domain column."
+ );
+
+ ok(
+ redirectDomainSecurityIcon.classList.contains("security-state-secure"),
+ "Redirected request was marked secure for domain column."
+ );
+
+ ok(
+ initialUrlSecurityIcon.classList.contains("security-state-insecure"),
+ "Initial request was marked insecure for URL column."
+ );
+
+ ok(
+ redirectUrlSecurityIcon.classList.contains("security-state-secure"),
+ "Redirected request was marked secure for URL column."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_security-state.js b/devtools/client/netmonitor/test/browser_net_security-state.js
new file mode 100644
index 0000000000..29d40b3058
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_security-state.js
@@ -0,0 +1,109 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that correct security state indicator appears depending on the security
+ * state.
+ */
+
+add_task(async function () {
+ // This test explicitly asserts some insecure domains.
+ await pushPref("dom.security.https_first", false);
+
+ const EXPECTED_SECURITY_STATES = {
+ "test1.example.com": "security-state-insecure",
+ "example.com": "security-state-secure",
+ "nocert.example.com": "security-state-broken",
+ localhost: "security-state-secure",
+ };
+
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ await performRequests();
+
+ for (const subitemNode of Array.from(
+ document.querySelectorAll(".requests-list-column.requests-list-domain")
+ )) {
+ // Skip header
+ const icon = subitemNode.querySelector(".requests-security-state-icon");
+ if (!icon) {
+ continue;
+ }
+
+ const domain = subitemNode.textContent;
+ info("Found a request to " + domain);
+
+ const classes = icon.classList;
+ const expectedClass = EXPECTED_SECURITY_STATES[domain];
+
+ info("Classes of security state icon are: " + classes);
+ info("Security state icon is expected to contain class: " + expectedClass);
+ ok(
+ classes.contains(expectedClass),
+ "Icon contained the correct class name."
+ );
+ }
+
+ return teardown(monitor);
+
+ /**
+ * A helper that performs requests to
+ * - https://nocert.example.com (broken)
+ * - https://example.com (secure)
+ * - http://test1.example.com (insecure)
+ * - http://localhost (local)
+ * and waits until NetworkMonitor has handled all packets sent by the server.
+ */
+ async function performRequests() {
+ function executeRequests(count, url) {
+ return SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [{ count, url }],
+ async function (args) {
+ content.wrappedJSObject.performRequests(args.count, args.url);
+ }
+ );
+ }
+
+ let done = waitForNetworkEvents(monitor, 1);
+ info("Requesting a resource that has a certificate problem.");
+ await executeRequests(1, "https://nocert.example.com");
+
+ // Wait for the request to complete before firing another request. Otherwise
+ // the request with security issues interfere with waitForNetworkEvents.
+ info("Waiting for request to complete.");
+ await done;
+
+ // Next perform a request over HTTP. If done the other way around the latter
+ // occasionally hangs waiting for event timings that don't seem to appear...
+ done = waitForNetworkEvents(monitor, 1);
+ info("Requesting a resource over HTTP.");
+ await executeRequests(1, "http://test1.example.com" + CORS_SJS_PATH);
+ await done;
+
+ done = waitForNetworkEvents(monitor, 1);
+ info("Requesting a resource over HTTPS.");
+ await executeRequests(1, "https://example.com" + CORS_SJS_PATH);
+ await done;
+
+ done = waitForNetworkEvents(monitor, 1);
+ info("Requesting a resource over HTTP to localhost.");
+ await executeRequests(1, "http://localhost" + CORS_SJS_PATH);
+ await done;
+
+ const expectedCount = Object.keys(EXPECTED_SECURITY_STATES).length;
+ is(
+ store.getState().requests.requests.length,
+ expectedCount,
+ expectedCount + " events logged."
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_security-tab-deselect.js b/devtools/client/netmonitor/test/browser_net_security-tab-deselect.js
new file mode 100644
index 0000000000..ac4750e564
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_security-tab-deselect.js
@@ -0,0 +1,67 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that security details tab is no longer selected if an insecure request
+ * is selected.
+ */
+
+add_task(async function () {
+ // This test needs to trigger http and https requests.
+ // Disable https-first to avoid blocking the HTTP request due to mixed content.
+ await pushPref("dom.security.https_first", false);
+
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Performing requests.");
+ let wait = waitForNetworkEvents(monitor, 2);
+ const REQUEST_URLS = [
+ "https://example.com" + CORS_SJS_PATH,
+ "http://example.com" + CORS_SJS_PATH,
+ ];
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [REQUEST_URLS],
+ async function (urls) {
+ for (const url of urls) {
+ content.wrappedJSObject.performRequests(1, url);
+ }
+ }
+ );
+ await wait;
+
+ info("Selecting secure request.");
+ wait = waitForDOM(document, ".tabs");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ info("Selecting security tab.");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelector("#security-tab")
+ );
+
+ info("Selecting insecure request.");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[1]
+ );
+
+ ok(
+ document.querySelector("#headers-tab[aria-selected=true]"),
+ "Selected tab was reset when selected security tab was hidden."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_security-tab-visibility.js b/devtools/client/netmonitor/test/browser_net_security-tab-visibility.js
new file mode 100644
index 0000000000..8ffc8efd50
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_security-tab-visibility.js
@@ -0,0 +1,142 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that security details tab is visible only when it should.
+ */
+
+add_task(async function () {
+ // This test explicitly asserts some insecure domains.
+ await pushPref("dom.security.https_first", false);
+
+ const TEST_DATA = [
+ {
+ desc: "http request",
+ uri: "http://example.com" + CORS_SJS_PATH,
+ visibleOnNewEvent: false,
+ visibleOnSecurityInfo: false,
+ visibleOnceComplete: false,
+ securityState: "insecure",
+ },
+ {
+ desc: "working https request",
+ uri: "https://example.com" + CORS_SJS_PATH,
+ visibleOnNewEvent: true,
+ visibleOnSecurityInfo: true,
+ visibleOnceComplete: true,
+ securityState: "secure",
+ },
+ {
+ desc: "broken https request",
+ uri: "https://nocert.example.com",
+ isBroken: true,
+ visibleOnNewEvent: true,
+ visibleOnSecurityInfo: true,
+ visibleOnceComplete: true,
+ securityState: "broken",
+ },
+ ];
+
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSelectedRequest } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ for (const testcase of TEST_DATA) {
+ info("Testing Security tab visibility for " + testcase.desc);
+ const onNewItem = monitor.panelWin.api.once(TEST_EVENTS.NETWORK_EVENT);
+ const onComplete = testcase.isBroken
+ ? waitForSecurityBrokenNetworkEvent()
+ : waitForNetworkEvents(monitor, 1);
+
+ info("Performing a request to " + testcase.uri);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [testcase.uri],
+ async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ }
+ );
+
+ info("Waiting for new network event.");
+ await onNewItem;
+
+ info("Waiting for request to complete.");
+ await onComplete;
+
+ info("Selecting the request.");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ is(
+ getSelectedRequest(store.getState()).securityState,
+ testcase.securityState,
+ "Security state is immediately set"
+ );
+ is(
+ !!document.querySelector("#security-tab"),
+ testcase.visibleOnNewEvent,
+ "Security tab is " +
+ (testcase.visibleOnNewEvent ? "visible" : "hidden") +
+ " after new request was added to the menu."
+ );
+
+ if (testcase.visibleOnSecurityInfo) {
+ // click security panel to lazy load the securityState
+ await waitUntil(() => document.querySelector("#security-tab"));
+ clickOnSidebarTab(document, "security");
+ await waitUntil(() =>
+ document.querySelector("#security-panel .security-info-value")
+ );
+ info("Waiting for security information to arrive.");
+
+ await waitUntil(
+ () => !!getSelectedRequest(store.getState()).securityState
+ );
+ }
+
+ is(
+ !!document.querySelector("#security-tab"),
+ testcase.visibleOnSecurityInfo,
+ "Security tab is " +
+ (testcase.visibleOnSecurityInfo ? "visible" : "hidden") +
+ " after security information arrived."
+ );
+
+ is(
+ !!document.querySelector("#security-tab"),
+ testcase.visibleOnceComplete,
+ "Security tab is " +
+ (testcase.visibleOnceComplete ? "visible" : "hidden") +
+ " after request has been completed."
+ );
+
+ await clearNetworkEvents(monitor);
+ }
+
+ return teardown(monitor);
+
+ /**
+ * Returns a promise that's resolved once a request with security issues is
+ * completed.
+ */
+ function waitForSecurityBrokenNetworkEvent() {
+ const awaitedEvents = ["UPDATING_EVENT_TIMINGS", "RECEIVED_EVENT_TIMINGS"];
+
+ const promises = awaitedEvents.map(event => {
+ return monitor.panelWin.api.once(EVENTS[event]);
+ });
+
+ return Promise.all(promises);
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_security-warnings.js b/devtools/client/netmonitor/test/browser_net_security-warnings.js
new file mode 100644
index 0000000000..dfb6e9bef8
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_security-warnings.js
@@ -0,0 +1,66 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that warning indicators are shown when appropriate.
+ */
+
+const TEST_CASES = [
+ {
+ desc: "no warnings",
+ uri: "https://example.com" + CORS_SJS_PATH,
+ warnCipher: null,
+ },
+];
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ for (const test of TEST_CASES) {
+ info("Testing site with " + test.desc);
+
+ info("Performing request to " + test.uri);
+ let wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [test.uri],
+ async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ }
+ );
+ await wait;
+
+ info("Selecting the request.");
+ wait = waitForDOM(document, ".tabs");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ if (!document.querySelector("#security-tab[aria-selected=true]")) {
+ info("Selecting security tab.");
+ wait = waitForDOM(document, "#security-panel .properties-view");
+ clickOnSidebarTab(document, "security");
+ await wait;
+ }
+
+ is(
+ document.querySelector("#security-warning-cipher"),
+ test.warnCipher,
+ "Cipher suite warning is hidden."
+ );
+
+ await clearNetworkEvents(monitor);
+ }
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_send-beacon-other-tab.js b/devtools/client/netmonitor/test/browser_net_send-beacon-other-tab.js
new file mode 100644
index 0000000000..900f5f48c8
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_send-beacon-other-tab.js
@@ -0,0 +1,49 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if beacons from other tabs are properly ignored.
+ */
+
+add_task(async function () {
+ const { monitor, tab } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ const { store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const beaconTab = await addTab(SEND_BEACON_URL);
+ info("Beacon tab added successfully.");
+
+ is(
+ store.getState().requests.requests.length,
+ 0,
+ "The requests menu should be empty."
+ );
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(beaconTab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.performRequests();
+ });
+ await reloadBrowser({ browser: tab.linkedBrowser });
+ await wait;
+
+ is(
+ store.getState().requests.requests.length,
+ 1,
+ "Only the reload should be recorded."
+ );
+ const request = getSortedRequests(store.getState())[0];
+ is(request.method, "GET", "The method is correct.");
+ is(request.status, "200", "The status is correct.");
+
+ await removeTab(beaconTab);
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_send-beacon.js b/devtools/client/netmonitor/test/browser_net_send-beacon.js
new file mode 100644
index 0000000000..d47299ca7f
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_send-beacon.js
@@ -0,0 +1,44 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if beacons are handled correctly.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(SEND_BEACON_URL, {
+ requestCount: 1,
+ });
+ const { store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ is(
+ store.getState().requests.requests.length,
+ 0,
+ "The requests menu should be empty."
+ );
+
+ // Execute requests.
+ await performRequests(monitor, tab, 1);
+
+ is(
+ store.getState().requests.requests.length,
+ 1,
+ "The beacon should be recorded."
+ );
+
+ const request = getSortedRequests(store.getState())[0];
+ is(request.method, "POST", "The method is correct.");
+ ok(request.url.endsWith("beacon_request"), "The URL is correct.");
+ is(request.status, "404", "The status is correct.");
+ is(request.blockedReason, 0, "The request is not blocked");
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_server_timings.js b/devtools/client/netmonitor/test/browser_net_server_timings.js
new file mode 100644
index 0000000000..1ed635168f
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_server_timings.js
@@ -0,0 +1,74 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if server side timings are displayed
+ */
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(HTTPS_CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ let wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [SERVER_TIMINGS_TYPE_SJS],
+ async function (url) {
+ content.wrappedJSObject.performRequests(1, url);
+ }
+ );
+ await wait;
+
+ // There must be 4 timing values (including server side timings).
+ const timingsSelector = "#timings-panel .tabpanel-summary-container.server";
+ wait = waitForDOM(document, timingsSelector, 4);
+
+ AccessibilityUtils.setEnv({
+ // Keyboard users will will see the sidebar when the request row is
+ // selected. Accessibility is handled on the container level.
+ actionCountRule: false,
+ interactiveRule: false,
+ labelRule: false,
+ });
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ AccessibilityUtils.resetEnv();
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ clickOnSidebarTab(document, "timings");
+ await wait;
+
+ // Check the UI contains server side timings and correct values
+ const timings = document.querySelectorAll(timingsSelector, 4);
+ is(
+ timings[0].textContent,
+ "time1123 ms",
+ "The first server-timing must be correct"
+ );
+ is(
+ timings[1].textContent,
+ "time20 ms",
+ "The second server-timing must be correct"
+ );
+ is(
+ timings[2].textContent,
+ "time31.66 min",
+ "The third server-timing must be correct"
+ );
+ is(
+ timings[3].textContent,
+ "time41.11 s",
+ "The fourth server-timing must be correct"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_service-worker-status.js b/devtools/client/netmonitor/test/browser_net_service-worker-status.js
new file mode 100644
index 0000000000..7686ed6d52
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_service-worker-status.js
@@ -0,0 +1,112 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if requests intercepted by service workers have the correct status code
+ */
+
+// Service workers only work on https
+const URL = EXAMPLE_URL.replace("http:", "https:");
+
+const TEST_URL = URL + "service-workers/status-codes.html";
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(TEST_URL, {
+ enableCache: true,
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire, connector } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const REQUEST_DATA = [
+ {
+ method: "GET",
+ uri: URL + "service-workers/test/200",
+ details: {
+ status: 200,
+ statusText: "OK (service worker)",
+ displayedStatus: "service worker",
+ type: "plain",
+ fullMimeType: "text/plain; charset=UTF-8",
+ },
+ stackFunctions: ["doXHR", "performRequests"],
+ },
+ ];
+
+ info("Registering the service worker...");
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ await content.wrappedJSObject.registerServiceWorker();
+ });
+
+ info("Performing requests...");
+ // Execute requests.
+ await performRequests(monitor, tab, REQUEST_DATA.length);
+
+ // Fetch stack-trace data from the backend and wait till
+ // all packets are received.
+ const requests = getSortedRequests(store.getState());
+ await Promise.all(
+ requests.map(requestItem =>
+ connector.requestData(requestItem.id, "stackTrace")
+ )
+ );
+
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+ }
+
+ let index = 0;
+ for (const request of REQUEST_DATA) {
+ const item = getSortedRequests(store.getState())[index];
+
+ info(`Verifying request #${index}`);
+ await verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ item,
+ request.method,
+ request.uri,
+ request.details
+ );
+
+ const { stacktrace } = item;
+ const stackLen = stacktrace ? stacktrace.length : 0;
+
+ ok(stacktrace, `Request #${index} has a stacktrace`);
+ ok(
+ stackLen >= request.stackFunctions.length,
+ `Request #${index} has a stacktrace with enough (${stackLen}) items`
+ );
+
+ request.stackFunctions.forEach((functionName, j) => {
+ is(
+ stacktrace[j].functionName,
+ functionName,
+ `Request #${index} has the correct function at position #${j} on the stack`
+ );
+ });
+
+ index++;
+ }
+
+ info("Unregistering the service worker...");
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ await content.wrappedJSObject.unregisterServiceWorker();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_set-cookie-same-site.js b/devtools/client/netmonitor/test/browser_net_set-cookie-same-site.js
new file mode 100644
index 0000000000..ecfa4bedcf
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_set-cookie-same-site.js
@@ -0,0 +1,85 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if the 'Same site' cookie attribute is correctly set in the cookie panel
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SET_COOKIE_SAME_SITE_SJS, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ let wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ wait = waitForDOM(document, ".headers-overview");
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ clickOnSidebarTab(document, "cookies");
+
+ info("Checking the SameSite property");
+ const expectedValues = [
+ {
+ key: "foo",
+ value: "",
+ },
+ {
+ key: "samesite",
+ value: '"Lax"',
+ },
+ {
+ key: "value",
+ value: '"bar"',
+ },
+ {
+ key: "foo",
+ value: '"bar"',
+ },
+ ];
+ const labelCells = document.querySelectorAll(".treeLabelCell");
+ const valueCells = document.querySelectorAll(".treeValueCell");
+ is(
+ valueCells.length,
+ labelCells.length,
+ "Number of labels " +
+ labelCells.length +
+ " different from number of values " +
+ valueCells.length
+ );
+
+ // Go through the cookie properties and check if each one has the expected
+ // label and value
+ for (let index = 0; index < labelCells.length; ++index) {
+ is(
+ labelCells[index].innerText,
+ expectedValues[index].key,
+ "Actual label " +
+ labelCells[index].innerText +
+ " not equal to expected label " +
+ expectedValues[index].key
+ );
+ is(
+ valueCells[index].innerText,
+ expectedValues[index].value,
+ "Actual value " +
+ valueCells[index].innerText +
+ " not equal to expected value " +
+ expectedValues[index].value
+ );
+ }
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_simple-request-data.js b/devtools/client/netmonitor/test/browser_net_simple-request-data.js
new file mode 100644
index 0000000000..4e7fef0f83
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_simple-request-data.js
@@ -0,0 +1,488 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if requests render correct information in the menu UI.
+ */
+
+function test() {
+ // Disable tcp fast open, because it is setting a response header indicator
+ // (bug 1352274). TCP Fast Open is not present on all platforms therefore the
+ // number of response headers will vary depending on the platform.
+ Services.prefs.setBoolPref("network.tcp.tcp_fastopen_enable", false);
+
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ initNetMonitor(SIMPLE_SJS, { requestCount: 1 }).then(
+ async ({ tab, monitor }) => {
+ info("Starting test... ");
+
+ const { document, store, windowRequire, connector } = monitor.panelWin;
+ const { EVENTS, TEST_EVENTS } = windowRequire(
+ "devtools/client/netmonitor/src/constants"
+ );
+ const { getDisplayedRequests, getSelectedRequest, getSortedRequests } =
+ windowRequire("devtools/client/netmonitor/src/selectors/index");
+
+ const promiseList = [];
+ promiseList.push(waitForNetworkEvents(monitor, 1));
+
+ function expectEvent(evt, cb) {
+ promiseList.push(
+ new Promise((resolve, reject) => {
+ monitor.panelWin.api.once(evt, _ => {
+ cb().then(resolve, reject);
+ });
+ })
+ );
+ }
+
+ expectEvent(TEST_EVENTS.NETWORK_EVENT, async () => {
+ is(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There shouldn't be any selected item in the requests menu."
+ );
+ is(
+ store.getState().requests.requests.length,
+ 1,
+ "The requests menu should not be empty after the first request."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The network details panel should still be hidden after first request."
+ );
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ is(
+ typeof requestItem.id,
+ "string",
+ "The attached request id is incorrect."
+ );
+ isnot(
+ requestItem.id,
+ "",
+ "The attached request id should not be empty."
+ );
+
+ is(
+ typeof requestItem.startedMs,
+ "number",
+ "The attached startedMs is incorrect."
+ );
+ isnot(
+ requestItem.startedMs,
+ 0,
+ "The attached startedMs should not be zero."
+ );
+
+ /*
+ * Bug 1666495: this is not possible to assert not yet set attributes
+ * because of throttling, which only updates the frontend after a few attributes
+ * are already retrieved via onResourceUpdates events.
+ * This test should be tweaked with slow responding requests in order to assert
+ * such behavior without disabling throttling.
+
+ is(
+ requestItem.requestHeaders,
+ undefined,
+ "The requestHeaders should not yet be set."
+ );
+ is(
+ requestItem.requestCookies,
+ undefined,
+ "The requestCookies should not yet be set."
+ );
+ is(
+ requestItem.requestPostData,
+ undefined,
+ "The requestPostData should not yet be set."
+ );
+
+ is(
+ requestItem.responseHeaders,
+ undefined,
+ "The responseHeaders should not yet be set."
+ );
+ is(
+ requestItem.responseCookies,
+ undefined,
+ "The responseCookies should not yet be set."
+ );
+
+ is(
+ requestItem.httpVersion,
+ undefined,
+ "The httpVersion should not yet be set."
+ );
+ is(requestItem.status, undefined, "The status should not yet be set.");
+ is(
+ requestItem.statusText,
+ undefined,
+ "The statusText should not yet be set."
+ );
+
+ is(
+ requestItem.headersSize,
+ undefined,
+ "The headersSize should not yet be set."
+ );
+ is(
+ requestItem.transferredSize,
+ undefined,
+ "The transferredSize should not yet be set."
+ );
+ is(
+ requestItem.contentSize,
+ undefined,
+ "The contentSize should not yet be set."
+ );
+
+ is(
+ requestItem.responseContent,
+ undefined,
+ "The responseContent should not yet be set."
+ );
+
+ is(
+ requestItem.totalTime,
+ undefined,
+ "The totalTime should not yet be set."
+ );
+ is(
+ requestItem.eventTimings,
+ undefined,
+ "The eventTimings should not yet be set."
+ );
+ */
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ "GET",
+ SIMPLE_SJS
+ );
+ });
+
+ expectEvent(TEST_EVENTS.RECEIVED_REQUEST_HEADERS, async () => {
+ await waitForRequestData(store, ["requestHeaders"]);
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ ok(
+ requestItem.requestHeaders,
+ "There should be a requestHeaders data available."
+ );
+ is(
+ requestItem.requestHeaders.headers.length,
+ 10,
+ "The requestHeaders data has an incorrect |headers| property."
+ );
+ isnot(
+ requestItem.requestHeaders.headersSize,
+ 0,
+ "The requestHeaders data has an incorrect |headersSize| property."
+ );
+ // Can't test for the exact request headers size because the value may
+ // vary across platforms ("User-Agent" header differs).
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ "GET",
+ SIMPLE_SJS
+ );
+ });
+
+ expectEvent(TEST_EVENTS.RECEIVED_REQUEST_COOKIES, async () => {
+ await waitForRequestData(store, ["requestCookies"]);
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ ok(
+ requestItem.requestCookies,
+ "There should be a requestCookies data available."
+ );
+ is(
+ requestItem.requestCookies.length,
+ 2,
+ "The requestCookies data has an incorrect |cookies| property."
+ );
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ "GET",
+ SIMPLE_SJS
+ );
+ });
+
+ monitor.panelWin.api.once(TEST_EVENTS.RECEIVED_REQUEST_POST_DATA, () => {
+ ok(false, "Trap listener: this request doesn't have any post data.");
+ });
+
+ expectEvent(TEST_EVENTS.RECEIVED_RESPONSE_HEADERS, async () => {
+ await waitForRequestData(store, ["responseHeaders"]);
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ ok(
+ requestItem.responseHeaders,
+ "There should be a responseHeaders data available."
+ );
+ is(
+ requestItem.responseHeaders.headers.length,
+ 13,
+ "The responseHeaders data has an incorrect |headers| property."
+ );
+ is(
+ requestItem.responseHeaders.headersSize,
+ 335,
+ "The responseHeaders data has an incorrect |headersSize| property."
+ );
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ "GET",
+ SIMPLE_SJS
+ );
+ });
+
+ expectEvent(TEST_EVENTS.RECEIVED_RESPONSE_COOKIES, async () => {
+ await waitForRequestData(store, ["responseCookies"]);
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ ok(
+ requestItem.responseCookies,
+ "There should be a responseCookies data available."
+ );
+ is(
+ requestItem.responseCookies.length,
+ 2,
+ "The responseCookies data has an incorrect |cookies| property."
+ );
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ "GET",
+ SIMPLE_SJS
+ );
+ });
+
+ expectEvent(TEST_EVENTS.STARTED_RECEIVING_RESPONSE, async () => {
+ await waitForRequestData(store, [
+ "httpVersion",
+ "status",
+ "statusText",
+ "headersSize",
+ ]);
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ is(
+ requestItem.httpVersion,
+ "HTTP/1.1",
+ "The httpVersion data has an incorrect value."
+ );
+ is(
+ requestItem.status,
+ "200",
+ "The status data has an incorrect value."
+ );
+ is(
+ requestItem.statusText,
+ "Och Aye",
+ "The statusText data has an incorrect value."
+ );
+ is(
+ requestItem.headersSize,
+ 335,
+ "The headersSize data has an incorrect value."
+ );
+
+ const requestListItem = document.querySelector(".request-list-item");
+ requestListItem.scrollIntoView();
+ const requestsListStatus =
+ requestListItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(
+ requestListItem,
+ ".requests-list-timings-total"
+ );
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ "GET",
+ SIMPLE_SJS,
+ {
+ status: "200",
+ statusText: "Och Aye",
+ }
+ );
+ });
+
+ expectEvent(EVENTS.PAYLOAD_READY, async () => {
+ await waitForRequestData(store, [
+ "transferredSize",
+ "contentSize",
+ "mimeType",
+ ]);
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ is(
+ requestItem.transferredSize,
+ 347,
+ "The transferredSize data has an incorrect value."
+ );
+ is(
+ requestItem.contentSize,
+ 12,
+ "The contentSize data has an incorrect value."
+ );
+ is(
+ requestItem.mimeType,
+ "text/plain; charset=utf-8",
+ "The mimeType data has an incorrect value."
+ );
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ "GET",
+ SIMPLE_SJS,
+ {
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 347),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 12),
+ }
+ );
+ });
+
+ expectEvent(EVENTS.UPDATING_EVENT_TIMINGS, async () => {
+ await waitForRequestData(store, ["eventTimings"]);
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ is(
+ typeof requestItem.totalTime,
+ "number",
+ "The attached totalTime is incorrect."
+ );
+ ok(
+ requestItem.totalTime >= 0,
+ "The attached totalTime should be positive."
+ );
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ "GET",
+ SIMPLE_SJS,
+ {
+ time: true,
+ }
+ );
+ });
+
+ expectEvent(EVENTS.RECEIVED_EVENT_TIMINGS, async () => {
+ await waitForRequestData(store, ["eventTimings"]);
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ ok(
+ requestItem.eventTimings,
+ "There should be a eventTimings data available."
+ );
+ is(
+ typeof requestItem.eventTimings.timings.blocked,
+ "number",
+ "The eventTimings data has an incorrect |timings.blocked| property."
+ );
+ is(
+ typeof requestItem.eventTimings.timings.dns,
+ "number",
+ "The eventTimings data has an incorrect |timings.dns| property."
+ );
+ is(
+ typeof requestItem.eventTimings.timings.ssl,
+ "number",
+ "The eventTimings data has an incorrect |timings.ssl| property."
+ );
+ is(
+ typeof requestItem.eventTimings.timings.connect,
+ "number",
+ "The eventTimings data has an incorrect |timings.connect| property."
+ );
+ is(
+ typeof requestItem.eventTimings.timings.send,
+ "number",
+ "The eventTimings data has an incorrect |timings.send| property."
+ );
+ is(
+ typeof requestItem.eventTimings.timings.wait,
+ "number",
+ "The eventTimings data has an incorrect |timings.wait| property."
+ );
+ is(
+ typeof requestItem.eventTimings.timings.receive,
+ "number",
+ "The eventTimings data has an incorrect |timings.receive| property."
+ );
+ is(
+ typeof requestItem.eventTimings.totalTime,
+ "number",
+ "The eventTimings data has an incorrect |totalTime| property."
+ );
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ "GET",
+ SIMPLE_SJS,
+ {
+ time: true,
+ }
+ );
+ });
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ const requestItem = getSortedRequests(store.getState())[0];
+
+ if (!requestItem.requestHeaders) {
+ connector.requestData(requestItem.id, "requestHeaders");
+ }
+ if (!requestItem.responseHeaders) {
+ connector.requestData(requestItem.id, "responseHeaders");
+ }
+
+ await Promise.all(promiseList);
+ await teardown(monitor);
+ finish();
+ }
+ );
+}
diff --git a/devtools/client/netmonitor/test/browser_net_simple-request-details.js b/devtools/client/netmonitor/test/browser_net_simple-request-details.js
new file mode 100644
index 0000000000..e52a0b101a
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_simple-request-details.js
@@ -0,0 +1,388 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if requests render correct information in the details UI.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(SIMPLE_SJS, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { PANELS } = windowRequire("devtools/client/netmonitor/src/constants");
+ const { getSelectedRequest, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ is(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There shouldn't be any selected item in the requests menu."
+ );
+ is(
+ store.getState().requests.requests.length,
+ 1,
+ "The requests menu should not be empty after the first request."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The network details panel should still be hidden after first request."
+ );
+
+ const waitForHeaders = waitForDOM(document, ".headers-overview");
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ isnot(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should be a selected item in the requests menu."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ 0,
+ "The first item should be selected in the requests menu."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should not be hidden after toggle button was pressed."
+ );
+
+ await waitForHeaders;
+
+ await testHeadersTab();
+ await testCookiesTab();
+ await testParamsTab();
+ await testResponseTab();
+ await testTimingsTab();
+ await closePanelOnEsc();
+ return teardown(monitor);
+
+ function getSelectedIndex(state) {
+ if (!state.requests.selectedId) {
+ return -1;
+ }
+ return getSortedRequests(state).findIndex(
+ r => r.id === state.requests.selectedId
+ );
+ }
+
+ async function testHeadersTab() {
+ const tabEl = document.querySelectorAll(
+ ".network-details-bar .tabs-menu a"
+ )[0];
+ const tabpanel = document.querySelector("#headers-panel");
+
+ is(
+ tabEl.getAttribute("aria-selected"),
+ "true",
+ "The headers tab in the network details pane should be selected."
+ );
+ // Request URL
+ is(
+ tabpanel.querySelector(".url-preview .url").innerText,
+ SIMPLE_SJS,
+ "The url summary value is incorrect."
+ );
+
+ // Request method
+ is(
+ tabpanel.querySelectorAll(".treeLabel")[0].innerText,
+ "GET",
+ "The method summary value is incorrect."
+ );
+ // Status code
+ is(
+ tabpanel.querySelector(".requests-list-status-code").innerText,
+ "200",
+ "The status summary code is incorrect."
+ );
+ is(
+ tabpanel.querySelector(".status").childNodes[1].textContent,
+ "Och Aye",
+ "The status summary value is incorrect."
+ );
+ // Version
+ is(
+ tabpanel.querySelectorAll(".tabpanel-summary-value")[1].innerText,
+ "HTTP/1.1",
+ "The HTTP version is incorrect."
+ );
+
+ await waitForRequestData(store, ["requestHeaders", "responseHeaders"]);
+
+ is(
+ tabpanel.querySelectorAll(".accordion-item").length,
+ 2,
+ "There should be 2 header scopes displayed in this tabpanel."
+ );
+
+ is(
+ tabpanel.querySelectorAll(".accordion .treeLabelCell").length,
+ 23,
+ "There should be 23 header values displayed in this tabpanel."
+ );
+
+ const headersTable = tabpanel.querySelector(".accordion");
+ const responseScope = headersTable.querySelectorAll(
+ "tr[id^='/Response Headers']"
+ );
+ const requestScope = headersTable.querySelectorAll(
+ "tr[id^='/Request Headers']"
+ );
+
+ const headerLabels = headersTable.querySelectorAll(
+ ".accordion-item .accordion-header-label"
+ );
+
+ ok(
+ headerLabels[0].innerHTML.match(
+ new RegExp(L10N.getStr("responseHeaders") + " \\([0-9]+ .+\\)")
+ ),
+ "The response headers scope doesn't have the correct title."
+ );
+
+ ok(
+ headerLabels[1].innerHTML.includes(L10N.getStr("requestHeaders") + " ("),
+ "The request headers scope doesn't have the correct title."
+ );
+
+ const responseHeaders = [
+ {
+ name: "cache-control",
+ value: "no-cache, no-store, must-revalidate",
+ pos: "first",
+ index: 1,
+ },
+ {
+ name: "connection",
+ value: "close",
+ pos: "second",
+ index: 2,
+ },
+ {
+ name: "content-length",
+ value: "12",
+ pos: "third",
+ index: 3,
+ },
+ {
+ name: "content-type",
+ value: "text/plain; charset=utf-8",
+ pos: "fourth",
+ index: 4,
+ },
+ {
+ name: "foo-bar",
+ value: "baz",
+ pos: "seventh",
+ index: 7,
+ },
+ ];
+ responseHeaders.forEach(header => {
+ is(
+ responseScope[header.index - 1].querySelector(".treeLabel").innerHTML,
+ header.name,
+ `The ${header.pos} response header name was incorrect.`
+ );
+ is(
+ responseScope[header.index - 1].querySelector(".objectBox").innerHTML,
+ `${header.value}`,
+ `The ${header.pos} response header value was incorrect.`
+ );
+ });
+
+ const requestHeaders = [
+ {
+ name: "Cache-Control",
+ value: "no-cache",
+ pos: "fourth",
+ index: 4,
+ },
+ {
+ name: "Connection",
+ value: "keep-alive",
+ pos: "fifth",
+ index: 5,
+ },
+ {
+ name: "Host",
+ value: "example.com",
+ pos: "seventh",
+ index: 7,
+ },
+ {
+ name: "Pragma",
+ value: "no-cache",
+ pos: "eighth",
+ index: 8,
+ },
+ ];
+ requestHeaders.forEach(header => {
+ is(
+ requestScope[header.index - 1].querySelector(".treeLabel").innerHTML,
+ header.name,
+ `The ${header.pos} request header name was incorrect.`
+ );
+ is(
+ requestScope[header.index - 1].querySelector(".objectBox").innerHTML,
+ `${header.value}`,
+ `The ${header.pos} request header value was incorrect.`
+ );
+ });
+ }
+
+ async function testCookiesTab() {
+ const tabpanel = await selectTab(PANELS.COOKIES, 1);
+
+ const cookieAccordion = tabpanel.querySelector(".accordion");
+
+ is(
+ cookieAccordion.querySelectorAll(".accordion-item").length,
+ 2,
+ "There should be 2 cookie scopes displayed in this tabpanel."
+ );
+ // 2 Cookies in response - 1 httpOnly and 1 value for each cookie - total 6
+
+ const resCookiesTable = cookieAccordion.querySelector(
+ "li[id='responseCookies'] .accordion-content .treeTable"
+ );
+ is(
+ resCookiesTable.querySelectorAll("tr.treeRow").length,
+ 6,
+ "There should be 6 rows displayed in response cookies table"
+ );
+
+ const reqCookiesTable = cookieAccordion.querySelector(
+ "li[id='requestCookies'] .accordion-content .treeTable"
+ );
+ is(
+ reqCookiesTable.querySelectorAll("tr.treeRow").length,
+ 2,
+ "There should be 2 cookie values displayed in request cookies table."
+ );
+ }
+
+ async function testParamsTab() {
+ const tabpanel = await selectTab(PANELS.REQUEST, 2);
+
+ is(
+ tabpanel.querySelectorAll(".panel-container").length,
+ 0,
+ "There should be no param scopes displayed in this tabpanel."
+ );
+ is(
+ tabpanel.querySelectorAll(".empty-notice").length,
+ 1,
+ "The empty notice should be displayed in this tabpanel."
+ );
+ }
+
+ async function testResponseTab() {
+ const tabpanel = await selectTab(PANELS.RESPONSE, 3);
+ await waitForDOM(document, "#response-panel .source-editor-mount");
+
+ is(
+ tabpanel.querySelectorAll(
+ "#response-panel .raw-data-toggle-input .devtools-checkbox-toggle"
+ ).length,
+ 0,
+ "The raw data toggle should not be shown in this tabpanel."
+ );
+ is(
+ tabpanel.querySelectorAll(".source-editor-mount").length,
+ 1,
+ "The response payload should be shown initially."
+ );
+ }
+
+ async function testTimingsTab() {
+ const tabpanel = await selectTab(PANELS.TIMINGS, 4);
+
+ const displayFormat = new RegExp(/[0-9]+ ms$/);
+ const propsToVerify = [
+ "blocked",
+ "dns",
+ "connect",
+ "ssl",
+ "send",
+ "wait",
+ "receive",
+ ];
+
+ // To ensure that test case for a new property is written, otherwise this
+ // test will fail
+ is(
+ tabpanel.querySelectorAll(".tabpanel-summary-container").length,
+ propsToVerify.length,
+ `There should be exactly ${propsToVerify.length} values
+ displayed in this tabpanel`
+ );
+
+ propsToVerify.forEach(propName => {
+ ok(
+ tabpanel
+ .querySelector(
+ `#timings-summary-${propName}
+ .requests-list-timings-total`
+ )
+ .innerHTML.match(displayFormat),
+ `The ${propName} timing info does not appear to be correct.`
+ );
+ });
+ }
+
+ async function selectTab(tabName, pos) {
+ const tabEl = document.querySelectorAll(
+ ".network-details-bar .tabs-menu a"
+ )[pos];
+
+ const onPanelOpen = waitForDOM(document, `#${tabName}-panel`);
+ clickOnSidebarTab(
+ document,
+ tabEl.id.substring(0, tabEl.id.indexOf("-tab"))
+ );
+ await onPanelOpen;
+
+ is(
+ tabEl.getAttribute("aria-selected"),
+ "true",
+ `The ${tabName} tab in the network details pane should be selected.`
+ );
+
+ return document.querySelector(".network-details-bar .tab-panel");
+ }
+
+ // This test will timeout on failure
+ async function closePanelOnEsc() {
+ EventUtils.sendKey("ESCAPE", window);
+
+ await waitUntil(() => {
+ return document.querySelector(".network-details-bar") == null;
+ });
+
+ is(
+ document.querySelectorAll(".network-details-bar").length,
+ 0,
+ "Network details panel should close on ESC key"
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_simple-request.js b/devtools/client/netmonitor/test/browser_net_simple-request.js
new file mode 100644
index 0000000000..8f5af6f600
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_simple-request.js
@@ -0,0 +1,99 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test whether the UI state properly reflects existence of requests
+ * displayed in the Net panel. The following parts of the UI are
+ * tested:
+ * 1) Side panel visibility
+ * 2) Side panel toggle button
+ * 3) Empty user message visibility
+ * 4) Number of requests displayed
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ ok(
+ document.querySelector(".request-list-empty-notice"),
+ "An empty notice should be displayed when the frontend is opened."
+ );
+ is(
+ store.getState().requests.requests.length,
+ 0,
+ "The requests menu should be empty when the frontend is opened."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The network details panel should be hidden when the frontend is opened."
+ );
+
+ await reloadAndWait();
+
+ ok(
+ !document.querySelector(".request-list-empty-notice"),
+ "The empty notice should be hidden after the first request."
+ );
+ is(
+ store.getState().requests.requests.length,
+ 1,
+ "The requests menu should not be empty after the first request."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The network details panel should still be hidden after the first request."
+ );
+
+ await reloadAndWait();
+
+ ok(
+ !document.querySelector(".request-list-empty-notice"),
+ "The empty notice should be still hidden after a reload."
+ );
+ is(
+ store.getState().requests.requests.length,
+ 1,
+ "The requests menu should not be empty after a reload."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The network details panel should still be hidden after a reload."
+ );
+
+ await clearNetworkEvents(monitor);
+
+ ok(
+ document.querySelector(".request-list-empty-notice"),
+ "An empty notice should be displayed again after clear."
+ );
+ is(
+ store.getState().requests.requests.length,
+ 0,
+ "The requests menu should be empty after clear."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ false,
+ "The network details panel should still be hidden after clear."
+ );
+
+ return teardown(monitor);
+
+ async function reloadAndWait() {
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ return wait;
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_sort-01.js b/devtools/client/netmonitor/test/browser_net_sort-01.js
new file mode 100644
index 0000000000..8d2009a7db
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_sort-01.js
@@ -0,0 +1,316 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if sorting columns in the network table works correctly with new requests.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(SORTING_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ // It seems that this test may be slow on debug builds. This could be because
+ // of the heavy dom manipulation associated with sorting.
+ requestLongerTimeout(2);
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSelectedRequest, getSortedRequests } =
+ windowRequire("devtools/client/netmonitor/src/selectors/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Loading the frame script and preparing the xhr request URLs so we can
+ // generate some requests later.
+ const requests = [
+ {
+ url: "sjs_sorting-test-server.sjs?index=1&" + Math.random(),
+ method: "GET1",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=5&" + Math.random(),
+ method: "GET5",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=2&" + Math.random(),
+ method: "GET2",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=4&" + Math.random(),
+ method: "GET4",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=3&" + Math.random(),
+ method: "GET3",
+ },
+ ];
+
+ let wait = waitForNetworkEvents(monitor, 5);
+ await performRequestsInContent(requests);
+ await wait;
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ isnot(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should be a selected item in the requests menu."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ 0,
+ "The first item should be selected in the requests menu."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should be visible after toggle button was pressed."
+ );
+
+ testHeaders();
+ await testContents([0, 2, 4, 3, 1], 0);
+
+ info("Testing status sort, ascending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-status-button")
+ );
+ testHeaders("status", "ascending");
+ await testContents([0, 1, 2, 3, 4], 0);
+
+ info("Performing more requests.");
+ wait = waitForNetworkEvents(monitor, 5);
+ await performRequestsInContent(requests);
+ await wait;
+
+ info("Testing status sort again, ascending.");
+ testHeaders("status", "ascending");
+ await testContents([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 0);
+
+ info("Testing status sort, descending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-status-button")
+ );
+ testHeaders("status", "descending");
+ await testContents([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], 9);
+
+ info("Performing more requests.");
+ wait = waitForNetworkEvents(monitor, 5);
+ await performRequestsInContent(requests);
+ await wait;
+
+ info("Testing status sort again, descending.");
+ testHeaders("status", "descending");
+ await testContents([14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0], 14);
+
+ info("Testing status sort yet again, ascending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-status-button")
+ );
+ testHeaders("status", "ascending");
+ await testContents([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 0);
+
+ info("Testing status sort yet again, descending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-status-button")
+ );
+ testHeaders("status", "descending");
+ await testContents([14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0], 14);
+
+ return teardown(monitor);
+
+ function testHeaders(sortType, direction) {
+ const doc = monitor.panelWin.document;
+ const target = doc.querySelector("#requests-list-" + sortType + "-button");
+ const headers = doc.querySelectorAll(".requests-list-header-button");
+
+ for (const header of headers) {
+ if (header != target) {
+ ok(
+ !header.hasAttribute("data-sorted"),
+ "The " +
+ header.id +
+ " header does not have a 'data-sorted' attribute."
+ );
+ ok(
+ !header
+ .getAttribute("title")
+ .includes(L10N.getStr("networkMenu.sortedAsc")) &&
+ !header
+ .getAttribute("title")
+ .includes(L10N.getStr("networkMenu.sortedDesc")),
+ "The " +
+ header.id +
+ " header does not include any sorting in the 'title' attribute."
+ );
+ } else {
+ is(
+ header.getAttribute("data-sorted"),
+ direction,
+ "The " + header.id + " header has a correct 'data-sorted' attribute."
+ );
+ const sorted =
+ direction == "ascending"
+ ? L10N.getStr("networkMenu.sortedAsc")
+ : L10N.getStr("networkMenu.sortedDesc");
+ ok(
+ header.getAttribute("title").includes(sorted),
+ "The " +
+ header.id +
+ " header includes the used sorting in the 'title' attribute."
+ );
+ }
+ }
+ }
+
+ function getSelectedIndex(state) {
+ if (!state.requests.selectedId) {
+ return -1;
+ }
+ return getSortedRequests(state).findIndex(
+ r => r.id === state.requests.selectedId
+ );
+ }
+
+ async function testContents(order, selection) {
+ isnot(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should still be a selected item after sorting."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ selection,
+ "The first item should be still selected after sorting."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should still be visible after sorting."
+ );
+
+ is(
+ getSortedRequests(store.getState()).length,
+ order.length,
+ "There should be a specific number of items in the requests menu."
+ );
+ is(
+ getDisplayedRequests(store.getState()).length,
+ order.length,
+ "There should be a specific number of visbile items in the requests menu."
+ );
+ is(
+ document.querySelectorAll(".request-list-item").length,
+ order.length,
+ "The visible items in the requests menu are, in fact, visible!"
+ );
+
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ }
+
+ for (let i = 0, len = order.length / 5; i < len; i++) {
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[order[i]],
+ "GET1",
+ SORTING_SJS + "?index=1",
+ {
+ fuzzyUrl: true,
+ status: 101,
+ statusText: "Meh",
+ type: "1",
+ fullMimeType: "text/1",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 198),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 0),
+ }
+ );
+ }
+ for (let i = 0, len = order.length / 5; i < len; i++) {
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[order[i + len]],
+ "GET2",
+ SORTING_SJS + "?index=2",
+ {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "Meh",
+ type: "2",
+ fullMimeType: "text/2",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 217),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 19),
+ }
+ );
+ }
+ for (let i = 0, len = order.length / 5; i < len; i++) {
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[order[i + len * 2]],
+ "GET3",
+ SORTING_SJS + "?index=3",
+ {
+ fuzzyUrl: true,
+ status: 300,
+ statusText: "Meh",
+ type: "3",
+ fullMimeType: "text/3",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 227),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 29),
+ }
+ );
+ }
+ for (let i = 0, len = order.length / 5; i < len; i++) {
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[order[i + len * 3]],
+ "GET4",
+ SORTING_SJS + "?index=4",
+ {
+ fuzzyUrl: true,
+ status: 400,
+ statusText: "Meh",
+ type: "4",
+ fullMimeType: "text/4",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 237),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 39),
+ }
+ );
+ }
+ for (let i = 0, len = order.length / 5; i < len; i++) {
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[order[i + len * 4]],
+ "GET5",
+ SORTING_SJS + "?index=5",
+ {
+ fuzzyUrl: true,
+ status: 500,
+ statusText: "Meh",
+ type: "5",
+ fullMimeType: "text/5",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 247),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 49),
+ }
+ );
+ }
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_sort-02.js b/devtools/client/netmonitor/test/browser_net_sort-02.js
new file mode 100644
index 0000000000..5a2ae472fc
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_sort-02.js
@@ -0,0 +1,460 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if sorting columns in the network table works correctly.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(SORTING_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ // It seems that this test may be slow on debug builds. This could be because
+ // of the heavy dom manipulation associated with sorting.
+ requestLongerTimeout(2);
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSelectedRequest, getSortedRequests } =
+ windowRequire("devtools/client/netmonitor/src/selectors/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Loading the frame script and preparing the xhr request URLs so we can
+ // generate some requests later.
+ const requests = [
+ {
+ url: "sjs_sorting-test-server.sjs?index=1&" + Math.random(),
+ method: "GET1",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=5&" + Math.random(),
+ method: "GET5",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=2&" + Math.random(),
+ method: "GET2",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=4&" + Math.random(),
+ method: "GET4",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=3&" + Math.random(),
+ method: "GET3",
+ },
+ ];
+
+ const wait = waitForNetworkEvents(monitor, 5);
+ await performRequestsInContent(requests);
+ await wait;
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ isnot(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should be a selected item in the requests menu."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ 0,
+ "The first item should be selected in the requests menu."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should be visible after toggle button was pressed."
+ );
+
+ testHeaders();
+ await testContents([0, 2, 4, 3, 1]);
+
+ info("Testing status sort, ascending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-status-button")
+ );
+ testHeaders("status", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing status sort, descending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-status-button")
+ );
+ testHeaders("status", "descending");
+ await testContents([4, 3, 2, 1, 0]);
+
+ info("Testing status sort, ascending. Checking sort loops correctly.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-status-button")
+ );
+ testHeaders("status", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing method sort, ascending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-method-button")
+ );
+ testHeaders("method", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing method sort, descending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-method-button")
+ );
+ testHeaders("method", "descending");
+ await testContents([4, 3, 2, 1, 0]);
+
+ info("Testing method sort, ascending. Checking sort loops correctly.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-method-button")
+ );
+ testHeaders("method", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing file sort, ascending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-file-button")
+ );
+ testHeaders("file", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing file sort, descending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-file-button")
+ );
+ testHeaders("file", "descending");
+ await testContents([4, 3, 2, 1, 0]);
+
+ info("Testing file sort, ascending. Checking sort loops correctly.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-file-button")
+ );
+ testHeaders("file", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing URL sort, ascending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-url-button")
+ );
+ testHeaders("url", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing URL sort, descending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-url-button")
+ );
+ testHeaders("url", "descending");
+ await testContents([4, 3, 2, 1, 0]);
+
+ info("Testing URL sort, ascending. Checking sort loops correctly.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-url-button")
+ );
+ testHeaders("url", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing type sort, ascending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-type-button")
+ );
+ testHeaders("type", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing type sort, descending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-type-button")
+ );
+ testHeaders("type", "descending");
+ await testContents([4, 3, 2, 1, 0]);
+
+ info("Testing type sort, ascending. Checking sort loops correctly.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-type-button")
+ );
+ testHeaders("type", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing transferred sort, ascending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-transferred-button")
+ );
+ testHeaders("transferred", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing transferred sort, descending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-transferred-button")
+ );
+ testHeaders("transferred", "descending");
+ await testContents([4, 3, 2, 1, 0]);
+
+ info("Testing transferred sort, ascending. Checking sort loops correctly.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-transferred-button")
+ );
+ testHeaders("transferred", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing size sort, ascending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-contentSize-button")
+ );
+ testHeaders("contentSize", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing size sort, descending.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-contentSize-button")
+ );
+ testHeaders("contentSize", "descending");
+ await testContents([4, 3, 2, 1, 0]);
+
+ info("Testing size sort, ascending. Checking sort loops correctly.");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-contentSize-button")
+ );
+ testHeaders("contentSize", "ascending");
+ await testContents([0, 1, 2, 3, 4]);
+
+ info("Testing waterfall sort, ascending.");
+
+ // Because the waterfall column is hidden when the network details panel is
+ // opened, the waterfall button is not visible. Therefore we hide the network
+ // details panel
+ await store.dispatch(Actions.toggleNetworkDetails());
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-waterfall-button")
+ );
+ await store.dispatch(Actions.toggleNetworkDetails());
+ testHeaders("waterfall", "ascending");
+ await testContents([0, 2, 4, 3, 1]);
+
+ info("Testing waterfall sort, descending.");
+ await store.dispatch(Actions.toggleNetworkDetails());
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-waterfall-button")
+ );
+ testHeaders("waterfall", "descending");
+ await store.dispatch(Actions.toggleNetworkDetails());
+ await testContents([4, 2, 0, 1, 3], true);
+
+ info("Testing waterfall sort, ascending. Checking sort loops correctly.");
+ await store.dispatch(Actions.toggleNetworkDetails());
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-waterfall-button")
+ );
+ testHeaders("waterfall", "ascending");
+ await store.dispatch(Actions.toggleNetworkDetails());
+ await testContents([0, 2, 4, 3, 1]);
+
+ return teardown(monitor);
+
+ function getSelectedIndex(state) {
+ if (!state.requests.selectedId) {
+ return -1;
+ }
+ return getSortedRequests(state).findIndex(
+ r => r.id === state.requests.selectedId
+ );
+ }
+
+ function testHeaders(sortType, direction) {
+ const doc = monitor.panelWin.document;
+ const target = doc.querySelector("#requests-list-" + sortType + "-button");
+ const headers = doc.querySelectorAll(".requests-list-header-button");
+
+ for (const header of headers) {
+ if (header != target) {
+ ok(
+ !header.hasAttribute("data-sorted"),
+ "The " +
+ header.id +
+ " header does not have a 'data-sorted' attribute."
+ );
+ ok(
+ !header
+ .getAttribute("title")
+ .includes(L10N.getStr("networkMenu.sortedAsc")) &&
+ !header
+ .getAttribute("title")
+ .includes(L10N.getStr("networkMenu.sortedDesc")),
+ "The " +
+ header.id +
+ " header does not include any sorting in the 'title' attribute."
+ );
+ } else {
+ is(
+ header.getAttribute("data-sorted"),
+ direction,
+ "The " + header.id + " header has a correct 'data-sorted' attribute."
+ );
+ const sorted =
+ direction == "ascending"
+ ? L10N.getStr("networkMenu.sortedAsc")
+ : L10N.getStr("networkMenu.sortedDesc");
+ ok(
+ header.getAttribute("title").includes(sorted),
+ "The " +
+ header.id +
+ " header includes the used sorting in the 'title' attribute."
+ );
+ }
+ }
+ }
+
+ async function testContents([a, b, c, d, e], waterfall = false) {
+ isnot(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should still be a selected item after sorting."
+ );
+ if (!waterfall) {
+ is(
+ getSelectedIndex(store.getState()),
+ a,
+ "The first item should be still selected after sorting."
+ );
+ }
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should still be visible after sorting."
+ );
+
+ is(
+ getSortedRequests(store.getState()).length,
+ 5,
+ "There should be a total of 5 items in the requests menu."
+ );
+ is(
+ getDisplayedRequests(store.getState()).length,
+ 5,
+ "There should be a total of 5 visible items in the requests menu."
+ );
+ is(
+ document.querySelectorAll(".request-list-item").length,
+ 5,
+ "The visible items in the requests menu are, in fact, visible!"
+ );
+
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ }
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[a],
+ "GET1",
+ SORTING_SJS + "?index=1",
+ {
+ fuzzyUrl: true,
+ status: 101,
+ statusText: "Meh",
+ type: "1",
+ fullMimeType: "text/1",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 198),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 0),
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[b],
+ "GET2",
+ SORTING_SJS + "?index=2",
+ {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "Meh",
+ type: "2",
+ fullMimeType: "text/2",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 217),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 19),
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[c],
+ "GET3",
+ SORTING_SJS + "?index=3",
+ {
+ fuzzyUrl: true,
+ status: 300,
+ statusText: "Meh",
+ type: "3",
+ fullMimeType: "text/3",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 227),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 29),
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[d],
+ "GET4",
+ SORTING_SJS + "?index=4",
+ {
+ fuzzyUrl: true,
+ status: 400,
+ statusText: "Meh",
+ type: "4",
+ fullMimeType: "text/4",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 237),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 39),
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[e],
+ "GET5",
+ SORTING_SJS + "?index=5",
+ {
+ fuzzyUrl: true,
+ status: 500,
+ statusText: "Meh",
+ type: "5",
+ fullMimeType: "text/5",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 247),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 49),
+ }
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_sort-reset.js b/devtools/client/netmonitor/test/browser_net_sort-reset.js
new file mode 100644
index 0000000000..f2b58e203d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_sort-reset.js
@@ -0,0 +1,284 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if sorting columns in the network table works correctly.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(SORTING_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ // It seems that this test may be slow on debug builds. This could be because
+ // of the heavy dom manipulation associated with sorting.
+ requestLongerTimeout(2);
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSelectedRequest, getSortedRequests } =
+ windowRequire("devtools/client/netmonitor/src/selectors/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Loading the frame script and preparing the xhr request URLs so we can
+ // generate some requests later.
+ const requests = [
+ {
+ url: "sjs_sorting-test-server.sjs?index=1&" + Math.random(),
+ method: "GET1",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=5&" + Math.random(),
+ method: "GET5",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=2&" + Math.random(),
+ method: "GET2",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=4&" + Math.random(),
+ method: "GET4",
+ },
+ {
+ url: "sjs_sorting-test-server.sjs?index=3&" + Math.random(),
+ method: "GET3",
+ },
+ ];
+
+ const wait = waitForNetworkEvents(monitor, 5);
+ await performRequestsInContent(requests);
+ await wait;
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ testHeaders();
+ await testContents([0, 2, 4, 3, 1]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-status-button")
+ );
+ info("Testing sort reset using middle click.");
+ EventUtils.sendMouseEvent(
+ { type: "click", button: 1 },
+ document.querySelector("#requests-list-status-button")
+ );
+ testHeaders();
+ await testContents([0, 2, 4, 3, 1]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-status-button")
+ );
+ info("Testing sort reset using context menu 'Reset Sorting'");
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector("#requests-list-contentSize-button")
+ );
+ await selectContextMenuItem(monitor, "request-list-header-reset-sorting");
+ testHeaders();
+ await testContents([0, 2, 4, 3, 1]);
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#requests-list-status-button")
+ );
+ info("Testing sort reset using context menu 'Reset Columns'");
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector("#requests-list-contentSize-button")
+ );
+ await selectContextMenuItem(monitor, "request-list-header-reset-columns");
+ testHeaders();
+ // add columns because verifyRequestItemTarget expects some extra columns
+ await showColumn(monitor, "protocol");
+ await showColumn(monitor, "remoteip");
+ await showColumn(monitor, "scheme");
+ await showColumn(monitor, "duration");
+ await showColumn(monitor, "latency");
+ await testContents([0, 2, 4, 3, 1]);
+
+ return teardown(monitor);
+
+ function getSelectedIndex(state) {
+ if (!state.requests.selectedId) {
+ return -1;
+ }
+ return getSortedRequests(state).findIndex(
+ r => r.id === state.requests.selectedId
+ );
+ }
+
+ function testHeaders(sortType, direction) {
+ const doc = monitor.panelWin.document;
+ const target = doc.querySelector("#requests-list-" + sortType + "-button");
+ const headers = doc.querySelectorAll(".requests-list-header-button");
+
+ for (const header of headers) {
+ if (header != target) {
+ ok(
+ !header.hasAttribute("data-sorted"),
+ "The " +
+ header.id +
+ " header does not have a 'data-sorted' attribute."
+ );
+ ok(
+ !header
+ .getAttribute("title")
+ .includes(L10N.getStr("networkMenu.sortedAsc")) &&
+ !header
+ .getAttribute("title")
+ .includes(L10N.getStr("networkMenu.sortedDesc")),
+ "The " +
+ header.id +
+ " header does not include any sorting in the 'title' attribute."
+ );
+ } else {
+ is(
+ header.getAttribute("data-sorted"),
+ direction,
+ "The " + header.id + " header has a correct 'data-sorted' attribute."
+ );
+ const sorted =
+ direction == "ascending"
+ ? L10N.getStr("networkMenu.sortedAsc")
+ : L10N.getStr("networkMenu.sortedDesc");
+ ok(
+ header.getAttribute("title").includes(sorted),
+ "The " +
+ header.id +
+ " header includes the used sorting in the 'title' attribute."
+ );
+ }
+ }
+ }
+
+ async function testContents([a, b, c, d, e]) {
+ isnot(
+ getSelectedRequest(store.getState()),
+ undefined,
+ "There should still be a selected item after sorting."
+ );
+ is(
+ getSelectedIndex(store.getState()),
+ a,
+ "The first item should be still selected after sorting."
+ );
+ is(
+ !!document.querySelector(".network-details-bar"),
+ true,
+ "The network details panel should still be visible after sorting."
+ );
+
+ is(
+ getSortedRequests(store.getState()).length,
+ 5,
+ "There should be a total of 5 items in the requests menu."
+ );
+ is(
+ getDisplayedRequests(store.getState()).length,
+ 5,
+ "There should be a total of 5 visible items in the requests menu."
+ );
+ is(
+ document.querySelectorAll(".request-list-item").length,
+ 5,
+ "The visible items in the requests menu are, in fact, visible!"
+ );
+
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ }
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[a],
+ "GET1",
+ SORTING_SJS + "?index=1",
+ {
+ fuzzyUrl: true,
+ status: 101,
+ statusText: "Meh",
+ type: "1",
+ fullMimeType: "text/1",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 198),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 0),
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[b],
+ "GET2",
+ SORTING_SJS + "?index=2",
+ {
+ fuzzyUrl: true,
+ status: 200,
+ statusText: "Meh",
+ type: "2",
+ fullMimeType: "text/2",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 217),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 19),
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[c],
+ "GET3",
+ SORTING_SJS + "?index=3",
+ {
+ fuzzyUrl: true,
+ status: 300,
+ statusText: "Meh",
+ type: "3",
+ fullMimeType: "text/3",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 227),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 29),
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[d],
+ "GET4",
+ SORTING_SJS + "?index=4",
+ {
+ fuzzyUrl: true,
+ status: 400,
+ statusText: "Meh",
+ type: "4",
+ fullMimeType: "text/4",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 237),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 39),
+ }
+ );
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[e],
+ "GET5",
+ SORTING_SJS + "?index=5",
+ {
+ fuzzyUrl: true,
+ status: 500,
+ statusText: "Meh",
+ type: "5",
+ fullMimeType: "text/5",
+ transferred: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 247),
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 49),
+ }
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_sse-basic.js b/devtools/client/netmonitor/test/browser_net_sse-basic.js
new file mode 100644
index 0000000000..bb1af5c1c3
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_sse-basic.js
@@ -0,0 +1,119 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test basic SSE connection.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ "http://mochi.test:8888/browser/devtools/client/netmonitor/test/html_sse-test-page.html",
+ {
+ requestCount: 1,
+ }
+ );
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection();
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Select the request to open the side panel.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Wait for messages to be displayed in DevTools
+ const wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 1
+ );
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 1, "There should be one message");
+
+ is(
+ frames[0].querySelector(".message-list-payload").textContent,
+ // Initial whitespace comes from ColumnData.
+ " Why so serious?",
+ "Data column shows correct payload"
+ );
+
+ // Closed message may already be here
+ if (
+ !document.querySelector("#messages-view .msg-connection-closed-message")
+ ) {
+ await waitForDOM(
+ document,
+ "#messages-view .msg-connection-closed-message",
+ 1
+ );
+ }
+
+ is(
+ !!document.querySelector("#messages-view .msg-connection-closed-message"),
+ true,
+ "Connection closed message should be displayed"
+ );
+
+ is(
+ document.querySelector(".message-network-summary-count").textContent,
+ "1 message",
+ "Correct message count is displayed"
+ );
+
+ is(
+ document.querySelector(".message-network-summary-total-size").textContent,
+ "15 B total",
+ "Correct total size should be displayed"
+ );
+
+ is(
+ !!document.querySelector(".message-network-summary-total-millis"),
+ true,
+ "Total time is displayed"
+ );
+
+ is(
+ document.getElementById("frame-filter-menu"),
+ null,
+ "Toolbar filter menu is hidden"
+ );
+
+ await waitForTick();
+
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector(".message-list-headers")
+ );
+
+ const columns = ["data", "time", "retry", "size", "eventName", "lastEventId"];
+ for (const column of columns) {
+ is(
+ !!getContextMenuItem(monitor, `message-list-header-${column}-toggle`),
+ true,
+ `Context menu item "${column}" is displayed`
+ );
+ }
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_stacktraces-visibility.js b/devtools/client/netmonitor/test/browser_net_stacktraces-visibility.js
new file mode 100644
index 0000000000..2edb68c4c2
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_stacktraces-visibility.js
@@ -0,0 +1,86 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that opening the stacktrace details panel in the netmonitor and console
+ * show the expected stacktraces.
+ */
+
+add_task(async function () {
+ const URL = EXAMPLE_URL + "html_single-get-page.html";
+ const REQUEST =
+ "http://example.com/browser/devtools/client/netmonitor/test/request_0";
+
+ const { monitor } = await initNetMonitor(URL, {
+ requestCount: 1,
+ });
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Starting test... ");
+
+ const allRequestsVisible = waitUntil(
+ () => document.querySelectorAll(".request-list-item").length == 2
+ );
+
+ await waitForAllNetworkUpdateEvents();
+ await reloadBrowser();
+ await allRequestsVisible;
+
+ const onStackTracesVisible = waitUntil(
+ () => document.querySelector("#stack-trace-panel .stack-trace .frame-link"),
+ "Wait for the stacktrace to be rendered"
+ );
+
+ // Select the request initiated by html_single-get-page.html
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelector(
+ `.request-list-item .requests-list-file[title="${REQUEST}"]`
+ )
+ );
+
+ // Wait for the stack trace tab to show
+ await waitUntil(() =>
+ document.querySelector(".network-details-bar #stack-trace-tab")
+ );
+
+ clickOnSidebarTab(document, "stack-trace");
+
+ await onStackTracesVisible;
+
+ // Switch to the webconsole.
+ const { hud } = await monitor.toolbox.selectTool("webconsole");
+ await waitFor(
+ () =>
+ hud.ui.outputNode.querySelector(
+ ".webconsole-output .cm-s-mozilla.message.network"
+ ),
+ "Wait for the network request log to show"
+ );
+ const fetchRequestUrlNode = hud.ui.outputNode.querySelector(
+ `.webconsole-output .cm-s-mozilla.message.network a[title="${REQUEST}"]`
+ );
+ fetchRequestUrlNode.click();
+
+ const messageWrapper = fetchRequestUrlNode.closest(".message-body-wrapper");
+
+ await waitFor(
+ () => messageWrapper.querySelector(".network-info"),
+ "Wait for .network-info to be rendered"
+ );
+
+ // Select stacktrace details panel and check the content.
+ messageWrapper.querySelector("#stack-trace-tab").click();
+ await waitFor(
+ () => messageWrapper.querySelector("#stack-trace-panel .frame-link"),
+ "Wait for stacktrace to be rendered"
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_statistics-01.js b/devtools/client/netmonitor/test/browser_net_statistics-01.js
new file mode 100644
index 0000000000..5a0c5f661e
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_statistics-01.js
@@ -0,0 +1,65 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the statistics panel displays correctly.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(STATISTICS_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ const panel = monitor.panelWin;
+ const { document, store, windowRequire, connector } = panel;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ ok(
+ document.querySelector(".monitor-panel"),
+ "The current main panel is correct."
+ );
+
+ info("Displaying statistics panel");
+ store.dispatch(Actions.openStatistics(connector, true));
+
+ ok(
+ document.querySelector(".statistics-panel"),
+ "The current main panel is correct."
+ );
+
+ info("Waiting for placeholder to display");
+
+ await waitUntil(
+ () =>
+ document.querySelectorAll(".pie-chart-container[placeholder=true]")
+ .length == 2
+ );
+ ok(true, "Two placeholder pie charts appear to be rendered correctly.");
+
+ await waitUntil(
+ () =>
+ document.querySelectorAll(".table-chart-container[placeholder=true]")
+ .length == 2
+ );
+ ok(true, "Two placeholde table charts appear to be rendered correctly.");
+
+ info("Waiting for chart to display");
+
+ await waitUntil(
+ () =>
+ document.querySelectorAll(".pie-chart-container:not([placeholder=true])")
+ .length == 2
+ );
+ ok(true, "Two real pie charts appear to be rendered correctly.");
+
+ await waitUntil(
+ () =>
+ document.querySelectorAll(
+ ".table-chart-container:not([placeholder=true])"
+ ).length == 2
+ );
+ ok(true, "Two real table charts appear to be rendered correctly.");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_statistics-02.js b/devtools/client/netmonitor/test/browser_net_statistics-02.js
new file mode 100644
index 0000000000..ccc25a387d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_statistics-02.js
@@ -0,0 +1,74 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test if the correct filtering predicates are used when filtering from
+ * the performance analysis view.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(FILTERING_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ const panel = monitor.panelWin;
+ const { document, store, windowRequire, connector } = panel;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-html-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-css-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-js-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-ws-button")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-other-button")
+ );
+ testFilterButtonsCustom(monitor, [0, 1, 1, 1, 0, 0, 0, 0, 1, 1]);
+ info(
+ "The correct filtering predicates are used before entering perf. analysis mode."
+ );
+
+ store.dispatch(Actions.openStatistics(connector, true));
+
+ ok(
+ document.querySelector(".statistics-panel"),
+ "The main panel is switched to the statistics panel."
+ );
+
+ await waitUntil(
+ () =>
+ document.querySelectorAll(".pie-chart-container:not([placeholder=true])")
+ .length == 2
+ );
+ ok(true, "Two real pie charts appear to be rendered correctly.");
+
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".pie-chart-slice-container")
+ );
+
+ ok(
+ document.querySelector(".monitor-panel"),
+ "The main panel is switched back to the monitor panel."
+ );
+
+ testFilterButtons(monitor, "html");
+ info(
+ "The correct filtering predicate is used when exiting perf. analysis mode."
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_statistics-edge-case.js b/devtools/client/netmonitor/test/browser_net_statistics-edge-case.js
new file mode 100644
index 0000000000..811147743b
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_statistics-edge-case.js
@@ -0,0 +1,112 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if the statistics panel displays correctly for a page containing
+ * requests which have been known to create issues in the past for this Panel:
+ * - cached image (http-on-image-cache-response) requests in the content process
+ * - long polling requests remaining open for a long time
+ */
+
+add_task(async function () {
+ // We start the netmonitor on a basic page to avoid opening the panel on
+ // an incomplete polling request.
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ enableCache: true,
+ });
+
+ // The navigation should lead to 3 requests (html + image + long polling).
+ // Additionally we will have a 4th request to call unblock(), so there are 4
+ // requests in total.
+ // However we need to make sure that unblock() is only called once the long
+ // polling request has been started, so we wait for network events in 2 sets:
+ // - first the 3 initial requests, with only 2 completing
+ // - then the unblock request, bundled with the completion of the long polling
+ let onNetworkEvents = waitForNetworkEvents(monitor, 3, {
+ expectedPayloadReady: 2,
+ expectedEventTimings: 2,
+ });
+
+ // Here we explicitly do not await on navigateTo.
+ // The netmonitor will not emit "reloaded" if there are pending requests,
+ // so if the long polling request already started, we will never receive the
+ // event. Waiting for the network events should be sufficient here.
+ const onNavigationCompleted = navigateTo(STATISTICS_EDGE_CASE_URL);
+
+ info("Wait for the 3 first network events (initial)");
+ await onNetworkEvents;
+
+ // Prepare to wait for the second set of network events.
+ onNetworkEvents = waitForNetworkEvents(monitor, 1, {
+ expectedPayloadReady: 2,
+ expectedEventTimings: 2,
+ });
+
+ // Calling unblock() should allow for the polling request to be displayed and
+ // to complete, so we can consistently expect 2 events and 2 timings.
+ info("Call unblock()");
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], () =>
+ content.wrappedJSObject.unblock()
+ );
+
+ info("Wait for polling and unblock (initial)");
+ await onNetworkEvents;
+
+ info("Wait for the navigation to complete");
+ await onNavigationCompleted;
+
+ // Opening the statistics panel will trigger a reload, expect the same requests
+ // again, we use the same pattern to wait for network events.
+ onNetworkEvents = waitForNetworkEvents(monitor, 3, {
+ expectedPayloadReady: 2,
+ expectedEventTimings: 2,
+ });
+
+ info("Open the statistics panel");
+ const panel = monitor.panelWin;
+ const { document, store, windowRequire, connector } = panel;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.openStatistics(connector, true));
+
+ await waitFor(
+ () => !!document.querySelector(".statistics-panel"),
+ "The statistics panel is displayed"
+ );
+
+ await waitFor(
+ () =>
+ document.querySelectorAll(
+ ".table-chart-container:not([placeholder=true])"
+ ).length == 2,
+ "Two real table charts appear to be rendered correctly."
+ );
+
+ info("Close statistics panel");
+ store.dispatch(Actions.openStatistics(connector, false));
+
+ await waitFor(
+ () => !!document.querySelector(".monitor-panel"),
+ "The regular netmonitor panel is displayed"
+ );
+ info("Wait for the 3 first network events (after opening statistics panel)");
+ await onNetworkEvents;
+
+ onNetworkEvents = waitForNetworkEvents(monitor, 1, {
+ expectedPayloadReady: 2,
+ expectedEventTimings: 2,
+ });
+
+ info("Call unblock()");
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [], () =>
+ content.wrappedJSObject.unblock()
+ );
+
+ // We need to cleanly wait for all events to be finished, otherwise the UI
+ // will throw many unhandled promise rejections.
+ info("Wait for polling and unblock (after opening statistics panel)");
+ await onNetworkEvents;
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_status-bar-transferred-size.js b/devtools/client/netmonitor/test/browser_net_status-bar-transferred-size.js
new file mode 100644
index 0000000000..bc60a2c87c
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_status-bar-transferred-size.js
@@ -0,0 +1,77 @@
+"use strict";
+
+/**
+ * Test if the value of total data transferred is displayed correctly in the Status Bar
+ * Test for Bug 1481002
+ */
+add_task(async () => {
+ // Clear cache, so we see expected number of cached requests.
+ Services.cache2.clear();
+ // Disable rcwn to make cache behavior deterministic.
+ await pushPref("network.http.rcwn.enabled", false);
+
+ const {
+ getFormattedSize,
+ } = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+ const { tab, monitor } = await initNetMonitor(STATUS_CODES_URL, {
+ enableCache: true,
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequestsSummary } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const { L10N } = windowRequire("devtools/client/netmonitor/src/utils/l10n");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ info("Performing requests...");
+ await performRequestsAndWait();
+
+ let cachedItemsInUI = 0;
+ for (const requestItem of document.querySelectorAll(".request-list-item")) {
+ const requestTransferStatus = requestItem.querySelector(
+ ".requests-list-transferred"
+ ).textContent;
+ if (requestTransferStatus === "cached") {
+ cachedItemsInUI++;
+ }
+ }
+
+ is(cachedItemsInUI, 1, "Number of cached requests displayed is correct");
+
+ const state = store.getState();
+ const totalRequestsCount = state.requests.requests.length;
+ const requestsSummary = getDisplayedRequestsSummary(state);
+ info(`Current requests: ${requestsSummary.count} of ${totalRequestsCount}.`);
+
+ const valueTransfer = document.querySelector(
+ ".requests-list-network-summary-transfer"
+ ).textContent;
+ info("Current summary transfer: " + valueTransfer);
+ const expectedTransfer = L10N.getFormatStrWithNumbers(
+ "networkMenu.summary.transferred",
+ getFormattedSize(requestsSummary.contentSize),
+ getFormattedSize(requestsSummary.transferredSize)
+ );
+
+ is(
+ valueTransfer,
+ expectedTransfer,
+ "The current summary transfer is correct."
+ );
+
+ await teardown(monitor);
+
+ async function performRequestsAndWait() {
+ const wait = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.performOneCachedRequest();
+ });
+ await wait;
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_status-bar.js b/devtools/client/netmonitor/test/browser_net_status-bar.js
new file mode 100644
index 0000000000..3ca8ac2da6
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_status-bar.js
@@ -0,0 +1,60 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test whether the StatusBar properly renders expected labels.
+ */
+add_task(async () => {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ await SpecialPowers.pushPrefEnv({
+ set: [["privacy.reduceTimerPrecision", false]],
+ });
+
+ const requestsDone = waitForNetworkEvents(monitor, 1);
+ const markersDone = waitForTimelineMarkers(monitor);
+ await reloadBrowser();
+ await Promise.all([requestsDone, markersDone]);
+
+ const statusBar = document.querySelector(".devtools-toolbar-bottom");
+ const requestCount = statusBar.querySelector(
+ ".requests-list-network-summary-count"
+ );
+ const size = statusBar.querySelector(
+ ".requests-list-network-summary-transfer"
+ );
+ const onContentLoad = statusBar.querySelector(".dom-content-loaded");
+ const onLoad = statusBar.querySelector(".load");
+
+ // All expected labels should be there
+ ok(requestCount, "There must be request count label");
+ ok(size, "There must be size label");
+ ok(onContentLoad, "There must be DOMContentLoaded label");
+ ok(onLoad, "There must be load label");
+
+ // The content should not be empty. The UI update can also be async,
+ // so use waitUntil.
+ await waitUntil(() => requestCount.textContent);
+ ok(true, "There must be request count label text");
+
+ await waitUntil(() => size.textContent);
+ ok(true, "There must be size label text");
+
+ await waitUntil(() => onContentLoad.textContent);
+ ok(true, "There must be DOMContentLoaded label text");
+
+ await waitUntil(() => onLoad.textContent);
+ ok(true, "There must be load label text");
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_status-codes.js b/devtools/client/netmonitor/test/browser_net_status-codes.js
new file mode 100644
index 0000000000..8fd430e740
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_status-codes.js
@@ -0,0 +1,213 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if requests display the correct status code and text in the UI.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { tab, monitor } = await initNetMonitor(STATUS_CODES_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const requestItems = [];
+
+ const REQUEST_DATA = [
+ {
+ // request #0
+ method: "GET",
+ uri: STATUS_CODES_SJS + "?sts=100",
+ correctUri: STATUS_CODES_SJS + "?sts=100",
+ details: {
+ status: 101,
+ statusText: "Switching Protocols",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 0),
+ time: true,
+ },
+ },
+ {
+ // request #1
+ method: "GET",
+ uri: STATUS_CODES_SJS + "?sts=200",
+ correctUri: STATUS_CODES_SJS + "?sts=200",
+ details: {
+ status: 202,
+ statusText: "Created",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 22),
+ time: true,
+ },
+ },
+ {
+ // request #2
+ method: "GET",
+ uri: STATUS_CODES_SJS + "?sts=300",
+ correctUri: STATUS_CODES_SJS + "?sts=300",
+ details: {
+ status: 303,
+ statusText: "See Other",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 22),
+ time: true,
+ },
+ },
+ {
+ // request #3
+ method: "GET",
+ uri: STATUS_CODES_SJS + "?sts=400",
+ correctUri: STATUS_CODES_SJS + "?sts=400",
+ details: {
+ status: 404,
+ statusText: "Not Found",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 22),
+ time: true,
+ },
+ },
+ {
+ // request #4
+ method: "GET",
+ uri: STATUS_CODES_SJS + "?sts=500",
+ correctUri: STATUS_CODES_SJS + "?sts=500",
+ details: {
+ status: 501,
+ statusText: "Not Implemented",
+ type: "plain",
+ fullMimeType: "text/plain; charset=utf-8",
+ size: L10N.getFormatStrWithNumbers("networkMenu.sizeB", 22),
+ time: true,
+ },
+ },
+ ];
+
+ // Execute requests.
+ await performRequests(monitor, tab, 5);
+
+ info("Performing tests");
+ await verifyRequests();
+ await testTab(0, testHeaders);
+
+ return teardown(monitor);
+
+ /**
+ * A helper that verifies all requests show the correct information and caches
+ * request list items to requestItems array.
+ */
+ async function verifyRequests() {
+ const requestListItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestListItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ }
+
+ info("Verifying requests contain correct information.");
+ let index = 0;
+ for (const request of REQUEST_DATA) {
+ const item = getSortedRequests(store.getState())[index];
+ requestItems[index] = item;
+
+ info("Verifying request #" + index);
+ await verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ item,
+ request.method,
+ request.uri,
+ request.details
+ );
+
+ index++;
+ }
+ }
+
+ /**
+ * A helper that opens a given tab of request details pane, selects and passes
+ * all requests to the given test function.
+ *
+ * @param Number tabIdx
+ * The index of tab to activate.
+ * @param Function testFn(requestItem)
+ * A function that should perform all necessary tests. It's called once
+ * for every item of REQUEST_DATA with that item being selected in the
+ * NetworkMonitor.
+ */
+ async function testTab(tabIdx, testFn) {
+ let counter = 0;
+ for (const item of REQUEST_DATA) {
+ info("Testing tab #" + tabIdx + " to update with request #" + counter);
+ await testFn(item, counter);
+
+ counter++;
+ }
+ }
+
+ /**
+ * A function that tests "Headers" panel contains correct information.
+ */
+ async function testHeaders(data, index) {
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+
+ // wait till all the summary section is loaded
+ await waitUntil(() =>
+ document.querySelector("#headers-panel .tabpanel-summary-value")
+ );
+ const panel = document.querySelector("#headers-panel");
+ const {
+ method,
+ correctUri,
+ details: { status, statusText },
+ } = data;
+
+ const statusCode = panel.querySelector(".status-code");
+
+ EventUtils.sendMouseEvent({ type: "mouseover" }, statusCode);
+ await waitUntil(() => statusCode.title);
+
+ is(
+ panel.querySelector(".url-preview .url").textContent,
+ correctUri,
+ "The url summary value is incorrect."
+ );
+ is(
+ panel.querySelectorAll(".treeLabel")[0].textContent,
+ method,
+ "The method value is incorrect."
+ );
+ is(
+ parseInt(statusCode.dataset.code, 10),
+ status,
+ "The status summary code is incorrect."
+ );
+ is(
+ statusCode.getAttribute("title"),
+ status + " " + statusText,
+ "The status summary value is incorrect."
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_streaming-response.js b/devtools/client/netmonitor/test/browser_net_streaming-response.js
new file mode 100644
index 0000000000..854c496ca4
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_streaming-response.js
@@ -0,0 +1,89 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if reponses from streaming content types (MPEG-DASH, HLS) are
+ * displayed as XML or plain text
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests, getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const REQUESTS = [
+ ["hls-m3u8", /^#EXTM3U/],
+ ["mpeg-dash", /^<\?xml/],
+ ];
+
+ let wait = waitForNetworkEvents(monitor, REQUESTS.length);
+ for (const [fmt] of REQUESTS) {
+ const url = CONTENT_TYPE_SJS + "?fmt=" + fmt;
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [{ url }],
+ async function (args) {
+ content.wrappedJSObject.performRequests(1, args.url);
+ }
+ );
+ }
+ await wait;
+
+ const requestItems = document.querySelectorAll(".request-list-item");
+ for (const requestItem of requestItems) {
+ requestItem.scrollIntoView();
+ const requestsListStatus = requestItem.querySelector(".status-code");
+ EventUtils.sendMouseEvent({ type: "mouseover" }, requestsListStatus);
+ await waitUntil(() => requestsListStatus.title);
+ await waitForDOMIfNeeded(requestItem, ".requests-list-timings-total");
+ }
+
+ REQUESTS.forEach(([fmt], i) => {
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ getSortedRequests(store.getState())[i],
+ "GET",
+ CONTENT_TYPE_SJS + "?fmt=" + fmt,
+ {
+ status: 200,
+ statusText: "OK",
+ }
+ );
+ });
+
+ wait = waitForDOM(document, "#response-panel");
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ store.dispatch(Actions.selectRequest(null));
+
+ await selectIndexAndWaitForSourceEditor(monitor, 0);
+ // the hls-m3u8 part
+ testEditorContent(REQUESTS[0]);
+
+ await selectIndexAndWaitForSourceEditor(monitor, 1);
+ // the mpeg-dash part
+ testEditorContent(REQUESTS[1]);
+
+ return teardown(monitor);
+
+ function testEditorContent([fmt, textRe]) {
+ ok(
+ getCodeMirrorValue(monitor).match(textRe),
+ "The text shown in the source editor for " + fmt + " is correct."
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_tabbar_focus.js b/devtools/client/netmonitor/test/browser_net_tabbar_focus.js
new file mode 100644
index 0000000000..3bcc7c0ca1
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_tabbar_focus.js
@@ -0,0 +1,90 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if selecting a tab in a tab bar makes it visible
+ */
+add_task(async function () {
+ Services.prefs.clearUserPref(
+ "devtools.netmonitor.panes-network-details-width"
+ );
+
+ const { tab, monitor } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const topMostDocument = DevToolsUtils.getTopWindow(
+ document.defaultView
+ ).document;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ const networkEvent = waitForNetworkEvents(monitor, 1);
+ tab.linkedBrowser.reload();
+ await networkEvent;
+
+ store.dispatch(Actions.toggleNetworkDetails());
+
+ const splitter = document.querySelector(".splitter");
+
+ await EventUtils.synthesizeMouse(
+ splitter,
+ 0,
+ 1,
+ { type: "mousedown" },
+ monitor.panelWin
+ );
+ await EventUtils.synthesizeMouse(
+ splitter,
+ 300,
+ 1,
+ { type: "mousemove" },
+ monitor.panelWin
+ );
+ await EventUtils.synthesizeMouse(
+ splitter,
+ 300,
+ 1,
+ { type: "mouseup" },
+ monitor.panelWin
+ );
+
+ await waitUntil(() => document.querySelector(".all-tabs-menu"));
+ const allTabsMenu = document.querySelector(".all-tabs-menu");
+ const panelsWidth = document.querySelector(".tabs-menu").offsetWidth;
+
+ const selectTabFromTabsMenuButton = async id => {
+ EventUtils.sendMouseEvent({ type: "click" }, allTabsMenu);
+ const tabMenuElement = topMostDocument.querySelector(
+ `#devtools-sidebar-${id}`
+ );
+ if (tabMenuElement != null) {
+ tabMenuElement.click();
+ // The tab should be visible within the panel
+ const tabLi = document.querySelector(`#${id}-tab`).parentElement;
+ const ulScrollPos =
+ tabLi.parentElement.scrollLeft + tabLi.parentElement.offsetLeft;
+ ok(
+ tabLi.offsetLeft >= ulScrollPos &&
+ tabLi.offsetLeft + tabLi.offsetWidth <= panelsWidth + ulScrollPos,
+ `The ${id} tab is visible`
+ );
+ }
+ };
+
+ for (const elem of [
+ "headers",
+ "cookies",
+ "request",
+ "response",
+ "timings",
+ "security",
+ ]) {
+ await selectTabFromTabsMenuButton(elem);
+ }
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_telemetry_edit_resend.js b/devtools/client/netmonitor/test/browser_net_telemetry_edit_resend.js
new file mode 100644
index 0000000000..3ed6b55aeb
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_telemetry_edit_resend.js
@@ -0,0 +1,71 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const ALL_CHANNELS = Ci.nsITelemetry.DATASET_ALL_CHANNELS;
+
+/**
+ * Test the edit_resend telemetry event.
+ */
+add_task(async function () {
+ if (
+ Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend",
+ true
+ )
+ ) {
+ ok(
+ true,
+ "Skip this test when pref is true, because this panel won't be default when that is the case."
+ );
+ return;
+ }
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Remove all telemetry events (you can check about:telemetry).
+ Services.telemetry.clearEvents();
+
+ // Ensure no events have been logged
+ const snapshot = Services.telemetry.snapshotEvents(ALL_CHANNELS, true);
+ ok(!snapshot.parent, "No events have been logged for the main process");
+
+ // Reload to have one request in the list.
+ const waitForEvents = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await waitForEvents;
+
+ // Open context menu and execute "Edit & Resend".
+ const firstRequest = document.querySelectorAll(".request-list-item")[0];
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, firstRequest);
+ await waitForHeaders;
+ await waitForRequestData(store, ["requestHeaders", "responseHeaders"]);
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, firstRequest);
+
+ // Open "New Request" form and resend.
+ await selectContextMenuItem(monitor, "request-list-context-edit-resend");
+ await waitUntil(() => document.querySelector("#custom-request-send-button"));
+ document.querySelector("#custom-request-send-button").click();
+
+ await waitForNetworkEvents(monitor, 1);
+
+ // Verify existence of the telemetry event.
+ checkTelemetryEvent(
+ {},
+ {
+ method: "edit_resend",
+ }
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_telemetry_filters_changed.js b/devtools/client/netmonitor/test/browser_net_telemetry_filters_changed.js
new file mode 100644
index 0000000000..43ae10f489
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_telemetry_filters_changed.js
@@ -0,0 +1,100 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const ALL_CHANNELS = Ci.nsITelemetry.DATASET_ALL_CHANNELS;
+
+/**
+ * Test the filters_changed telemetry event.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ await waitForAllNetworkUpdateEvents();
+ // Remove all telemetry events (you can check about:telemetry).
+ Services.telemetry.clearEvents();
+
+ // Ensure no events have been logged
+ const snapshot = Services.telemetry.snapshotEvents(ALL_CHANNELS, true);
+ ok(!snapshot.parent, "No events have been logged for the main process");
+
+ // Reload to have one request in the list.
+ const wait = waitForNetworkEvents(monitor, 1);
+ await waitForAllNetworkUpdateEvents();
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await wait;
+
+ info("Click on the 'HTML' filter");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-html-button")
+ );
+
+ checkTelemetryEvent(
+ {
+ trigger: "html",
+ active: "html",
+ inactive: "all,css,js,xhr,fonts,images,media,ws,other",
+ },
+ {
+ method: "filters_changed",
+ }
+ );
+
+ info("Click on the 'CSS' filter");
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector(".requests-list-filter-css-button")
+ );
+
+ checkTelemetryEvent(
+ {
+ trigger: "css",
+ active: "html,css",
+ inactive: "all,js,xhr,fonts,images,media,ws,other",
+ },
+ {
+ method: "filters_changed",
+ }
+ );
+
+ info("Filter the output using the text filter input");
+ setFreetextFilter(monitor, "nomatch");
+
+ // Wait till the text filter is applied.
+ await waitUntil(() => !getDisplayedRequests(store.getState()).length);
+
+ checkTelemetryEvent(
+ {
+ trigger: "text",
+ active: "html,css",
+ inactive: "all,js,xhr,fonts,images,media,ws,other",
+ },
+ {
+ method: "filters_changed",
+ }
+ );
+
+ return teardown(monitor);
+});
+
+function setFreetextFilter(monitor, value) {
+ const { document } = monitor.panelWin;
+
+ const filterBox = document.querySelector(".devtools-filterinput");
+ filterBox.focus();
+ filterBox.value = "";
+ typeInNetmonitor(value, monitor);
+}
diff --git a/devtools/client/netmonitor/test/browser_net_telemetry_persist_toggle_changed.js b/devtools/client/netmonitor/test/browser_net_telemetry_persist_toggle_changed.js
new file mode 100644
index 0000000000..7a8aa956d4
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_telemetry_persist_toggle_changed.js
@@ -0,0 +1,81 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests the log persistence telemetry event
+ */
+const { TelemetryTestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/TelemetryTestUtils.sys.mjs"
+);
+
+function togglePersistLogsOption(monitor) {
+ clickSettingsMenuItem(monitor, "persist-logs");
+}
+
+function ensurePersistLogsCheckedState(monitor, isChecked) {
+ openSettingsMenu(monitor);
+ const persistNode = getSettingsMenuItem(monitor, "persist-logs");
+ return !!persistNode?.getAttribute("aria-checked") === isChecked;
+}
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SINGLE_GET_URL, { requestCount: 1 });
+ info("Starting test... ");
+
+ const { store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ await waitForAllNetworkUpdateEvents();
+
+ // Clear all events
+ Services.telemetry.clearEvents();
+
+ // Ensure no events have been logged
+ TelemetryTestUtils.assertNumberOfEvents(0);
+
+ // Click on the toggle - "true" and make sure it was set to correct value
+ let onPersistChanged = monitor.panelWin.api.once(TEST_EVENTS.PERSIST_CHANGED);
+ togglePersistLogsOption(monitor);
+ await waitUntil(() => ensurePersistLogsCheckedState(monitor, true));
+ await onPersistChanged;
+
+ // Click a second time - "false" and make sure it was set to correct value
+ onPersistChanged = monitor.panelWin.api.once(TEST_EVENTS.PERSIST_CHANGED);
+ togglePersistLogsOption(monitor);
+ await waitUntil(() => ensurePersistLogsCheckedState(monitor, false));
+ await onPersistChanged;
+
+ const expectedEvents = [
+ {
+ category: "devtools.main",
+ method: "persist_changed",
+ object: "netmonitor",
+ value: "true",
+ },
+ {
+ category: "devtools.main",
+ method: "persist_changed",
+ object: "netmonitor",
+ value: "false",
+ },
+ ];
+
+ const filter = {
+ category: "devtools.main",
+ method: "persist_changed",
+ object: "netmonitor",
+ };
+
+ await waitForAllNetworkUpdateEvents();
+ // Will compare filtered events to event list above
+ await TelemetryTestUtils.assertEvents(expectedEvents, filter);
+
+ // Set Persist log preference back to false
+ Services.prefs.setBoolPref("devtools.netmonitor.persistlog", false);
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_telemetry_select_ws_frame.js b/devtools/client/netmonitor/test/browser_net_telemetry_select_ws_frame.js
new file mode 100644
index 0000000000..c3a55dc8cf
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_telemetry_select_ws_frame.js
@@ -0,0 +1,83 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests the select_ws_frame telemetry event.
+ */
+const { TelemetryTestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/TelemetryTestUtils.sys.mjs"
+);
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Clear all events.
+ Services.telemetry.clearEvents();
+
+ // Ensure no events have been logged.
+ TelemetryTestUtils.assertNumberOfEvents(0);
+
+ // Wait for WS connection to be established + send messages.
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(1);
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Select the request to open the side panel.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Wait for all sent/received messages to be displayed in DevTools.
+ const wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+
+ // Click on the "Response" panel.
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel.
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results.
+ is(frames.length, 2, "There should be two frames");
+
+ // Wait for tick, so the `mousedown` event works.
+ await waitForTick();
+
+ // Wait for the payload to be resolved (LongString)
+ const payloadResolved = monitor.panelWin.api.once(
+ TEST_EVENTS.LONGSTRING_RESOLVED
+ );
+
+ // Select frame
+ EventUtils.sendMouseEvent({ type: "mousedown" }, frames[0]);
+ await payloadResolved;
+
+ // Verify existence of the telemetry event.
+ checkTelemetryEvent(
+ {},
+ {
+ method: "select_ws_frame",
+ }
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_telemetry_sidepanel_changed.js b/devtools/client/netmonitor/test/browser_net_telemetry_sidepanel_changed.js
new file mode 100644
index 0000000000..4cb482e569
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_telemetry_sidepanel_changed.js
@@ -0,0 +1,61 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const ALL_CHANNELS = Ci.nsITelemetry.DATASET_ALL_CHANNELS;
+
+/**
+ * Test the sidepanel_changed telemetry event.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Remove all telemetry events (you can check about:telemetry).
+ Services.telemetry.clearEvents();
+
+ // Ensure no events have been logged
+ const snapshot = Services.telemetry.snapshotEvents(ALL_CHANNELS, true);
+ ok(!snapshot.parent, "No events have been logged for the main process");
+
+ // Reload to have one request in the list.
+ const waitForEvents = waitForNetworkEvents(monitor, 1);
+ await navigateTo(HTTPS_SIMPLE_URL);
+ await waitForEvents;
+
+ // Click on a request and wait till the default "Headers" side panel is opened.
+ info("Click on a request");
+ const waitForHeaders = waitUntil(() =>
+ document.querySelector(".headers-overview")
+ );
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await waitForHeaders;
+ await waitForRequestData(store, ["requestHeaders", "responseHeaders"]);
+
+ // Click on the Cookies panel and wait till it's opened.
+ info("Click on the Cookies panel");
+ clickOnSidebarTab(document, "cookies");
+ await waitForRequestData(store, ["requestCookies", "responseCookies"]);
+
+ checkTelemetryEvent(
+ {
+ oldpanel: "headers",
+ newpanel: "cookies",
+ },
+ {
+ method: "sidepanel_changed",
+ }
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_telemetry_throttle_changed.js b/devtools/client/netmonitor/test/browser_net_telemetry_throttle_changed.js
new file mode 100644
index 0000000000..ee27f5de2d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_telemetry_throttle_changed.js
@@ -0,0 +1,50 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const ALL_CHANNELS = Ci.nsITelemetry.DATASET_ALL_CHANNELS;
+
+/**
+ * Test the throttle_change telemetry event.
+ */
+add_task(async function () {
+ const { monitor, toolbox } = await initNetMonitor(SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Remove all telemetry events.
+ Services.telemetry.clearEvents();
+
+ // Ensure no events have been logged
+ const snapshot = Services.telemetry.snapshotEvents(ALL_CHANNELS, true);
+ ok(!snapshot.parent, "No events have been logged for the main process");
+
+ document.getElementById("network-throttling-menu").click();
+ // Throttling menu items cannot be retrieved by id so we can't use getContextMenuItem
+ // here. Instead use querySelector on the toolbox top document, where the context menu
+ // will be rendered.
+ const item = toolbox.topWindow.document.querySelector(
+ "menuitem[label='GPRS']"
+ );
+ await BrowserTestUtils.waitForPopupEvent(item.parentNode, "shown");
+ item.parentNode.activateItem(item);
+ await monitor.panelWin.api.once(TEST_EVENTS.THROTTLING_CHANGED);
+
+ // Verify existence of the telemetry event.
+ checkTelemetryEvent(
+ {
+ mode: "GPRS",
+ },
+ {
+ method: "throttle_changed",
+ }
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_throttle.js b/devtools/client/netmonitor/test/browser_net_throttle.js
new file mode 100644
index 0000000000..dcdfde3ec7
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_throttle.js
@@ -0,0 +1,60 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Network throttling integration test.
+
+"use strict";
+
+requestLongerTimeout(2);
+
+add_task(async function () {
+ await throttleTest({ throttle: true, addLatency: true });
+ await throttleTest({ throttle: true, addLatency: false });
+ await throttleTest({ throttle: false, addLatency: false });
+});
+
+async function throttleTest(options) {
+ const { throttle, addLatency } = options;
+ const { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+ const { store, windowRequire, connector } = monitor.panelWin;
+ const { ACTIVITY_TYPE } = windowRequire(
+ "devtools/client/netmonitor/src/constants"
+ );
+ const { updateNetworkThrottling, triggerActivity } = connector;
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ info(`Starting test... (throttle = ${throttle}, addLatency = ${addLatency})`);
+
+ // When throttling, must be smaller than the length of the content
+ // of SIMPLE_URL in bytes.
+ const size = throttle ? 200 : 0;
+ const latency = addLatency ? 100 : 0;
+
+ const throttleProfile = {
+ latency,
+ download: size,
+ upload: 10000,
+ };
+
+ info("sending throttle request");
+
+ await updateNetworkThrottling(true, throttleProfile);
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await triggerActivity(ACTIVITY_TYPE.RELOAD.WITH_CACHE_DISABLED);
+ await wait;
+
+ await waitForRequestData(store, ["eventTimings"]);
+
+ const requestItem = getSortedRequests(store.getState())[0];
+ const reportedOneSecond = requestItem.eventTimings.timings.receive > 1000;
+ if (throttle) {
+ ok(reportedOneSecond, "download reported as taking more than one second");
+ } else {
+ ok(!reportedOneSecond, "download reported as taking less than one second");
+ }
+
+ await teardown(monitor);
+}
diff --git a/devtools/client/netmonitor/test/browser_net_throttling_profiles.js b/devtools/client/netmonitor/test/browser_net_throttling_profiles.js
new file mode 100644
index 0000000000..707efb8189
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_throttling_profiles.js
@@ -0,0 +1,67 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Test all the network throttling profiles
+
+"use strict";
+
+requestLongerTimeout(2);
+
+const throttlingProfiles = require("resource://devtools/client/shared/components/throttling/profiles.js");
+
+const httpServer = createTestHTTPServer();
+httpServer.registerPathHandler(`/`, function (request, response) {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.write(`<meta charset=utf8><h1>Test throttling profiles</h1>`);
+});
+
+// The "data" path takes a size query parameter and will return a body of the
+// requested size.
+httpServer.registerPathHandler("/data", function (request, response) {
+ const size = request.queryString.match(/size=(\d+)/)[1];
+ response.setHeader("Content-Type", "text/plain");
+
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ const body = new Array(size * 1).join("a");
+ response.bodyOutputStream.write(body, body.length);
+});
+
+const TEST_URI = `http://localhost:${httpServer.identity.primaryPort}/`;
+
+add_task(async function () {
+ await pushPref("devtools.cache.disabled", true);
+
+ const { monitor } = await initNetMonitor(TEST_URI, { requestCount: 1 });
+ const { store, connector, windowRequire } = monitor.panelWin;
+ const { updateNetworkThrottling } = connector;
+
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ for (const profile of throttlingProfiles) {
+ info(`Starting test for throttling profile ${JSON.stringify(profile)}`);
+
+ info("sending throttle request");
+ await updateNetworkThrottling(true, profile);
+
+ const onRequest = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(gBrowser.selectedBrowser, [profile], _profile => {
+ // Size must be greater than the profile download cap.
+ const size = _profile.download * 2;
+ content.fetch("data?size=" + size);
+ });
+ await onRequest;
+
+ info(`Wait for eventTimings for throttling profile ${profile.id}`);
+ await waitForRequestData(store, ["eventTimings"]);
+
+ const requestItem = getSortedRequests(store.getState()).at(-1);
+ ok(
+ requestItem.eventTimings.timings.receive > 1000,
+ `Request was properly throttled for profile ${profile.id}`
+ );
+ }
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_timeline_ticks.js b/devtools/client/netmonitor/test/browser_net_timeline_ticks.js
new file mode 100644
index 0000000000..6989e08f54
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_timeline_ticks.js
@@ -0,0 +1,208 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if timeline correctly displays interval divisions.
+ */
+
+add_task(async function () {
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { monitor } = await initNetMonitor(HTTPS_SIMPLE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { $, $all, NetMonitorView, NetMonitorController } = monitor.panelWin;
+ const { RequestsMenu } = NetMonitorView;
+
+ // Disable transferred size column support for this test.
+ // Without this, the waterfall only has enough room for one division, which
+ // would remove most of the value of this test.
+ // $("#requests-list-transferred-header-box").hidden = true;
+ // $("#requests-list-item-template .requests-list-transferred").hidden = true;
+
+ RequestsMenu.lazyUpdate = false;
+
+ ok(
+ $("#requests-list-waterfall-label"),
+ "An timeline label should be displayed when the frontend is opened."
+ );
+ ok(
+ !$all(".requests-list-timings-division").length,
+ "No tick labels should be displayed when the frontend is opened."
+ );
+
+ ok(
+ !RequestsMenu._canvas,
+ "No canvas should be created when the frontend is opened."
+ );
+ ok(
+ !RequestsMenu._ctx,
+ "No 2d context should be created when the frontend is opened."
+ );
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ // Make sure the DOMContentLoaded and load markers don't interfere with
+ // this test by removing them and redrawing the waterfall (bug 1224088).
+ NetMonitorController.NetworkEventsHandler.clearMarkers();
+ RequestsMenu._flushWaterfallViews(true);
+
+ ok(
+ !$("#requests-list-waterfall-label"),
+ "The timeline label should be hidden after the first request."
+ );
+ ok(
+ $all(".requests-list-timings-division").length >= 3,
+ "There should be at least 3 tick labels in the network requests header."
+ );
+
+ const timingDivisionEls = $all(".requests-list-timings-division");
+ is(
+ timingDivisionEls[0].textContent,
+ L10N.getFormatStr("networkMenu.millisecond", 0),
+ "The first tick label has correct value"
+ );
+ is(
+ timingDivisionEls[1].textContent,
+ L10N.getFormatStr("networkMenu.millisecond", 80),
+ "The second tick label has correct value"
+ );
+ is(
+ timingDivisionEls[2].textContent,
+ L10N.getFormatStr("networkMenu.millisecond", 160),
+ "The third tick label has correct value"
+ );
+
+ is(
+ timingDivisionEls[0].style.width,
+ "78px",
+ "The first tick label has correct width"
+ );
+ is(
+ timingDivisionEls[1].style.width,
+ "80px",
+ "The second tick label has correct width"
+ );
+ is(
+ timingDivisionEls[2].style.width,
+ "80px",
+ "The third tick label has correct width"
+ );
+
+ ok(
+ RequestsMenu._canvas,
+ "A canvas should be created after the first request."
+ );
+ ok(
+ RequestsMenu._ctx,
+ "A 2d context should be created after the first request."
+ );
+
+ const imageData = RequestsMenu._ctx.getImageData(0, 0, 161, 1);
+ ok(imageData, "The image data should have been created.");
+
+ const { data } = imageData;
+ ok(data, "The image data should contain a pixel array.");
+
+ ok(hasPixelAt(0), "The tick at 0 is should not be empty.");
+ ok(!hasPixelAt(1), "The tick at 1 is should be empty.");
+ ok(!hasPixelAt(19), "The tick at 19 is should be empty.");
+ ok(hasPixelAt(20), "The tick at 20 is should not be empty.");
+ ok(!hasPixelAt(21), "The tick at 21 is should be empty.");
+ ok(!hasPixelAt(39), "The tick at 39 is should be empty.");
+ ok(hasPixelAt(40), "The tick at 40 is should not be empty.");
+ ok(!hasPixelAt(41), "The tick at 41 is should be empty.");
+ ok(!hasPixelAt(59), "The tick at 59 is should be empty.");
+ ok(hasPixelAt(60), "The tick at 60 is should not be empty.");
+ ok(!hasPixelAt(61), "The tick at 61 is should be empty.");
+ ok(!hasPixelAt(79), "The tick at 79 is should be empty.");
+ ok(hasPixelAt(80), "The tick at 80 is should not be empty.");
+ ok(!hasPixelAt(81), "The tick at 81 is should be empty.");
+ ok(!hasPixelAt(159), "The tick at 159 is should be empty.");
+ ok(hasPixelAt(160), "The tick at 160 is should not be empty.");
+ ok(!hasPixelAt(161), "The tick at 161 is should be empty.");
+
+ ok(
+ isPixelBrighterAtThan(0, 20),
+ "The tick at 0 should be brighter than the one at 20"
+ );
+ ok(
+ isPixelBrighterAtThan(40, 20),
+ "The tick at 40 should be brighter than the one at 20"
+ );
+ ok(
+ isPixelBrighterAtThan(40, 60),
+ "The tick at 40 should be brighter than the one at 60"
+ );
+ ok(
+ isPixelBrighterAtThan(80, 60),
+ "The tick at 80 should be brighter than the one at 60"
+ );
+
+ ok(
+ isPixelBrighterAtThan(80, 100),
+ "The tick at 80 should be brighter than the one at 100"
+ );
+ ok(
+ isPixelBrighterAtThan(120, 100),
+ "The tick at 120 should be brighter than the one at 100"
+ );
+ ok(
+ isPixelBrighterAtThan(120, 140),
+ "The tick at 120 should be brighter than the one at 140"
+ );
+ ok(
+ isPixelBrighterAtThan(160, 140),
+ "The tick at 160 should be brighter than the one at 140"
+ );
+
+ ok(
+ isPixelEquallyBright(20, 60),
+ "The tick at 20 should be equally bright to the one at 60"
+ );
+ ok(
+ isPixelEquallyBright(100, 140),
+ "The tick at 100 should be equally bright to the one at 140"
+ );
+
+ ok(
+ isPixelEquallyBright(40, 120),
+ "The tick at 40 should be equally bright to the one at 120"
+ );
+
+ ok(
+ isPixelEquallyBright(0, 80),
+ "The tick at 80 should be equally bright to the one at 160"
+ );
+ ok(
+ isPixelEquallyBright(80, 160),
+ "The tick at 80 should be equally bright to the one at 160"
+ );
+
+ function hasPixelAt(x) {
+ const i = (x | 0) * 4;
+ return data[i] && data[i + 1] && data[i + 2] && data[i + 3];
+ }
+
+ function isPixelBrighterAtThan(x1, x2) {
+ const i = (x1 | 0) * 4;
+ const j = (x2 | 0) * 4;
+ return data[i + 3] > data[j + 3];
+ }
+
+ function isPixelEquallyBright(x1, x2) {
+ const i = (x1 | 0) * 4;
+ const j = (x2 | 0) * 4;
+ return data[i + 3] == data[j + 3];
+ }
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_timing-division.js b/devtools/client/netmonitor/test/browser_net_timing-division.js
new file mode 100644
index 0000000000..05935999a1
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_timing-division.js
@@ -0,0 +1,67 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if timing intervals are divided against seconds when appropriate.
+ */
+add_task(async function () {
+ // Show only few columns, so there is enough space
+ // for the waterfall.
+ await pushPref(
+ "devtools.netmonitor.visibleColumns",
+ '["status", "contentSize", "waterfall"]'
+ );
+
+ const { tab, monitor } = await initNetMonitor(CUSTOM_GET_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ const wait = waitForNetworkEvents(monitor, 2);
+ // Timeout needed for having enough divisions on the time scale.
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.performRequests(2, null, 3000);
+ });
+ await wait;
+
+ const milDivs = document.querySelectorAll(
+ ".requests-list-timings-division[data-division-scale=millisecond]"
+ );
+ const secDivs = document.querySelectorAll(
+ ".requests-list-timings-division[data-division-scale=second]"
+ );
+ const minDivs = document.querySelectorAll(
+ ".requests-list-timings-division[data-division-scale=minute]"
+ );
+
+ info("Number of millisecond divisions: " + milDivs.length);
+ info("Number of second divisions: " + secDivs.length);
+ info("Number of minute divisions: " + minDivs.length);
+
+ milDivs.forEach(div => info(`Millisecond division: ${div.textContent}`));
+ secDivs.forEach(div => info(`Second division: ${div.textContent}`));
+ minDivs.forEach(div => info(`Minute division: ${div.textContent}`));
+
+ is(
+ store.getState().requests.requests.length,
+ 2,
+ "There should be only two requests made."
+ );
+
+ ok(
+ secDivs.length,
+ "There should be at least one division on the seconds time scale."
+ );
+ ok(
+ secDivs[0].textContent.match(/\d+\.\d{2}\s\w+/),
+ "The division on the seconds time scale looks legit."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_tracking-resources.js b/devtools/client/netmonitor/test/browser_net_tracking-resources.js
new file mode 100644
index 0000000000..6d7365cb73
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_tracking-resources.js
@@ -0,0 +1,50 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { UrlClassifierTestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/UrlClassifierTestUtils.sys.mjs"
+);
+
+const TEST_URI =
+ "https://example.com/browser/devtools/client/" +
+ "netmonitor/test/html_tracking-protection.html";
+
+registerCleanupFunction(function () {
+ UrlClassifierTestUtils.cleanupTestTrackers();
+});
+
+/**
+ * Test that tracking resources are properly marked in the Network panel.
+ */
+add_task(async function () {
+ await UrlClassifierTestUtils.addTestTrackers();
+
+ const { monitor, tab } = await initNetMonitor(TEST_URI, { requestCount: 1 });
+ info("Starting test...");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute request with third party tracking protection flag.
+ await performRequests(monitor, tab, 1);
+
+ const domainRequests = document.querySelectorAll(
+ ".requests-list-domain .tracking-resource"
+ );
+ const UrlRequests = document.querySelectorAll(
+ ".requests-list-url .tracking-resource"
+ );
+
+ is(
+ domainRequests.length,
+ 1,
+ "There should be one domain column tracking request"
+ );
+ is(UrlRequests.length, 1, "There should be one URL column tracking request");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_truncate-post-data.js b/devtools/client/netmonitor/test/browser_net_truncate-post-data.js
new file mode 100644
index 0000000000..70cdab11b4
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_truncate-post-data.js
@@ -0,0 +1,78 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Bug 1542172 -
+ * Verifies that requests with large post data are truncated and error is displayed.
+ */
+add_task(async function () {
+ const { monitor, tab } = await initNetMonitor(POST_JSON_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ requestLongerTimeout(2);
+
+ info("Perform requests");
+ await performRequestsAndWait(monitor, tab);
+
+ await waitUntil(() => document.querySelector(".request-list-item"));
+ const item = document.querySelectorAll(".request-list-item")[0];
+ await waitUntil(() => item.querySelector(".requests-list-type").title);
+
+ // Make sure the header and editor are loaded
+ const waitHeader = waitForDOM(document, "#request-panel .data-header");
+ const waitSourceEditor = waitForDOM(
+ document,
+ "#request-panel .CodeMirror.cm-s-mozilla"
+ );
+
+ store.dispatch(Actions.toggleNetworkDetails());
+ clickOnSidebarTab(document, "request");
+
+ await Promise.all([waitHeader, waitSourceEditor]);
+
+ const tabpanel = document.querySelector("#request-panel");
+ is(
+ tabpanel.querySelector(".request-error-header") === null,
+ false,
+ "The request error header doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelector(".request-error-header").textContent,
+ "Request has been truncated",
+ "The error message shown is incorrect"
+ );
+ const jsonView = tabpanel.querySelector(".data-label") || {};
+ is(
+ jsonView.textContent === L10N.getStr("jsonScopeName"),
+ false,
+ "The params json view doesn't have the intended visibility."
+ );
+ is(
+ tabpanel.querySelector("PRE") === null,
+ false,
+ "The Request Payload has the intended visibility."
+ );
+
+ return teardown(monitor);
+});
+
+async function performRequestsAndWait(monitor, tab) {
+ const wait = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async function () {
+ content.wrappedJSObject.performLargePostDataRequest();
+ });
+ await wait;
+}
diff --git a/devtools/client/netmonitor/test/browser_net_truncate.js b/devtools/client/netmonitor/test/browser_net_truncate.js
new file mode 100644
index 0000000000..77e6451f7e
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_truncate.js
@@ -0,0 +1,59 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Verifies that truncated response bodies still have the correct reported size.
+ */
+add_task(async function () {
+ const limit = Services.prefs.getIntPref(
+ "devtools.netmonitor.responseBodyLimit"
+ );
+ const URL = EXAMPLE_URL + "sjs_truncate-test-server.sjs?limit=" + limit;
+ const { monitor } = await initNetMonitor(URL, { requestCount: 1 });
+
+ info("Starting test... ");
+
+ const {
+ L10N,
+ } = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+ const { document } = monitor.panelWin;
+
+ const wait = waitForNetworkEvents(monitor, 1);
+ await reloadBrowser();
+ await wait;
+
+ // Response content will be updated asynchronously, we should make sure data is updated
+ // on DOM before asserting.
+ await waitUntil(() => document.querySelector(".request-list-item"));
+ const item = document.querySelectorAll(".request-list-item")[0];
+ await waitUntil(() => item.querySelector(".requests-list-type").title);
+
+ const type = item.querySelector(".requests-list-type").textContent;
+ const fullMimeType = item.querySelector(".requests-list-type").title;
+ const transferred = item.querySelector(
+ ".requests-list-transferred"
+ ).textContent;
+ const size = item.querySelector(".requests-list-size").textContent;
+
+ is(type, "plain", "Type should be rendered correctly.");
+ is(
+ fullMimeType,
+ "text/plain; charset=utf-8",
+ "Mimetype should be rendered correctly."
+ );
+ is(
+ transferred,
+ L10N.getFormatStrWithNumbers("networkMenu.sizeMB", 2.1),
+ "Transferred size should be rendered correctly."
+ );
+ is(
+ size,
+ L10N.getFormatStrWithNumbers("networkMenu.sizeMB", 2.1),
+ "Size should be rendered correctly."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_url-preview.js b/devtools/client/netmonitor/test/browser_net_url-preview.js
new file mode 100644
index 0000000000..c692f5c02d
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_url-preview.js
@@ -0,0 +1,203 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests the url preview expanded state is persisted across requests selections.
+ */
+
+add_task(async function () {
+ const { monitor, tab } = await initNetMonitor(PARAMS_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 12);
+
+ let wait = waitForDOM(document, "#headers-panel .url-preview", 1);
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ await wait;
+
+ // Expand preview
+ await toggleUrlPreview(true, document, monitor);
+
+ // Select the second request
+ wait = waitForDOM(document, "#headers-panel .url-preview", 1);
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[1]
+ );
+ await wait;
+
+ // Test that the url is still expanded
+ const noOfVisibleRowsAfterExpand = document.querySelectorAll(
+ "#headers-panel .url-preview tr.treeRow"
+ ).length;
+ ok(
+ noOfVisibleRowsAfterExpand > 1,
+ "The url preview should still be expanded."
+ );
+
+ // Collapse preview
+ await toggleUrlPreview(false, document, monitor);
+
+ // Select the third request
+ wait = waitForDOM(document, "#headers-panel .url-preview", 1);
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[2]
+ );
+ await wait;
+
+ // Test that the url is still collapsed
+ const noOfVisibleRowsAfterCollapse = document.querySelectorAll(
+ "#headers-panel .url-preview tr.treeRow"
+ ).length;
+ ok(
+ noOfVisibleRowsAfterCollapse == 1,
+ "The url preview should still be collapsed."
+ );
+
+ return teardown(monitor);
+});
+
+/**
+ * Checks if the query parameter arrays are formatted as we expected.
+ */
+
+add_task(async function () {
+ const { monitor } = await initNetMonitor(PARAMS_URL, {
+ requestCount: 1,
+ });
+
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const netWorkEvent = waitForNetworkEvents(monitor, 3);
+ await performRequestsInContent([
+ // URL with same parameter name with different values
+ { url: "sjs_content-type-test-server.sjs?a=3&a=45&a=60" },
+
+ // URL with mix of different parameter names
+ { url: "sjs_content-type-test-server.sjs?x=5&a=3&a=4&a=3&b=3" },
+
+ // URL contains a parameter with `query` as the name. This makes sure
+ // there is no conflict with the query property on the Url Object in the
+ // UrlPreview
+ { url: "sjs_content-type-test-server.sjs?x=5&a=3&a=4&a=3&query=3" },
+
+ // URL contains a paramter with `__proto__` as the name. This makes sure
+ // there is no conflict with the prototype chain of the JS object.
+ { url: "sjs_content-type-test-server.sjs?__proto__=5" },
+ ]);
+ await netWorkEvent;
+
+ let urlPreview = waitForDOM(document, "#headers-panel .url-preview", 1);
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+ let urlPreviewValue = (await urlPreview)[0].textContent;
+
+ ok(
+ urlPreviewValue.endsWith("?a=3&a=45&a=60"),
+ "The parameters in the url preview match."
+ );
+
+ urlPreview = waitForDOM(document, "#headers-panel .url-preview", 1);
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[1]
+ );
+
+ urlPreviewValue = (await urlPreview)[0].textContent;
+ ok(
+ urlPreviewValue.endsWith("?x=5&a=3&a=4&a=3&b=3"),
+ "The parameters in the url preview match."
+ );
+
+ urlPreview = waitForDOM(document, "#headers-panel .url-preview", 1);
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[2]
+ );
+
+ urlPreviewValue = (await urlPreview)[0].textContent;
+ ok(
+ urlPreviewValue.endsWith("?x=5&a=3&a=4&a=3&query=3"),
+ "The parameters in the url preview match."
+ );
+
+ // Expand preview
+ await toggleUrlPreview(true, document, monitor);
+
+ // Check if the expanded preview contains the "query" parameter
+ is(
+ document.querySelector(
+ "#headers-panel .url-preview tr#\\/GET\\/query\\/query .treeLabelCell"
+ ).textContent,
+ "query",
+ "Contains the query parameter"
+ );
+
+ // Collapse preview
+ await toggleUrlPreview(false, document, monitor);
+
+ urlPreview = waitForDOM(document, "#headers-panel .url-preview", 1);
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[3]
+ );
+
+ urlPreviewValue = (await urlPreview)[0].textContent;
+ ok(
+ urlPreviewValue.endsWith("?__proto__=5"),
+ "The parameters in the url preview match."
+ );
+
+ // Expand preview
+ await toggleUrlPreview(true, document, monitor);
+
+ // Check if the expanded preview contains the "__proto__" parameter
+ is(
+ document.querySelector(
+ "#headers-panel .url-preview tr#\\/GET\\/query\\/__proto__ .treeLabelCell"
+ ).textContent,
+ "__proto__",
+ "Contains the __proto__ parameter"
+ );
+
+ return teardown(monitor);
+});
+
+async function toggleUrlPreview(shouldExpand, document, monitor) {
+ const wait = waitUntil(() => {
+ const rowSize = document.querySelectorAll(
+ "#headers-panel .url-preview tr.treeRow"
+ ).length;
+ return shouldExpand ? rowSize > 1 : rowSize == 1;
+ });
+
+ clickElement(
+ document.querySelector(
+ "#headers-panel .url-preview tr:first-child span.treeIcon.theme-twisty"
+ ),
+ monitor
+ );
+ return wait;
+}
diff --git a/devtools/client/netmonitor/test/browser_net_use_as_fetch.js b/devtools/client/netmonitor/test/browser_net_use_as_fetch.js
new file mode 100644
index 0000000000..a49b47f75b
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_use_as_fetch.js
@@ -0,0 +1,85 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests if Use as Fetch works.
+ */
+
+add_task(async function () {
+ const { tab, monitor, toolbox } = await initNetMonitor(CURL_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ // GET request, no cookies (first request)
+ await performRequest("GET");
+ await testConsoleInput(`await fetch("http://example.com/browser/devtools/client/netmonitor/test/sjs_simple-test-server.sjs", {
+ "credentials": "omit",
+ "headers": {
+ "User-Agent": "${navigator.userAgent}",
+ "Accept": "*/*",
+ "Accept-Language": "en-US",
+ "X-Custom-Header-1": "Custom value",
+ "X-Custom-Header-2": "8.8.8.8",
+ "X-Custom-Header-3": "Mon, 3 Mar 2014 11:11:11 GMT",
+ "Pragma": "no-cache",
+ "Cache-Control": "no-cache"
+ },
+ "referrer": "http://example.com/browser/devtools/client/netmonitor/test/html_copy-as-curl.html",
+ "method": "GET",
+ "mode": "cors"
+});`);
+
+ await teardown(monitor);
+
+ async function performRequest(method, payload) {
+ const waitRequest = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(
+ tab.linkedBrowser,
+ [
+ {
+ url: SIMPLE_SJS,
+ method_: method,
+ payload_: payload,
+ },
+ ],
+ async function ({ url, method_, payload_ }) {
+ content.wrappedJSObject.performRequest(url, method_, payload_);
+ }
+ );
+ await waitRequest;
+ }
+
+ async function testConsoleInput(expectedResult) {
+ const { document } = monitor.panelWin;
+
+ const items = document.querySelectorAll(".request-list-item");
+ EventUtils.sendMouseEvent({ type: "mousedown" }, items[items.length - 1]);
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelectorAll(".request-list-item")[0]
+ );
+
+ /* Ensure that the use as fetch option is always visible */
+ is(
+ !!getContextMenuItem(monitor, "request-list-context-use-as-fetch"),
+ true,
+ 'The "Use as Fetch" context menu item should not be hidden.'
+ );
+
+ const split = toolbox.once("split-console");
+ await selectContextMenuItem(monitor, "request-list-context-use-as-fetch");
+
+ await split;
+ const hud = toolbox.getPanel("webconsole").hud;
+ await hud.jsterm.once("set-input-value");
+
+ is(
+ hud.getInputValue(),
+ expectedResult,
+ "Console input contains fetch request for item " + (items.length - 1)
+ );
+ }
+});
diff --git a/devtools/client/netmonitor/test/browser_net_view-source-debugger.js b/devtools/client/netmonitor/test/browser_net_view-source-debugger.js
new file mode 100644
index 0000000000..e443001da0
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_view-source-debugger.js
@@ -0,0 +1,80 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// There are shutdown issues for which multiple rejections are left uncaught.
+// See bug 1018184 for resolving these issues.
+const { PromiseTestUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/PromiseTestUtils.sys.mjs"
+);
+PromiseTestUtils.allowMatchingRejectionsGlobally(/Component not initialized/);
+PromiseTestUtils.allowMatchingRejectionsGlobally(/Connection closed/);
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/devtools/client/debugger/test/mochitest/shared-head.js",
+ this
+);
+
+/**
+ * Tests if on clicking the stack frame, UI switches to the Debugger panel.
+ */
+add_task(async function () {
+ // Set a higher panel height in order to get full CodeMirror content
+ await pushPref("devtools.toolbox.footer.height", 400);
+
+ const { tab, monitor, toolbox } = await initNetMonitor(POST_DATA_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ store.dispatch(Actions.batchEnable(false));
+
+ // Execute requests.
+ await performRequests(monitor, tab, 2);
+
+ info("Clicking stack-trace tab and waiting for stack-trace panel to open");
+ const waitForTab = waitForDOM(document, "#stack-trace-tab");
+ // Click on the first request
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelector(".request-list-item")
+ );
+ await waitForTab;
+ const waitForPanel = waitForDOM(
+ document,
+ "#stack-trace-panel .frame-link",
+ 6
+ );
+ // Open the stack-trace tab for that request
+ document.getElementById("stack-trace-tab").click();
+ await waitForPanel;
+
+ const frameLinkNode = document.querySelector(".frame-link");
+ await checkClickOnNode(toolbox, frameLinkNode);
+
+ await teardown(monitor);
+});
+
+/**
+ * Helper function for testOpenInDebugger.
+ */
+async function checkClickOnNode(toolbox, frameLinkNode) {
+ info("checking click on node location");
+
+ const url = frameLinkNode.getAttribute("data-url");
+ ok(url, `source url found ("${url}")`);
+
+ const line = frameLinkNode.getAttribute("data-line");
+ ok(line, `source line found ("${line}")`);
+
+ // Fire the click event
+ frameLinkNode.querySelector(".frame-link-source").click();
+
+ // Wait for the debugger to have fully processed the opened source
+ await toolbox.getPanelWhenReady("jsdebugger");
+ const dbg = createDebuggerContext(toolbox);
+ await waitForSelectedSource(dbg, url);
+}
diff --git a/devtools/client/netmonitor/test/browser_net_waterfall-click.js b/devtools/client/netmonitor/test/browser_net_waterfall-click.js
new file mode 100644
index 0000000000..a54b3b8eee
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_waterfall-click.js
@@ -0,0 +1,36 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that clicking on the waterfall opens the timing sidebar panel.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ CONTENT_TYPE_WITHOUT_CACHE_URL,
+ { requestCount: 1 }
+ );
+ const { document } = monitor.panelWin;
+
+ // Execute requests.
+ await performRequests(monitor, tab, CONTENT_TYPE_WITHOUT_CACHE_REQUESTS);
+
+ info("Clicking waterfall and waiting for panel update.");
+ const wait = waitForDOM(document, "#timings-panel");
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".requests-list-timings")[0]
+ );
+
+ await wait;
+
+ ok(
+ document.querySelector("#timings-tab[aria-selected=true]"),
+ "Timings tab is selected."
+ );
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_websocket_stacks.js b/devtools/client/netmonitor/test/browser_net_websocket_stacks.js
new file mode 100644
index 0000000000..cb9acf9d5b
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_websocket_stacks.js
@@ -0,0 +1,94 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Test that we get stack traces for the network requests made when creating
+// web sockets on the main or worker threads.
+
+const TOP_FILE_NAME = "html_websocket-test-page.html";
+const TOP_URL = HTTPS_EXAMPLE_URL + TOP_FILE_NAME;
+const WORKER_FILE_NAME = "js_websocket-worker-test.js";
+
+const EXPECTED_REQUESTS = {
+ [TOP_URL]: {
+ method: "GET",
+ url: TOP_URL,
+ causeType: "document",
+ causeUri: null,
+ stack: false,
+ },
+ "ws://localhost:8080/": {
+ method: "GET",
+ url: "ws://localhost:8080/",
+ causeType: "websocket",
+ causeUri: TOP_URL,
+ stack: [
+ { fn: "openSocket", file: TOP_URL, line: 6 },
+ { file: TOP_FILE_NAME, line: 3 },
+ ],
+ },
+ [HTTPS_EXAMPLE_URL + WORKER_FILE_NAME]: {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + WORKER_FILE_NAME,
+ causeType: "script",
+ causeUri: TOP_URL,
+ stack: [{ file: TOP_URL, line: 9 }],
+ },
+ "wss://localhost:8081/": {
+ method: "GET",
+ url: "wss://localhost:8081/",
+ causeType: "websocket",
+ causeUri: TOP_URL,
+ stack: [
+ {
+ fn: "openWorkerSocket",
+ file: HTTPS_EXAMPLE_URL + WORKER_FILE_NAME,
+ line: 5,
+ },
+ { file: WORKER_FILE_NAME, line: 2 },
+ ],
+ },
+};
+
+add_task(async function () {
+ // Load a different URL first to instantiate the network monitor before we
+ // load the page we're really interested in.
+ const { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+
+ const { store, windowRequire, connector } = monitor.panelWin;
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ const onNetworkEvents = waitForNetworkEvents(
+ monitor,
+ Object.keys(EXPECTED_REQUESTS).length
+ );
+ await navigateTo(TOP_URL);
+ await onNetworkEvents;
+
+ is(
+ store.getState().requests.requests.length,
+ Object.keys(EXPECTED_REQUESTS).length,
+ "All the page events should be recorded."
+ );
+
+ const requests = getSortedRequests(store.getState());
+ // The expected requests in the same order as the
+ // requests. The platform does not guarantee the order so the
+ // tests should not depend on that.
+ const expectedRequests = [];
+
+ // Wait for stack traces from all requests.
+ await Promise.all(
+ requests.map(request => {
+ expectedRequests.push(EXPECTED_REQUESTS[request.url]);
+ return connector.requestData(request.id, "stackTrace");
+ })
+ );
+
+ validateRequests(expectedRequests, monitor);
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_worker_stacks.js b/devtools/client/netmonitor/test/browser_net_worker_stacks.js
new file mode 100644
index 0000000000..febbea8d09
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_worker_stacks.js
@@ -0,0 +1,119 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Test that we get stack traces for the network requests made when starting or
+// running worker threads.
+
+const TOP_FILE_NAME = "html_worker-test-page.html";
+const TOP_URL = HTTPS_EXAMPLE_URL + TOP_FILE_NAME;
+const WORKER_FILE_NAME = "js_worker-test.js";
+const WORKER_URL = HTTPS_EXAMPLE_URL + WORKER_FILE_NAME;
+
+const EXPECTED_REQUESTS = [
+ {
+ method: "GET",
+ url: TOP_URL,
+ causeType: "document",
+ causeUri: null,
+ stack: false,
+ },
+ {
+ method: "GET",
+ url: WORKER_URL,
+ causeType: "script",
+ causeUri: TOP_URL,
+ stack: [
+ { fn: "startWorkerInner", file: TOP_URL, line: 11 },
+ { fn: "startWorker", file: TOP_URL, line: 8 },
+ { file: TOP_URL, line: 4 },
+ ],
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "missing1.js",
+ causeType: "script",
+ causeUri: TOP_URL,
+ stack: [
+ { fn: "importScriptsFromWorker", file: WORKER_URL, line: 14 },
+ { file: WORKER_URL, line: 10 },
+ ],
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "missing2.js",
+ causeType: "script",
+ causeUri: TOP_URL,
+ stack: [
+ { fn: "importScriptsFromWorker", file: WORKER_URL, line: 14 },
+ { file: WORKER_URL, line: 10 },
+ ],
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "js_worker-test2.js",
+ causeType: "script",
+ causeUri: TOP_URL,
+ stack: [
+ { fn: "startWorkerFromWorker", file: WORKER_URL, line: 7 },
+ { file: WORKER_URL, line: 3 },
+ ],
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "missing.json",
+ causeType: "xhr",
+ causeUri: TOP_URL,
+ stack: [
+ { fn: "createJSONRequest", file: WORKER_URL, line: 22 },
+ { file: WORKER_URL, line: 18 },
+ ],
+ },
+ {
+ method: "GET",
+ url: HTTPS_EXAMPLE_URL + "missing.txt",
+ causeType: "fetch",
+ causeUri: TOP_URL,
+ stack: [
+ { fn: "fetchThing", file: WORKER_URL, line: 29 },
+ { file: WORKER_URL, line: 26 },
+ ],
+ },
+];
+
+add_task(async function () {
+ // Load a different URL first to instantiate the network monitor before we
+ // load the page we're really interested in.
+ const { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+
+ const { store, windowRequire, connector } = monitor.panelWin;
+ const { getSortedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+
+ const onNetworkEvents = waitForNetworkEvents(
+ monitor,
+ EXPECTED_REQUESTS.length
+ );
+ await navigateTo(TOP_URL);
+ await onNetworkEvents;
+
+ is(
+ store.getState().requests.requests.length,
+ EXPECTED_REQUESTS.length,
+ "All the page events should be recorded."
+ );
+
+ // Wait for stack traces from all requests.
+ const requests = getSortedRequests(store.getState());
+ await Promise.all(
+ requests.map(requestItem =>
+ connector.requestData(requestItem.id, "stackTrace")
+ )
+ );
+
+ validateRequests(EXPECTED_REQUESTS, monitor, { allowDifferentOrder: true });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-basic.js b/devtools/client/netmonitor/test/browser_net_ws-basic.js
new file mode 100644
index 0000000000..a6d0d0070e
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-basic.js
@@ -0,0 +1,79 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WS connection is established successfully and sent/received messages are correct.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connection to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(1);
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Select the request to open the side panel.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ const wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 2, "There should be two frames");
+
+ // Sent frame
+ is(
+ frames[0].children[0].textContent,
+ " Payload 0",
+ "The correct sent payload should be displayed"
+ );
+ is(frames[0].classList.contains("sent"), true, "The payload type is 'Sent'");
+
+ // Received frame
+ is(
+ frames[1].children[0].textContent,
+ " Payload 0",
+ "The correct received payload should be displayed"
+ );
+ is(
+ frames[1].classList.contains("received"),
+ true,
+ "The payload type is 'Received'"
+ );
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-clear.js b/devtools/client/netmonitor/test/browser_net_ws-clear.js
new file mode 100644
index 0000000000..0636f862bd
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-clear.js
@@ -0,0 +1,84 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WS connection is established successfully and clearing messages works correctly.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connection(s) to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(2);
+ await content.wrappedJSObject.openConnection(1);
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 2, "There should be two requests");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ let wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 4
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 4, "There should be four frames");
+
+ // Clear messages
+ const clearButton = document.querySelector(
+ "#messages-view .message-list-clear-button"
+ );
+ clearButton.click();
+ is(
+ document.querySelectorAll(".message-list-empty-notice").length,
+ 1,
+ "Empty notice visible"
+ );
+
+ // Select the second request and check that the messages are not cleared
+ wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[1]);
+ await wait;
+ const secondRequestFrames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+ is(secondRequestFrames.length, 2, "There should be two frames");
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-connection-closed.js b/devtools/client/netmonitor/test/browser_net_ws-connection-closed.js
new file mode 100644
index 0000000000..900c11df7e
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-connection-closed.js
@@ -0,0 +1,54 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WS connection is established successfully and message is displayed when the connection is closed.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connection to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await ContentTask.spawn(tab.linkedBrowser, {}, async () => {
+ await content.wrappedJSObject.openConnection(1);
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+
+ // Select the request to open the side panel.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+
+ const wait = waitForDOM(
+ document,
+ "#messages-view .msg-connection-closed-message"
+ );
+
+ // Close WS connection
+ await ContentTask.spawn(tab.linkedBrowser, {}, async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+ await wait;
+
+ is(
+ !!document.querySelector("#messages-view .msg-connection-closed-message"),
+ true,
+ "Connection closed message should be displayed"
+ );
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-early-connection.js b/devtools/client/netmonitor/test/browser_net_ws-early-connection.js
new file mode 100644
index 0000000000..e64dcc53f1
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-early-connection.js
@@ -0,0 +1,62 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WS connection created while the page is still loading
+ * is properly tracked and there are WS frames displayed in the
+ * Messages side panel.
+ */
+add_task(async function () {
+ const { monitor } = await initNetMonitor(SIMPLE_URL, { requestCount: 1 });
+
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Make the WS Messages side panel the default so, we avoid
+ // request headers from the backend by selecting the Headers
+ // panel
+ store.dispatch(Actions.selectDetailsPanelTab("response"));
+
+ // Load page that opens WS connection during the load time.
+ const waitForEvents = waitForNetworkEvents(monitor, 3);
+ await navigateTo(WS_PAGE_EARLY_CONNECTION_URL);
+ await waitForEvents;
+
+ const requests = document.querySelectorAll(
+ ".request-list-item .requests-list-file"
+ );
+ is(requests.length, 3, "There should be three requests");
+
+ // Get index of the WS connection request.
+ const index = Array.from(requests).findIndex(element => {
+ return element.textContent === "file_ws_backend";
+ });
+
+ ok(index !== -1, "There must be one WS connection request");
+
+ // Select the connection request to see WS frames in the side panel.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[index]);
+
+ info("Waiting for WS frames...");
+
+ // Wait for two frames to be displayed in the panel
+ await waitForDOMIfNeeded(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+
+ // Check the payload of the first frame.
+ const firstFramePayload = document.querySelector(
+ "#messages-view .message-list-table .message-list-item .message-list-payload"
+ );
+ is(firstFramePayload.textContent.trim(), "readyState:loading");
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-filter-dropdown.js b/devtools/client/netmonitor/test/browser_net_ws-filter-dropdown.js
new file mode 100644
index 0000000000..c17fbeba49
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-filter-dropdown.js
@@ -0,0 +1,136 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WS connection is established successfully and filtered messages using the dropdown menu are correct.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connection to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(2);
+ await content.wrappedJSObject.openConnection(3);
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 2, "There should be two requests");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ let wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 4
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 4, "There should be four frames");
+
+ // Click on filter menu
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#frame-filter-menu")
+ );
+
+ // Click on "sent" option and check
+ await selectContextMenuItem(monitor, "message-list-context-filter-sent");
+
+ const sentFrames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+ is(sentFrames.length, 2, "There should be two frames");
+ is(
+ sentFrames[0].classList.contains("sent"),
+ true,
+ "The payload type is 'Sent'"
+ );
+ is(
+ sentFrames[1].classList.contains("sent"),
+ true,
+ "The payload type is 'Sent'"
+ );
+
+ // Click on filter menu
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ document.querySelector("#frame-filter-menu")
+ );
+
+ // Click on "received" option and check
+ await selectContextMenuItem(monitor, "message-list-context-filter-received");
+
+ const receivedFrames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+ is(receivedFrames.length, 2, "There should be two frames");
+ is(
+ receivedFrames[0].classList.contains("received"),
+ true,
+ "The payload type is 'Received'"
+ );
+ is(
+ receivedFrames[1].classList.contains("received"),
+ true,
+ "The payload type is 'Received'"
+ );
+
+ // Select the second request and check that the filter option is the same
+ wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 3
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[1]);
+ await wait;
+ const secondRequestFrames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+ is(secondRequestFrames.length, 3, "There should be three frames");
+ is(
+ secondRequestFrames[0].classList.contains("received"),
+ true,
+ "The payload type is 'Received'"
+ );
+ is(
+ secondRequestFrames[1].classList.contains("received"),
+ true,
+ "The payload type is 'Received'"
+ );
+ is(
+ secondRequestFrames[2].classList.contains("received"),
+ true,
+ "The payload type is 'Received'"
+ );
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-filter-regex.js b/devtools/client/netmonitor/test/browser_net_ws-filter-regex.js
new file mode 100644
index 0000000000..0081b46cb4
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-filter-regex.js
@@ -0,0 +1,76 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that RegEx filter is worrking.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+ const { getDisplayedMessages } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/messages"
+ );
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connection(s) to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(1);
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ const wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 2, "There should be two frames");
+
+ const filterInput = document.querySelector(
+ "#messages-view .devtools-filterinput"
+ );
+ filterInput.focus();
+ typeInNetmonitor("/Payload [0-9]+/", monitor);
+
+ // Wait till the text filter is applied.
+ await waitUntil(() => getDisplayedMessages(store.getState()).length == 2);
+
+ const filteredFrames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+ is(filteredFrames.length, 2, "There should be two frames");
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-json-action-cable-payload.js b/devtools/client/netmonitor/test/browser_net_ws-json-action-cable-payload.js
new file mode 100644
index 0000000000..7ad45a2030
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-json-action-cable-payload.js
@@ -0,0 +1,109 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WebSocket payloads containing action cable messages are parsed
+ * correctly and displayed in a user friendly way
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connections to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(0);
+ content.wrappedJSObject.sendData(`{"data":"{\\"x\\":2}"}`);
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ let wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ await clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 2, "There should be two frames");
+
+ // Wait for next tick to do async stuff (The MessagePayload component uses the async function getMessagePayload)
+ await waitForTick();
+ const waitForData = waitForDOM(document, "#messages-view .properties-view");
+ const [requestFrame] = frames;
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requestFrame);
+
+ await waitForData;
+
+ is(
+ document.querySelector("#messages-view .data-label").innerText,
+ "Action Cable",
+ "The Action Cable payload panel should be displayed"
+ );
+
+ ok(
+ document.querySelector("#messages-view .treeTable"),
+ "A tree table should be used to display the formatted payload"
+ );
+
+ ok(
+ document.getElementById("/data"),
+ "The 'data' property should be displayed"
+ );
+ ok(
+ document.getElementById("/data/x"),
+ "The 'x' property in the 'data' object should be displayed"
+ );
+
+ // Toggle raw data display
+ wait = waitForDOM(document, "#messages-view .message-rawData-payload");
+ const rawDataToggle = document.querySelector(
+ "#messages-view .devtools-checkbox-toggle"
+ );
+ clickElement(rawDataToggle, monitor);
+ await wait;
+
+ is(
+ document.querySelector("#messages-view .data-label").innerText,
+ "Raw Data (20 B)",
+ "The raw data payload info should be displayed"
+ );
+
+ is(
+ document.querySelector("#messages-view .message-rawData-payload").value,
+ `{"data":"{\\"x\\":2}"}`,
+ "The raw data must be shown correctly"
+ );
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-json-payload.js b/devtools/client/netmonitor/test/browser_net_ws-json-payload.js
new file mode 100644
index 0000000000..8980dde313
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-json-payload.js
@@ -0,0 +1,112 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WebSocket payloads containing a basic JSON message is parsed
+ * correctly and displayed in a user friendly way
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connections to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(0);
+ content.wrappedJSObject.sendData(
+ `{\"foo\":{\"x\":1,\"y\":2}, \"bar\":{\"x\":1,\"y\":2}}`
+ );
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ let wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ await clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 2, "There should be two frames");
+
+ // Wait for next tick to do async stuff (The MessagePayload component uses the async function getMessagePayload)
+ await waitForTick();
+ const waitForData = waitForDOM(document, "#messages-view .properties-view");
+ const [requestFrame] = frames;
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requestFrame);
+
+ await waitForData;
+
+ is(
+ document.querySelector("#messages-view .data-label").innerText,
+ "JSON",
+ "The JSON payload panel should be displayed"
+ );
+
+ ok(
+ document.querySelector("#messages-view .treeTable"),
+ "A tree table should be used to display the formatted payload"
+ );
+
+ ok(document.getElementById("/foo"), "The 'foo' property should be displayed");
+ ok(
+ document.getElementById("/foo/x"),
+ "The 'x' property in the `foo` object should be displayed"
+ );
+ ok(
+ document.getElementById("/bar/y"),
+ "The 'y' property in the `bar` object should be displayed"
+ );
+
+ // Toggle raw data display
+ wait = waitForDOM(document, "#messages-view .message-rawData-payload");
+ const rawDataToggle = document.querySelector(
+ "#messages-view .devtools-checkbox-toggle"
+ );
+ clickElement(rawDataToggle, monitor);
+ await wait;
+
+ is(
+ document.querySelector("#messages-view .data-label").innerText,
+ "Raw Data (42 B)",
+ "The raw data payload info should be displayed"
+ );
+
+ is(
+ document.querySelector("#messages-view .message-rawData-payload").value,
+ `{\"foo\":{\"x\":1,\"y\":2}, \"bar\":{\"x\":1,\"y\":2}}`,
+ "The raw data must be shown correctly"
+ );
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-json-stomp-payload.js b/devtools/client/netmonitor/test/browser_net_ws-json-stomp-payload.js
new file mode 100644
index 0000000000..74c5d08dd0
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-json-stomp-payload.js
@@ -0,0 +1,115 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WebSocket payloads containing an array of STOMP messages are parsed
+ * correctly and displayed in a user friendly way
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connections to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(0);
+ content.wrappedJSObject.sendData(
+ `[\"SEND\\nx-firefox-test:true\\ncontent-length:17\\n\\n[{\\\"key\\\":\\\"value\\\"}]\\u0000\"]`
+ );
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ let wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 2, "There should be two frames");
+
+ // Wait for next tick to do async stuff (The MessagePayload component uses the async function getMessagePayload)
+ await waitForTick();
+ const waitForData = waitForDOM(document, "#messages-view .properties-view");
+ const [requestFrame] = frames;
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requestFrame);
+
+ await waitForData;
+
+ is(
+ document.querySelector("#messages-view .data-label").innerText,
+ "JSON",
+ "The JSON payload panel should be displayed"
+ );
+
+ ok(
+ document.querySelector("#messages-view .treeTable"),
+ "A tree table should be used to display the formatted payload"
+ );
+
+ ok(
+ document.getElementById("/0/command"),
+ "The message 'command' should be displayed"
+ );
+ ok(
+ document.getElementById("/0/headers"),
+ "The message 'headers' should be displayed"
+ );
+ ok(
+ document.getElementById("/0/body"),
+ "The message 'body' should be displayed"
+ );
+
+ // Toggle raw data display
+ wait = waitForDOM(document, "#messages-view .message-rawData-payload");
+ const rawDataToggle = document.querySelector(
+ "#messages-view .devtools-checkbox-toggle"
+ );
+ clickElement(rawDataToggle, monitor);
+ await wait;
+
+ is(
+ document.querySelector("#messages-view .data-label").innerText,
+ "Raw Data (79 B)",
+ "The raw data payload info should be displayed"
+ );
+
+ is(
+ document.querySelector("#messages-view .message-rawData-payload").value,
+ `[\"SEND\\nx-firefox-test:true\\ncontent-length:17\\n\\n[{\\\"key\\\":\\\"value\\\"}]\\u0000\"]`,
+ "The raw data must be shown correctly"
+ );
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-keep-future-frames.js b/devtools/client/netmonitor/test/browser_net_ws-keep-future-frames.js
new file mode 100644
index 0000000000..a4eda01d0b
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-keep-future-frames.js
@@ -0,0 +1,87 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async function () {
+ // Set WS messages limit to a lower value for testing
+ await pushPref("devtools.netmonitor.msg.displayed-messages.limit", 10);
+
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connections to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(10);
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Wait for truncated message notification to appear
+ const truncatedMessageWait = waitForDOM(
+ document,
+ "#messages-view .truncated-message"
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await truncatedMessageWait;
+
+ // Wait for truncated message notification to appear and to have an expected text
+ await waitFor(() =>
+ document
+ .querySelector("#messages-view .truncated-message")
+ .textContent.includes("10 messages")
+ );
+
+ // Set on 'Keep all future messages' checkbox
+ const truncationCheckbox = document.querySelector(
+ "#messages-view .truncation-checkbox"
+ );
+ truncationCheckbox.click();
+
+ // Get rid of all current messages
+ const clearButton = document.querySelector(
+ "#messages-view .message-list-clear-button"
+ );
+ clearButton.click();
+
+ // And request new messages
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.sendFrames(10);
+ });
+
+ // Wait while they appear in the Response tab
+ // We should see all requested messages (sometimes more than 20 = 10 sent + 10 received)
+ await waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 20
+ );
+
+ const truncatedMessage = document.querySelector(
+ "#messages-view .truncated-message"
+ ).textContent;
+
+ is(truncatedMessage, "0 messages have been truncated to conserve memory");
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-limit-frames.js b/devtools/client/netmonitor/test/browser_net_ws-limit-frames.js
new file mode 100644
index 0000000000..1c9ee009cd
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-limit-frames.js
@@ -0,0 +1,63 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WS connection is established successfully and the truncated message notification displays correctly.
+ */
+
+add_task(async function () {
+ // Set WS messages limit to a lower value for testing
+ await pushPref("devtools.netmonitor.msg.displayed-messages.limit", 30);
+
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connections to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(20);
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Wait for truncated message notification to appear
+ const wait = waitForDOM(document, "#messages-view .truncated-message");
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 30, "There should be thirty frames");
+ is(
+ document.querySelectorAll("#messages-view .truncated-message").length,
+ 1,
+ "Truncated message notification is shown"
+ );
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-limit-payload.js b/devtools/client/netmonitor/test/browser_net_ws-limit-payload.js
new file mode 100644
index 0000000000..8a3082810a
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-limit-payload.js
@@ -0,0 +1,80 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WS connection is established successfully and the truncated payload is correct.
+ */
+
+add_task(async function () {
+ // Set WS message payload limit to a lower value for testing
+ await pushPref("devtools.netmonitor.msg.messageDataLimit", 100);
+
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connections to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(0);
+ content.wrappedJSObject.sendData(new Array(10 * 11).toString()); // > 100B payload
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ const wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 2, "There should be two frames");
+
+ // Wait for next tick to do async stuff (The MessagePayload component uses the async function getMessagePayload)
+ await waitForTick();
+ EventUtils.sendMouseEvent({ type: "mousedown" }, frames[0]);
+
+ await waitForDOM(document, "#messages-view .truncated-data-message");
+
+ ok(
+ document.querySelector("#messages-view .truncated-data-message"),
+ "Truncated data header shown"
+ );
+ is(
+ document.querySelector("#messages-view .message-rawData-payload")
+ .textContent.length,
+ 100,
+ "Payload size is kept to the limit"
+ );
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-messages-navigation.js b/devtools/client/netmonitor/test/browser_net_ws-messages-navigation.js
new file mode 100644
index 0000000000..4555dc27eb
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-messages-navigation.js
@@ -0,0 +1,106 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WS messages can be navigated between using the keyboard.
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connections to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(0);
+ // Send 5 WS messages
+ Array(5)
+ .fill(undefined)
+ .forEach((_, index) => {
+ content.wrappedJSObject.sendData(index);
+ });
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ const wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 10
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 10, "There should be ten frames");
+ // Wait for next tick to do async stuff (The MessagePayload component uses the async function getMessagePayload)
+ await waitForTick();
+
+ const waitForSelected = waitForDOM(
+ document,
+ // The first message is actually the second child, there is a hidden row.
+ `.message-list-item:nth-child(${2}).selected`
+ );
+ EventUtils.sendMouseEvent({ type: "mousedown" }, frames[0]);
+ await waitForSelected;
+
+ const checkSelected = messageRowNumber => {
+ is(
+ Array.from(frames).findIndex(el => el.matches(".selected")),
+ messageRowNumber - 1,
+ `Message ${messageRowNumber} should be selected.`
+ );
+ };
+
+ // Need focus for keyboard shortcuts to work
+ frames[0].focus();
+
+ checkSelected(1);
+
+ EventUtils.sendKey("DOWN", window);
+ checkSelected(2);
+
+ EventUtils.sendKey("UP", window);
+ checkSelected(1);
+
+ EventUtils.sendKey("PAGE_DOWN", window);
+ checkSelected(3);
+
+ EventUtils.sendKey("PAGE_UP", window);
+ checkSelected(1);
+
+ EventUtils.sendKey("END", window);
+ checkSelected(10);
+
+ EventUtils.sendKey("HOME", window);
+ checkSelected(1);
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-sockjs-stomp-payload.js b/devtools/client/netmonitor/test/browser_net_ws-sockjs-stomp-payload.js
new file mode 100644
index 0000000000..2fe8e6e949
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-sockjs-stomp-payload.js
@@ -0,0 +1,115 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WebSocket payloads containing SockJS+STOMP messages are parsed
+ * correctly and displayed in a user friendly way
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connections to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(0);
+ content.wrappedJSObject.sendData(
+ `a[\"SEND\\nx-firefox-test:true\\ncontent-length:17\\n\\n[{\\\"key\\\":\\\"value\\\"}]\\u0000\"]`
+ );
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one requests");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ let wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 2, "There should be two frames");
+
+ // Wait for next tick to do async stuff (The MessagePayload component uses the async function getMessagePayload)
+ await waitForTick();
+ const waitForData = waitForDOM(document, "#messages-view .properties-view");
+ const [, responseFrame] = frames;
+ EventUtils.sendMouseEvent({ type: "mousedown" }, responseFrame);
+
+ await waitForData;
+
+ is(
+ document.querySelector("#messages-view .data-label").innerText,
+ "SockJS",
+ "The SockJS payload panel should be displayed"
+ );
+
+ ok(
+ document.querySelector("#messages-view .treeTable"),
+ "A tree table should be used to display the formatted payload"
+ );
+
+ ok(
+ document.getElementById("/0/command"),
+ "The message 'command' should be displayed"
+ );
+ ok(
+ document.getElementById("/0/headers"),
+ "The message 'headers' should be displayed"
+ );
+ ok(
+ document.getElementById("/0/body"),
+ "The message 'body' should be displayed"
+ );
+
+ // Toggle raw data display
+ wait = waitForDOM(document, "#messages-view .message-rawData-payload");
+ const rawDataToggle = document.querySelector(
+ "#messages-view .devtools-checkbox-toggle"
+ );
+ clickElement(rawDataToggle, monitor);
+ await wait;
+
+ is(
+ document.querySelector("#messages-view .data-label").innerText,
+ "Raw Data (80 B)",
+ "The raw data payload info should be displayed"
+ );
+
+ is(
+ document.querySelector("#messages-view .message-rawData-payload").value,
+ `a[\"SEND\\nx-firefox-test:true\\ncontent-length:17\\n\\n[{\\\"key\\\":\\\"value\\\"}]\\u0000\"]`,
+ "The raw data must be shown correctly"
+ );
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-sse-persist-columns.js b/devtools/client/netmonitor/test/browser_net_ws-sse-persist-columns.js
new file mode 100644
index 0000000000..66a7f36e74
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-sse-persist-columns.js
@@ -0,0 +1,268 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test columns' state for WS and SSE connection.
+ */
+
+function shallowArrayEqual(arr1, arr2) {
+ if (arr1.length !== arr2.length) {
+ return false;
+ }
+ for (let i = 0; i < arr1.length; i++) {
+ if (
+ (arr2[i] instanceof RegExp && !arr2[i].test(arr1[i])) ||
+ (typeof arr2[i] === "string" && arr2[i] !== arr1[i])
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function shallowObjectEqual(obj1, obj2) {
+ const k1 = Object.keys(obj1);
+ const k2 = Object.keys(obj2);
+
+ if (k1.length !== k2.length) {
+ return false;
+ }
+
+ for (const key of k1) {
+ if (obj1[key] !== obj2[key]) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+function shallowEqual(obj1, obj2) {
+ if (Array.isArray(obj1) && Array.isArray(obj2)) {
+ return shallowArrayEqual(obj1, obj2);
+ }
+ return shallowObjectEqual(obj1, obj2);
+}
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(
+ "http://mochi.test:8888/browser/devtools/client/netmonitor/test/html_ws-sse-test-page.html",
+ {
+ requestCount: 1,
+ }
+ );
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ const onNetworkEvents = waitForNetworkEvents(monitor, 2);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openWsConnection(1);
+ // Running openSseConnection() here causes intermittent behavior.
+ });
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openSseConnection();
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 2, "There should be two requests");
+
+ // Select the WS request.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ store.dispatch(Actions.toggleMessageColumn("size"));
+ store.dispatch(Actions.toggleMessageColumn("opCode"));
+ store.dispatch(Actions.toggleMessageColumn("maskBit"));
+ store.dispatch(Actions.toggleMessageColumn("finBit"));
+ clickOnSidebarTab(document, "response");
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 2, "There should be two frames");
+
+ let columnHeaders = Array.prototype.map.call(
+ document.querySelectorAll(
+ "#messages-view .message-list-headers .button-text"
+ ),
+ node => node.textContent
+ );
+
+ is(
+ shallowEqual(columnHeaders, [
+ "Data",
+ "Size",
+ "OpCode",
+ "MaskBit",
+ "FinBit",
+ "Time",
+ ]),
+ true,
+ "WS Column headers are in correct order"
+ );
+
+ // Get column values of first row for WS.
+ let columnValues = Array.prototype.map.call(frames, frame =>
+ Array.prototype.map.call(
+ frame.querySelectorAll(".message-list-column"),
+ column => column.textContent.trim()
+ )
+ )[0];
+
+ is(
+ shallowEqual(columnValues, [
+ "Payload 0",
+ "9 B",
+ "1",
+ "true",
+ "true",
+ // Time format is "hh:mm:ss.mmm".
+ /\d+:\d+:\d+\.\d+/,
+ ]),
+ true,
+ "WS Column values are in correct order"
+ );
+
+ // Select the SSE request.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[1]);
+
+ store.dispatch(Actions.toggleMessageColumn("lastEventId"));
+ store.dispatch(Actions.toggleMessageColumn("eventName"));
+ store.dispatch(Actions.toggleMessageColumn("retry"));
+
+ columnHeaders = Array.prototype.map.call(
+ document.querySelectorAll(
+ "#messages-view .message-list-headers .button-text"
+ ),
+ node => node.textContent
+ );
+
+ is(
+ shallowEqual(columnHeaders, [
+ "Data",
+ "Time",
+ "Event Name",
+ "Last Event ID",
+ "Retry",
+ ]),
+ true,
+ "SSE Column headers are in correct order"
+ );
+
+ // Get column values of first row for SSE.
+ columnValues = Array.prototype.map.call(frames, frame =>
+ Array.prototype.map.call(
+ frame.querySelectorAll(".message-list-column"),
+ column => column.textContent.trim()
+ )
+ )[0];
+
+ is(
+ shallowEqual(columnValues, [
+ "Why so serious?",
+ /\d+:\d+:\d+\.\d+/,
+ "message",
+ "",
+ "5000",
+ ]),
+ true,
+ "SSE Column values are in correct order"
+ );
+
+ // Select the WS request again.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+ is(
+ shallowEqual(store.getState().messages.columns, {
+ data: true,
+ time: true,
+ size: true,
+ opCode: true,
+ maskBit: true,
+ finBit: true,
+ }),
+ true,
+ "WS columns should persist after request switch"
+ );
+
+ // Select the SSE request again.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[1]);
+ is(
+ shallowEqual(store.getState().messages.columns, {
+ data: true,
+ time: true,
+ size: false,
+ lastEventId: true,
+ eventName: true,
+ retry: true,
+ }),
+ true,
+ "SSE columns should persist after request switch"
+ );
+
+ // Reset SSE columns.
+ store.dispatch(Actions.resetMessageColumns());
+
+ // Switch to WS request again.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+ is(
+ shallowEqual(store.getState().messages.columns, {
+ data: true,
+ time: true,
+ size: true,
+ opCode: true,
+ maskBit: true,
+ finBit: true,
+ }),
+ true,
+ "WS columns should not reset after resetting SSE columns"
+ );
+
+ // Reset WS columns.
+ store.dispatch(Actions.resetMessageColumns());
+
+ // Switch to SSE request again.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[1]);
+ is(
+ shallowEqual(store.getState().messages.columns, {
+ data: true,
+ time: true,
+ size: false,
+ lastEventId: false,
+ eventName: false,
+ retry: false,
+ }),
+ true,
+ "SSE columns' reset state should persist after request switch"
+ );
+
+ // Switch to WS request again.
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+ is(
+ shallowEqual(store.getState().messages.columns, {
+ data: true,
+ time: true,
+ size: false,
+ opCode: false,
+ maskBit: false,
+ finBit: false,
+ }),
+ true,
+ "WS columns' reset state should persist after request switch"
+ );
+
+ // Close WS connection.
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeWsConnection();
+ });
+
+ return teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/browser_net_ws-stomp-payload.js b/devtools/client/netmonitor/test/browser_net_ws-stomp-payload.js
new file mode 100644
index 0000000000..c3bd284c7b
--- /dev/null
+++ b/devtools/client/netmonitor/test/browser_net_ws-stomp-payload.js
@@ -0,0 +1,115 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that WebSocket payloads containing a STOMP formatted message are parsed
+ * correctly and displayed in a user friendly way
+ */
+
+add_task(async function () {
+ const { tab, monitor } = await initNetMonitor(WS_PAGE_URL, {
+ requestCount: 1,
+ });
+ info("Starting test... ");
+
+ const { document, store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ store.dispatch(Actions.batchEnable(false));
+
+ // Wait for WS connections to be established + send messages
+ const onNetworkEvents = waitForNetworkEvents(monitor, 1);
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.openConnection(0);
+ content.wrappedJSObject.sendData(
+ `SEND\nx-firefox-test:true\ncontent-length:17\n\n[{"key":"value"}]\u0000\n`
+ );
+ });
+ await onNetworkEvents;
+
+ const requests = document.querySelectorAll(".request-list-item");
+ is(requests.length, 1, "There should be one request");
+
+ // Wait for all sent/received messages to be displayed in DevTools
+ let wait = waitForDOM(
+ document,
+ "#messages-view .message-list-table .message-list-item",
+ 2
+ );
+
+ // Select the first request
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requests[0]);
+
+ // Click on the "Response" panel
+ clickOnSidebarTab(document, "response");
+ await wait;
+
+ // Get all messages present in the "Response" panel
+ const frames = document.querySelectorAll(
+ "#messages-view .message-list-table .message-list-item"
+ );
+
+ // Check expected results
+ is(frames.length, 2, "There should be two frames");
+
+ // Wait for next tick to do async stuff (The MessagePayload component uses the async function getMessagePayload)
+ await waitForTick();
+ const waitForData = waitForDOM(document, "#messages-view .properties-view");
+ const [requestFrame] = frames;
+ EventUtils.sendMouseEvent({ type: "mousedown" }, requestFrame);
+
+ await waitForData;
+
+ is(
+ document.querySelector("#messages-view .data-label").innerText,
+ "STOMP",
+ "The STOMP payload panel should be displayed"
+ );
+
+ ok(
+ document.querySelector("#messages-view .treeTable"),
+ "A tree table should be used to display the formatted payload"
+ );
+
+ ok(
+ document.getElementById("/command"),
+ "The message 'command' should be displayed"
+ );
+ ok(
+ document.getElementById("/headers"),
+ "The message 'headers' should be displayed"
+ );
+ ok(
+ document.getElementById("/body"),
+ "The message 'body' should be displayed"
+ );
+
+ // Toggle raw data display
+ wait = waitForDOM(document, "#messages-view .message-rawData-payload");
+ const rawDataToggle = document.querySelector(
+ "#messages-view .devtools-checkbox-toggle"
+ );
+ clickElement(rawDataToggle, monitor);
+ await wait;
+
+ is(
+ document.querySelector("#messages-view .data-label").innerText,
+ "Raw Data (63 B)",
+ "The raw data payload info should be displayed"
+ );
+
+ is(
+ document.querySelector("#messages-view .message-rawData-payload").value,
+ `SEND\nx-firefox-test:true\ncontent-length:17\n\n[{"key":"value"}]\u0000\n`,
+ "The raw data must be shown correctly"
+ );
+
+ // Close WS connection
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await content.wrappedJSObject.closeConnection();
+ });
+
+ await teardown(monitor);
+});
diff --git a/devtools/client/netmonitor/test/dropmarker.svg b/devtools/client/netmonitor/test/dropmarker.svg
new file mode 100644
index 0000000000..3e2987682b
--- /dev/null
+++ b/devtools/client/netmonitor/test/dropmarker.svg
@@ -0,0 +1,6 @@
+<!-- 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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" width="8" height="4" viewBox="0 0 8 4">
+ <polygon points="0,0 4,4 8,0" fill="#b6babf"/>
+</svg>
diff --git a/devtools/client/netmonitor/test/file_ws_backend_wsh.py b/devtools/client/netmonitor/test/file_ws_backend_wsh.py
new file mode 100644
index 0000000000..fe74ae2065
--- /dev/null
+++ b/devtools/client/netmonitor/test/file_ws_backend_wsh.py
@@ -0,0 +1,13 @@
+from mod_pywebsocket import msgutil
+
+
+def web_socket_do_extra_handshake(request):
+ pass
+
+
+def web_socket_transfer_data(request):
+ while not request.client_terminated:
+ resp = msgutil.receive_message(request)
+ msgutil.send_message(request, resp)
+
+ msgutil.close_connection(request)
diff --git a/devtools/client/netmonitor/test/head.js b/devtools/client/netmonitor/test/head.js
new file mode 100644
index 0000000000..d1c3112f02
--- /dev/null
+++ b/devtools/client/netmonitor/test/head.js
@@ -0,0 +1,1493 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/**
+ * This file (head.js) is injected into all other test contexts within
+ * this directory, allowing one to utilize the functions here in said
+ * tests without referencing head.js explicitly.
+ */
+
+/* exported Toolbox, restartNetMonitor, teardown, waitForExplicitFinish,
+ verifyRequestItemTarget, waitFor, waitForDispatch, testFilterButtons,
+ performRequestsInContent, waitForNetworkEvents, selectIndexAndWaitForSourceEditor,
+ testColumnsAlignment, hideColumn, showColumn, performRequests, waitForRequestData,
+ toggleBlockedUrl, registerFaviconNotifier, clickOnSidebarTab */
+
+"use strict";
+
+// The below file (shared-head.js) handles imports, constants, and
+// utility functions, and is loaded into this context.
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/devtools/client/shared/test/shared-head.js",
+ this
+);
+
+const { LinkHandlerParent } = ChromeUtils.importESModule(
+ "resource:///actors/LinkHandlerParent.sys.mjs"
+);
+
+const {
+ getFormattedIPAndPort,
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+const {
+ getSortedRequests,
+ getRequestById,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+const {
+ getUnicodeUrl,
+ getUnicodeHostname,
+} = require("resource://devtools/client/shared/unicode-url.js");
+const {
+ getFormattedProtocol,
+ getUrlHost,
+ getUrlScheme,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ EVENTS,
+ TEST_EVENTS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+/* eslint-disable no-unused-vars, max-len */
+const EXAMPLE_URL =
+ "http://example.com/browser/devtools/client/netmonitor/test/";
+const EXAMPLE_ORG_URL =
+ "http://example.org/browser/devtools/client/netmonitor/test/";
+const HTTPS_EXAMPLE_URL =
+ "https://example.com/browser/devtools/client/netmonitor/test/";
+const HTTPS_EXAMPLE_ORG_URL =
+ "https://example.org/browser/devtools/client/netmonitor/test/";
+/* Since the test server will proxy `ws://example.com` to websocket server on 9988,
+so we must sepecify the port explicitly */
+const WS_URL = "ws://127.0.0.1:8888/browser/devtools/client/netmonitor/test/";
+const WS_HTTP_URL =
+ "http://127.0.0.1:8888/browser/devtools/client/netmonitor/test/";
+
+const WS_BASE_URL =
+ "http://mochi.test:8888/browser/devtools/client/netmonitor/test/";
+const WS_PAGE_URL = WS_BASE_URL + "html_ws-test-page.html";
+const WS_PAGE_EARLY_CONNECTION_URL =
+ WS_BASE_URL + "html_ws-early-connection-page.html";
+const API_CALLS_URL = HTTPS_EXAMPLE_URL + "html_api-calls-test-page.html";
+const SIMPLE_URL = EXAMPLE_URL + "html_simple-test-page.html";
+const HTTPS_SIMPLE_URL = HTTPS_EXAMPLE_URL + "html_simple-test-page.html";
+const NAVIGATE_URL = EXAMPLE_URL + "html_navigate-test-page.html";
+const CONTENT_TYPE_WITHOUT_CACHE_URL =
+ EXAMPLE_URL + "html_content-type-without-cache-test-page.html";
+const CONTENT_TYPE_WITHOUT_CACHE_REQUESTS = 8;
+const CYRILLIC_URL = EXAMPLE_URL + "html_cyrillic-test-page.html";
+const STATUS_CODES_URL = EXAMPLE_URL + "html_status-codes-test-page.html";
+const HTTPS_STATUS_CODES_URL =
+ HTTPS_EXAMPLE_URL + "html_status-codes-test-page.html";
+const POST_DATA_URL = EXAMPLE_URL + "html_post-data-test-page.html";
+const POST_ARRAY_DATA_URL = EXAMPLE_URL + "html_post-array-data-test-page.html";
+const POST_JSON_URL = EXAMPLE_URL + "html_post-json-test-page.html";
+const POST_RAW_URL = EXAMPLE_URL + "html_post-raw-test-page.html";
+const POST_RAW_URL_WITH_HASH = EXAMPLE_URL + "html_header-test-page.html";
+const POST_RAW_WITH_HEADERS_URL =
+ EXAMPLE_URL + "html_post-raw-with-headers-test-page.html";
+const PARAMS_URL = EXAMPLE_URL + "html_params-test-page.html";
+const JSONP_URL = EXAMPLE_URL + "html_jsonp-test-page.html";
+const JSON_LONG_URL = EXAMPLE_URL + "html_json-long-test-page.html";
+const JSON_MALFORMED_URL = EXAMPLE_URL + "html_json-malformed-test-page.html";
+const JSON_CUSTOM_MIME_URL =
+ EXAMPLE_URL + "html_json-custom-mime-test-page.html";
+const JSON_TEXT_MIME_URL = EXAMPLE_URL + "html_json-text-mime-test-page.html";
+const JSON_B64_URL = EXAMPLE_URL + "html_json-b64.html";
+const JSON_BASIC_URL = EXAMPLE_URL + "html_json-basic.html";
+const JSON_EMPTY_URL = EXAMPLE_URL + "html_json-empty.html";
+const JSON_XSSI_PROTECTION_URL = EXAMPLE_URL + "html_json-xssi-protection.html";
+const FONTS_URL = EXAMPLE_URL + "html_fonts-test-page.html";
+const SORTING_URL = EXAMPLE_URL + "html_sorting-test-page.html";
+const FILTERING_URL = EXAMPLE_URL + "html_filter-test-page.html";
+const HTTPS_FILTERING_URL = HTTPS_EXAMPLE_URL + "html_filter-test-page.html";
+const INFINITE_GET_URL = EXAMPLE_URL + "html_infinite-get-page.html";
+const CUSTOM_GET_URL = EXAMPLE_URL + "html_custom-get-page.html";
+const HTTPS_CUSTOM_GET_URL = HTTPS_EXAMPLE_URL + "html_custom-get-page.html";
+const SINGLE_GET_URL = EXAMPLE_URL + "html_single-get-page.html";
+const HTTPS_SINGLE_GET_URL = HTTPS_EXAMPLE_URL + "html_single-get-page.html";
+const STATISTICS_URL = EXAMPLE_URL + "html_statistics-test-page.html";
+const STATISTICS_EDGE_CASE_URL =
+ EXAMPLE_URL + "html_statistics-edge-case-page.html";
+const CURL_URL = EXAMPLE_URL + "html_copy-as-curl.html";
+const HTTPS_CURL_URL = HTTPS_EXAMPLE_URL + "html_copy-as-curl.html";
+const HTTPS_CURL_UTILS_URL = HTTPS_EXAMPLE_URL + "html_curl-utils.html";
+const SEND_BEACON_URL = EXAMPLE_URL + "html_send-beacon.html";
+const CORS_URL = EXAMPLE_URL + "html_cors-test-page.html";
+const HTTPS_CORS_URL = HTTPS_EXAMPLE_URL + "html_cors-test-page.html";
+const PAUSE_URL = EXAMPLE_URL + "html_pause-test-page.html";
+const OPEN_REQUEST_IN_TAB_URL = EXAMPLE_URL + "html_open-request-in-tab.html";
+const CSP_URL = EXAMPLE_URL + "html_csp-test-page.html";
+const CSP_RESEND_URL = EXAMPLE_URL + "html_csp-resend-test-page.html";
+const IMAGE_CACHE_URL = HTTPS_EXAMPLE_URL + "html_image-cache.html";
+const SLOW_REQUESTS_URL = EXAMPLE_URL + "html_slow-requests-test-page.html";
+
+const SIMPLE_SJS = EXAMPLE_URL + "sjs_simple-test-server.sjs";
+const HTTPS_SIMPLE_SJS = HTTPS_EXAMPLE_URL + "sjs_simple-test-server.sjs";
+const SIMPLE_UNSORTED_COOKIES_SJS =
+ EXAMPLE_URL + "sjs_simple-unsorted-cookies-test-server.sjs";
+const CONTENT_TYPE_SJS = EXAMPLE_URL + "sjs_content-type-test-server.sjs";
+const WS_CONTENT_TYPE_SJS = WS_HTTP_URL + "sjs_content-type-test-server.sjs";
+const WS_WS_CONTENT_TYPE_SJS = WS_URL + "sjs_content-type-test-server.sjs";
+const HTTPS_CONTENT_TYPE_SJS =
+ HTTPS_EXAMPLE_URL + "sjs_content-type-test-server.sjs";
+const SERVER_TIMINGS_TYPE_SJS =
+ HTTPS_EXAMPLE_URL + "sjs_timings-test-server.sjs";
+const STATUS_CODES_SJS = EXAMPLE_URL + "sjs_status-codes-test-server.sjs";
+const SORTING_SJS = EXAMPLE_URL + "sjs_sorting-test-server.sjs";
+const HTTPS_REDIRECT_SJS = EXAMPLE_URL + "sjs_https-redirect-test-server.sjs";
+const CORS_SJS_PATH =
+ "/browser/devtools/client/netmonitor/test/sjs_cors-test-server.sjs";
+const HSTS_SJS = EXAMPLE_URL + "sjs_hsts-test-server.sjs";
+const METHOD_SJS = EXAMPLE_URL + "sjs_method-test-server.sjs";
+const HTTPS_SLOW_SJS = HTTPS_EXAMPLE_URL + "sjs_slow-test-server.sjs";
+const SET_COOKIE_SAME_SITE_SJS = EXAMPLE_URL + "sjs_set-cookie-same-site.sjs";
+const SEARCH_SJS = EXAMPLE_URL + "sjs_search-test-server.sjs";
+const HTTPS_SEARCH_SJS = HTTPS_EXAMPLE_URL + "sjs_search-test-server.sjs";
+
+const HSTS_BASE_URL = EXAMPLE_URL;
+const HSTS_PAGE_URL = CUSTOM_GET_URL;
+
+const TEST_IMAGE = EXAMPLE_URL + "test-image.png";
+const TEST_IMAGE_DATA_URI =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==";
+
+const SETTINGS_MENU_ITEMS = {
+ "persist-logs": ".netmonitor-settings-persist-item",
+ "import-har": ".netmonitor-settings-import-har-item",
+ "save-har": ".netmonitor-settings-import-save-item",
+ "copy-har": ".netmonitor-settings-import-copy-item",
+};
+
+/* eslint-enable no-unused-vars, max-len */
+
+// All tests are asynchronous.
+waitForExplicitFinish();
+
+const gEnableLogging = Services.prefs.getBoolPref("devtools.debugger.log");
+// To enable logging for try runs, just set the pref to true.
+Services.prefs.setBoolPref("devtools.debugger.log", false);
+
+// Uncomment this pref to dump all devtools emitted events to the console.
+// Services.prefs.setBoolPref("devtools.dump.emit", true);
+
+// Always reset some prefs to their original values after the test finishes.
+const gDefaultFilters = Services.prefs.getCharPref(
+ "devtools.netmonitor.filters"
+);
+
+// Reveal many columns for test
+Services.prefs.setCharPref(
+ "devtools.netmonitor.visibleColumns",
+ '["initiator","contentSize","cookies","domain","duration",' +
+ '"endTime","file","url","latency","method","protocol",' +
+ '"remoteip","responseTime","scheme","setCookies",' +
+ '"startTime","status","transferred","type","waterfall"]'
+);
+
+Services.prefs.setCharPref(
+ "devtools.netmonitor.columnsData",
+ '[{"name":"status","minWidth":30,"width":5},' +
+ '{"name":"method","minWidth":30,"width":5},' +
+ '{"name":"domain","minWidth":30,"width":10},' +
+ '{"name":"file","minWidth":30,"width":25},' +
+ '{"name":"url","minWidth":30,"width":25},' +
+ '{"name":"initiator","minWidth":30,"width":20},' +
+ '{"name":"type","minWidth":30,"width":5},' +
+ '{"name":"transferred","minWidth":30,"width":10},' +
+ '{"name":"contentSize","minWidth":30,"width":5},' +
+ '{"name":"waterfall","minWidth":150,"width":15}]'
+);
+
+registerCleanupFunction(() => {
+ info("finish() was called, cleaning up...");
+
+ Services.prefs.setBoolPref("devtools.debugger.log", gEnableLogging);
+ Services.prefs.setCharPref("devtools.netmonitor.filters", gDefaultFilters);
+ Services.prefs.clearUserPref("devtools.cache.disabled");
+ Services.prefs.clearUserPref("devtools.netmonitor.columnsData");
+ Services.prefs.clearUserPref("devtools.netmonitor.visibleColumns");
+ Services.cookies.removeAll();
+});
+
+async function disableCacheAndReload(toolbox, waitForLoad) {
+ // Disable the cache for any toolbox that it is opened from this point on.
+ Services.prefs.setBoolPref("devtools.cache.disabled", true);
+
+ await toolbox.commands.targetConfigurationCommand.updateConfiguration({
+ cacheDisabled: true,
+ });
+
+ // If the page which is reloaded is not found, this will likely cause
+ // reloadTopLevelTarget to not return so let not wait for it.
+ if (waitForLoad) {
+ await toolbox.commands.targetCommand.reloadTopLevelTarget();
+ } else {
+ toolbox.commands.targetCommand.reloadTopLevelTarget();
+ }
+}
+
+/**
+ * Wait for 2 markers during document load.
+ */
+function waitForTimelineMarkers(monitor) {
+ return new Promise(resolve => {
+ const markers = [];
+
+ function handleTimelineEvent(marker) {
+ info(`Got marker: ${marker.name}`);
+ markers.push(marker);
+ if (markers.length == 2) {
+ monitor.panelWin.api.off(
+ TEST_EVENTS.TIMELINE_EVENT,
+ handleTimelineEvent
+ );
+ info("Got two timeline markers, done waiting");
+ resolve(markers);
+ }
+ }
+
+ monitor.panelWin.api.on(TEST_EVENTS.TIMELINE_EVENT, handleTimelineEvent);
+ });
+}
+
+let finishedQueue = {};
+const updatingTypes = [
+ "NetMonitor:NetworkEventUpdating:RequestCookies",
+ "NetMonitor:NetworkEventUpdating:ResponseCookies",
+ "NetMonitor:NetworkEventUpdating:RequestHeaders",
+ "NetMonitor:NetworkEventUpdating:ResponseHeaders",
+ "NetMonitor:NetworkEventUpdating:RequestPostData",
+ "NetMonitor:NetworkEventUpdating:ResponseContent",
+ "NetMonitor:NetworkEventUpdating:SecurityInfo",
+ "NetMonitor:NetworkEventUpdating:EventTimings",
+];
+const updatedTypes = [
+ "NetMonitor:NetworkEventUpdated:RequestCookies",
+ "NetMonitor:NetworkEventUpdated:ResponseCookies",
+ "NetMonitor:NetworkEventUpdated:RequestHeaders",
+ "NetMonitor:NetworkEventUpdated:ResponseHeaders",
+ "NetMonitor:NetworkEventUpdated:RequestPostData",
+ "NetMonitor:NetworkEventUpdated:ResponseContent",
+ "NetMonitor:NetworkEventUpdated:SecurityInfo",
+ "NetMonitor:NetworkEventUpdated:EventTimings",
+];
+
+// Start collecting all networkEventUpdate event when panel is opened.
+// removeTab() should be called once all corresponded RECEIVED_* events finished.
+function startNetworkEventUpdateObserver(panelWin) {
+ updatingTypes.forEach(type =>
+ panelWin.api.on(type, actor => {
+ const key = actor + "-" + updatedTypes[updatingTypes.indexOf(type)];
+ finishedQueue[key] = finishedQueue[key] ? finishedQueue[key] + 1 : 1;
+ })
+ );
+
+ updatedTypes.forEach(type =>
+ panelWin.api.on(type, payload => {
+ const key = payload.from + "-" + type;
+ finishedQueue[key] = finishedQueue[key] ? finishedQueue[key] - 1 : -1;
+ })
+ );
+
+ panelWin.api.on("clear-network-resources", () => {
+ finishedQueue = {};
+ });
+}
+
+async function waitForAllNetworkUpdateEvents() {
+ function checkNetworkEventUpdateState() {
+ for (const key in finishedQueue) {
+ if (finishedQueue[key] > 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+ info("Wait for completion of all NetworkUpdateEvents packets...");
+ await waitUntil(() => checkNetworkEventUpdateState());
+ finishedQueue = {};
+}
+
+function initNetMonitor(
+ url,
+ {
+ requestCount,
+ expectedEventTimings,
+ waitForLoad = true,
+ enableCache = false,
+ }
+) {
+ info("Initializing a network monitor pane.");
+
+ if (!requestCount && !enableCache) {
+ ok(
+ false,
+ "initNetMonitor should be given a number of requests the page will perform"
+ );
+ }
+
+ return (async function () {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ // Capture all stacks so that the timing of devtools opening
+ // doesn't affect the stack trace results.
+ ["javascript.options.asyncstack_capture_debuggee_only", false],
+ ],
+ });
+
+ const tab = await addTab(url, { waitForLoad });
+ info("Net tab added successfully: " + url);
+
+ const toolbox = await gDevTools.showToolboxForTab(tab, {
+ toolId: "netmonitor",
+ });
+ info("Network monitor pane shown successfully.");
+
+ const monitor = toolbox.getCurrentPanel();
+
+ startNetworkEventUpdateObserver(monitor.panelWin);
+
+ if (!enableCache) {
+ info("Disabling cache and reloading page.");
+
+ const allComplete = [];
+ allComplete.push(
+ waitForNetworkEvents(monitor, requestCount, {
+ expectedEventTimings,
+ })
+ );
+
+ if (waitForLoad) {
+ allComplete.push(waitForTimelineMarkers(monitor));
+ }
+ await disableCacheAndReload(toolbox, waitForLoad);
+ await Promise.all(allComplete);
+ await clearNetworkEvents(monitor);
+ }
+
+ return { tab, monitor, toolbox };
+ })();
+}
+
+function restartNetMonitor(monitor, { requestCount }) {
+ info("Restarting the specified network monitor.");
+
+ return (async function () {
+ const tab = monitor.commands.descriptorFront.localTab;
+ const url = tab.linkedBrowser.currentURI.spec;
+
+ await waitForAllNetworkUpdateEvents();
+ info("All pending requests finished.");
+
+ const onDestroyed = monitor.once("destroyed");
+ await removeTab(tab);
+ await onDestroyed;
+
+ return initNetMonitor(url, { requestCount });
+ })();
+}
+
+/**
+ * Clears the network requests in the UI
+ * @param {Object} monitor
+ * The netmonitor instance used for retrieving a context menu element.
+ */
+async function clearNetworkEvents(monitor) {
+ const { store, windowRequire } = monitor.panelWin;
+ const Actions = windowRequire("devtools/client/netmonitor/src/actions/index");
+
+ await waitForAllNetworkUpdateEvents();
+
+ info("Clearing the network requests in the UI");
+ store.dispatch(Actions.clearRequests());
+}
+
+function teardown(monitor) {
+ info("Destroying the specified network monitor.");
+
+ return (async function () {
+ const tab = monitor.commands.descriptorFront.localTab;
+
+ await waitForAllNetworkUpdateEvents();
+ info("All pending requests finished.");
+
+ await monitor.toolbox.destroy();
+ await removeTab(tab);
+ })();
+}
+
+/**
+ * Wait for the request(s) to be fully notified to the frontend.
+ *
+ * @param {Object} monitor
+ * The netmonitor instance used for retrieving a context menu element.
+ * @param {Number} getRequests
+ * The number of request to wait for
+ * @param {Object} options (optional)
+ * - expectedEventTimings {Number} Number of EVENT_TIMINGS events to wait for.
+ * In case of filtering, we get less of such events.
+ */
+function waitForNetworkEvents(monitor, getRequests, options = {}) {
+ return new Promise(resolve => {
+ const panel = monitor.panelWin;
+ let networkEvent = 0;
+ let nonBlockedNetworkEvent = 0;
+ let payloadReady = 0;
+ let eventTimings = 0;
+
+ function onNetworkEvent(resource) {
+ networkEvent++;
+ if (!resource.blockedReason) {
+ nonBlockedNetworkEvent++;
+ }
+ maybeResolve(TEST_EVENTS.NETWORK_EVENT, resource.actor);
+ }
+
+ function onPayloadReady(resource) {
+ payloadReady++;
+ maybeResolve(EVENTS.PAYLOAD_READY, resource.actor);
+ }
+
+ function onEventTimings(response) {
+ eventTimings++;
+ maybeResolve(EVENTS.RECEIVED_EVENT_TIMINGS, response.from);
+ }
+
+ function onClearNetworkResources() {
+ // Reset all counters.
+ networkEvent = 0;
+ nonBlockedNetworkEvent = 0;
+ payloadReady = 0;
+ eventTimings = 0;
+ }
+
+ function maybeResolve(event, actor) {
+ const { document } = monitor.panelWin;
+ // Wait until networkEvent, payloadReady and event timings finish for each request.
+ // The UI won't fetch timings when:
+ // * hidden in background,
+ // * for any blocked request,
+ let expectedEventTimings =
+ document.visibilityState == "hidden" ? 0 : nonBlockedNetworkEvent;
+ let expectedPayloadReady = getRequests;
+ // Typically ignore this option if it is undefined or null
+ if (typeof options?.expectedEventTimings == "number") {
+ expectedEventTimings = options.expectedEventTimings;
+ }
+ if (typeof options?.expectedPayloadReady == "number") {
+ expectedPayloadReady = options.expectedPayloadReady;
+ }
+ info(
+ "> Network event progress: " +
+ "NetworkEvent: " +
+ networkEvent +
+ "/" +
+ getRequests +
+ ", " +
+ "PayloadReady: " +
+ payloadReady +
+ "/" +
+ expectedPayloadReady +
+ ", " +
+ "EventTimings: " +
+ eventTimings +
+ "/" +
+ expectedEventTimings +
+ ", " +
+ "got " +
+ event +
+ " for " +
+ actor
+ );
+
+ if (
+ networkEvent >= getRequests &&
+ payloadReady >= expectedPayloadReady &&
+ eventTimings >= expectedEventTimings
+ ) {
+ panel.api.off(TEST_EVENTS.NETWORK_EVENT, onNetworkEvent);
+ panel.api.off(EVENTS.PAYLOAD_READY, onPayloadReady);
+ panel.api.off(EVENTS.RECEIVED_EVENT_TIMINGS, onEventTimings);
+ panel.api.off("clear-network-resources", onClearNetworkResources);
+ executeSoon(resolve);
+ }
+ }
+
+ panel.api.on(TEST_EVENTS.NETWORK_EVENT, onNetworkEvent);
+ panel.api.on(EVENTS.PAYLOAD_READY, onPayloadReady);
+ panel.api.on(EVENTS.RECEIVED_EVENT_TIMINGS, onEventTimings);
+ panel.api.on("clear-network-resources", onClearNetworkResources);
+ });
+}
+
+function verifyRequestItemTarget(
+ document,
+ requestList,
+ requestItem,
+ method,
+ url,
+ data = {}
+) {
+ info("> Verifying: " + method + " " + url + " " + data.toSource());
+
+ const visibleIndex = requestList.findIndex(
+ needle => needle.id === requestItem.id
+ );
+
+ isnot(visibleIndex, -1, "The requestItem exists");
+ info("Visible index of item: " + visibleIndex);
+
+ const {
+ fuzzyUrl,
+ status,
+ statusText,
+ cause,
+ type,
+ fullMimeType,
+ transferred,
+ size,
+ time,
+ displayedStatus,
+ } = data;
+
+ const target = document.querySelectorAll(".request-list-item")[visibleIndex];
+
+ // Bug 1414981 - Request URL should not show #hash
+ const unicodeUrl = getUnicodeUrl(url.split("#")[0]);
+ const ORIGINAL_FILE_URL = L10N.getFormatStr(
+ "netRequest.originalFileURL.tooltip",
+ url
+ );
+ const DECODED_FILE_URL = L10N.getFormatStr(
+ "netRequest.decodedFileURL.tooltip",
+ unicodeUrl
+ );
+ const fileToolTip =
+ url === unicodeUrl ? url : ORIGINAL_FILE_URL + "\n\n" + DECODED_FILE_URL;
+ const requestedFile = requestItem.urlDetails.baseNameWithQuery;
+ const host = getUnicodeHostname(getUrlHost(url));
+ const scheme = getUrlScheme(url);
+ const {
+ remoteAddress,
+ remotePort,
+ totalTime,
+ eventTimings = { timings: {} },
+ } = requestItem;
+ const formattedIPPort = getFormattedIPAndPort(remoteAddress, remotePort);
+ const remoteIP = remoteAddress ? `${formattedIPPort}` : "unknown";
+ const duration = getFormattedTime(totalTime);
+ const latency = getFormattedTime(eventTimings.timings.wait);
+ const protocol = getFormattedProtocol(requestItem);
+
+ if (fuzzyUrl) {
+ ok(
+ requestItem.method.startsWith(method),
+ "The attached method is correct."
+ );
+ ok(requestItem.url.startsWith(url), "The attached url is correct.");
+ } else {
+ is(requestItem.method, method, "The attached method is correct.");
+ is(requestItem.url, url.split("#")[0], "The attached url is correct.");
+ }
+
+ is(
+ target.querySelector(".requests-list-method").textContent,
+ method,
+ "The displayed method is correct."
+ );
+
+ if (fuzzyUrl) {
+ ok(
+ target
+ .querySelector(".requests-list-file")
+ .textContent.startsWith(requestedFile),
+ "The displayed file is correct."
+ );
+ ok(
+ target
+ .querySelector(".requests-list-file")
+ .getAttribute("title")
+ .startsWith(fileToolTip),
+ "The tooltip file is correct."
+ );
+ } else {
+ is(
+ target.querySelector(".requests-list-file").textContent,
+ requestedFile,
+ "The displayed file is correct."
+ );
+ is(
+ target.querySelector(".requests-list-file").getAttribute("title"),
+ fileToolTip,
+ "The tooltip file is correct."
+ );
+ }
+
+ is(
+ target.querySelector(".requests-list-protocol").textContent,
+ protocol,
+ "The displayed protocol is correct."
+ );
+
+ is(
+ target.querySelector(".requests-list-protocol").getAttribute("title"),
+ protocol,
+ "The tooltip protocol is correct."
+ );
+
+ is(
+ target.querySelector(".requests-list-domain").textContent,
+ host,
+ "The displayed domain is correct."
+ );
+
+ const domainTooltip =
+ host + (remoteAddress ? " (" + formattedIPPort + ")" : "");
+ is(
+ target.querySelector(".requests-list-domain").getAttribute("title"),
+ domainTooltip,
+ "The tooltip domain is correct."
+ );
+
+ is(
+ target.querySelector(".requests-list-remoteip").textContent,
+ remoteIP,
+ "The displayed remote IP is correct."
+ );
+
+ is(
+ target.querySelector(".requests-list-remoteip").getAttribute("title"),
+ remoteIP,
+ "The tooltip remote IP is correct."
+ );
+
+ is(
+ target.querySelector(".requests-list-scheme").textContent,
+ scheme,
+ "The displayed scheme is correct."
+ );
+
+ is(
+ target.querySelector(".requests-list-scheme").getAttribute("title"),
+ scheme,
+ "The tooltip scheme is correct."
+ );
+
+ is(
+ target.querySelector(".requests-list-duration-time").textContent,
+ duration,
+ "The displayed duration is correct."
+ );
+
+ is(
+ target.querySelector(".requests-list-duration-time").getAttribute("title"),
+ duration,
+ "The tooltip duration is correct."
+ );
+
+ is(
+ target.querySelector(".requests-list-latency-time").textContent,
+ latency,
+ "The displayed latency is correct."
+ );
+
+ is(
+ target.querySelector(".requests-list-latency-time").getAttribute("title"),
+ latency,
+ "The tooltip latency is correct."
+ );
+
+ if (status !== undefined) {
+ const value = target
+ .querySelector(".requests-list-status-code")
+ .getAttribute("data-status-code");
+ const codeValue = target.querySelector(
+ ".requests-list-status-code"
+ ).textContent;
+ const tooltip = target
+ .querySelector(".requests-list-status-code")
+ .getAttribute("title");
+ info("Displayed status: " + value);
+ info("Displayed code: " + codeValue);
+ info("Tooltip status: " + tooltip);
+ is(
+ `${value}`,
+ displayedStatus ? `${displayedStatus}` : `${status}`,
+ "The displayed status is correct."
+ );
+ is(`${codeValue}`, `${status}`, "The displayed status code is correct.");
+ is(tooltip, status + " " + statusText, "The tooltip status is correct.");
+ }
+ if (cause !== undefined) {
+ const value = Array.from(
+ target.querySelector(".requests-list-initiator").childNodes
+ )
+ .filter(node => node.nodeType === Node.ELEMENT_NODE)
+ .map(({ textContent }) => textContent)
+ .join("");
+ const tooltip = target
+ .querySelector(".requests-list-initiator")
+ .getAttribute("title");
+ info("Displayed cause: " + value);
+ info("Tooltip cause: " + tooltip);
+ ok(value.includes(cause.type), "The displayed cause is correct.");
+ ok(tooltip.includes(cause.type), "The tooltip cause is correct.");
+ }
+ if (type !== undefined) {
+ const value = target.querySelector(".requests-list-type").textContent;
+ let tooltip = target
+ .querySelector(".requests-list-type")
+ .getAttribute("title");
+ info("Displayed type: " + value);
+ info("Tooltip type: " + tooltip);
+ is(value, type, "The displayed type is correct.");
+ if (Object.is(tooltip, null)) {
+ tooltip = undefined;
+ }
+ is(tooltip, fullMimeType, "The tooltip type is correct.");
+ }
+ if (transferred !== undefined) {
+ const value = target.querySelector(
+ ".requests-list-transferred"
+ ).textContent;
+ const tooltip = target
+ .querySelector(".requests-list-transferred")
+ .getAttribute("title");
+ info("Displayed transferred size: " + value);
+ info("Tooltip transferred size: " + tooltip);
+ is(value, transferred, "The displayed transferred size is correct.");
+ is(tooltip, transferred, "The tooltip transferred size is correct.");
+ }
+ if (size !== undefined) {
+ const value = target.querySelector(".requests-list-size").textContent;
+ const tooltip = target
+ .querySelector(".requests-list-size")
+ .getAttribute("title");
+ info("Displayed size: " + value);
+ info("Tooltip size: " + tooltip);
+ is(value, size, "The displayed size is correct.");
+ is(tooltip, size, "The tooltip size is correct.");
+ }
+ if (time !== undefined) {
+ const value = target.querySelector(
+ ".requests-list-timings-total"
+ ).textContent;
+ const tooltip = target
+ .querySelector(".requests-list-timings-total")
+ .getAttribute("title");
+ info("Displayed time: " + value);
+ info("Tooltip time: " + tooltip);
+ ok(~~value.match(/[0-9]+/) >= 0, "The displayed time is correct.");
+ ok(~~tooltip.match(/[0-9]+/) >= 0, "The tooltip time is correct.");
+ }
+
+ if (visibleIndex !== -1) {
+ if (visibleIndex % 2 === 0) {
+ ok(target.classList.contains("even"), "Item should have 'even' class.");
+ ok(!target.classList.contains("odd"), "Item shouldn't have 'odd' class.");
+ } else {
+ ok(
+ !target.classList.contains("even"),
+ "Item shouldn't have 'even' class."
+ );
+ ok(target.classList.contains("odd"), "Item should have 'odd' class.");
+ }
+ }
+}
+
+/**
+ * Tests if a button for a filter of given type is the only one checked.
+ *
+ * @param string filterType
+ * The type of the filter that should be the only one checked.
+ */
+function testFilterButtons(monitor, filterType) {
+ const doc = monitor.panelWin.document;
+ const target = doc.querySelector(
+ ".requests-list-filter-" + filterType + "-button"
+ );
+ ok(target, `Filter button '${filterType}' was found`);
+ const buttons = [
+ ...doc.querySelectorAll(".requests-list-filter-buttons button"),
+ ];
+ ok(!!buttons.length, "More than zero filter buttons were found");
+
+ // Only target should be checked.
+ const checkStatus = buttons.map(button => (button == target ? 1 : 0));
+ testFilterButtonsCustom(monitor, checkStatus);
+}
+
+/**
+ * Tests if filter buttons have 'checked' attributes set correctly.
+ *
+ * @param array aIsChecked
+ * An array specifying if a button at given index should have a
+ * 'checked' attribute. For example, if the third item of the array
+ * evaluates to true, the third button should be checked.
+ */
+function testFilterButtonsCustom(monitor, isChecked) {
+ const doc = monitor.panelWin.document;
+ const buttons = doc.querySelectorAll(".requests-list-filter-buttons button");
+ for (let i = 0; i < isChecked.length; i++) {
+ const button = buttons[i];
+ if (isChecked[i]) {
+ is(
+ button.getAttribute("aria-pressed"),
+ "true",
+ "The " + button.id + " button should set 'aria-pressed' = true."
+ );
+ } else {
+ is(
+ button.getAttribute("aria-pressed"),
+ "false",
+ "The " + button.id + " button should set 'aria-pressed' = false."
+ );
+ }
+ }
+}
+
+/**
+ * Performs a single XMLHttpRequest and returns a promise that resolves once
+ * the request has loaded.
+ *
+ * @param Object data
+ * { method: the request method (default: "GET"),
+ * url: the url to request (default: content.location.href),
+ * body: the request body to send (default: ""),
+ * nocache: append an unique token to the query string (default: true),
+ * requestHeaders: set request headers (default: none)
+ * }
+ *
+ * @return Promise A promise that's resolved with object
+ * { status: XMLHttpRequest.status,
+ * response: XMLHttpRequest.response }
+ *
+ */
+function promiseXHR(data) {
+ return new Promise((resolve, reject) => {
+ const xhr = new content.XMLHttpRequest();
+
+ const method = data.method || "GET";
+ let url = data.url || content.location.href;
+ const body = data.body || "";
+
+ if (data.nocache) {
+ url += "?devtools-cachebust=" + Math.random();
+ }
+
+ xhr.addEventListener(
+ "loadend",
+ function (event) {
+ resolve({ status: xhr.status, response: xhr.response });
+ },
+ { once: true }
+ );
+
+ xhr.open(method, url);
+
+ // Set request headers
+ if (data.requestHeaders) {
+ data.requestHeaders.forEach(header => {
+ xhr.setRequestHeader(header.name, header.value);
+ });
+ }
+
+ xhr.send(body);
+ });
+}
+
+/**
+ * Performs a single websocket request and returns a promise that resolves once
+ * the request has loaded.
+ *
+ * @param Object data
+ * { url: the url to request (default: content.location.href),
+ * nocache: append an unique token to the query string (default: true),
+ * }
+ *
+ * @return Promise A promise that's resolved with object
+ * { status: websocket status(101),
+ * response: empty string }
+ *
+ */
+function promiseWS(data) {
+ return new Promise((resolve, reject) => {
+ let url = data.url;
+
+ if (data.nocache) {
+ url += "?devtools-cachebust=" + Math.random();
+ }
+
+ /* Create websocket instance */
+ const socket = new content.WebSocket(url);
+
+ /* Since we only use HTTP server to mock websocket, so just ignore the error */
+ socket.onclose = e => {
+ socket.close();
+ resolve({
+ status: 101,
+ response: "",
+ });
+ };
+
+ socket.onerror = e => {
+ socket.close();
+ resolve({
+ status: 101,
+ response: "",
+ });
+ };
+ });
+}
+
+/**
+ * Perform the specified requests in the context of the page content.
+ *
+ * @param Array requests
+ * An array of objects specifying the requests to perform. See
+ * shared/test/frame-script-utils.js for more information.
+ *
+ * @return A promise that resolves once the requests complete.
+ */
+async function performRequestsInContent(requests) {
+ if (!Array.isArray(requests)) {
+ requests = [requests];
+ }
+
+ const responses = [];
+
+ info("Performing requests in the context of the content.");
+
+ for (const request of requests) {
+ const requestFn = request.ws ? promiseWS : promiseXHR;
+ const response = await SpecialPowers.spawn(
+ gBrowser.selectedBrowser,
+ [request],
+ requestFn
+ );
+ responses.push(response);
+ }
+}
+
+function testColumnsAlignment(headers, requestList) {
+ const firstRequestLine = requestList.childNodes[0];
+
+ // Find number of columns
+ const numberOfColumns = headers.childElementCount;
+ for (let i = 0; i < numberOfColumns; i++) {
+ const headerColumn = headers.childNodes[i];
+ const requestColumn = firstRequestLine.childNodes[i];
+ is(
+ headerColumn.getBoundingClientRect().left,
+ requestColumn.getBoundingClientRect().left,
+ "Headers for columns number " + i + " are aligned."
+ );
+ }
+}
+
+async function hideColumn(monitor, column) {
+ const { document } = monitor.panelWin;
+
+ info(`Clicking context-menu item for ${column}`);
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector(".requests-list-headers")
+ );
+
+ const onHeaderRemoved = waitForDOM(
+ document,
+ `#requests-list-${column}-button`,
+ 0
+ );
+ await selectContextMenuItem(monitor, `request-list-header-${column}-toggle`);
+ await onHeaderRemoved;
+
+ ok(
+ !document.querySelector(`#requests-list-${column}-button`),
+ `Column ${column} should be hidden`
+ );
+}
+
+async function showColumn(monitor, column) {
+ const { document } = monitor.panelWin;
+
+ info(`Clicking context-menu item for ${column}`);
+ EventUtils.sendMouseEvent(
+ { type: "contextmenu" },
+ document.querySelector(".requests-list-headers")
+ );
+
+ const onHeaderAdded = waitForDOM(
+ document,
+ `#requests-list-${column}-button`,
+ 1
+ );
+ await selectContextMenuItem(monitor, `request-list-header-${column}-toggle`);
+ await onHeaderAdded;
+
+ ok(
+ document.querySelector(`#requests-list-${column}-button`),
+ `Column ${column} should be visible`
+ );
+}
+
+/**
+ * Select a request and switch to its response panel.
+ *
+ * @param {Number} index The request index to be selected
+ */
+async function selectIndexAndWaitForSourceEditor(monitor, index) {
+ const { document } = monitor.panelWin;
+ const onResponseContent = monitor.panelWin.api.once(
+ TEST_EVENTS.RECEIVED_RESPONSE_CONTENT
+ );
+ // Select the request first, as it may try to fetch whatever is the current request's
+ // responseContent if we select the ResponseTab first.
+ EventUtils.sendMouseEvent(
+ { type: "mousedown" },
+ document.querySelectorAll(".request-list-item")[index]
+ );
+ // We may already be on the ResponseTab, so only select it if needed.
+ const editor = document.querySelector("#response-panel .CodeMirror-code");
+ if (!editor) {
+ const waitDOM = waitForDOM(document, "#response-panel .CodeMirror-code");
+ document.querySelector("#response-tab").click();
+ await waitDOM;
+ }
+ await onResponseContent;
+}
+
+/**
+ * Helper function for executing XHRs on a test page.
+ *
+ * @param {Number} count Number of requests to be executed.
+ */
+async function performRequests(monitor, tab, count) {
+ const wait = waitForNetworkEvents(monitor, count);
+ await ContentTask.spawn(tab.linkedBrowser, count, requestCount => {
+ content.wrappedJSObject.performRequests(requestCount);
+ });
+ await wait;
+}
+
+/**
+ * Helper function for retrieving `.CodeMirror` content
+ */
+function getCodeMirrorValue(monitor) {
+ const { document } = monitor.panelWin;
+ return document.querySelector(".CodeMirror").CodeMirror.getValue();
+}
+
+/**
+ * Helper function opening the options menu
+ */
+function openSettingsMenu(monitor) {
+ const { document } = monitor.panelWin;
+ document.querySelector(".netmonitor-settings-menu-button").click();
+}
+
+function clickSettingsMenuItem(monitor, itemKey) {
+ openSettingsMenu(monitor);
+ const node = getSettingsMenuItem(monitor, itemKey);
+ node.click();
+}
+
+function getSettingsMenuItem(monitor, itemKey) {
+ // The settings menu is injected into the toolbox document,
+ // so we must use the panelWin parent to query for items
+ const { parent } = monitor.panelWin;
+ const { document } = parent;
+
+ return document.querySelector(SETTINGS_MENU_ITEMS[itemKey]);
+}
+
+/**
+ * Wait for lazy fields to be loaded in a request.
+ *
+ * @param Object Store redux store containing request list.
+ * @param array fields array of strings which contain field names to be checked
+ * on the request.
+ */
+function waitForRequestData(store, fields, id) {
+ return waitUntil(() => {
+ let item;
+ if (id) {
+ item = getRequestById(store.getState(), id);
+ } else {
+ item = getSortedRequests(store.getState())[0];
+ }
+ if (!item) {
+ return false;
+ }
+ for (const field of fields) {
+ if (!item[field]) {
+ return false;
+ }
+ }
+ return true;
+ });
+}
+
+// Telemetry
+
+/**
+ * Helper for verifying telemetry event.
+ *
+ * @param Object expectedEvent object representing expected event data.
+ * @param Object query fields specifying category, method and object
+ * of the target telemetry event.
+ */
+function checkTelemetryEvent(expectedEvent, query) {
+ const events = queryTelemetryEvents(query);
+ is(events.length, 1, "There was only 1 event logged");
+
+ const [event] = events;
+ ok(event.session_id > 0, "There is a valid session_id in the logged event");
+
+ const f = e => JSON.stringify(e, null, 2);
+ is(
+ f(event),
+ f({
+ ...expectedEvent,
+ session_id: event.session_id,
+ }),
+ "The event has the expected data"
+ );
+}
+
+function queryTelemetryEvents(query) {
+ const ALL_CHANNELS = Ci.nsITelemetry.DATASET_ALL_CHANNELS;
+ const snapshot = Services.telemetry.snapshotEvents(ALL_CHANNELS, true);
+ const category = query.category || "devtools.main";
+ const object = query.object || "netmonitor";
+
+ const filtersChangedEvents = snapshot.parent.filter(
+ event =>
+ event[1] === category && event[2] === query.method && event[3] === object
+ );
+
+ // Return the `extra` field (which is event[5]e).
+ return filtersChangedEvents.map(event => event[5]);
+}
+/**
+ * Check that the provided requests match the requests displayed in the netmonitor.
+ *
+ * @param {array} requests
+ * The expected requests.
+ * @param {object} monitor
+ * The netmonitor instance.
+ * @param {object=} options
+ * @param {boolean} allowDifferentOrder
+ * When set to true, requests are allowed to be in a different order in the
+ * netmonitor than in the expected requests array. Defaults to false.
+ */
+function validateRequests(requests, monitor, options = {}) {
+ const { allowDifferentOrder } = options;
+ const { document, store, windowRequire } = monitor.panelWin;
+
+ const { getDisplayedRequests } = windowRequire(
+ "devtools/client/netmonitor/src/selectors/index"
+ );
+ const sortedRequests = getSortedRequests(store.getState());
+
+ requests.forEach((spec, i) => {
+ const { method, url, causeType, causeUri, stack } = spec;
+
+ let requestItem;
+ if (allowDifferentOrder) {
+ requestItem = sortedRequests.find(r => r.url === url);
+ } else {
+ requestItem = sortedRequests[i];
+ }
+
+ verifyRequestItemTarget(
+ document,
+ getDisplayedRequests(store.getState()),
+ requestItem,
+ method,
+ url,
+ { cause: { type: causeType, loadingDocumentUri: causeUri } }
+ );
+
+ const { stacktrace } = requestItem;
+ const stackLen = stacktrace ? stacktrace.length : 0;
+
+ if (stack) {
+ ok(stacktrace, `Request #${i} has a stacktrace`);
+ ok(
+ stackLen > 0,
+ `Request #${i} (${causeType}) has a stacktrace with ${stackLen} items`
+ );
+
+ // if "stack" is array, check the details about the top stack frames
+ if (Array.isArray(stack)) {
+ stack.forEach((frame, j) => {
+ // If the `fn` is "*", it means the request is triggered from chrome
+ // resources, e.g. `resource:///modules/XX.jsm`, so we skip checking
+ // the function name for now (bug 1280266).
+ if (frame.file.startsWith("resource:///")) {
+ todo(false, "Requests from chrome resource should not be included");
+ } else {
+ let value = stacktrace[j].functionName;
+ if (Object.is(value, null)) {
+ value = undefined;
+ }
+ is(
+ value,
+ frame.fn,
+ `Request #${i} has the correct function on JS stack frame #${j}`
+ );
+ is(
+ stacktrace[j].filename.split("/").pop(),
+ frame.file.split("/").pop(),
+ `Request #${i} has the correct file on JS stack frame #${j}`
+ );
+ is(
+ stacktrace[j].lineNumber,
+ frame.line,
+ `Request #${i} has the correct line number on JS stack frame #${j}`
+ );
+ value = stacktrace[j].asyncCause;
+ if (Object.is(value, null)) {
+ value = undefined;
+ }
+ is(
+ value,
+ frame.asyncCause,
+ `Request #${i} has the correct async cause on JS stack frame #${j}`
+ );
+ }
+ });
+ }
+ } else {
+ is(stackLen, 0, `Request #${i} (${causeType}) has an empty stacktrace`);
+ }
+ });
+}
+
+/**
+ * Retrieve the context menu element corresponding to the provided id, for the provided
+ * netmonitor instance.
+ * @param {Object} monitor
+ * The network monnitor object
+ * @param {String} id
+ * The id of the context menu item
+ */
+function getContextMenuItem(monitor, id) {
+ const Menu = require("resource://devtools/client/framework/menu.js");
+ return Menu.getMenuElementById(id, monitor.panelWin.document);
+}
+
+async function maybeOpenAncestorMenu(menuItem) {
+ const parentPopup = menuItem.parentNode;
+ if (parentPopup.state == "shown") {
+ return;
+ }
+ const shown = BrowserTestUtils.waitForEvent(parentPopup, "popupshown");
+ if (parentPopup.state == "showing") {
+ await shown;
+ return;
+ }
+ const parentMenu = parentPopup.parentNode;
+ await maybeOpenAncestorMenu(parentMenu);
+ parentMenu.openMenu(true);
+ await shown;
+}
+
+/*
+ * Selects and clicks the context menu item, it should
+ * also wait for the popup to close.
+ * @param {Object} monitor
+ * The network monnitor object
+ * @param {String} id
+ * The id of the context menu item
+ */
+async function selectContextMenuItem(monitor, id) {
+ const contextMenuItem = getContextMenuItem(monitor, id);
+
+ const popup = contextMenuItem.parentNode;
+ await maybeOpenAncestorMenu(contextMenuItem);
+ const hidden = BrowserTestUtils.waitForEvent(popup, "popuphidden");
+ popup.activateItem(contextMenuItem);
+ await hidden;
+}
+
+/**
+ * Wait for DOM being in specific state. But, do not wait
+ * for change if it's in the expected state already.
+ */
+async function waitForDOMIfNeeded(target, selector, expectedLength = 1) {
+ return new Promise(resolve => {
+ const elements = target.querySelectorAll(selector);
+ if (elements.length == expectedLength) {
+ resolve(elements);
+ } else {
+ waitForDOM(target, selector, expectedLength).then(elems => {
+ resolve(elems);
+ });
+ }
+ });
+}
+
+/**
+ * Helper for blocking or unblocking a request via the list item's context menu.
+ *
+ * @param {Element} element
+ * Target request list item to be right clicked to bring up its context menu.
+ * @param {Object} monitor
+ * The netmonitor instance used for retrieving a context menu element.
+ * @param {Object} store
+ * The redux store (wait-service middleware required).
+ * @param {String} action
+ * The action, block or unblock, to construct a corresponding context menu id.
+ */
+async function toggleBlockedUrl(element, monitor, store, action = "block") {
+ EventUtils.sendMouseEvent({ type: "contextmenu" }, element);
+ const contextMenuId = `request-list-context-${action}-url`;
+ const onRequestComplete = waitForDispatch(
+ store,
+ "REQUEST_BLOCKING_UPDATE_COMPLETE"
+ );
+ await selectContextMenuItem(monitor, contextMenuId);
+
+ info(`Wait for selected request to be ${action}ed`);
+ await onRequestComplete;
+ info(`Selected request is now ${action}ed`);
+}
+
+/**
+ * Find and click an element
+ *
+ * @param {Element} element
+ * Target element to be clicked
+ * @param {Object} monitor
+ * The netmonitor instance used for retrieving the window.
+ */
+
+function clickElement(element, monitor) {
+ EventUtils.synthesizeMouseAtCenter(element, {}, monitor.panelWin);
+}
+
+/**
+ * Register a listener to be notified when a favicon finished loading and
+ * dispatch a "devtools:test:favicon" event to the favicon's link element.
+ *
+ * @param {Browser} browser
+ * Target browser to observe the favicon load.
+ */
+function registerFaviconNotifier(browser) {
+ const listener = async (name, data) => {
+ if (name == "SetIcon" || name == "SetFailedIcon") {
+ await SpecialPowers.spawn(browser, [], async () => {
+ content.document
+ .querySelector("link[rel='icon']")
+ .dispatchEvent(new content.CustomEvent("devtools:test:favicon"));
+ });
+ LinkHandlerParent.removeListenerForTests(listener);
+ }
+ };
+ LinkHandlerParent.addListenerForTests(listener);
+}
+
+/**
+ * Predicates used when sorting items.
+ *
+ * @param object first
+ * The first item used in the comparison.
+ * @param object second
+ * The second item used in the comparison.
+ * @return number
+ * <0 to sort first to a lower index than second
+ * =0 to leave first and second unchanged with respect to each other
+ * >0 to sort second to a lower index than first
+ */
+
+function compareValues(first, second) {
+ if (first === second) {
+ return 0;
+ }
+ return first > second ? 1 : -1;
+}
+
+/**
+ * Click on the "Response" tab to open "Response" panel in the sidebar.
+ * @param {Document} doc
+ * Network panel document.
+ * @param {String} name
+ * Network panel sidebar tab name.
+ */
+const clickOnSidebarTab = (doc, name) => {
+ AccessibilityUtils.setEnv({
+ // Keyboard accessibility is handled on the sidebar tabs container level
+ // (nav). Users can use arrow keys to navigate between and select tabs.
+ nonNegativeTabIndexRule: false,
+ });
+ EventUtils.sendMouseEvent(
+ { type: "click" },
+ doc.querySelector(`#${name}-tab`)
+ );
+ AccessibilityUtils.resetEnv();
+};
+
+/**
+ * Add a new blocked request URL pattern. The request blocking sidepanel should
+ * already be opened.
+ *
+ * @param {string} pattern
+ * The URL pattern to add to block requests.
+ * @param {Object} monitor
+ * The netmonitor instance.
+ */
+async function addBlockedRequest(pattern, monitor) {
+ info("Add a blocked request for the URL pattern " + pattern);
+ const doc = monitor.panelWin.document;
+
+ const addRequestForm = await waitFor(() =>
+ doc.querySelector(
+ "#network-action-bar-blocked-panel .request-blocking-add-form"
+ )
+ );
+ ok(!!addRequestForm, "The request blocking side panel is not available");
+
+ info("Wait for the add input to get focus");
+ await waitFor(() =>
+ addRequestForm.querySelector("input.devtools-searchinput:focus")
+ );
+
+ typeInNetmonitor(pattern, monitor);
+ EventUtils.synthesizeKey("KEY_Enter");
+}
+
+/**
+ * Check if the provided .request-list-item element corresponds to a blocked
+ * request.
+ *
+ * @param {Element}
+ * The request's DOM element.
+ * @returns {boolean}
+ * True if the request is displayed as blocked, false otherwise.
+ */
+function checkRequestListItemBlocked(item) {
+ return item.className.includes("blocked");
+}
+
+/**
+ * Type the provided string the netmonitor window. The correct input should be
+ * focused prior to using this helper.
+ *
+ * @param {string} string
+ * The string to type.
+ * @param {Object} monitor
+ * The netmonitor instance used to type the string.
+ */
+function typeInNetmonitor(string, monitor) {
+ for (const ch of string) {
+ EventUtils.synthesizeKey(ch, {}, monitor.panelWin);
+ }
+}
diff --git a/devtools/client/netmonitor/test/html_api-calls-test-page.html b/devtools/client/netmonitor/test/html_api-calls-test-page.html
new file mode 100644
index 0000000000..1385101a64
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_api-calls-test-page.html
@@ -0,0 +1,45 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>API calls request test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send();
+ });
+ }
+
+ async function performRequests() {
+ await get("/api/fileName.xml");
+ await get("/api/file%E2%98%A2.xml");
+ await get("/api/ascii/get/");
+ await get("/api/unicode/%E2%98%A2/");
+ await get("/api/search/?q=search%E2%98%A2");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_brotli-test-page.html b/devtools/client/netmonitor/test/html_brotli-test-page.html
new file mode 100644
index 0000000000..7b3f01c4d2
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_brotli-test-page.html
@@ -0,0 +1,41 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Brotli test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_content-type-test-server.sjs?fmt=br");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_cache-test-page.html b/devtools/client/netmonitor/test/html_cache-test-page.html
new file mode 100644
index 0000000000..fa71a415f6
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_cache-test-page.html
@@ -0,0 +1,28 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor cache test page</title>
+ </head>
+
+ <body>
+ <p>Cache test</p>
+
+ <script type="text/javascript">
+ "use strict";
+
+ window.sendRequestWithStatus = status => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", `sjs_content-type-test-server.sjs?sts=${status}&fmt=html`, true);
+ xhr.send(null);
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_cause-test-page.html b/devtools/client/netmonitor/test/html_cause-test-page.html
new file mode 100644
index 0000000000..4ec79936e4
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_cause-test-page.html
@@ -0,0 +1,98 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ <link rel="stylesheet" type="text/css" href="stylesheet_request" />
+ </head>
+
+ <body>
+ <p>Request cause test</p>
+ <img src="img_request" />
+ <img srcset="img_srcset_request" />
+ <!-- ensure that the two next <img> are offscreen
+ so that the error listener is registered before we try loading them -->
+ <div style="height: 2000vh;"></div>
+ <img loading="lazy" src="lazy_img_request" />
+ <img loading="lazy" srcset="lazy_img_srcset_request" />
+ <script type="text/javascript">
+ "use strict";
+
+ function performXhrRequest() {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", "xhr_request", true);
+ return new Promise(function performXhrRequestCallback(resolve) {
+ xhr.onload = resolve;
+ xhr.send();
+ });
+ }
+
+ function performFetchRequest() {
+ return fetch("fetch_request");
+ }
+
+ // Perform some requests with async stacks
+ function performPromiseFetchRequest() {
+ return Promise.resolve().then(function performPromiseFetchRequestCallback() {
+ return fetch("promise_fetch_request");
+ });
+ }
+
+ function performTimeoutFetchRequest() {
+ return new Promise(function performTimeoutFetchRequestCallback1(resolve) {
+ setTimeout(function performTimeoutFetchRequestCallback2() {
+ resolve(fetch("timeout_fetch_request"));
+ }, 0);
+ });
+ }
+
+ function performFavicon() {
+ return new Promise(function (resolve) {
+ const link = document.createElement("link");
+ link.rel = "icon";
+ link.href = "favicon_request";
+ document.querySelector("head").appendChild(link);
+ link.addEventListener("devtools:test:favicon", resolve);
+ });
+ }
+
+ function performLazyLoadingImage() {
+ return new Promise(function (resolve) {
+ const lazyImgs = document.querySelectorAll("img[loading='lazy']");
+
+ const promises = [
+ new Promise(r => lazyImgs[0].addEventListener("error", r)),
+ new Promise(r => lazyImgs[1].addEventListener("error", r)),
+ ];
+
+ // Given that the default display style of <img> is `inline` so
+ // it's sufficient to scroll to an <img>.
+ lazyImgs[0].scrollIntoView({ behavior: "instant" });
+ resolve(Promise.all(promises));
+ });
+ }
+
+ function performBeaconRequest() {
+ navigator.sendBeacon("beacon_request");
+ }
+
+ (async function() {
+ await performXhrRequest();
+ await performFetchRequest();
+ await performPromiseFetchRequest();
+ await performTimeoutFetchRequest();
+ await performFavicon();
+ await performLazyLoadingImage();
+
+ // Finally, send a beacon request
+ performBeaconRequest();
+ })();
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_content-type-without-cache-test-page.html b/devtools/client/netmonitor/test/html_content-type-without-cache-test-page.html
new file mode 100644
index 0000000000..af27ab0835
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_content-type-without-cache-test-page.html
@@ -0,0 +1,47 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Content type test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_content-type-test-server.sjs?fmt=xml");
+ await get("sjs_content-type-test-server.sjs?fmt=css");
+ await get("sjs_content-type-test-server.sjs?fmt=js");
+ await get("sjs_content-type-test-server.sjs?fmt=json");
+ await get("sjs_content-type-test-server.sjs?fmt=bogus");
+ await get("test-image.png?v=" + Math.random());
+ await get("sjs_content-type-test-server.sjs?fmt=gzip");
+ await get("sjs_content-type-test-server.sjs?fmt=br");
+ }
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_copy-as-curl.html b/devtools/client/netmonitor/test/html_copy-as-curl.html
new file mode 100644
index 0000000000..87930954ab
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_copy-as-curl.html
@@ -0,0 +1,33 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Performing requests of various methods, with or without payload.</p>
+
+ <script type="text/javascript">
+ /* exported performRequest */
+ "use strict";
+
+ function performRequest(url, method, payload = null) {
+ const xhr = new XMLHttpRequest();
+ xhr.open(method, url, true);
+ xhr.setRequestHeader("Accept-Language", window.navigator.language);
+ xhr.setRequestHeader("X-Custom-Header-1", "Custom value");
+ xhr.setRequestHeader("X-Custom-Header-2", "8.8.8.8");
+ xhr.setRequestHeader("X-Custom-Header-3", "Mon, 3 Mar 2014 11:11:11 GMT");
+ xhr.send(payload);
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_cors-test-page.html b/devtools/client/netmonitor/test/html_cors-test-page.html
new file mode 100644
index 0000000000..9ad1f82344
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_cors-test-page.html
@@ -0,0 +1,34 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>POST with CORS test page</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function post(url, contentType, postData) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", url, true);
+ xhr.setRequestHeader("Content-Type", contentType);
+ xhr.send(postData);
+ }
+
+ function performRequests(url, contentType, postData) {
+ post(url, contentType, postData);
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_csp-frame-test-page.html b/devtools/client/netmonitor/test/html_csp-frame-test-page.html
new file mode 100644
index 0000000000..7ef4e23825
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_csp-frame-test-page.html
@@ -0,0 +1,9 @@
+<!DOCTYPE HTML>
+<html>
+ <head>
+ <meta charset=utf-8>
+ </head>
+ <body>
+ <iframe src="https://example.org/browser/devtools/client/netmonitor/test/html_csp-test-page.html" width="50%" height="50%"></iframe>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_csp-resend-test-page.html b/devtools/client/netmonitor/test/html_csp-resend-test-page.html
new file mode 100644
index 0000000000..f6ec955a32
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_csp-resend-test-page.html
@@ -0,0 +1,25 @@
+<!DOCTYPE HTML>
+<html>
+ <head>
+ <meta charset=utf-8>
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src *; script-src 'unsafe-inline'">
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Tests 'Edit and Resend' requests re-uses the same content-type</title>
+ </head>
+ <body>
+ The image will be allowed to load by the CSP.<br/>
+ <img id="test-img"></img><br/>
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function performRequests() {
+ const testImg = document.getElementById("test-img");
+ testImg.src = "test-image.png";
+ }
+
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_csp-test-page.html b/devtools/client/netmonitor/test/html_csp-test-page.html
new file mode 100644
index 0000000000..2329f4fa1e
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_csp-test-page.html
@@ -0,0 +1,18 @@
+<!DOCTYPE HTML>
+<html>
+ <head>
+ <meta charset=utf-8>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <meta http-equiv="Content-Security-Policy" content="script-src 'none'; style-src 'none';">
+ <title>Tests breaking CSP with script</title>
+ <link href="internal-loaded.css" rel="stylesheet" type="text/css">
+ </head>
+ <body>
+
+ The script in this page will CSP:
+
+ <script src="js_websocket-worker-test.js"></script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_curl-utils.html b/devtools/client/netmonitor/test/html_curl-utils.html
new file mode 100644
index 0000000000..bd09a63ba5
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_curl-utils.html
@@ -0,0 +1,136 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Performing requests</p>
+
+ <p>
+ <canvas width="100" height="100"></canvas>
+ </p>
+
+ <hr/>
+
+ <form method="post" action="#" enctype="multipart/form-data" target="target" id="post-form">
+ <input type="text" name="param1" value="value1"/>
+ <input type="text" name="param2" value="value2"/>
+ <input type="text" name="param3" value="value3"/>
+ <input type="submit"/>
+ </form>
+ <iframe name="target"></iframe>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ /* eslint-disable max-nested-callbacks */
+ "use strict";
+
+ function ajaxGet(url, callback) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", url + "?param1=value1&param2=value2&param3=value3", true);
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ xhr.onload = function() {
+ callback();
+ };
+ xhr.send();
+ }
+
+ function ajaxPost(url, callback) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", url, true);
+ xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ xhr.onload = function() {
+ callback();
+ };
+ const params = "param1=value1&param2=value2&param3=value3";
+ xhr.send(params);
+ }
+
+ function ajaxPostJson(url, callback) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", url, true);
+ xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ xhr.onload = function() {
+ callback();
+ };
+ const params = {
+ param1: "value1",
+ param2: "value2",
+ };
+ const jsonParams = JSON.stringify(params);
+ xhr.send(jsonParams);
+ }
+
+ function ajaxPatch(url, callback) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("PATCH", url, true);
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ xhr.onload = function() {
+ callback();
+ };
+ const params = "param1=value1&param2=value2&param3=value3";
+ xhr.send(params);
+ }
+
+ function ajaxMultipart(url, callback) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", url, true);
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ xhr.onload = function() {
+ callback();
+ };
+
+ getCanvasElem().toBlob((blob) => {
+ const formData = new FormData();
+ formData.append("param1", "value1");
+ formData.append("file", blob, "filename.png");
+ xhr.send(formData);
+ });
+ }
+
+ function submitForm() {
+ const form = document.querySelector("#post-form");
+ form.submit();
+ }
+
+ function getCanvasElem() {
+ return document.querySelector("canvas");
+ }
+
+ function initCanvas() {
+ const canvas = getCanvasElem();
+ const ctx = canvas.getContext("2d");
+ ctx.fillRect(0, 0, 100, 100);
+ ctx.clearRect(20, 20, 60, 60);
+ ctx.strokeRect(25, 25, 50, 50);
+ }
+
+ function performRequests(url) {
+ ajaxGet(url, () => {
+ ajaxPost(url, () => {
+ ajaxPostJson(url, () => {
+ ajaxPatch(url, () => {
+ ajaxMultipart(url, () => {
+ submitForm();
+ });
+ });
+ });
+ });
+ });
+ }
+
+ initCanvas();
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_custom-get-page.html b/devtools/client/netmonitor/test/html_custom-get-page.html
new file mode 100644
index 0000000000..f97c2b09fe
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_custom-get-page.html
@@ -0,0 +1,48 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Performing a custom number of GETs</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ // Use a count parameter to defeat caching.
+ let count = 0;
+
+ async function performRequests(total, url, timeout = 0) {
+ if (!total) {
+ return;
+ }
+ await get(url || "request_" + (count++));
+ setTimeout(performRequests.bind(this, --total, url, timeout), timeout);
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_cyrillic-test-page.html b/devtools/client/netmonitor/test/html_cyrillic-test-page.html
new file mode 100644
index 0000000000..309edb473b
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_cyrillic-test-page.html
@@ -0,0 +1,42 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Cyrillic type test</p>
+ <p>Братан, ты вообще качаешься?</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_content-type-test-server.sjs?fmt=txt");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_filter-test-page.html b/devtools/client/netmonitor/test/html_filter-test-page.html
new file mode 100644
index 0000000000..b0bd48301f
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_filter-test-page.html
@@ -0,0 +1,58 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Filtering test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ // Use a random parameter to defeat caching.
+ xhr.open("GET", address + "&" + Math.random(), true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests(optionsText) {
+ const options = JSON.parse(optionsText);
+
+ await get("sjs_content-type-test-server.sjs?fmt=html&res=" + options.htmlContent);
+ await get("sjs_content-type-test-server.sjs?fmt=css");
+ await get("sjs_content-type-test-server.sjs?fmt=js");
+ await get("sjs_content-type-test-server.sjs?fmt=xhtml");
+ if (!options.getMedia) {
+ return;
+ }
+ await get("sjs_content-type-test-server.sjs?fmt=font");
+ await get("sjs_content-type-test-server.sjs?fmt=image");
+ await get("sjs_content-type-test-server.sjs?fmt=audio");
+ await get("sjs_content-type-test-server.sjs?fmt=video");
+ if (!options.getFlash) {
+ return;
+ }
+ await get("sjs_content-type-test-server.sjs?fmt=flash");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_fonts-test-page.html b/devtools/client/netmonitor/test/html_fonts-test-page.html
new file mode 100644
index 0000000000..c68b35f08d
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_fonts-test-page.html
@@ -0,0 +1,45 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ <style>
+ @font-face {
+ font-family: test-font;
+ src: url("ostrich-regular.ttf") format("truetype");
+ font-style: normal;
+ font-weight: 400;
+ font-display: swap;
+ }
+
+ @font-face {
+ font-family: test-font-bold;
+ src: url("ostrich-black.ttf") format("truetype");
+ font-style: normal;
+ font-weight: 700;
+ font-display: swap;
+ }
+
+ .regular {
+ font-family: test-font;
+ }
+
+ .bold {
+ font-family: test-font-bold;
+ font-weight: 700;
+ }
+ </style>
+ </head>
+
+ <body>
+ <p class="regular">Regular font</p>
+ <p class="bold">Bold font</p>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_frame-subdocument.html b/devtools/client/netmonitor/test/html_frame-subdocument.html
new file mode 100644
index 0000000000..84a160a266
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_frame-subdocument.html
@@ -0,0 +1,50 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ <link rel="stylesheet" type="text/css" href="stylesheet_request" />
+ </head>
+
+ <body>
+ <p>Request frame test</p>
+ <img src="img_request" />
+ <script type="text/javascript">
+ "use strict";
+
+ function performXhrRequest() {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", "xhr_request", true);
+ xhr.send();
+ }
+
+ function performFetchRequest() {
+ fetch("fetch_request");
+ }
+
+ function performBeaconRequest() {
+ navigator.sendBeacon("beacon_request");
+ }
+
+ performXhrRequest();
+ performFetchRequest();
+
+ // Perform some requests with async stacks
+ Promise.resolve().then(function performPromiseFetchRequest() {
+ fetch("promise_fetch_request");
+ setTimeout(function performTimeoutFetchRequest() {
+ fetch("timeout_fetch_request");
+
+ // Finally, send a beacon request
+ performBeaconRequest();
+ }, 0);
+ });
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_frame-test-page.html b/devtools/client/netmonitor/test/html_frame-test-page.html
new file mode 100644
index 0000000000..edf251ada3
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_frame-test-page.html
@@ -0,0 +1,51 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ <link rel="stylesheet" type="text/css" href="stylesheet_request" />
+ </head>
+
+ <body>
+ <p>Request frame test</p>
+ <img src="img_request" />
+ <iframe src="html_frame-subdocument.html"></iframe>
+ <script type="text/javascript">
+ "use strict";
+
+ function performXhrRequest() {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", "xhr_request", true);
+ xhr.send();
+ }
+
+ function performFetchRequest() {
+ fetch("fetch_request");
+ }
+
+ function performBeaconRequest() {
+ navigator.sendBeacon("beacon_request");
+ }
+
+ performXhrRequest();
+ performFetchRequest();
+
+ // Perform some requests with async stacks
+ Promise.resolve().then(function performPromiseFetchRequest() {
+ fetch("promise_fetch_request");
+ setTimeout(function performTimeoutFetchRequest() {
+ fetch("timeout_fetch_request");
+
+ // Finally, send a beacon request
+ performBeaconRequest();
+ }, 0);
+ });
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_header-test-page.html b/devtools/client/netmonitor/test/html_header-test-page.html
new file mode 100644
index 0000000000..c0d9a85bdc
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_header-test-page.html
@@ -0,0 +1,43 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>POST raw test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function post(address, message, callback) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", address, true);
+ xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ callback();
+ }
+ };
+ xhr.send(message);
+ }
+
+ function performRequests() {
+ const rawData = "";
+ post("sjs_simple-test-server.sjs?file=foo+%23+bar#home", rawData, function() {
+ // Done.
+ });
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_image-cache.html b/devtools/client/netmonitor/test/html_image-cache.html
new file mode 100644
index 0000000000..b36e388755
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_image-cache.html
@@ -0,0 +1,7 @@
+<html>
+ <body>
+ <img src="test-image.png">
+ <img src="test-image.png">
+ <img src="test-image.png">
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_image-tooltip-test-page.html b/devtools/client/netmonitor/test/html_image-tooltip-test-page.html
new file mode 100644
index 0000000000..299a75a1ab
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_image-tooltip-test-page.html
@@ -0,0 +1,29 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>tooltip test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function performRequests() {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", "test-image.png?v=" + Math.random(), true);
+ xhr.send(null);
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_infinite-get-page.html b/devtools/client/netmonitor/test/html_infinite-get-page.html
new file mode 100644
index 0000000000..462627e81d
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_infinite-get-page.html
@@ -0,0 +1,50 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Infinite GETs</p>
+
+ <script type="text/javascript">
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ // Use a count parameter to defeat caching.
+ let count = 0;
+ let doRequests = true;
+ function stopRequests() { // eslint-disable-line no-unused-vars
+ doRequests = false;
+ }
+
+ (async function performRequests() {
+ await get("request_" + (count++));
+ if (doRequests) {
+ setTimeout(performRequests, 50);
+ }
+ })();
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_internal-stylesheet.html b/devtools/client/netmonitor/test/html_internal-stylesheet.html
new file mode 100644
index 0000000000..c0870d84a1
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_internal-stylesheet.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<script>
+"use strict";
+
+const html = `
+ <!DOCTYPE html>
+ <head>
+ <link rel="stylesheet" href="internal-loaded.css">
+ </head>
+`;
+onload = function() {
+ // eslint-disable-next-line no-unsanitized/method
+ document.write(html);
+}
+</script>
diff --git a/devtools/client/netmonitor/test/html_json-b64.html b/devtools/client/netmonitor/test/html_json-b64.html
new file mode 100644
index 0000000000..dd76b74e36
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_json-b64.html
@@ -0,0 +1,41 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>JSON b64 test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_content-type-test-server.sjs?fmt=json-b64");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_json-basic.html b/devtools/client/netmonitor/test/html_json-basic.html
new file mode 100644
index 0000000000..2f48d8fab6
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_json-basic.html
@@ -0,0 +1,43 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>JSON request test page</p>
+ <p>Pass the JSON name (as supported by sjs_json-test-server.sjs) as a query parameter</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ // Forward the query parameter for this page to sjs_json-test-server
+ await get("sjs_json-test-server.sjs" + window.location.search);
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_json-custom-mime-test-page.html b/devtools/client/netmonitor/test/html_json-custom-mime-test-page.html
new file mode 100644
index 0000000000..c203f94dff
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_json-custom-mime-test-page.html
@@ -0,0 +1,41 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>JSONP test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_content-type-test-server.sjs?fmt=json-custom-mime");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_json-empty.html b/devtools/client/netmonitor/test/html_json-empty.html
new file mode 100644
index 0000000000..99e743a4bb
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_json-empty.html
@@ -0,0 +1,42 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Empty JSON test page</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ // Forward the query parameter for this page to sjs_json-test-server
+ await get("sjs_json-test-server.sjs" + window.location.search);
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_json-long-test-page.html b/devtools/client/netmonitor/test/html_json-long-test-page.html
new file mode 100644
index 0000000000..afa9f47079
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_json-long-test-page.html
@@ -0,0 +1,41 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>JSON long string test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_content-type-test-server.sjs?fmt=json-long");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_json-malformed-test-page.html b/devtools/client/netmonitor/test/html_json-malformed-test-page.html
new file mode 100644
index 0000000000..61966a454e
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_json-malformed-test-page.html
@@ -0,0 +1,41 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>JSON malformed test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_content-type-test-server.sjs?fmt=json-malformed");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_json-text-mime-test-page.html b/devtools/client/netmonitor/test/html_json-text-mime-test-page.html
new file mode 100644
index 0000000000..98d42a9450
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_json-text-mime-test-page.html
@@ -0,0 +1,41 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>JSON text test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_content-type-test-server.sjs?fmt=json-text-mime");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_json-xssi-protection.html b/devtools/client/netmonitor/test/html_json-xssi-protection.html
new file mode 100644
index 0000000000..2daf1725b8
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_json-xssi-protection.html
@@ -0,0 +1,42 @@
+
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>JSON XSSI protection test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise (resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send();
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_content-type-test-server.sjs?fmt=json-valid-xssi-protection");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_jsonp-test-page.html b/devtools/client/netmonitor/test/html_jsonp-test-page.html
new file mode 100644
index 0000000000..d30de40c06
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_jsonp-test-page.html
@@ -0,0 +1,42 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>JSONP test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_content-type-test-server.sjs?fmt=jsonp&jsonp=$_0123Fun");
+ await get("sjs_content-type-test-server.sjs?fmt=jsonp2&jsonp=$_4567Sad");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_maps-test-page.html b/devtools/client/netmonitor/test/html_maps-test-page.html
new file mode 100644
index 0000000000..401d472e73
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_maps-test-page.html
@@ -0,0 +1,24 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor source maps test page</title>
+ <link rel="stylesheet" type="text/css" href="stylesheet_request" />
+ </head>
+
+ <body>
+ <script type="text/javascript" src="xhr_bundle.js" charset="utf-8"></script>
+ <script type="text/javascript">
+ "use strict";
+
+ /* globals doxhr */
+ doxhr();
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_navigate-test-page.html b/devtools/client/netmonitor/test/html_navigate-test-page.html
new file mode 100644
index 0000000000..23f00f3dfd
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_navigate-test-page.html
@@ -0,0 +1,18 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Navigation test</p>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_open-request-in-tab.html b/devtools/client/netmonitor/test/html_open-request-in-tab.html
new file mode 100644
index 0000000000..dd399c4364
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_open-request-in-tab.html
@@ -0,0 +1,33 @@
+<!-- Any copyright is dedicated to the Public Domain.
+http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Performing a GET or POST request</p>
+
+ <script type="text/javascript">
+ /* exported performRequest */
+ "use strict";
+
+ function performRequest(method, contentType, payload) {
+ const xhr = new XMLHttpRequest();
+ const url = "sjs_method-test-server.sjs";
+ xhr.open(method, url, true);
+ xhr.setRequestHeader("Accept-Language", window.navigator.language);
+ if (contentType) {
+ xhr.setRequestHeader("Content-Type", contentType);
+ }
+ xhr.send(payload || "");
+ }
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_params-test-page.html b/devtools/client/netmonitor/test/html_params-test-page.html
new file mode 100644
index 0000000000..4bdb248b85
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_params-test-page.html
@@ -0,0 +1,78 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Request params type test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ async function get(address, query) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address + query, true);
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send();
+ });
+ }
+
+ async function request(address, query, contentType, requestBody, method) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open(method, address + query, true);
+ xhr.setRequestHeader("content-type", contentType);
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(requestBody);
+ });
+ }
+
+ async function post(address, query, contentType, postBody) {
+ return request(address, query, contentType, postBody, "POST");
+ }
+
+ async function patch(address, query, contentType, patchBody) {
+ return request(address, query, contentType, patchBody, "PATCH");
+ }
+
+ async function put(address, query, contentType, putBody) {
+ return request(address, query, contentType, putBody, "PUT");
+ }
+
+ async function performRequests() {
+ const urlencoded = "application/x-www-form-urlencoded";
+ await post("baz", "?a", urlencoded, '{ "foo": "bar" }');
+ await post("baz", "?a=b", urlencoded, '{ "foo": "bar" }');
+ await post("baz", "?a=b", urlencoded, "?foo=bar");
+ await post("baz", "?a", undefined, '{ "foo": "bar" }');
+ await post("baz", "?a=b", undefined, '{ "foo": "bar" }');
+ await post("baz", "?a=b", undefined, "?foo=bar");
+ await get("baz", "");
+ await patch("baz", "?a=b", urlencoded, '{ "foo": "bar" }');
+ await put("baz", "?a=b", urlencoded, '{ "foo": "bar" }');
+ await get("baz", "?species=in=(52,60)");
+ await get("baz", "?a=&a=b");
+ await get("baz", "?a=b&a=c&d=1");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_pause-test-page.html b/devtools/client/netmonitor/test/html_pause-test-page.html
new file mode 100644
index 0000000000..a4ed668ce8
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_pause-test-page.html
@@ -0,0 +1,36 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Performing a custom number of GETs</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function performRequests(url) {
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", url, true);
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_post-array-data-test-page.html b/devtools/client/netmonitor/test/html_post-array-data-test-page.html
new file mode 100644
index 0000000000..386b043d1a
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_post-array-data-test-page.html
@@ -0,0 +1,34 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function performRequests() {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", "sjs_simple-test-server.sjs", true);
+
+ const postData = JSON.stringify({
+ watches: ["hello", "how", "are", "you", {
+ a: 10,
+ c: 15,
+ b: ["a", "c", "b"],
+ }],
+ });
+ xhr.send(postData);
+ }
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_post-data-test-page.html b/devtools/client/netmonitor/test/html_post-data-test-page.html
new file mode 100644
index 0000000000..61a77bcbab
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_post-data-test-page.html
@@ -0,0 +1,82 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ <style>
+ input {
+ display: block;
+ margin: 12px;
+ }
+ </style>
+ </head>
+
+ <body>
+ <p>POST data test</p>
+ <form enctype="multipart/form-data" method="post" name="form-name">
+ <input type="text" name="text" placeholder="text" value="Some text..."/>
+ <input type="email" name="email" placeholder="email"/>
+ <input type="range" name="range" value="42"/>
+ <input type="button" value="Post me!" onclick="window.form()">
+ </form>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function post(address, message) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", address, true);
+ xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+
+ let data = "";
+ for (const i in message) {
+ data += "&" + i + "=" + message[i];
+ }
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(data);
+ });
+ }
+
+ function form(address, formName) {
+ return new Promise(resolve => {
+ const formData = new FormData(document.forms.namedItem(formName));
+ formData.append("Custom field", "Extra data");
+
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", address, true);
+ xhr.setRequestHeader("custom-header-xxx", "custom-value-xxx");
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(formData);
+ });
+ }
+
+ async function performRequests() {
+ const url = "sjs_simple-test-server.sjs";
+ const url1 = url + "?foo=bar&baz=42&type=urlencoded";
+ const url2 = url + "?foo=bar&baz=42&type=multipart";
+
+ await post(url1, { foo: "bar", baz: 123 });
+ await form(url2, "form-name");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_post-json-test-page.html b/devtools/client/netmonitor/test/html_post-json-test-page.html
new file mode 100644
index 0000000000..8c18e91dbb
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_post-json-test-page.html
@@ -0,0 +1,48 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>POST raw test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests performLargePostDataRequest */
+ "use strict";
+
+ function post(address, message, callback) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", address, true);
+ xhr.setRequestHeader("Content-Type", "application/json");
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(message);
+ });
+ }
+
+ async function performRequests() {
+ await post("sjs_simple-test-server.sjs", JSON.stringify({a: 1}));
+ }
+
+ async function performLargePostDataRequest() {
+ const limit = 1048576;
+ const data = "x".repeat(2 * limit);
+ await post("sjs_simple-test-server.sjs", JSON.stringify(data));
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_post-raw-test-page.html b/devtools/client/netmonitor/test/html_post-raw-test-page.html
new file mode 100644
index 0000000000..190d384042
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_post-raw-test-page.html
@@ -0,0 +1,43 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>POST raw test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function post(address, message) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", address, true);
+ xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(message);
+ });
+ }
+
+ async function performRequests() {
+ const rawData = "foo=bar&baz=123";
+ await post("sjs_simple-test-server.sjs", rawData);
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_post-raw-with-headers-test-page.html b/devtools/client/netmonitor/test/html_post-raw-with-headers-test-page.html
new file mode 100644
index 0000000000..1ff853edea
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_post-raw-with-headers-test-page.html
@@ -0,0 +1,67 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>POST raw with headers test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function post(address, message) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(message);
+ });
+ }
+
+ async function performRequests() {
+ const rawData = [
+ // Only one header
+ [
+ "content-type: application/x-www-form-urlencoded\r",
+ "\r",
+ "\r",
+ "foo=bar&baz=123",
+ ],
+ // No form body content
+ [
+ "content-type: application/x-www-form-urlencoded\r",
+ "\r",
+ "\r",
+ ],
+ // Multiple headers
+ [
+ "content-type: application/x-www-form-urlencoded\r",
+ "custom-header: hello world!\r",
+ "\r",
+ "\r",
+ "foo=bar&baz=123",
+ ],
+ ];
+
+ for (const data of rawData) {
+ await post("sjs_simple-test-server.sjs", data.join("\n"));
+ }
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_send-beacon.html b/devtools/client/netmonitor/test/html_send-beacon.html
new file mode 100644
index 0000000000..12ab8737d2
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_send-beacon.html
@@ -0,0 +1,26 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Send beacon test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function performRequests() {
+ navigator.sendBeacon("beacon_request");
+ }
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_simple-test-page.html b/devtools/client/netmonitor/test/html_simple-test-page.html
new file mode 100644
index 0000000000..846681dbd9
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_simple-test-page.html
@@ -0,0 +1,18 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Simple test</p>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_single-get-page.html b/devtools/client/netmonitor/test/html_single-get-page.html
new file mode 100644
index 0000000000..79c4b13e81
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_single-get-page.html
@@ -0,0 +1,40 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Performing a custom number of GETs</p>
+
+ <script type="text/javascript">
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ (async function performRequests() {
+ await get("request_0");
+ })();
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_slow-requests-test-page.html b/devtools/client/netmonitor/test/html_slow-requests-test-page.html
new file mode 100644
index 0000000000..93941d2705
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_slow-requests-test-page.html
@@ -0,0 +1,15 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+
+ <!doctype HTML>
+ <html>
+ <head>
+ <meta charset="utf-8"/>
+ <title>Slow Network Requests Test Page</title>
+ </head>
+ <body>
+ <h1>Slow Network Requests Test Page</h1>
+ <script type="text/javascript"
+ src="http://example.com/browser/devtools/client/netmonitor/test/sjs_slow-script-server.sjs"></script>
+ </body>
+ </html>
diff --git a/devtools/client/netmonitor/test/html_sorting-test-page.html b/devtools/client/netmonitor/test/html_sorting-test-page.html
new file mode 100644
index 0000000000..640c58b8e8
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_sorting-test-page.html
@@ -0,0 +1,18 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Sorting test</p>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_sse-test-page.html b/devtools/client/netmonitor/test/html_sse-test-page.html
new file mode 100644
index 0000000000..bb726d4c1f
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_sse-test-page.html
@@ -0,0 +1,31 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype HTML>
+
+<html>
+<head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>SSE Inspection Test Page</title>
+</head>
+<body>
+ <h1>SSE Inspection Test Page</h1>
+ <script type="text/javascript">
+ /* exported openConnection */
+ "use strict";
+
+ let es;
+ function openConnection() {
+ return new Promise(resolve => {
+ es = new EventSource("sjs_sse-test-server.sjs");
+ es.onmessage = function (e) {
+ es.close();
+ resolve();
+ };
+ });
+ }
+ </script>
+</body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_statistics-edge-case-page.html b/devtools/client/netmonitor/test/html_statistics-edge-case-page.html
new file mode 100644
index 0000000000..2355639008
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_statistics-edge-case-page.html
@@ -0,0 +1,23 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <title>Test page with slow requests and image-cache requests</title>
+ </head>
+ <body>
+ <script type="text/javascript">
+ "use strict";
+ /* exported unblock */
+
+ // Open a request which will not resolve until unblock() is called.
+ fetch("sjs_long-polling-server.sjs").then(res => res.text()).then(console.log);
+
+ function unblock() {
+ fetch("sjs_long-polling-server.sjs?unblock");
+ }
+ </script>
+ <img src="test-image.png">
+ <img src="test-image.png">
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_statistics-test-page.html b/devtools/client/netmonitor/test/html_statistics-test-page.html
new file mode 100644
index 0000000000..a8afabe975
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_statistics-test-page.html
@@ -0,0 +1,42 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Statistics test</p>
+
+ <script type="text/javascript">
+ "use strict";
+
+ function get(address) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+ xhr.send(null);
+ }
+
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=txt");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=xml");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=html");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=css");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=js");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=json");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=jsonp");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=font");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=image");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=audio");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=video");
+ get("sjs_content-type-test-server.sjs?sts=304&fmt=flash");
+ get("test-image.png?v=" + Math.random());
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_status-codes-test-page.html b/devtools/client/netmonitor/test/html_status-codes-test-page.html
new file mode 100644
index 0000000000..99b4e2a22f
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_status-codes-test-page.html
@@ -0,0 +1,55 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Status codes test</p>
+
+ <script type="text/javascript">
+ /* exported performRequests, performCachedRequests, performOneCachedRequest */
+ "use strict";
+
+ function get(address) {
+ return new Promise(resolve => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", address, true);
+
+ xhr.onreadystatechange = function() {
+ if (this.readyState == this.DONE) {
+ resolve();
+ }
+ };
+ xhr.send(null);
+ });
+ }
+
+ async function performRequests() {
+ await get("sjs_status-codes-test-server.sjs?sts=100");
+ await get("sjs_status-codes-test-server.sjs?sts=200");
+ await get("sjs_status-codes-test-server.sjs?sts=300");
+ await get("sjs_status-codes-test-server.sjs?sts=400");
+ await get("sjs_status-codes-test-server.sjs?sts=500");
+ }
+
+ async function performCachedRequests() {
+ await get("sjs_status-codes-test-server.sjs?sts=ok&cached");
+ await get("sjs_status-codes-test-server.sjs?sts=redirect&cached");
+ }
+
+ async function performOneCachedRequest() {
+ await get("sjs_status-codes-test-server.sjs?sts=ok&cached");
+ await get("sjs_status-codes-test-server.sjs?sts=ok&cached");
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/html_tracking-protection.html b/devtools/client/netmonitor/test/html_tracking-protection.html
new file mode 100644
index 0000000000..7329ebdc3e
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_tracking-protection.html
@@ -0,0 +1,21 @@
+<!DOCTYPE HTML>
+<!-- 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/. -->
+<html dir="ltr" xml:lang="en-US" lang="en-US">
+ <head>
+ <meta charset="utf8">
+ </head>
+ <body>
+ <script type="text/javascript">
+ /* exported performRequests */
+ "use strict";
+
+ function performRequests() {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", "https://tracking.example.org/", true);
+ xhr.send(null);
+ }
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_websocket-test-page.html b/devtools/client/netmonitor/test/html_websocket-test-page.html
new file mode 100644
index 0000000000..1b4202c269
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_websocket-test-page.html
@@ -0,0 +1,10 @@
+<script>
+"use strict";
+openSocket();
+
+function openSocket() {
+ new WebSocket("ws://localhost:8080/");
+}
+
+new Worker("js_websocket-worker-test.js");
+</script>
diff --git a/devtools/client/netmonitor/test/html_worker-test-page.html b/devtools/client/netmonitor/test/html_worker-test-page.html
new file mode 100644
index 0000000000..46f64368a1
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_worker-test-page.html
@@ -0,0 +1,13 @@
+<script>
+/* eslint-disable no-unused-vars */
+"use strict";
+startWorker();
+
+var w;
+function startWorker() {
+ startWorkerInner();
+}
+function startWorkerInner() {
+ w = new Worker("js_worker-test.js");
+}
+</script>
diff --git a/devtools/client/netmonitor/test/html_ws-early-connection-page.html b/devtools/client/netmonitor/test/html_ws-early-connection-page.html
new file mode 100644
index 0000000000..9bc062f85f
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_ws-early-connection-page.html
@@ -0,0 +1,24 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype HTML>
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <title>WebSocket Inspection Test Page</title>
+ </head>
+ <body>
+ <h1>WebSocket Inspection Test Page</h1>
+ <script type="text/javascript">
+ "use strict";
+ const ws = new WebSocket(
+ "ws://mochi.test:8888/browser/devtools/client/netmonitor/test/file_ws_backend");
+
+ ws.onopen = () => {
+ ws.send("readyState:" + document.readyState);
+ ws.close();
+ }
+ </script>
+ <script type="text/javascript"
+ src="http://example.com/browser/devtools/client/netmonitor/test/sjs_slow-script-server.sjs"></script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/html_ws-sse-test-page.html b/devtools/client/netmonitor/test/html_ws-sse-test-page.html
new file mode 100644
index 0000000000..8936efa81e
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_ws-sse-test-page.html
@@ -0,0 +1,59 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+ <!doctype HTML>
+ <html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>WebSocket/SSE Inspection Test Page</title>
+ </head>
+ <body>
+ <h1>WebSocket/SSE Inspection Test Page</h1>
+ <script type="text/javascript">
+ /* exported openWsConnection, openSseConnection, closeWsConnection, sendData */
+ "use strict";
+
+ let ws;
+ function openWsConnection(numFramesToSend) {
+ return new Promise(resolve => {
+ ws = new WebSocket(
+ "ws://mochi.test:8888/browser/devtools/client/netmonitor/test/file_ws_backend"
+ );
+
+ ws.onopen = e => {
+ for (let i = 0; i < numFramesToSend; i++) {
+ ws.send("Payload " + i);
+ }
+ resolve();
+ };
+ });
+ }
+
+ function closeWsConnection() {
+ return new Promise(resolve => {
+ ws.onclose = e => {
+ resolve();
+ };
+ ws.close();
+ });
+ }
+
+ function sendData(payload) {
+ ws.send(payload);
+ }
+
+ let es;
+ function openSseConnection() {
+ return new Promise(resolve => {
+ es = new EventSource("sjs_sse-test-server.sjs");
+ es.onmessage = function(e) {
+ es.close();
+ resolve();
+ };
+ });
+ }
+ </script>
+ </body>
+ </html>
diff --git a/devtools/client/netmonitor/test/html_ws-test-page.html b/devtools/client/netmonitor/test/html_ws-test-page.html
new file mode 100644
index 0000000000..4bfe1a040c
--- /dev/null
+++ b/devtools/client/netmonitor/test/html_ws-test-page.html
@@ -0,0 +1,56 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+<!doctype HTML>
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>WebSocket Inspection Test Page</title>
+ </head>
+ <body>
+ <h1>WebSocket Inspection Test Page</h1>
+ <script type="text/javascript">
+ /* exported openConnection, closeConnection, sendData, sendFrames */
+ "use strict";
+
+ let ws;
+ function openConnection(numFramesToSend) {
+ return new Promise(resolve => {
+ ws = new WebSocket(
+ "ws://mochi.test:8888/browser/devtools/client/netmonitor/test/file_ws_backend");
+
+ ws.onopen = e => {
+ for (let i = 0; i < numFramesToSend; i++) {
+ ws.send("Payload " + i);
+ }
+ resolve();
+ };
+ });
+ }
+
+ function sendFrames(numFramesToSend) {
+ return new Promise(resolve => {
+ for (let i = 0; i < numFramesToSend; i++) {
+ ws.send("Payload " + i);
+ }
+ resolve();
+ })
+ }
+
+ function closeConnection() {
+ return new Promise(resolve => {
+ ws.onclose = e => {
+ resolve();
+ }
+ ws.close();
+ })
+ }
+
+ function sendData(payload) {
+ ws.send(payload);
+ }
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/netmonitor/test/js_websocket-worker-test.js b/devtools/client/netmonitor/test/js_websocket-worker-test.js
new file mode 100644
index 0000000000..9920f09cb8
--- /dev/null
+++ b/devtools/client/netmonitor/test/js_websocket-worker-test.js
@@ -0,0 +1,6 @@
+"use strict";
+openWorkerSocket();
+
+function openWorkerSocket() {
+ new WebSocket("wss://localhost:8081");
+}
diff --git a/devtools/client/netmonitor/test/js_worker-test.js b/devtools/client/netmonitor/test/js_worker-test.js
new file mode 100644
index 0000000000..7b9538b0b9
--- /dev/null
+++ b/devtools/client/netmonitor/test/js_worker-test.js
@@ -0,0 +1,30 @@
+/* eslint-disable no-unused-vars, no-undef */
+"use strict";
+startWorkerFromWorker();
+
+var w;
+function startWorkerFromWorker() {
+ w = new Worker("js_worker-test2.js");
+}
+
+importScriptsFromWorker();
+
+function importScriptsFromWorker() {
+ try {
+ importScripts("missing1.js", "missing2.js");
+ } catch (e) {}
+}
+
+createJSONRequest();
+
+function createJSONRequest() {
+ const request = new XMLHttpRequest();
+ request.open("GET", "missing.json", true);
+ request.send(null);
+}
+
+fetchThing();
+
+function fetchThing() {
+ fetch("missing.txt");
+}
diff --git a/devtools/client/netmonitor/test/js_worker-test2.js b/devtools/client/netmonitor/test/js_worker-test2.js
new file mode 100644
index 0000000000..9ee307f2ec
--- /dev/null
+++ b/devtools/client/netmonitor/test/js_worker-test2.js
@@ -0,0 +1,3 @@
+"use strict";
+
+console.log("I AM A WORKER");
diff --git a/devtools/client/netmonitor/test/node/jest.config.js b/devtools/client/netmonitor/test/node/jest.config.js
new file mode 100644
index 0000000000..7491db85b9
--- /dev/null
+++ b/devtools/client/netmonitor/test/node/jest.config.js
@@ -0,0 +1,12 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* global __dirname */
+
+const sharedJestConfig = require(`${__dirname}/../../../shared/test-helpers/shared-jest.config`);
+
+module.exports = {
+ ...sharedJestConfig,
+};
diff --git a/devtools/client/netmonitor/test/node/package.json b/devtools/client/netmonitor/test/node/package.json
new file mode 100644
index 0000000000..ff1a6a0e7e
--- /dev/null
+++ b/devtools/client/netmonitor/test/node/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "netmonitor-tests",
+ "license": "MPL-2.0",
+ "version": "0.0.1",
+ "engines": {
+ "node": ">=8.9.4"
+ },
+ "scripts": {
+ "test": "jest",
+ "test-ci": "jest --json"
+ },
+ "dependencies": {
+ "jest": "^24.6.0"
+ }
+}
diff --git a/devtools/client/netmonitor/test/node/reducers/sort.spec.js b/devtools/client/netmonitor/test/node/reducers/sort.spec.js
new file mode 100644
index 0000000000..4afd7c0fe3
--- /dev/null
+++ b/devtools/client/netmonitor/test/node/reducers/sort.spec.js
@@ -0,0 +1,28 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const {
+ Sort,
+ sortReducer,
+} = require("resource://devtools/client/netmonitor/src/reducers/sort.js");
+const {
+ SORT_BY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+describe("sorting reducer", () => {
+ it("it should sort by sort type", () => {
+ const initialState = new Sort();
+ const action = {
+ type: SORT_BY,
+ sortType: "TimeWhen",
+ };
+ const expectedState = {
+ type: "TimeWhen",
+ ascending: true,
+ };
+
+ expect(expectedState).toEqual(sortReducer(initialState, action));
+ });
+});
diff --git a/devtools/client/netmonitor/test/node/yarn.lock b/devtools/client/netmonitor/test/node/yarn.lock
new file mode 100644
index 0000000000..8d3b6674c0
--- /dev/null
+++ b/devtools/client/netmonitor/test/node/yarn.lock
@@ -0,0 +1,3553 @@
+# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
+# yarn lockfile v1
+
+
+"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.5.5":
+ version "7.5.5"
+ resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.5.5.tgz#bc0782f6d69f7b7d49531219699b988f669a8f9d"
+ integrity sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw==
+ dependencies:
+ "@babel/highlight" "^7.0.0"
+
+"@babel/core@^7.1.0":
+ version "7.5.5"
+ resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.5.5.tgz#17b2686ef0d6bc58f963dddd68ab669755582c30"
+ integrity sha512-i4qoSr2KTtce0DmkuuQBV4AuQgGPUcPXMr9L5MyYAtk06z068lQ10a4O009fe5OB/DfNV+h+qqT7ddNV8UnRjg==
+ dependencies:
+ "@babel/code-frame" "^7.5.5"
+ "@babel/generator" "^7.5.5"
+ "@babel/helpers" "^7.5.5"
+ "@babel/parser" "^7.5.5"
+ "@babel/template" "^7.4.4"
+ "@babel/traverse" "^7.5.5"
+ "@babel/types" "^7.5.5"
+ convert-source-map "^1.1.0"
+ debug "^4.1.0"
+ json5 "^2.1.0"
+ lodash "^4.17.13"
+ resolve "^1.3.2"
+ semver "^5.4.1"
+ source-map "^0.5.0"
+
+"@babel/generator@^7.4.0", "@babel/generator@^7.5.5":
+ version "7.5.5"
+ resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.5.5.tgz#873a7f936a3c89491b43536d12245b626664e3cf"
+ integrity sha512-ETI/4vyTSxTzGnU2c49XHv2zhExkv9JHLTwDAFz85kmcwuShvYG2H08FwgIguQf4JC75CBnXAUM5PqeF4fj0nQ==
+ dependencies:
+ "@babel/types" "^7.5.5"
+ jsesc "^2.5.1"
+ lodash "^4.17.13"
+ source-map "^0.5.0"
+ trim-right "^1.0.1"
+
+"@babel/helper-function-name@^7.1.0":
+ version "7.1.0"
+ resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz#a0ceb01685f73355d4360c1247f582bfafc8ff53"
+ integrity sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==
+ dependencies:
+ "@babel/helper-get-function-arity" "^7.0.0"
+ "@babel/template" "^7.1.0"
+ "@babel/types" "^7.0.0"
+
+"@babel/helper-get-function-arity@^7.0.0":
+ version "7.0.0"
+ resolved "https://registry.yarnpkg.com/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz#83572d4320e2a4657263734113c42868b64e49c3"
+ integrity sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==
+ dependencies:
+ "@babel/types" "^7.0.0"
+
+"@babel/helper-plugin-utils@^7.0.0":
+ version "7.0.0"
+ resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz#bbb3fbee98661c569034237cc03967ba99b4f250"
+ integrity sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==
+
+"@babel/helper-split-export-declaration@^7.4.4":
+ version "7.4.4"
+ resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.4.tgz#ff94894a340be78f53f06af038b205c49d993677"
+ integrity sha512-Ro/XkzLf3JFITkW6b+hNxzZ1n5OQ80NvIUdmHspih1XAhtN3vPTuUFT4eQnela+2MaZ5ulH+iyP513KJrxbN7Q==
+ dependencies:
+ "@babel/types" "^7.4.4"
+
+"@babel/helpers@^7.5.5":
+ version "7.5.5"
+ resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.5.5.tgz#63908d2a73942229d1e6685bc2a0e730dde3b75e"
+ integrity sha512-nRq2BUhxZFnfEn/ciJuhklHvFOqjJUD5wpx+1bxUF2axL9C+v4DE/dmp5sT2dKnpOs4orZWzpAZqlCy8QqE/7g==
+ dependencies:
+ "@babel/template" "^7.4.4"
+ "@babel/traverse" "^7.5.5"
+ "@babel/types" "^7.5.5"
+
+"@babel/highlight@^7.0.0":
+ version "7.5.0"
+ resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.5.0.tgz#56d11312bd9248fa619591d02472be6e8cb32540"
+ integrity sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ==
+ dependencies:
+ chalk "^2.0.0"
+ esutils "^2.0.2"
+ js-tokens "^4.0.0"
+
+"@babel/parser@^7.1.0", "@babel/parser@^7.4.3", "@babel/parser@^7.4.4", "@babel/parser@^7.5.5":
+ version "7.5.5"
+ resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.5.5.tgz#02f077ac8817d3df4a832ef59de67565e71cca4b"
+ integrity sha512-E5BN68cqR7dhKan1SfqgPGhQ178bkVKpXTPEXnFJBrEt8/DKRZlybmy+IgYLTeN7tp1R5Ccmbm2rBk17sHYU3g==
+
+"@babel/plugin-syntax-object-rest-spread@^7.0.0":
+ version "7.2.0"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz#3b7a3e733510c57e820b9142a6579ac8b0dfad2e"
+ integrity sha512-t0JKGgqk2We+9may3t0xDdmneaXmyxq0xieYcKHxIsrJO64n1OiMWNUtc5gQK1PA0NpdCRrtZp4z+IUaKugrSA==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.0.0"
+
+"@babel/template@^7.1.0", "@babel/template@^7.4.0", "@babel/template@^7.4.4":
+ version "7.4.4"
+ resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.4.4.tgz#f4b88d1225689a08f5bc3a17483545be9e4ed237"
+ integrity sha512-CiGzLN9KgAvgZsnivND7rkA+AeJ9JB0ciPOD4U59GKbQP2iQl+olF1l76kJOupqidozfZ32ghwBEJDhnk9MEcw==
+ dependencies:
+ "@babel/code-frame" "^7.0.0"
+ "@babel/parser" "^7.4.4"
+ "@babel/types" "^7.4.4"
+
+"@babel/traverse@^7.1.0", "@babel/traverse@^7.4.3", "@babel/traverse@^7.5.5":
+ version "7.5.5"
+ resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.5.5.tgz#f664f8f368ed32988cd648da9f72d5ca70f165bb"
+ integrity sha512-MqB0782whsfffYfSjH4TM+LMjrJnhCNEDMDIjeTpl+ASaUvxcjoiVCo/sM1GhS1pHOXYfWVCYneLjMckuUxDaQ==
+ dependencies:
+ "@babel/code-frame" "^7.5.5"
+ "@babel/generator" "^7.5.5"
+ "@babel/helper-function-name" "^7.1.0"
+ "@babel/helper-split-export-declaration" "^7.4.4"
+ "@babel/parser" "^7.5.5"
+ "@babel/types" "^7.5.5"
+ debug "^4.1.0"
+ globals "^11.1.0"
+ lodash "^4.17.13"
+
+"@babel/types@^7.0.0", "@babel/types@^7.3.0", "@babel/types@^7.4.0", "@babel/types@^7.4.4", "@babel/types@^7.5.5":
+ version "7.5.5"
+ resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.5.5.tgz#97b9f728e182785909aa4ab56264f090a028d18a"
+ integrity sha512-s63F9nJioLqOlW3UkyMd+BYhXt44YuaFm/VV0VwuteqjYwRrObkU7ra9pY4wAJR3oXi8hJrMcrcJdO/HH33vtw==
+ dependencies:
+ esutils "^2.0.2"
+ lodash "^4.17.13"
+ to-fast-properties "^2.0.0"
+
+"@cnakazawa/watch@^1.0.3":
+ version "1.0.3"
+ resolved "https://registry.yarnpkg.com/@cnakazawa/watch/-/watch-1.0.3.tgz#099139eaec7ebf07a27c1786a3ff64f39464d2ef"
+ integrity sha512-r5160ogAvGyHsal38Kux7YYtodEKOj89RGb28ht1jh3SJb08VwRwAKKJL0bGb04Zd/3r9FL3BFIc3bBidYffCA==
+ dependencies:
+ exec-sh "^0.3.2"
+ minimist "^1.2.0"
+
+"@jest/console@^24.7.1":
+ version "24.7.1"
+ resolved "https://registry.yarnpkg.com/@jest/console/-/console-24.7.1.tgz#32a9e42535a97aedfe037e725bd67e954b459545"
+ integrity sha512-iNhtIy2M8bXlAOULWVTUxmnelTLFneTNEkHCgPmgd+zNwy9zVddJ6oS5rZ9iwoscNdT5mMwUd0C51v/fSlzItg==
+ dependencies:
+ "@jest/source-map" "^24.3.0"
+ chalk "^2.0.1"
+ slash "^2.0.0"
+
+"@jest/core@^24.8.0":
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/@jest/core/-/core-24.8.0.tgz#fbbdcd42a41d0d39cddbc9f520c8bab0c33eed5b"
+ integrity sha512-R9rhAJwCBQzaRnrRgAdVfnglUuATXdwTRsYqs6NMdVcAl5euG8LtWDe+fVkN27YfKVBW61IojVsXKaOmSnqd/A==
+ dependencies:
+ "@jest/console" "^24.7.1"
+ "@jest/reporters" "^24.8.0"
+ "@jest/test-result" "^24.8.0"
+ "@jest/transform" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ ansi-escapes "^3.0.0"
+ chalk "^2.0.1"
+ exit "^0.1.2"
+ graceful-fs "^4.1.15"
+ jest-changed-files "^24.8.0"
+ jest-config "^24.8.0"
+ jest-haste-map "^24.8.0"
+ jest-message-util "^24.8.0"
+ jest-regex-util "^24.3.0"
+ jest-resolve-dependencies "^24.8.0"
+ jest-runner "^24.8.0"
+ jest-runtime "^24.8.0"
+ jest-snapshot "^24.8.0"
+ jest-util "^24.8.0"
+ jest-validate "^24.8.0"
+ jest-watcher "^24.8.0"
+ micromatch "^3.1.10"
+ p-each-series "^1.0.0"
+ pirates "^4.0.1"
+ realpath-native "^1.1.0"
+ rimraf "^2.5.4"
+ strip-ansi "^5.0.0"
+
+"@jest/environment@^24.8.0":
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/@jest/environment/-/environment-24.8.0.tgz#0342261383c776bdd652168f68065ef144af0eac"
+ integrity sha512-vlGt2HLg7qM+vtBrSkjDxk9K0YtRBi7HfRFaDxoRtyi+DyVChzhF20duvpdAnKVBV6W5tym8jm0U9EfXbDk1tw==
+ dependencies:
+ "@jest/fake-timers" "^24.8.0"
+ "@jest/transform" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ jest-mock "^24.8.0"
+
+"@jest/fake-timers@^24.8.0":
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/@jest/fake-timers/-/fake-timers-24.8.0.tgz#2e5b80a4f78f284bcb4bd5714b8e10dd36a8d3d1"
+ integrity sha512-2M4d5MufVXwi6VzZhJ9f5S/wU4ud2ck0kxPof1Iz3zWx6Y+V2eJrES9jEktB6O3o/oEyk+il/uNu9PvASjWXQw==
+ dependencies:
+ "@jest/types" "^24.8.0"
+ jest-message-util "^24.8.0"
+ jest-mock "^24.8.0"
+
+"@jest/reporters@^24.8.0":
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/@jest/reporters/-/reporters-24.8.0.tgz#075169cd029bddec54b8f2c0fc489fd0b9e05729"
+ integrity sha512-eZ9TyUYpyIIXfYCrw0UHUWUvE35vx5I92HGMgS93Pv7du+GHIzl+/vh8Qj9MCWFK/4TqyttVBPakWMOfZRIfxw==
+ dependencies:
+ "@jest/environment" "^24.8.0"
+ "@jest/test-result" "^24.8.0"
+ "@jest/transform" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ chalk "^2.0.1"
+ exit "^0.1.2"
+ glob "^7.1.2"
+ istanbul-lib-coverage "^2.0.2"
+ istanbul-lib-instrument "^3.0.1"
+ istanbul-lib-report "^2.0.4"
+ istanbul-lib-source-maps "^3.0.1"
+ istanbul-reports "^2.1.1"
+ jest-haste-map "^24.8.0"
+ jest-resolve "^24.8.0"
+ jest-runtime "^24.8.0"
+ jest-util "^24.8.0"
+ jest-worker "^24.6.0"
+ node-notifier "^5.2.1"
+ slash "^2.0.0"
+ source-map "^0.6.0"
+ string-length "^2.0.0"
+
+"@jest/source-map@^24.3.0":
+ version "24.3.0"
+ resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-24.3.0.tgz#563be3aa4d224caf65ff77edc95cd1ca4da67f28"
+ integrity sha512-zALZt1t2ou8le/crCeeiRYzvdnTzaIlpOWaet45lNSqNJUnXbppUUFR4ZUAlzgDmKee4Q5P/tKXypI1RiHwgag==
+ dependencies:
+ callsites "^3.0.0"
+ graceful-fs "^4.1.15"
+ source-map "^0.6.0"
+
+"@jest/test-result@^24.8.0":
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/@jest/test-result/-/test-result-24.8.0.tgz#7675d0aaf9d2484caa65e048d9b467d160f8e9d3"
+ integrity sha512-+YdLlxwizlfqkFDh7Mc7ONPQAhA4YylU1s529vVM1rsf67vGZH/2GGm5uO8QzPeVyaVMobCQ7FTxl38QrKRlng==
+ dependencies:
+ "@jest/console" "^24.7.1"
+ "@jest/types" "^24.8.0"
+ "@types/istanbul-lib-coverage" "^2.0.0"
+
+"@jest/test-sequencer@^24.8.0":
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/@jest/test-sequencer/-/test-sequencer-24.8.0.tgz#2f993bcf6ef5eb4e65e8233a95a3320248cf994b"
+ integrity sha512-OzL/2yHyPdCHXEzhoBuq37CE99nkme15eHkAzXRVqthreWZamEMA0WoetwstsQBCXABhczpK03JNbc4L01vvLg==
+ dependencies:
+ "@jest/test-result" "^24.8.0"
+ jest-haste-map "^24.8.0"
+ jest-runner "^24.8.0"
+ jest-runtime "^24.8.0"
+
+"@jest/transform@^24.8.0":
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/@jest/transform/-/transform-24.8.0.tgz#628fb99dce4f9d254c6fd9341e3eea262e06fef5"
+ integrity sha512-xBMfFUP7TortCs0O+Xtez2W7Zu1PLH9bvJgtraN1CDST6LBM/eTOZ9SfwS/lvV8yOfcDpFmwf9bq5cYbXvqsvA==
+ dependencies:
+ "@babel/core" "^7.1.0"
+ "@jest/types" "^24.8.0"
+ babel-plugin-istanbul "^5.1.0"
+ chalk "^2.0.1"
+ convert-source-map "^1.4.0"
+ fast-json-stable-stringify "^2.0.0"
+ graceful-fs "^4.1.15"
+ jest-haste-map "^24.8.0"
+ jest-regex-util "^24.3.0"
+ jest-util "^24.8.0"
+ micromatch "^3.1.10"
+ realpath-native "^1.1.0"
+ slash "^2.0.0"
+ source-map "^0.6.1"
+ write-file-atomic "2.4.1"
+
+"@jest/types@^24.8.0":
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/@jest/types/-/types-24.8.0.tgz#f31e25948c58f0abd8c845ae26fcea1491dea7ad"
+ integrity sha512-g17UxVr2YfBtaMUxn9u/4+siG1ptg9IGYAYwvpwn61nBg779RXnjE/m7CxYcIzEt0AbHZZAHSEZNhkE2WxURVg==
+ dependencies:
+ "@types/istanbul-lib-coverage" "^2.0.0"
+ "@types/istanbul-reports" "^1.1.1"
+ "@types/yargs" "^12.0.9"
+
+"@types/babel__core@^7.1.0":
+ version "7.1.2"
+ resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.2.tgz#608c74f55928033fce18b99b213c16be4b3d114f"
+ integrity sha512-cfCCrFmiGY/yq0NuKNxIQvZFy9kY/1immpSpTngOnyIbD4+eJOG5mxphhHDv3CHL9GltO4GcKr54kGBg3RNdbg==
+ dependencies:
+ "@babel/parser" "^7.1.0"
+ "@babel/types" "^7.0.0"
+ "@types/babel__generator" "*"
+ "@types/babel__template" "*"
+ "@types/babel__traverse" "*"
+
+"@types/babel__generator@*":
+ version "7.0.2"
+ resolved "https://registry.yarnpkg.com/@types/babel__generator/-/babel__generator-7.0.2.tgz#d2112a6b21fad600d7674274293c85dce0cb47fc"
+ integrity sha512-NHcOfab3Zw4q5sEE2COkpfXjoE7o+PmqD9DQW4koUT3roNxwziUdXGnRndMat/LJNUtePwn1TlP4do3uoe3KZQ==
+ dependencies:
+ "@babel/types" "^7.0.0"
+
+"@types/babel__template@*":
+ version "7.0.2"
+ resolved "https://registry.yarnpkg.com/@types/babel__template/-/babel__template-7.0.2.tgz#4ff63d6b52eddac1de7b975a5223ed32ecea9307"
+ integrity sha512-/K6zCpeW7Imzgab2bLkLEbz0+1JlFSrUMdw7KoIIu+IUdu51GWaBZpd3y1VXGVXzynvGa4DaIaxNZHiON3GXUg==
+ dependencies:
+ "@babel/parser" "^7.1.0"
+ "@babel/types" "^7.0.0"
+
+"@types/babel__traverse@*", "@types/babel__traverse@^7.0.6":
+ version "7.0.7"
+ resolved "https://registry.yarnpkg.com/@types/babel__traverse/-/babel__traverse-7.0.7.tgz#2496e9ff56196cc1429c72034e07eab6121b6f3f"
+ integrity sha512-CeBpmX1J8kWLcDEnI3Cl2Eo6RfbGvzUctA+CjZUhOKDFbLfcr7fc4usEqLNWetrlJd7RhAkyYe2czXop4fICpw==
+ dependencies:
+ "@babel/types" "^7.3.0"
+
+"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0":
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.1.tgz#42995b446db9a48a11a07ec083499a860e9138ff"
+ integrity sha512-hRJD2ahnnpLgsj6KWMYSrmXkM3rm2Dl1qkx6IOFD5FnuNPXJIG5L0dhgKXCYTRMGzU4n0wImQ/xfmRc4POUFlg==
+
+"@types/istanbul-lib-report@*":
+ version "1.1.1"
+ resolved "https://registry.yarnpkg.com/@types/istanbul-lib-report/-/istanbul-lib-report-1.1.1.tgz#e5471e7fa33c61358dd38426189c037a58433b8c"
+ integrity sha512-3BUTyMzbZa2DtDI2BkERNC6jJw2Mr2Y0oGI7mRxYNBPxppbtEK1F66u3bKwU2g+wxwWI7PAoRpJnOY1grJqzHg==
+ dependencies:
+ "@types/istanbul-lib-coverage" "*"
+
+"@types/istanbul-reports@^1.1.1":
+ version "1.1.1"
+ resolved "https://registry.yarnpkg.com/@types/istanbul-reports/-/istanbul-reports-1.1.1.tgz#7a8cbf6a406f36c8add871625b278eaf0b0d255a"
+ integrity sha512-UpYjBi8xefVChsCoBpKShdxTllC9pwISirfoZsUa2AAdQg/Jd2KQGtSbw+ya7GPo7x/wAPlH6JBhKhAsXUEZNA==
+ dependencies:
+ "@types/istanbul-lib-coverage" "*"
+ "@types/istanbul-lib-report" "*"
+
+"@types/stack-utils@^1.0.1":
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-1.0.1.tgz#0a851d3bd96498fa25c33ab7278ed3bd65f06c3e"
+ integrity sha512-l42BggppR6zLmpfU6fq9HEa2oGPEI8yrSPL3GITjfRInppYFahObbIQOQK3UGxEnyQpltZLaPe75046NOZQikw==
+
+"@types/yargs@^12.0.2", "@types/yargs@^12.0.9":
+ version "12.0.12"
+ resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-12.0.12.tgz#45dd1d0638e8c8f153e87d296907659296873916"
+ integrity sha512-SOhuU4wNBxhhTHxYaiG5NY4HBhDIDnJF60GU+2LqHAdKKer86//e4yg69aENCtQ04n0ovz+tq2YPME5t5yp4pw==
+
+abab@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/abab/-/abab-2.0.0.tgz#aba0ab4c5eee2d4c79d3487d85450fb2376ebb0f"
+ integrity sha512-sY5AXXVZv4Y1VACTtR11UJCPHHudgY5i26Qj5TypE6DKlIApbwb5uqhXcJ5UUGbvZNRh7EeIoW+LrJumBsKp7w==
+
+abbrev@1:
+ version "1.1.1"
+ resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8"
+ integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==
+
+acorn-globals@^4.1.0:
+ version "4.3.2"
+ resolved "https://registry.yarnpkg.com/acorn-globals/-/acorn-globals-4.3.2.tgz#4e2c2313a597fd589720395f6354b41cd5ec8006"
+ integrity sha512-BbzvZhVtZP+Bs1J1HcwrQe8ycfO0wStkSGxuul3He3GkHOIZ6eTqOkPuw9IP1X3+IkOo4wiJmwkobzXYz4wewQ==
+ dependencies:
+ acorn "^6.0.1"
+ acorn-walk "^6.0.1"
+
+acorn-walk@^6.0.1:
+ version "6.2.0"
+ resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-6.2.0.tgz#123cb8f3b84c2171f1f7fb252615b1c78a6b1a8c"
+ integrity sha512-7evsyfH1cLOCdAzZAd43Cic04yKydNx0cF+7tiA19p1XnLLPU4dpCQOqpjqwokFe//vS0QqfqqjCS2JkiIs0cA==
+
+acorn@^5.5.3:
+ version "5.7.3"
+ resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.7.3.tgz#67aa231bf8812974b85235a96771eb6bd07ea279"
+ integrity sha512-T/zvzYRfbVojPWahDsE5evJdHb3oJoQfFbsrKM7w5Zcs++Tr257tia3BmMP8XYVjp1S9RZXQMh7gao96BlqZOw==
+
+acorn@^6.0.1:
+ version "6.2.0"
+ resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.2.0.tgz#67f0da2fc339d6cfb5d6fb244fd449f33cd8bbe3"
+ integrity sha512-8oe72N3WPMjA+2zVG71Ia0nXZ8DpQH+QyyHO+p06jT8eg8FGG3FbcUIi8KziHlAfheJQZeoqbvq1mQSQHXKYLw==
+
+ajv@^6.5.5:
+ version "6.10.2"
+ resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.10.2.tgz#d3cea04d6b017b2894ad69040fec8b623eb4bd52"
+ integrity sha512-TXtUUEYHuaTEbLZWIKUr5pmBuhDLy+8KYtPYdcV8qC+pOZL+NKqYwvWSRrVXHn+ZmRRAu8vJTAznH7Oag6RVRw==
+ dependencies:
+ fast-deep-equal "^2.0.1"
+ fast-json-stable-stringify "^2.0.0"
+ json-schema-traverse "^0.4.1"
+ uri-js "^4.2.2"
+
+ansi-escapes@^3.0.0:
+ version "3.2.0"
+ resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-3.2.0.tgz#8780b98ff9dbf5638152d1f1fe5c1d7b4442976b"
+ integrity sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==
+
+ansi-regex@^2.0.0:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df"
+ integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8=
+
+ansi-regex@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998"
+ integrity sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=
+
+ansi-regex@^4.0.0, ansi-regex@^4.1.0:
+ version "4.1.0"
+ resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.0.tgz#8b9f8f08cf1acb843756a839ca8c7e3168c51997"
+ integrity sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==
+
+ansi-styles@^3.2.0, ansi-styles@^3.2.1:
+ version "3.2.1"
+ resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d"
+ integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==
+ dependencies:
+ color-convert "^1.9.0"
+
+anymatch@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-2.0.0.tgz#bcb24b4f37934d9aa7ac17b4adaf89e7c76ef2eb"
+ integrity sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==
+ dependencies:
+ micromatch "^3.1.4"
+ normalize-path "^2.1.1"
+
+aproba@^1.0.3:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/aproba/-/aproba-1.2.0.tgz#6802e6264efd18c790a1b0d517f0f2627bf2c94a"
+ integrity sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==
+
+are-we-there-yet@~1.1.2:
+ version "1.1.5"
+ resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz#4b35c2944f062a8bfcda66410760350fe9ddfc21"
+ integrity sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w==
+ dependencies:
+ delegates "^1.0.0"
+ readable-stream "^2.0.6"
+
+arr-diff@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520"
+ integrity sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=
+
+arr-flatten@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1"
+ integrity sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==
+
+arr-union@^3.1.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4"
+ integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=
+
+array-equal@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/array-equal/-/array-equal-1.0.0.tgz#8c2a5ef2472fd9ea742b04c77a75093ba2757c93"
+ integrity sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=
+
+array-unique@^0.3.2:
+ version "0.3.2"
+ resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428"
+ integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=
+
+asn1@~0.2.3:
+ version "0.2.4"
+ resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.4.tgz#8d2475dfab553bb33e77b54e59e880bb8ce23136"
+ integrity sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==
+ dependencies:
+ safer-buffer "~2.1.0"
+
+assert-plus@1.0.0, assert-plus@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525"
+ integrity sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=
+
+assign-symbols@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367"
+ integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=
+
+astral-regex@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-1.0.0.tgz#6c8c3fb827dd43ee3918f27b82782ab7658a6fd9"
+ integrity sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==
+
+async-limiter@~1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/async-limiter/-/async-limiter-1.0.0.tgz#78faed8c3d074ab81f22b4e985d79e8738f720f8"
+ integrity sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==
+
+asynckit@^0.4.0:
+ version "0.4.0"
+ resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
+ integrity sha1-x57Zf380y48robyXkLzDZkdLS3k=
+
+atob@^2.1.1:
+ version "2.1.2"
+ resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9"
+ integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==
+
+aws-sign2@~0.7.0:
+ version "0.7.0"
+ resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8"
+ integrity sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=
+
+aws4@^1.8.0:
+ version "1.8.0"
+ resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.8.0.tgz#f0e003d9ca9e7f59c7a508945d7b2ef9a04a542f"
+ integrity sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==
+
+babel-jest@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-24.8.0.tgz#5c15ff2b28e20b0f45df43fe6b7f2aae93dba589"
+ integrity sha512-+5/kaZt4I9efoXzPlZASyK/lN9qdRKmmUav9smVc0ruPQD7IsfucQ87gpOE8mn2jbDuS6M/YOW6n3v9ZoIfgnw==
+ dependencies:
+ "@jest/transform" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ "@types/babel__core" "^7.1.0"
+ babel-plugin-istanbul "^5.1.0"
+ babel-preset-jest "^24.6.0"
+ chalk "^2.4.2"
+ slash "^2.0.0"
+
+babel-plugin-istanbul@^5.1.0:
+ version "5.1.4"
+ resolved "https://registry.yarnpkg.com/babel-plugin-istanbul/-/babel-plugin-istanbul-5.1.4.tgz#841d16b9a58eeb407a0ddce622ba02fe87a752ba"
+ integrity sha512-dySz4VJMH+dpndj0wjJ8JPs/7i1TdSPb1nRrn56/92pKOF9VKC1FMFJmMXjzlGGusnCAqujP6PBCiKq0sVA+YQ==
+ dependencies:
+ find-up "^3.0.0"
+ istanbul-lib-instrument "^3.3.0"
+ test-exclude "^5.2.3"
+
+babel-plugin-jest-hoist@^24.6.0:
+ version "24.6.0"
+ resolved "https://registry.yarnpkg.com/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-24.6.0.tgz#f7f7f7ad150ee96d7a5e8e2c5da8319579e78019"
+ integrity sha512-3pKNH6hMt9SbOv0F3WVmy5CWQ4uogS3k0GY5XLyQHJ9EGpAT9XWkFd2ZiXXtkwFHdAHa5j7w7kfxSP5lAIwu7w==
+ dependencies:
+ "@types/babel__traverse" "^7.0.6"
+
+babel-preset-jest@^24.6.0:
+ version "24.6.0"
+ resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-24.6.0.tgz#66f06136eefce87797539c0d63f1769cc3915984"
+ integrity sha512-pdZqLEdmy1ZK5kyRUfvBb2IfTPb2BUvIJczlPspS8fWmBQslNNDBqVfh7BW5leOVJMDZKzjD8XEyABTk6gQ5yw==
+ dependencies:
+ "@babel/plugin-syntax-object-rest-spread" "^7.0.0"
+ babel-plugin-jest-hoist "^24.6.0"
+
+balanced-match@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"
+ integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c=
+
+base@^0.11.1:
+ version "0.11.2"
+ resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f"
+ integrity sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==
+ dependencies:
+ cache-base "^1.0.1"
+ class-utils "^0.3.5"
+ component-emitter "^1.2.1"
+ define-property "^1.0.0"
+ isobject "^3.0.1"
+ mixin-deep "^1.2.0"
+ pascalcase "^0.1.1"
+
+bcrypt-pbkdf@^1.0.0:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz#a4301d389b6a43f9b67ff3ca11a3f6637e360e9e"
+ integrity sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=
+ dependencies:
+ tweetnacl "^0.14.3"
+
+brace-expansion@^1.1.7:
+ version "1.1.11"
+ resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"
+ integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==
+ dependencies:
+ balanced-match "^1.0.0"
+ concat-map "0.0.1"
+
+braces@^2.3.1:
+ version "2.3.2"
+ resolved "https://registry.yarnpkg.com/braces/-/braces-2.3.2.tgz#5979fd3f14cd531565e5fa2df1abfff1dfaee729"
+ integrity sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==
+ dependencies:
+ arr-flatten "^1.1.0"
+ array-unique "^0.3.2"
+ extend-shallow "^2.0.1"
+ fill-range "^4.0.0"
+ isobject "^3.0.1"
+ repeat-element "^1.1.2"
+ snapdragon "^0.8.1"
+ snapdragon-node "^2.0.1"
+ split-string "^3.0.2"
+ to-regex "^3.0.1"
+
+browser-process-hrtime@^0.1.2:
+ version "0.1.3"
+ resolved "https://registry.yarnpkg.com/browser-process-hrtime/-/browser-process-hrtime-0.1.3.tgz#616f00faef1df7ec1b5bf9cfe2bdc3170f26c7b4"
+ integrity sha512-bRFnI4NnjO6cnyLmOV/7PVoDEMJChlcfN0z4s1YMBY989/SvlfMI1lgCnkFUs53e9gQF+w7qu7XdllSTiSl8Aw==
+
+browser-resolve@^1.11.3:
+ version "1.11.3"
+ resolved "https://registry.yarnpkg.com/browser-resolve/-/browser-resolve-1.11.3.tgz#9b7cbb3d0f510e4cb86bdbd796124d28b5890af6"
+ integrity sha512-exDi1BYWB/6raKHmDTCicQfTkqwN5fioMFV4j8BsfMU4R2DK/QfZfK7kOVkmWCNANf0snkBzqGqAJBao9gZMdQ==
+ dependencies:
+ resolve "1.1.7"
+
+bser@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/bser/-/bser-2.1.0.tgz#65fc784bf7f87c009b973c12db6546902fa9c7b5"
+ integrity sha512-8zsjWrQkkBoLK6uxASk1nJ2SKv97ltiGDo6A3wA0/yRPz+CwmEyDo0hUrhIuukG2JHpAl3bvFIixw2/3Hi0DOg==
+ dependencies:
+ node-int64 "^0.4.0"
+
+buffer-from@^1.0.0:
+ version "1.1.1"
+ resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef"
+ integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==
+
+cache-base@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/cache-base/-/cache-base-1.0.1.tgz#0a7f46416831c8b662ee36fe4e7c59d76f666ab2"
+ integrity sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==
+ dependencies:
+ collection-visit "^1.0.0"
+ component-emitter "^1.2.1"
+ get-value "^2.0.6"
+ has-value "^1.0.0"
+ isobject "^3.0.1"
+ set-value "^2.0.0"
+ to-object-path "^0.3.0"
+ union-value "^1.0.0"
+ unset-value "^1.0.0"
+
+callsites@^3.0.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73"
+ integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==
+
+camelcase@^5.0.0:
+ version "5.3.1"
+ resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320"
+ integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==
+
+capture-exit@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/capture-exit/-/capture-exit-2.0.0.tgz#fb953bfaebeb781f62898239dabb426d08a509a4"
+ integrity sha512-PiT/hQmTonHhl/HFGN+Lx3JJUznrVYJ3+AQsnthneZbvW7x+f08Tk7yLJTLEOUvBTbduLeeBkxEaYXUOUrRq6g==
+ dependencies:
+ rsvp "^4.8.4"
+
+caseless@~0.12.0:
+ version "0.12.0"
+ resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc"
+ integrity sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=
+
+chalk@^2.0.0, chalk@^2.0.1, chalk@^2.4.2:
+ version "2.4.2"
+ resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424"
+ integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==
+ dependencies:
+ ansi-styles "^3.2.1"
+ escape-string-regexp "^1.0.5"
+ supports-color "^5.3.0"
+
+chownr@^1.1.1:
+ version "1.1.2"
+ resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.2.tgz#a18f1e0b269c8a6a5d3c86eb298beb14c3dd7bf6"
+ integrity sha512-GkfeAQh+QNy3wquu9oIZr6SS5x7wGdSgNQvD10X3r+AZr1Oys22HW8kAmDMvNg2+Dm0TeGaEuO8gFwdBXxwO8A==
+
+ci-info@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-2.0.0.tgz#67a9e964be31a51e15e5010d58e6f12834002f46"
+ integrity sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==
+
+class-utils@^0.3.5:
+ version "0.3.6"
+ resolved "https://registry.yarnpkg.com/class-utils/-/class-utils-0.3.6.tgz#f93369ae8b9a7ce02fd41faad0ca83033190c463"
+ integrity sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==
+ dependencies:
+ arr-union "^3.1.0"
+ define-property "^0.2.5"
+ isobject "^3.0.0"
+ static-extend "^0.1.1"
+
+cliui@^4.0.0:
+ version "4.1.0"
+ resolved "https://registry.yarnpkg.com/cliui/-/cliui-4.1.0.tgz#348422dbe82d800b3022eef4f6ac10bf2e4d1b49"
+ integrity sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ==
+ dependencies:
+ string-width "^2.1.1"
+ strip-ansi "^4.0.0"
+ wrap-ansi "^2.0.0"
+
+co@^4.6.0:
+ version "4.6.0"
+ resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184"
+ integrity sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=
+
+code-point-at@^1.0.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77"
+ integrity sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=
+
+collection-visit@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/collection-visit/-/collection-visit-1.0.0.tgz#4bc0373c164bc3291b4d368c829cf1a80a59dca0"
+ integrity sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=
+ dependencies:
+ map-visit "^1.0.0"
+ object-visit "^1.0.0"
+
+color-convert@^1.9.0:
+ version "1.9.3"
+ resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8"
+ integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==
+ dependencies:
+ color-name "1.1.3"
+
+color-name@1.1.3:
+ version "1.1.3"
+ resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25"
+ integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=
+
+combined-stream@^1.0.6, combined-stream@~1.0.6:
+ version "1.0.8"
+ resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
+ integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==
+ dependencies:
+ delayed-stream "~1.0.0"
+
+commander@~2.20.0:
+ version "2.20.0"
+ resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.0.tgz#d58bb2b5c1ee8f87b0d340027e9e94e222c5a422"
+ integrity sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==
+
+component-emitter@^1.2.1:
+ version "1.3.0"
+ resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz#16e4070fba8ae29b679f2215853ee181ab2eabc0"
+ integrity sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==
+
+concat-map@0.0.1:
+ version "0.0.1"
+ resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
+ integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=
+
+console-control-strings@^1.0.0, console-control-strings@~1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e"
+ integrity sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=
+
+convert-source-map@^1.1.0, convert-source-map@^1.4.0:
+ version "1.6.0"
+ resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.6.0.tgz#51b537a8c43e0f04dec1993bffcdd504e758ac20"
+ integrity sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==
+ dependencies:
+ safe-buffer "~5.1.1"
+
+copy-descriptor@^0.1.0:
+ version "0.1.1"
+ resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d"
+ integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=
+
+core-util-is@1.0.2, core-util-is@~1.0.0:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7"
+ integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=
+
+cross-spawn@^6.0.0:
+ version "6.0.5"
+ resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4"
+ integrity sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==
+ dependencies:
+ nice-try "^1.0.4"
+ path-key "^2.0.1"
+ semver "^5.5.0"
+ shebang-command "^1.2.0"
+ which "^1.2.9"
+
+cssom@0.3.x, "cssom@>= 0.3.2 < 0.4.0":
+ version "0.3.8"
+ resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.3.8.tgz#9f1276f5b2b463f2114d3f2c75250af8c1a36f4a"
+ integrity sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==
+
+cssstyle@^1.0.0:
+ version "1.4.0"
+ resolved "https://registry.yarnpkg.com/cssstyle/-/cssstyle-1.4.0.tgz#9d31328229d3c565c61e586b02041a28fccdccf1"
+ integrity sha512-GBrLZYZ4X4x6/QEoBnIrqb8B/f5l4+8me2dkom/j1Gtbxy0kBv6OGzKuAsGM75bkGwGAFkt56Iwg28S3XTZgSA==
+ dependencies:
+ cssom "0.3.x"
+
+dashdash@^1.12.0:
+ version "1.14.1"
+ resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0"
+ integrity sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=
+ dependencies:
+ assert-plus "^1.0.0"
+
+data-urls@^1.0.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-1.1.0.tgz#15ee0582baa5e22bb59c77140da8f9c76963bbfe"
+ integrity sha512-YTWYI9se1P55u58gL5GkQHW4P6VJBJ5iBT+B5a7i2Tjadhv52paJG0qHX4A0OR6/t52odI64KP2YvFpkDOi3eQ==
+ dependencies:
+ abab "^2.0.0"
+ whatwg-mimetype "^2.2.0"
+ whatwg-url "^7.0.0"
+
+debug@^2.2.0, debug@^2.3.3:
+ version "2.6.9"
+ resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"
+ integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==
+ dependencies:
+ ms "2.0.0"
+
+debug@^3.2.6:
+ version "3.2.6"
+ resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b"
+ integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==
+ dependencies:
+ ms "^2.1.1"
+
+debug@^4.1.0, debug@^4.1.1:
+ version "4.1.1"
+ resolved "https://registry.yarnpkg.com/debug/-/debug-4.1.1.tgz#3b72260255109c6b589cee050f1d516139664791"
+ integrity sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==
+ dependencies:
+ ms "^2.1.1"
+
+decamelize@^1.2.0:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290"
+ integrity sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=
+
+decode-uri-component@^0.2.0:
+ version "0.2.0"
+ resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545"
+ integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=
+
+deep-extend@^0.6.0:
+ version "0.6.0"
+ resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac"
+ integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==
+
+deep-is@~0.1.3:
+ version "0.1.3"
+ resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34"
+ integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=
+
+define-properties@^1.1.2:
+ version "1.1.3"
+ resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1"
+ integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==
+ dependencies:
+ object-keys "^1.0.12"
+
+define-property@^0.2.5:
+ version "0.2.5"
+ resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116"
+ integrity sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=
+ dependencies:
+ is-descriptor "^0.1.0"
+
+define-property@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/define-property/-/define-property-1.0.0.tgz#769ebaaf3f4a63aad3af9e8d304c9bbe79bfb0e6"
+ integrity sha1-dp66rz9KY6rTr56NMEybvnm/sOY=
+ dependencies:
+ is-descriptor "^1.0.0"
+
+define-property@^2.0.2:
+ version "2.0.2"
+ resolved "https://registry.yarnpkg.com/define-property/-/define-property-2.0.2.tgz#d459689e8d654ba77e02a817f8710d702cb16e9d"
+ integrity sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==
+ dependencies:
+ is-descriptor "^1.0.2"
+ isobject "^3.0.1"
+
+delayed-stream@~1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"
+ integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk=
+
+delegates@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a"
+ integrity sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=
+
+detect-libc@^1.0.2:
+ version "1.0.3"
+ resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-1.0.3.tgz#fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b"
+ integrity sha1-+hN8S9aY7fVc1c0CrFWfkaTEups=
+
+detect-newline@^2.1.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/detect-newline/-/detect-newline-2.1.0.tgz#f41f1c10be4b00e87b5f13da680759f2c5bfd3e2"
+ integrity sha1-9B8cEL5LAOh7XxPaaAdZ8sW/0+I=
+
+diff-sequences@^24.3.0:
+ version "24.3.0"
+ resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-24.3.0.tgz#0f20e8a1df1abddaf4d9c226680952e64118b975"
+ integrity sha512-xLqpez+Zj9GKSnPWS0WZw1igGocZ+uua8+y+5dDNTT934N3QuY1sp2LkHzwiaYQGz60hMq0pjAshdeXm5VUOEw==
+
+domexception@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/domexception/-/domexception-1.0.1.tgz#937442644ca6a31261ef36e3ec677fe805582c90"
+ integrity sha512-raigMkn7CJNNo6Ihro1fzG7wr3fHuYVytzquZKX5n0yizGsTcYgzdIUwj1X9pK0VvjeihV+XiclP+DjwbsSKug==
+ dependencies:
+ webidl-conversions "^4.0.2"
+
+ecc-jsbn@~0.1.1:
+ version "0.1.2"
+ resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz#3a83a904e54353287874c564b7549386849a98c9"
+ integrity sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=
+ dependencies:
+ jsbn "~0.1.0"
+ safer-buffer "^2.1.0"
+
+end-of-stream@^1.1.0:
+ version "1.4.1"
+ resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.1.tgz#ed29634d19baba463b6ce6b80a37213eab71ec43"
+ integrity sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==
+ dependencies:
+ once "^1.4.0"
+
+error-ex@^1.3.1:
+ version "1.3.2"
+ resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf"
+ integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==
+ dependencies:
+ is-arrayish "^0.2.1"
+
+es-abstract@^1.5.1:
+ version "1.13.0"
+ resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.13.0.tgz#ac86145fdd5099d8dd49558ccba2eaf9b88e24e9"
+ integrity sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg==
+ dependencies:
+ es-to-primitive "^1.2.0"
+ function-bind "^1.1.1"
+ has "^1.0.3"
+ is-callable "^1.1.4"
+ is-regex "^1.0.4"
+ object-keys "^1.0.12"
+
+es-to-primitive@^1.2.0:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.0.tgz#edf72478033456e8dda8ef09e00ad9650707f377"
+ integrity sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg==
+ dependencies:
+ is-callable "^1.1.4"
+ is-date-object "^1.0.1"
+ is-symbol "^1.0.2"
+
+escape-string-regexp@^1.0.5:
+ version "1.0.5"
+ resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4"
+ integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=
+
+escodegen@^1.9.1:
+ version "1.11.1"
+ resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.11.1.tgz#c485ff8d6b4cdb89e27f4a856e91f118401ca510"
+ integrity sha512-JwiqFD9KdGVVpeuRa68yU3zZnBEOcPs0nKW7wZzXky8Z7tffdYUHbe11bPCV5jYlK6DVdKLWLm0f5I/QlL0Kmw==
+ dependencies:
+ esprima "^3.1.3"
+ estraverse "^4.2.0"
+ esutils "^2.0.2"
+ optionator "^0.8.1"
+ optionalDependencies:
+ source-map "~0.6.1"
+
+esprima@^3.1.3:
+ version "3.1.3"
+ resolved "https://registry.yarnpkg.com/esprima/-/esprima-3.1.3.tgz#fdca51cee6133895e3c88d535ce49dbff62a4633"
+ integrity sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=
+
+estraverse@^4.2.0:
+ version "4.2.0"
+ resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.2.0.tgz#0dee3fed31fcd469618ce7342099fc1afa0bdb13"
+ integrity sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=
+
+esutils@^2.0.2:
+ version "2.0.2"
+ resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b"
+ integrity sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=
+
+exec-sh@^0.3.2:
+ version "0.3.2"
+ resolved "https://registry.yarnpkg.com/exec-sh/-/exec-sh-0.3.2.tgz#6738de2eb7c8e671d0366aea0b0db8c6f7d7391b"
+ integrity sha512-9sLAvzhI5nc8TpuQUh4ahMdCrWT00wPWz7j47/emR5+2qEfoZP5zzUXvx+vdx+H6ohhnsYC31iX04QLYJK8zTg==
+
+execa@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/execa/-/execa-1.0.0.tgz#c6236a5bb4df6d6f15e88e7f017798216749ddd8"
+ integrity sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==
+ dependencies:
+ cross-spawn "^6.0.0"
+ get-stream "^4.0.0"
+ is-stream "^1.1.0"
+ npm-run-path "^2.0.0"
+ p-finally "^1.0.0"
+ signal-exit "^3.0.0"
+ strip-eof "^1.0.0"
+
+exit@^0.1.2:
+ version "0.1.2"
+ resolved "https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c"
+ integrity sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=
+
+expand-brackets@^2.1.4:
+ version "2.1.4"
+ resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-2.1.4.tgz#b77735e315ce30f6b6eff0f83b04151a22449622"
+ integrity sha1-t3c14xXOMPa27/D4OwQVGiJEliI=
+ dependencies:
+ debug "^2.3.3"
+ define-property "^0.2.5"
+ extend-shallow "^2.0.1"
+ posix-character-classes "^0.1.0"
+ regex-not "^1.0.0"
+ snapdragon "^0.8.1"
+ to-regex "^3.0.1"
+
+expect@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/expect/-/expect-24.8.0.tgz#471f8ec256b7b6129ca2524b2a62f030df38718d"
+ integrity sha512-/zYvP8iMDrzaaxHVa724eJBCKqSHmO0FA7EDkBiRHxg6OipmMn1fN+C8T9L9K8yr7UONkOifu6+LLH+z76CnaA==
+ dependencies:
+ "@jest/types" "^24.8.0"
+ ansi-styles "^3.2.0"
+ jest-get-type "^24.8.0"
+ jest-matcher-utils "^24.8.0"
+ jest-message-util "^24.8.0"
+ jest-regex-util "^24.3.0"
+
+extend-shallow@^2.0.1:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f"
+ integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=
+ dependencies:
+ is-extendable "^0.1.0"
+
+extend-shallow@^3.0.0, extend-shallow@^3.0.2:
+ version "3.0.2"
+ resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-3.0.2.tgz#26a71aaf073b39fb2127172746131c2704028db8"
+ integrity sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=
+ dependencies:
+ assign-symbols "^1.0.0"
+ is-extendable "^1.0.1"
+
+extend@~3.0.2:
+ version "3.0.2"
+ resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa"
+ integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==
+
+extglob@^2.0.4:
+ version "2.0.4"
+ resolved "https://registry.yarnpkg.com/extglob/-/extglob-2.0.4.tgz#ad00fe4dc612a9232e8718711dc5cb5ab0285543"
+ integrity sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==
+ dependencies:
+ array-unique "^0.3.2"
+ define-property "^1.0.0"
+ expand-brackets "^2.1.4"
+ extend-shallow "^2.0.1"
+ fragment-cache "^0.2.1"
+ regex-not "^1.0.0"
+ snapdragon "^0.8.1"
+ to-regex "^3.0.1"
+
+extsprintf@1.3.0:
+ version "1.3.0"
+ resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05"
+ integrity sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=
+
+extsprintf@^1.2.0:
+ version "1.4.0"
+ resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f"
+ integrity sha1-4mifjzVvrWLMplo6kcXfX5VRaS8=
+
+fast-deep-equal@^2.0.1:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz#7b05218ddf9667bf7f370bf7fdb2cb15fdd0aa49"
+ integrity sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=
+
+fast-json-stable-stringify@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2"
+ integrity sha1-1RQsDK7msRifh9OnYREGT4bIu/I=
+
+fast-levenshtein@~2.0.4:
+ version "2.0.6"
+ resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917"
+ integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=
+
+fb-watchman@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/fb-watchman/-/fb-watchman-2.0.0.tgz#54e9abf7dfa2f26cd9b1636c588c1afc05de5d58"
+ integrity sha1-VOmr99+i8mzZsWNsWIwa/AXeXVg=
+ dependencies:
+ bser "^2.0.0"
+
+fill-range@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7"
+ integrity sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=
+ dependencies:
+ extend-shallow "^2.0.1"
+ is-number "^3.0.0"
+ repeat-string "^1.6.1"
+ to-regex-range "^2.1.0"
+
+find-up@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73"
+ integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==
+ dependencies:
+ locate-path "^3.0.0"
+
+for-in@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80"
+ integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=
+
+forever-agent@~0.6.1:
+ version "0.6.1"
+ resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91"
+ integrity sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=
+
+form-data@~2.3.2:
+ version "2.3.3"
+ resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.3.tgz#dcce52c05f644f298c6a7ab936bd724ceffbf3a6"
+ integrity sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==
+ dependencies:
+ asynckit "^0.4.0"
+ combined-stream "^1.0.6"
+ mime-types "^2.1.12"
+
+fragment-cache@^0.2.1:
+ version "0.2.1"
+ resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19"
+ integrity sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=
+ dependencies:
+ map-cache "^0.2.2"
+
+fs-minipass@^1.2.5:
+ version "1.2.6"
+ resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-1.2.6.tgz#2c5cc30ded81282bfe8a0d7c7c1853ddeb102c07"
+ integrity sha512-crhvyXcMejjv3Z5d2Fa9sf5xLYVCF5O1c71QxbVnbLsmYMBEvDAftewesN/HhY03YRoA7zOMxjNGrF5svGaaeQ==
+ dependencies:
+ minipass "^2.2.1"
+
+fs.realpath@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
+ integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8=
+
+fsevents@^1.2.7:
+ version "1.2.9"
+ resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.9.tgz#3f5ed66583ccd6f400b5a00db6f7e861363e388f"
+ integrity sha512-oeyj2H3EjjonWcFjD5NvZNE9Rqe4UW+nQBU2HNeKw0koVLEFIhtyETyAakeAM3de7Z/SW5kcA+fZUait9EApnw==
+ dependencies:
+ nan "^2.12.1"
+ node-pre-gyp "^0.12.0"
+
+function-bind@^1.1.1:
+ version "1.1.1"
+ resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d"
+ integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==
+
+gauge@~2.7.3:
+ version "2.7.4"
+ resolved "https://registry.yarnpkg.com/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7"
+ integrity sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=
+ dependencies:
+ aproba "^1.0.3"
+ console-control-strings "^1.0.0"
+ has-unicode "^2.0.0"
+ object-assign "^4.1.0"
+ signal-exit "^3.0.0"
+ string-width "^1.0.1"
+ strip-ansi "^3.0.1"
+ wide-align "^1.1.0"
+
+get-caller-file@^1.0.1:
+ version "1.0.3"
+ resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.3.tgz#f978fa4c90d1dfe7ff2d6beda2a515e713bdcf4a"
+ integrity sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==
+
+get-stream@^4.0.0:
+ version "4.1.0"
+ resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-4.1.0.tgz#c1b255575f3dc21d59bfc79cd3d2b46b1c3a54b5"
+ integrity sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==
+ dependencies:
+ pump "^3.0.0"
+
+get-value@^2.0.3, get-value@^2.0.6:
+ version "2.0.6"
+ resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28"
+ integrity sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=
+
+getpass@^0.1.1:
+ version "0.1.7"
+ resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa"
+ integrity sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=
+ dependencies:
+ assert-plus "^1.0.0"
+
+glob@^7.1.1, glob@^7.1.2, glob@^7.1.3:
+ version "7.1.4"
+ resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.4.tgz#aa608a2f6c577ad357e1ae5a5c26d9a8d1969255"
+ integrity sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==
+ dependencies:
+ fs.realpath "^1.0.0"
+ inflight "^1.0.4"
+ inherits "2"
+ minimatch "^3.0.4"
+ once "^1.3.0"
+ path-is-absolute "^1.0.0"
+
+globals@^11.1.0:
+ version "11.12.0"
+ resolved "https://registry.yarnpkg.com/globals/-/globals-11.12.0.tgz#ab8795338868a0babd8525758018c2a7eb95c42e"
+ integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==
+
+graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2:
+ version "4.2.0"
+ resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.0.tgz#8d8fdc73977cb04104721cb53666c1ca64cd328b"
+ integrity sha512-jpSvDPV4Cq/bgtpndIWbI5hmYxhQGHPC4d4cqBPb4DLniCfhJokdXhwhaDuLBGLQdvvRum/UiX6ECVIPvDXqdg==
+
+growly@^1.3.0:
+ version "1.3.0"
+ resolved "https://registry.yarnpkg.com/growly/-/growly-1.3.0.tgz#f10748cbe76af964b7c96c93c6bcc28af120c081"
+ integrity sha1-8QdIy+dq+WS3yWyTxrzCivEgwIE=
+
+handlebars@^4.1.2:
+ version "4.1.2"
+ resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.1.2.tgz#b6b37c1ced0306b221e094fc7aca3ec23b131b67"
+ integrity sha512-nvfrjqvt9xQ8Z/w0ijewdD/vvWDTOweBUm96NTr66Wfvo1mJenBLwcYmPs3TIBP5ruzYGD7Hx/DaM9RmhroGPw==
+ dependencies:
+ neo-async "^2.6.0"
+ optimist "^0.6.1"
+ source-map "^0.6.1"
+ optionalDependencies:
+ uglify-js "^3.1.4"
+
+har-schema@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92"
+ integrity sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=
+
+har-validator@~5.1.0:
+ version "5.1.3"
+ resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.1.3.tgz#1ef89ebd3e4996557675eed9893110dc350fa080"
+ integrity sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==
+ dependencies:
+ ajv "^6.5.5"
+ har-schema "^2.0.0"
+
+has-flag@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
+ integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0=
+
+has-symbols@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.0.tgz#ba1a8f1af2a0fc39650f5c850367704122063b44"
+ integrity sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=
+
+has-unicode@^2.0.0:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9"
+ integrity sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=
+
+has-value@^0.3.1:
+ version "0.3.1"
+ resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f"
+ integrity sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=
+ dependencies:
+ get-value "^2.0.3"
+ has-values "^0.1.4"
+ isobject "^2.0.0"
+
+has-value@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/has-value/-/has-value-1.0.0.tgz#18b281da585b1c5c51def24c930ed29a0be6b177"
+ integrity sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=
+ dependencies:
+ get-value "^2.0.6"
+ has-values "^1.0.0"
+ isobject "^3.0.0"
+
+has-values@^0.1.4:
+ version "0.1.4"
+ resolved "https://registry.yarnpkg.com/has-values/-/has-values-0.1.4.tgz#6d61de95d91dfca9b9a02089ad384bff8f62b771"
+ integrity sha1-bWHeldkd/Km5oCCJrThL/49it3E=
+
+has-values@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/has-values/-/has-values-1.0.0.tgz#95b0b63fec2146619a6fe57fe75628d5a39efe4f"
+ integrity sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=
+ dependencies:
+ is-number "^3.0.0"
+ kind-of "^4.0.0"
+
+has@^1.0.1, has@^1.0.3:
+ version "1.0.3"
+ resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796"
+ integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==
+ dependencies:
+ function-bind "^1.1.1"
+
+hosted-git-info@^2.1.4:
+ version "2.7.1"
+ resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.7.1.tgz#97f236977bd6e125408930ff6de3eec6281ec047"
+ integrity sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w==
+
+html-encoding-sniffer@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-1.0.2.tgz#e70d84b94da53aa375e11fe3a351be6642ca46f8"
+ integrity sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw==
+ dependencies:
+ whatwg-encoding "^1.0.1"
+
+http-signature@~1.2.0:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1"
+ integrity sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=
+ dependencies:
+ assert-plus "^1.0.0"
+ jsprim "^1.2.2"
+ sshpk "^1.7.0"
+
+iconv-lite@0.4.24, iconv-lite@^0.4.4:
+ version "0.4.24"
+ resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b"
+ integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==
+ dependencies:
+ safer-buffer ">= 2.1.2 < 3"
+
+ignore-walk@^3.0.1:
+ version "3.0.1"
+ resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-3.0.1.tgz#a83e62e7d272ac0e3b551aaa82831a19b69f82f8"
+ integrity sha512-DTVlMx3IYPe0/JJcYP7Gxg7ttZZu3IInhuEhbchuqneY9wWe5Ojy2mXLBaQFUQmo0AW2r3qG7m1mg86js+gnlQ==
+ dependencies:
+ minimatch "^3.0.4"
+
+import-local@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/import-local/-/import-local-2.0.0.tgz#55070be38a5993cf18ef6db7e961f5bee5c5a09d"
+ integrity sha512-b6s04m3O+s3CGSbqDIyP4R6aAwAeYlVq9+WUWep6iHa8ETRf9yei1U48C5MmfJmV9AiLYYBKPMq/W+/WRpQmCQ==
+ dependencies:
+ pkg-dir "^3.0.0"
+ resolve-cwd "^2.0.0"
+
+imurmurhash@^0.1.4:
+ version "0.1.4"
+ resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea"
+ integrity sha1-khi5srkoojixPcT7a21XbyMUU+o=
+
+inflight@^1.0.4:
+ version "1.0.6"
+ resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"
+ integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=
+ dependencies:
+ once "^1.3.0"
+ wrappy "1"
+
+inherits@2:
+ version "2.0.4"
+ resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c"
+ integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==
+
+inherits@~2.0.3:
+ version "2.0.3"
+ resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"
+ integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=
+
+ini@~1.3.0:
+ version "1.3.5"
+ resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.5.tgz#eee25f56db1c9ec6085e0c22778083f596abf927"
+ integrity sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==
+
+invariant@^2.2.4:
+ version "2.2.4"
+ resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.4.tgz#610f3c92c9359ce1db616e538008d23ff35158e6"
+ integrity sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==
+ dependencies:
+ loose-envify "^1.0.0"
+
+invert-kv@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-2.0.0.tgz#7393f5afa59ec9ff5f67a27620d11c226e3eec02"
+ integrity sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==
+
+is-accessor-descriptor@^0.1.6:
+ version "0.1.6"
+ resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6"
+ integrity sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=
+ dependencies:
+ kind-of "^3.0.2"
+
+is-accessor-descriptor@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656"
+ integrity sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==
+ dependencies:
+ kind-of "^6.0.0"
+
+is-arrayish@^0.2.1:
+ version "0.2.1"
+ resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d"
+ integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=
+
+is-buffer@^1.1.5:
+ version "1.1.6"
+ resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be"
+ integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==
+
+is-callable@^1.1.4:
+ version "1.1.4"
+ resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.4.tgz#1e1adf219e1eeb684d691f9d6a05ff0d30a24d75"
+ integrity sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==
+
+is-ci@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/is-ci/-/is-ci-2.0.0.tgz#6bc6334181810e04b5c22b3d589fdca55026404c"
+ integrity sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==
+ dependencies:
+ ci-info "^2.0.0"
+
+is-data-descriptor@^0.1.4:
+ version "0.1.4"
+ resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56"
+ integrity sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=
+ dependencies:
+ kind-of "^3.0.2"
+
+is-data-descriptor@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7"
+ integrity sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==
+ dependencies:
+ kind-of "^6.0.0"
+
+is-date-object@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16"
+ integrity sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=
+
+is-descriptor@^0.1.0:
+ version "0.1.6"
+ resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca"
+ integrity sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==
+ dependencies:
+ is-accessor-descriptor "^0.1.6"
+ is-data-descriptor "^0.1.4"
+ kind-of "^5.0.0"
+
+is-descriptor@^1.0.0, is-descriptor@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec"
+ integrity sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==
+ dependencies:
+ is-accessor-descriptor "^1.0.0"
+ is-data-descriptor "^1.0.0"
+ kind-of "^6.0.2"
+
+is-extendable@^0.1.0, is-extendable@^0.1.1:
+ version "0.1.1"
+ resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89"
+ integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=
+
+is-extendable@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-1.0.1.tgz#a7470f9e426733d81bd81e1155264e3a3507cab4"
+ integrity sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==
+ dependencies:
+ is-plain-object "^2.0.4"
+
+is-fullwidth-code-point@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb"
+ integrity sha1-754xOG8DGn8NZDr4L95QxFfvAMs=
+ dependencies:
+ number-is-nan "^1.0.0"
+
+is-fullwidth-code-point@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f"
+ integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=
+
+is-generator-fn@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/is-generator-fn/-/is-generator-fn-2.1.0.tgz#7d140adc389aaf3011a8f2a2a4cfa6faadffb118"
+ integrity sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==
+
+is-number@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195"
+ integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=
+ dependencies:
+ kind-of "^3.0.2"
+
+is-plain-object@^2.0.3, is-plain-object@^2.0.4:
+ version "2.0.4"
+ resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677"
+ integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==
+ dependencies:
+ isobject "^3.0.1"
+
+is-regex@^1.0.4:
+ version "1.0.4"
+ resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.0.4.tgz#5517489b547091b0930e095654ced25ee97e9491"
+ integrity sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=
+ dependencies:
+ has "^1.0.1"
+
+is-stream@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44"
+ integrity sha1-EtSj3U5o4Lec6428hBc66A2RykQ=
+
+is-symbol@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.2.tgz#a055f6ae57192caee329e7a860118b497a950f38"
+ integrity sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw==
+ dependencies:
+ has-symbols "^1.0.0"
+
+is-typedarray@~1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a"
+ integrity sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=
+
+is-windows@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d"
+ integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==
+
+is-wsl@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-1.1.0.tgz#1f16e4aa22b04d1336b66188a66af3c600c3a66d"
+ integrity sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=
+
+isarray@1.0.0, isarray@~1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11"
+ integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=
+
+isexe@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10"
+ integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=
+
+isobject@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89"
+ integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=
+ dependencies:
+ isarray "1.0.0"
+
+isobject@^3.0.0, isobject@^3.0.1:
+ version "3.0.1"
+ resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df"
+ integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8=
+
+isstream@~0.1.2:
+ version "0.1.2"
+ resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a"
+ integrity sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=
+
+istanbul-lib-coverage@^2.0.2, istanbul-lib-coverage@^2.0.5:
+ version "2.0.5"
+ resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz#675f0ab69503fad4b1d849f736baaca803344f49"
+ integrity sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA==
+
+istanbul-lib-instrument@^3.0.1, istanbul-lib-instrument@^3.3.0:
+ version "3.3.0"
+ resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-3.3.0.tgz#a5f63d91f0bbc0c3e479ef4c5de027335ec6d630"
+ integrity sha512-5nnIN4vo5xQZHdXno/YDXJ0G+I3dAm4XgzfSVTPLQpj/zAV2dV6Juy0yaf10/zrJOJeHoN3fraFe+XRq2bFVZA==
+ dependencies:
+ "@babel/generator" "^7.4.0"
+ "@babel/parser" "^7.4.3"
+ "@babel/template" "^7.4.0"
+ "@babel/traverse" "^7.4.3"
+ "@babel/types" "^7.4.0"
+ istanbul-lib-coverage "^2.0.5"
+ semver "^6.0.0"
+
+istanbul-lib-report@^2.0.4:
+ version "2.0.8"
+ resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-2.0.8.tgz#5a8113cd746d43c4889eba36ab10e7d50c9b4f33"
+ integrity sha512-fHBeG573EIihhAblwgxrSenp0Dby6tJMFR/HvlerBsrCTD5bkUuoNtn3gVh29ZCS824cGGBPn7Sg7cNk+2xUsQ==
+ dependencies:
+ istanbul-lib-coverage "^2.0.5"
+ make-dir "^2.1.0"
+ supports-color "^6.1.0"
+
+istanbul-lib-source-maps@^3.0.1:
+ version "3.0.6"
+ resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.6.tgz#284997c48211752ec486253da97e3879defba8c8"
+ integrity sha512-R47KzMtDJH6X4/YW9XTx+jrLnZnscW4VpNN+1PViSYTejLVPWv7oov+Duf8YQSPyVRUvueQqz1TcsC6mooZTXw==
+ dependencies:
+ debug "^4.1.1"
+ istanbul-lib-coverage "^2.0.5"
+ make-dir "^2.1.0"
+ rimraf "^2.6.3"
+ source-map "^0.6.1"
+
+istanbul-reports@^2.1.1:
+ version "2.2.6"
+ resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-2.2.6.tgz#7b4f2660d82b29303a8fe6091f8ca4bf058da1af"
+ integrity sha512-SKi4rnMyLBKe0Jy2uUdx28h8oG7ph2PPuQPvIAh31d+Ci+lSiEu4C+h3oBPuJ9+mPKhOyW0M8gY4U5NM1WLeXA==
+ dependencies:
+ handlebars "^4.1.2"
+
+jest-changed-files@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-changed-files/-/jest-changed-files-24.8.0.tgz#7e7eb21cf687587a85e50f3d249d1327e15b157b"
+ integrity sha512-qgANC1Yrivsq+UrLXsvJefBKVoCsKB0Hv+mBb6NMjjZ90wwxCDmU3hsCXBya30cH+LnPYjwgcU65i6yJ5Nfuug==
+ dependencies:
+ "@jest/types" "^24.8.0"
+ execa "^1.0.0"
+ throat "^4.0.0"
+
+jest-cli@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-cli/-/jest-cli-24.8.0.tgz#b075ac914492ed114fa338ade7362a301693e989"
+ integrity sha512-+p6J00jSMPQ116ZLlHJJvdf8wbjNbZdeSX9ptfHX06/MSNaXmKihQzx5vQcw0q2G6JsdVkUIdWbOWtSnaYs3yA==
+ dependencies:
+ "@jest/core" "^24.8.0"
+ "@jest/test-result" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ chalk "^2.0.1"
+ exit "^0.1.2"
+ import-local "^2.0.0"
+ is-ci "^2.0.0"
+ jest-config "^24.8.0"
+ jest-util "^24.8.0"
+ jest-validate "^24.8.0"
+ prompts "^2.0.1"
+ realpath-native "^1.1.0"
+ yargs "^12.0.2"
+
+jest-config@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-config/-/jest-config-24.8.0.tgz#77db3d265a6f726294687cbbccc36f8a76ee0f4f"
+ integrity sha512-Czl3Nn2uEzVGsOeaewGWoDPD8GStxCpAe0zOYs2x2l0fZAgPbCr3uwUkgNKV3LwE13VXythM946cd5rdGkkBZw==
+ dependencies:
+ "@babel/core" "^7.1.0"
+ "@jest/test-sequencer" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ babel-jest "^24.8.0"
+ chalk "^2.0.1"
+ glob "^7.1.1"
+ jest-environment-jsdom "^24.8.0"
+ jest-environment-node "^24.8.0"
+ jest-get-type "^24.8.0"
+ jest-jasmine2 "^24.8.0"
+ jest-regex-util "^24.3.0"
+ jest-resolve "^24.8.0"
+ jest-util "^24.8.0"
+ jest-validate "^24.8.0"
+ micromatch "^3.1.10"
+ pretty-format "^24.8.0"
+ realpath-native "^1.1.0"
+
+jest-diff@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-24.8.0.tgz#146435e7d1e3ffdf293d53ff97e193f1d1546172"
+ integrity sha512-wxetCEl49zUpJ/bvUmIFjd/o52J+yWcoc5ZyPq4/W1LUKGEhRYDIbP1KcF6t+PvqNrGAFk4/JhtxDq/Nnzs66g==
+ dependencies:
+ chalk "^2.0.1"
+ diff-sequences "^24.3.0"
+ jest-get-type "^24.8.0"
+ pretty-format "^24.8.0"
+
+jest-docblock@^24.3.0:
+ version "24.3.0"
+ resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-24.3.0.tgz#b9c32dac70f72e4464520d2ba4aec02ab14db5dd"
+ integrity sha512-nlANmF9Yq1dufhFlKG9rasfQlrY7wINJbo3q01tu56Jv5eBU5jirylhF2O5ZBnLxzOVBGRDz/9NAwNyBtG4Nyg==
+ dependencies:
+ detect-newline "^2.1.0"
+
+jest-each@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-each/-/jest-each-24.8.0.tgz#a05fd2bf94ddc0b1da66c6d13ec2457f35e52775"
+ integrity sha512-NrwK9gaL5+XgrgoCsd9svsoWdVkK4gnvyhcpzd6m487tXHqIdYeykgq3MKI1u4I+5Zf0tofr70at9dWJDeb+BA==
+ dependencies:
+ "@jest/types" "^24.8.0"
+ chalk "^2.0.1"
+ jest-get-type "^24.8.0"
+ jest-util "^24.8.0"
+ pretty-format "^24.8.0"
+
+jest-environment-jsdom@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-environment-jsdom/-/jest-environment-jsdom-24.8.0.tgz#300f6949a146cabe1c9357ad9e9ecf9f43f38857"
+ integrity sha512-qbvgLmR7PpwjoFjM/sbuqHJt/NCkviuq9vus9NBn/76hhSidO+Z6Bn9tU8friecegbJL8gzZQEMZBQlFWDCwAQ==
+ dependencies:
+ "@jest/environment" "^24.8.0"
+ "@jest/fake-timers" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ jest-mock "^24.8.0"
+ jest-util "^24.8.0"
+ jsdom "^11.5.1"
+
+jest-environment-node@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-environment-node/-/jest-environment-node-24.8.0.tgz#d3f726ba8bc53087a60e7a84ca08883a4c892231"
+ integrity sha512-vIGUEScd1cdDgR6sqn2M08sJTRLQp6Dk/eIkCeO4PFHxZMOgy+uYLPMC4ix3PEfM5Au/x3uQ/5Tl0DpXXZsJ/Q==
+ dependencies:
+ "@jest/environment" "^24.8.0"
+ "@jest/fake-timers" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ jest-mock "^24.8.0"
+ jest-util "^24.8.0"
+
+jest-get-type@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-24.8.0.tgz#a7440de30b651f5a70ea3ed7ff073a32dfe646fc"
+ integrity sha512-RR4fo8jEmMD9zSz2nLbs2j0zvPpk/KCEz3a62jJWbd2ayNo0cb+KFRxPHVhE4ZmgGJEQp0fosmNz84IfqM8cMQ==
+
+jest-haste-map@^24.8.0:
+ version "24.8.1"
+ resolved "https://registry.yarnpkg.com/jest-haste-map/-/jest-haste-map-24.8.1.tgz#f39cc1d2b1d907e014165b4bd5a957afcb992982"
+ integrity sha512-SwaxMGVdAZk3ernAx2Uv2sorA7jm3Kx+lR0grp6rMmnY06Kn/urtKx1LPN2mGTea4fCT38impYT28FfcLUhX0g==
+ dependencies:
+ "@jest/types" "^24.8.0"
+ anymatch "^2.0.0"
+ fb-watchman "^2.0.0"
+ graceful-fs "^4.1.15"
+ invariant "^2.2.4"
+ jest-serializer "^24.4.0"
+ jest-util "^24.8.0"
+ jest-worker "^24.6.0"
+ micromatch "^3.1.10"
+ sane "^4.0.3"
+ walker "^1.0.7"
+ optionalDependencies:
+ fsevents "^1.2.7"
+
+jest-jasmine2@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-jasmine2/-/jest-jasmine2-24.8.0.tgz#a9c7e14c83dd77d8b15e820549ce8987cc8cd898"
+ integrity sha512-cEky88npEE5LKd5jPpTdDCLvKkdyklnaRycBXL6GNmpxe41F0WN44+i7lpQKa/hcbXaQ+rc9RMaM4dsebrYong==
+ dependencies:
+ "@babel/traverse" "^7.1.0"
+ "@jest/environment" "^24.8.0"
+ "@jest/test-result" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ chalk "^2.0.1"
+ co "^4.6.0"
+ expect "^24.8.0"
+ is-generator-fn "^2.0.0"
+ jest-each "^24.8.0"
+ jest-matcher-utils "^24.8.0"
+ jest-message-util "^24.8.0"
+ jest-runtime "^24.8.0"
+ jest-snapshot "^24.8.0"
+ jest-util "^24.8.0"
+ pretty-format "^24.8.0"
+ throat "^4.0.0"
+
+jest-leak-detector@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-leak-detector/-/jest-leak-detector-24.8.0.tgz#c0086384e1f650c2d8348095df769f29b48e6980"
+ integrity sha512-cG0yRSK8A831LN8lIHxI3AblB40uhv0z+SsQdW3GoMMVcK+sJwrIIyax5tu3eHHNJ8Fu6IMDpnLda2jhn2pD/g==
+ dependencies:
+ pretty-format "^24.8.0"
+
+jest-matcher-utils@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-24.8.0.tgz#2bce42204c9af12bde46f83dc839efe8be832495"
+ integrity sha512-lex1yASY51FvUuHgm0GOVj7DCYEouWSlIYmCW7APSqB9v8mXmKSn5+sWVF0MhuASG0bnYY106/49JU1FZNl5hw==
+ dependencies:
+ chalk "^2.0.1"
+ jest-diff "^24.8.0"
+ jest-get-type "^24.8.0"
+ pretty-format "^24.8.0"
+
+jest-message-util@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-message-util/-/jest-message-util-24.8.0.tgz#0d6891e72a4beacc0292b638685df42e28d6218b"
+ integrity sha512-p2k71rf/b6ns8btdB0uVdljWo9h0ovpnEe05ZKWceQGfXYr4KkzgKo3PBi8wdnd9OtNh46VpNIJynUn/3MKm1g==
+ dependencies:
+ "@babel/code-frame" "^7.0.0"
+ "@jest/test-result" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ "@types/stack-utils" "^1.0.1"
+ chalk "^2.0.1"
+ micromatch "^3.1.10"
+ slash "^2.0.0"
+ stack-utils "^1.0.1"
+
+jest-mock@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-mock/-/jest-mock-24.8.0.tgz#2f9d14d37699e863f1febf4e4d5a33b7fdbbde56"
+ integrity sha512-6kWugwjGjJw+ZkK4mDa0Df3sDlUTsV47MSrT0nGQ0RBWJbpODDQ8MHDVtGtUYBne3IwZUhtB7elxHspU79WH3A==
+ dependencies:
+ "@jest/types" "^24.8.0"
+
+jest-pnp-resolver@^1.2.1:
+ version "1.2.1"
+ resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.1.tgz#ecdae604c077a7fbc70defb6d517c3c1c898923a"
+ integrity sha512-pgFw2tm54fzgYvc/OHrnysABEObZCUNFnhjoRjaVOCN8NYc032/gVjPaHD4Aq6ApkSieWtfKAFQtmDKAmhupnQ==
+
+jest-regex-util@^24.3.0:
+ version "24.3.0"
+ resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-24.3.0.tgz#d5a65f60be1ae3e310d5214a0307581995227b36"
+ integrity sha512-tXQR1NEOyGlfylyEjg1ImtScwMq8Oh3iJbGTjN7p0J23EuVX1MA8rwU69K4sLbCmwzgCUbVkm0FkSF9TdzOhtg==
+
+jest-resolve-dependencies@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-resolve-dependencies/-/jest-resolve-dependencies-24.8.0.tgz#19eec3241f2045d3f990dba331d0d7526acff8e0"
+ integrity sha512-hyK1qfIf/krV+fSNyhyJeq3elVMhK9Eijlwy+j5jqmZ9QsxwKBiP6qukQxaHtK8k6zql/KYWwCTQ+fDGTIJauw==
+ dependencies:
+ "@jest/types" "^24.8.0"
+ jest-regex-util "^24.3.0"
+ jest-snapshot "^24.8.0"
+
+jest-resolve@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-resolve/-/jest-resolve-24.8.0.tgz#84b8e5408c1f6a11539793e2b5feb1b6e722439f"
+ integrity sha512-+hjSzi1PoRvnuOICoYd5V/KpIQmkAsfjFO71458hQ2Whi/yf1GDeBOFj8Gxw4LrApHsVJvn5fmjcPdmoUHaVKw==
+ dependencies:
+ "@jest/types" "^24.8.0"
+ browser-resolve "^1.11.3"
+ chalk "^2.0.1"
+ jest-pnp-resolver "^1.2.1"
+ realpath-native "^1.1.0"
+
+jest-runner@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-runner/-/jest-runner-24.8.0.tgz#4f9ae07b767db27b740d7deffad0cf67ccb4c5bb"
+ integrity sha512-utFqC5BaA3JmznbissSs95X1ZF+d+4WuOWwpM9+Ak356YtMhHE/GXUondZdcyAAOTBEsRGAgH/0TwLzfI9h7ow==
+ dependencies:
+ "@jest/console" "^24.7.1"
+ "@jest/environment" "^24.8.0"
+ "@jest/test-result" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ chalk "^2.4.2"
+ exit "^0.1.2"
+ graceful-fs "^4.1.15"
+ jest-config "^24.8.0"
+ jest-docblock "^24.3.0"
+ jest-haste-map "^24.8.0"
+ jest-jasmine2 "^24.8.0"
+ jest-leak-detector "^24.8.0"
+ jest-message-util "^24.8.0"
+ jest-resolve "^24.8.0"
+ jest-runtime "^24.8.0"
+ jest-util "^24.8.0"
+ jest-worker "^24.6.0"
+ source-map-support "^0.5.6"
+ throat "^4.0.0"
+
+jest-runtime@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-runtime/-/jest-runtime-24.8.0.tgz#05f94d5b05c21f6dc54e427cd2e4980923350620"
+ integrity sha512-Mq0aIXhvO/3bX44ccT+czU1/57IgOMyy80oM0XR/nyD5zgBcesF84BPabZi39pJVA6UXw+fY2Q1N+4BiVUBWOA==
+ dependencies:
+ "@jest/console" "^24.7.1"
+ "@jest/environment" "^24.8.0"
+ "@jest/source-map" "^24.3.0"
+ "@jest/transform" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ "@types/yargs" "^12.0.2"
+ chalk "^2.0.1"
+ exit "^0.1.2"
+ glob "^7.1.3"
+ graceful-fs "^4.1.15"
+ jest-config "^24.8.0"
+ jest-haste-map "^24.8.0"
+ jest-message-util "^24.8.0"
+ jest-mock "^24.8.0"
+ jest-regex-util "^24.3.0"
+ jest-resolve "^24.8.0"
+ jest-snapshot "^24.8.0"
+ jest-util "^24.8.0"
+ jest-validate "^24.8.0"
+ realpath-native "^1.1.0"
+ slash "^2.0.0"
+ strip-bom "^3.0.0"
+ yargs "^12.0.2"
+
+jest-serializer@^24.4.0:
+ version "24.4.0"
+ resolved "https://registry.yarnpkg.com/jest-serializer/-/jest-serializer-24.4.0.tgz#f70c5918c8ea9235ccb1276d232e459080588db3"
+ integrity sha512-k//0DtglVstc1fv+GY/VHDIjrtNjdYvYjMlbLUed4kxrE92sIUewOi5Hj3vrpB8CXfkJntRPDRjCrCvUhBdL8Q==
+
+jest-snapshot@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-snapshot/-/jest-snapshot-24.8.0.tgz#3bec6a59da2ff7bc7d097a853fb67f9d415cb7c6"
+ integrity sha512-5ehtWoc8oU9/cAPe6fez6QofVJLBKyqkY2+TlKTOf0VllBB/mqUNdARdcjlZrs9F1Cv+/HKoCS/BknT0+tmfPg==
+ dependencies:
+ "@babel/types" "^7.0.0"
+ "@jest/types" "^24.8.0"
+ chalk "^2.0.1"
+ expect "^24.8.0"
+ jest-diff "^24.8.0"
+ jest-matcher-utils "^24.8.0"
+ jest-message-util "^24.8.0"
+ jest-resolve "^24.8.0"
+ mkdirp "^0.5.1"
+ natural-compare "^1.4.0"
+ pretty-format "^24.8.0"
+ semver "^5.5.0"
+
+jest-util@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-24.8.0.tgz#41f0e945da11df44cc76d64ffb915d0716f46cd1"
+ integrity sha512-DYZeE+XyAnbNt0BG1OQqKy/4GVLPtzwGx5tsnDrFcax36rVE3lTA5fbvgmbVPUZf9w77AJ8otqR4VBbfFJkUZA==
+ dependencies:
+ "@jest/console" "^24.7.1"
+ "@jest/fake-timers" "^24.8.0"
+ "@jest/source-map" "^24.3.0"
+ "@jest/test-result" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ callsites "^3.0.0"
+ chalk "^2.0.1"
+ graceful-fs "^4.1.15"
+ is-ci "^2.0.0"
+ mkdirp "^0.5.1"
+ slash "^2.0.0"
+ source-map "^0.6.0"
+
+jest-validate@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-24.8.0.tgz#624c41533e6dfe356ffadc6e2423a35c2d3b4849"
+ integrity sha512-+/N7VOEMW1Vzsrk3UWBDYTExTPwf68tavEPKDnJzrC6UlHtUDU/fuEdXqFoHzv9XnQ+zW6X3qMZhJ3YexfeLDA==
+ dependencies:
+ "@jest/types" "^24.8.0"
+ camelcase "^5.0.0"
+ chalk "^2.0.1"
+ jest-get-type "^24.8.0"
+ leven "^2.1.0"
+ pretty-format "^24.8.0"
+
+jest-watcher@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest-watcher/-/jest-watcher-24.8.0.tgz#58d49915ceddd2de85e238f6213cef1c93715de4"
+ integrity sha512-SBjwHt5NedQoVu54M5GEx7cl7IGEFFznvd/HNT8ier7cCAx/Qgu9ZMlaTQkvK22G1YOpcWBLQPFSImmxdn3DAw==
+ dependencies:
+ "@jest/test-result" "^24.8.0"
+ "@jest/types" "^24.8.0"
+ "@types/yargs" "^12.0.9"
+ ansi-escapes "^3.0.0"
+ chalk "^2.0.1"
+ jest-util "^24.8.0"
+ string-length "^2.0.0"
+
+jest-worker@^24.6.0:
+ version "24.6.0"
+ resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-24.6.0.tgz#7f81ceae34b7cde0c9827a6980c35b7cdc0161b3"
+ integrity sha512-jDwgW5W9qGNvpI1tNnvajh0a5IE/PuGLFmHk6aR/BZFz8tSgGw17GsDPXAJ6p91IvYDjOw8GpFbvvZGAK+DPQQ==
+ dependencies:
+ merge-stream "^1.0.1"
+ supports-color "^6.1.0"
+
+jest@^24.6.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/jest/-/jest-24.8.0.tgz#d5dff1984d0d1002196e9b7f12f75af1b2809081"
+ integrity sha512-o0HM90RKFRNWmAWvlyV8i5jGZ97pFwkeVoGvPW1EtLTgJc2+jcuqcbbqcSZLE/3f2S5pt0y2ZBETuhpWNl1Reg==
+ dependencies:
+ import-local "^2.0.0"
+ jest-cli "^24.8.0"
+
+"js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"
+ integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==
+
+jsbn@~0.1.0:
+ version "0.1.1"
+ resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513"
+ integrity sha1-peZUwuWi3rXyAdls77yoDA7y9RM=
+
+jsdom@^11.5.1:
+ version "11.12.0"
+ resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-11.12.0.tgz#1a80d40ddd378a1de59656e9e6dc5a3ba8657bc8"
+ integrity sha512-y8Px43oyiBM13Zc1z780FrfNLJCXTL40EWlty/LXUtcjykRBNgLlCjWXpfSPBl2iv+N7koQN+dvqszHZgT/Fjw==
+ dependencies:
+ abab "^2.0.0"
+ acorn "^5.5.3"
+ acorn-globals "^4.1.0"
+ array-equal "^1.0.0"
+ cssom ">= 0.3.2 < 0.4.0"
+ cssstyle "^1.0.0"
+ data-urls "^1.0.0"
+ domexception "^1.0.1"
+ escodegen "^1.9.1"
+ html-encoding-sniffer "^1.0.2"
+ left-pad "^1.3.0"
+ nwsapi "^2.0.7"
+ parse5 "4.0.0"
+ pn "^1.1.0"
+ request "^2.87.0"
+ request-promise-native "^1.0.5"
+ sax "^1.2.4"
+ symbol-tree "^3.2.2"
+ tough-cookie "^2.3.4"
+ w3c-hr-time "^1.0.1"
+ webidl-conversions "^4.0.2"
+ whatwg-encoding "^1.0.3"
+ whatwg-mimetype "^2.1.0"
+ whatwg-url "^6.4.1"
+ ws "^5.2.0"
+ xml-name-validator "^3.0.0"
+
+jsesc@^2.5.1:
+ version "2.5.2"
+ resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-2.5.2.tgz#80564d2e483dacf6e8ef209650a67df3f0c283a4"
+ integrity sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==
+
+json-parse-better-errors@^1.0.1:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9"
+ integrity sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==
+
+json-schema-traverse@^0.4.1:
+ version "0.4.1"
+ resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660"
+ integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==
+
+json-schema@0.2.3:
+ version "0.2.3"
+ resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13"
+ integrity sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=
+
+json-stringify-safe@~5.0.1:
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb"
+ integrity sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=
+
+json5@^2.1.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/json5/-/json5-2.1.0.tgz#e7a0c62c48285c628d20a10b85c89bb807c32850"
+ integrity sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==
+ dependencies:
+ minimist "^1.2.0"
+
+jsprim@^1.2.2:
+ version "1.4.1"
+ resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2"
+ integrity sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=
+ dependencies:
+ assert-plus "1.0.0"
+ extsprintf "1.3.0"
+ json-schema "0.2.3"
+ verror "1.10.0"
+
+kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0:
+ version "3.2.2"
+ resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64"
+ integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=
+ dependencies:
+ is-buffer "^1.1.5"
+
+kind-of@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57"
+ integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc=
+ dependencies:
+ is-buffer "^1.1.5"
+
+kind-of@^5.0.0:
+ version "5.1.0"
+ resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d"
+ integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==
+
+kind-of@^6.0.0, kind-of@^6.0.2:
+ version "6.0.2"
+ resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.2.tgz#01146b36a6218e64e58f3a8d66de5d7fc6f6d051"
+ integrity sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==
+
+kleur@^3.0.2:
+ version "3.0.3"
+ resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e"
+ integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==
+
+lcid@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/lcid/-/lcid-2.0.0.tgz#6ef5d2df60e52f82eb228a4c373e8d1f397253cf"
+ integrity sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==
+ dependencies:
+ invert-kv "^2.0.0"
+
+left-pad@^1.3.0:
+ version "1.3.0"
+ resolved "https://registry.yarnpkg.com/left-pad/-/left-pad-1.3.0.tgz#5b8a3a7765dfe001261dde915589e782f8c94d1e"
+ integrity sha512-XI5MPzVNApjAyhQzphX8BkmKsKUxD4LdyK24iZeQGinBN9yTQT3bFlCBy/aVx2HrNcqQGsdot8ghrjyrvMCoEA==
+
+leven@^2.1.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/leven/-/leven-2.1.0.tgz#c2e7a9f772094dee9d34202ae8acce4687875580"
+ integrity sha1-wuep93IJTe6dNCAq6KzORoeHVYA=
+
+levn@~0.3.0:
+ version "0.3.0"
+ resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee"
+ integrity sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=
+ dependencies:
+ prelude-ls "~1.1.2"
+ type-check "~0.3.2"
+
+load-json-file@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-4.0.0.tgz#2f5f45ab91e33216234fd53adab668eb4ec0993b"
+ integrity sha1-L19Fq5HjMhYjT9U62rZo607AmTs=
+ dependencies:
+ graceful-fs "^4.1.2"
+ parse-json "^4.0.0"
+ pify "^3.0.0"
+ strip-bom "^3.0.0"
+
+locate-path@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-3.0.0.tgz#dbec3b3ab759758071b58fe59fc41871af21400e"
+ integrity sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==
+ dependencies:
+ p-locate "^3.0.0"
+ path-exists "^3.0.0"
+
+lodash.sortby@^4.7.0:
+ version "4.7.0"
+ resolved "https://registry.yarnpkg.com/lodash.sortby/-/lodash.sortby-4.7.0.tgz#edd14c824e2cc9c1e0b0a1b42bb5210516a42438"
+ integrity sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=
+
+lodash@^4.17.11, lodash@^4.17.13:
+ version "4.17.14"
+ resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.14.tgz#9ce487ae66c96254fe20b599f21b6816028078ba"
+ integrity sha512-mmKYbW3GLuJeX+iGP+Y7Gp1AiGHGbXHCOh/jZmrawMmsE7MS4znI3RL2FsjbqOyMayHInjOeykW7PEajUk1/xw==
+
+loose-envify@^1.0.0:
+ version "1.4.0"
+ resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf"
+ integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==
+ dependencies:
+ js-tokens "^3.0.0 || ^4.0.0"
+
+make-dir@^2.1.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-2.1.0.tgz#5f0310e18b8be898cc07009295a30ae41e91e6f5"
+ integrity sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==
+ dependencies:
+ pify "^4.0.1"
+ semver "^5.6.0"
+
+makeerror@1.0.x:
+ version "1.0.11"
+ resolved "https://registry.yarnpkg.com/makeerror/-/makeerror-1.0.11.tgz#e01a5c9109f2af79660e4e8b9587790184f5a96c"
+ integrity sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw=
+ dependencies:
+ tmpl "1.0.x"
+
+map-age-cleaner@^0.1.1:
+ version "0.1.3"
+ resolved "https://registry.yarnpkg.com/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz#7d583a7306434c055fe474b0f45078e6e1b4b92a"
+ integrity sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==
+ dependencies:
+ p-defer "^1.0.0"
+
+map-cache@^0.2.2:
+ version "0.2.2"
+ resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf"
+ integrity sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=
+
+map-visit@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/map-visit/-/map-visit-1.0.0.tgz#ecdca8f13144e660f1b5bd41f12f3479d98dfb8f"
+ integrity sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=
+ dependencies:
+ object-visit "^1.0.0"
+
+mem@^4.0.0:
+ version "4.3.0"
+ resolved "https://registry.yarnpkg.com/mem/-/mem-4.3.0.tgz#461af497bc4ae09608cdb2e60eefb69bff744178"
+ integrity sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w==
+ dependencies:
+ map-age-cleaner "^0.1.1"
+ mimic-fn "^2.0.0"
+ p-is-promise "^2.0.0"
+
+merge-stream@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-1.0.1.tgz#4041202d508a342ba00174008df0c251b8c135e1"
+ integrity sha1-QEEgLVCKNCugAXQAjfDCUbjBNeE=
+ dependencies:
+ readable-stream "^2.0.1"
+
+micromatch@^3.1.10, micromatch@^3.1.4:
+ version "3.1.10"
+ resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23"
+ integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==
+ dependencies:
+ arr-diff "^4.0.0"
+ array-unique "^0.3.2"
+ braces "^2.3.1"
+ define-property "^2.0.2"
+ extend-shallow "^3.0.2"
+ extglob "^2.0.4"
+ fragment-cache "^0.2.1"
+ kind-of "^6.0.2"
+ nanomatch "^1.2.9"
+ object.pick "^1.3.0"
+ regex-not "^1.0.0"
+ snapdragon "^0.8.1"
+ to-regex "^3.0.2"
+
+mime-db@1.40.0:
+ version "1.40.0"
+ resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.40.0.tgz#a65057e998db090f732a68f6c276d387d4126c32"
+ integrity sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA==
+
+mime-types@^2.1.12, mime-types@~2.1.19:
+ version "2.1.24"
+ resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.24.tgz#b6f8d0b3e951efb77dedeca194cff6d16f676f81"
+ integrity sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==
+ dependencies:
+ mime-db "1.40.0"
+
+mimic-fn@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b"
+ integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==
+
+minimatch@^3.0.4:
+ version "3.0.4"
+ resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"
+ integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==
+ dependencies:
+ brace-expansion "^1.1.7"
+
+minimist@0.0.8:
+ version "0.0.8"
+ resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d"
+ integrity sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=
+
+minimist@^1.1.1, minimist@^1.2.0:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284"
+ integrity sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=
+
+minimist@~0.0.1:
+ version "0.0.10"
+ resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf"
+ integrity sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=
+
+minipass@^2.2.1, minipass@^2.3.5:
+ version "2.3.5"
+ resolved "https://registry.yarnpkg.com/minipass/-/minipass-2.3.5.tgz#cacebe492022497f656b0f0f51e2682a9ed2d848"
+ integrity sha512-Gi1W4k059gyRbyVUZQ4mEqLm0YIUiGYfvxhF6SIlk3ui1WVxMTGfGdQ2SInh3PDrRTVvPKgULkpJtT4RH10+VA==
+ dependencies:
+ safe-buffer "^5.1.2"
+ yallist "^3.0.0"
+
+minizlib@^1.2.1:
+ version "1.2.1"
+ resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-1.2.1.tgz#dd27ea6136243c7c880684e8672bb3a45fd9b614"
+ integrity sha512-7+4oTUOWKg7AuL3vloEWekXY2/D20cevzsrNT2kGWm+39J9hGTCBv8VI5Pm5lXZ/o3/mdR4f8rflAPhnQb8mPA==
+ dependencies:
+ minipass "^2.2.1"
+
+mixin-deep@^1.2.0:
+ version "1.3.2"
+ resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566"
+ integrity sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==
+ dependencies:
+ for-in "^1.0.2"
+ is-extendable "^1.0.1"
+
+mkdirp@^0.5.0, mkdirp@^0.5.1:
+ version "0.5.1"
+ resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903"
+ integrity sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=
+ dependencies:
+ minimist "0.0.8"
+
+ms@2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
+ integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=
+
+ms@^2.1.1:
+ version "2.1.2"
+ resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
+ integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==
+
+nan@^2.12.1:
+ version "2.14.0"
+ resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.0.tgz#7818f722027b2459a86f0295d434d1fc2336c52c"
+ integrity sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==
+
+nanomatch@^1.2.9:
+ version "1.2.13"
+ resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119"
+ integrity sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==
+ dependencies:
+ arr-diff "^4.0.0"
+ array-unique "^0.3.2"
+ define-property "^2.0.2"
+ extend-shallow "^3.0.2"
+ fragment-cache "^0.2.1"
+ is-windows "^1.0.2"
+ kind-of "^6.0.2"
+ object.pick "^1.3.0"
+ regex-not "^1.0.0"
+ snapdragon "^0.8.1"
+ to-regex "^3.0.1"
+
+natural-compare@^1.4.0:
+ version "1.4.0"
+ resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"
+ integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=
+
+needle@^2.2.1:
+ version "2.4.0"
+ resolved "https://registry.yarnpkg.com/needle/-/needle-2.4.0.tgz#6833e74975c444642590e15a750288c5f939b57c"
+ integrity sha512-4Hnwzr3mi5L97hMYeNl8wRW/Onhy4nUKR/lVemJ8gJedxxUyBLm9kkrDColJvoSfwi0jCNhD+xCdOtiGDQiRZg==
+ dependencies:
+ debug "^3.2.6"
+ iconv-lite "^0.4.4"
+ sax "^1.2.4"
+
+neo-async@^2.6.0:
+ version "2.6.1"
+ resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.1.tgz#ac27ada66167fa8849a6addd837f6b189ad2081c"
+ integrity sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw==
+
+nice-try@^1.0.4:
+ version "1.0.5"
+ resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366"
+ integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==
+
+node-int64@^0.4.0:
+ version "0.4.0"
+ resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b"
+ integrity sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs=
+
+node-modules-regexp@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz#8d9dbe28964a4ac5712e9131642107c71e90ec40"
+ integrity sha1-jZ2+KJZKSsVxLpExZCEHxx6Q7EA=
+
+node-notifier@^5.2.1:
+ version "5.4.0"
+ resolved "https://registry.yarnpkg.com/node-notifier/-/node-notifier-5.4.0.tgz#7b455fdce9f7de0c63538297354f3db468426e6a"
+ integrity sha512-SUDEb+o71XR5lXSTyivXd9J7fCloE3SyP4lSgt3lU2oSANiox+SxlNRGPjDKrwU1YN3ix2KN/VGGCg0t01rttQ==
+ dependencies:
+ growly "^1.3.0"
+ is-wsl "^1.1.0"
+ semver "^5.5.0"
+ shellwords "^0.1.1"
+ which "^1.3.0"
+
+node-pre-gyp@^0.12.0:
+ version "0.12.0"
+ resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.12.0.tgz#39ba4bb1439da030295f899e3b520b7785766149"
+ integrity sha512-4KghwV8vH5k+g2ylT+sLTjy5wmUOb9vPhnM8NHvRf9dHmnW/CndrFXy2aRPaPST6dugXSdHXfeaHQm77PIz/1A==
+ dependencies:
+ detect-libc "^1.0.2"
+ mkdirp "^0.5.1"
+ needle "^2.2.1"
+ nopt "^4.0.1"
+ npm-packlist "^1.1.6"
+ npmlog "^4.0.2"
+ rc "^1.2.7"
+ rimraf "^2.6.1"
+ semver "^5.3.0"
+ tar "^4"
+
+nopt@^4.0.1:
+ version "4.0.1"
+ resolved "https://registry.yarnpkg.com/nopt/-/nopt-4.0.1.tgz#d0d4685afd5415193c8c7505602d0d17cd64474d"
+ integrity sha1-0NRoWv1UFRk8jHUFYC0NF81kR00=
+ dependencies:
+ abbrev "1"
+ osenv "^0.1.4"
+
+normalize-package-data@^2.3.2:
+ version "2.5.0"
+ resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8"
+ integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==
+ dependencies:
+ hosted-git-info "^2.1.4"
+ resolve "^1.10.0"
+ semver "2 || 3 || 4 || 5"
+ validate-npm-package-license "^3.0.1"
+
+normalize-path@^2.1.1:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9"
+ integrity sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=
+ dependencies:
+ remove-trailing-separator "^1.0.1"
+
+npm-bundled@^1.0.1:
+ version "1.0.6"
+ resolved "https://registry.yarnpkg.com/npm-bundled/-/npm-bundled-1.0.6.tgz#e7ba9aadcef962bb61248f91721cd932b3fe6bdd"
+ integrity sha512-8/JCaftHwbd//k6y2rEWp6k1wxVfpFzB6t1p825+cUb7Ym2XQfhwIC5KwhrvzZRJu+LtDE585zVaS32+CGtf0g==
+
+npm-packlist@^1.1.6:
+ version "1.4.4"
+ resolved "https://registry.yarnpkg.com/npm-packlist/-/npm-packlist-1.4.4.tgz#866224233850ac534b63d1a6e76050092b5d2f44"
+ integrity sha512-zTLo8UcVYtDU3gdeaFu2Xu0n0EvelfHDGuqtNIn5RO7yQj4H1TqNdBc/yZjxnWA0PVB8D3Woyp0i5B43JwQ6Vw==
+ dependencies:
+ ignore-walk "^3.0.1"
+ npm-bundled "^1.0.1"
+
+npm-run-path@^2.0.0:
+ version "2.0.2"
+ resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-2.0.2.tgz#35a9232dfa35d7067b4cb2ddf2357b1871536c5f"
+ integrity sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=
+ dependencies:
+ path-key "^2.0.0"
+
+npmlog@^4.0.2:
+ version "4.1.2"
+ resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-4.1.2.tgz#08a7f2a8bf734604779a9efa4ad5cc717abb954b"
+ integrity sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==
+ dependencies:
+ are-we-there-yet "~1.1.2"
+ console-control-strings "~1.1.0"
+ gauge "~2.7.3"
+ set-blocking "~2.0.0"
+
+number-is-nan@^1.0.0:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d"
+ integrity sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=
+
+nwsapi@^2.0.7:
+ version "2.1.4"
+ resolved "https://registry.yarnpkg.com/nwsapi/-/nwsapi-2.1.4.tgz#e006a878db23636f8e8a67d33ca0e4edf61a842f"
+ integrity sha512-iGfd9Y6SFdTNldEy2L0GUhcarIutFmk+MPWIn9dmj8NMIup03G08uUF2KGbbmv/Ux4RT0VZJoP/sVbWA6d/VIw==
+
+oauth-sign@~0.9.0:
+ version "0.9.0"
+ resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.9.0.tgz#47a7b016baa68b5fa0ecf3dee08a85c679ac6455"
+ integrity sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==
+
+object-assign@^4.1.0:
+ version "4.1.1"
+ resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863"
+ integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=
+
+object-copy@^0.1.0:
+ version "0.1.0"
+ resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c"
+ integrity sha1-fn2Fi3gb18mRpBupde04EnVOmYw=
+ dependencies:
+ copy-descriptor "^0.1.0"
+ define-property "^0.2.5"
+ kind-of "^3.0.3"
+
+object-keys@^1.0.12:
+ version "1.1.1"
+ resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e"
+ integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==
+
+object-visit@^1.0.0:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb"
+ integrity sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=
+ dependencies:
+ isobject "^3.0.0"
+
+object.getownpropertydescriptors@^2.0.3:
+ version "2.0.3"
+ resolved "https://registry.yarnpkg.com/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz#8758c846f5b407adab0f236e0986f14b051caa16"
+ integrity sha1-h1jIRvW0B62rDyNuCYbxSwUcqhY=
+ dependencies:
+ define-properties "^1.1.2"
+ es-abstract "^1.5.1"
+
+object.pick@^1.3.0:
+ version "1.3.0"
+ resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747"
+ integrity sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=
+ dependencies:
+ isobject "^3.0.1"
+
+once@^1.3.0, once@^1.3.1, once@^1.4.0:
+ version "1.4.0"
+ resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"
+ integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E=
+ dependencies:
+ wrappy "1"
+
+optimist@^0.6.1:
+ version "0.6.1"
+ resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686"
+ integrity sha1-2j6nRob6IaGaERwybpDrFaAZZoY=
+ dependencies:
+ minimist "~0.0.1"
+ wordwrap "~0.0.2"
+
+optionator@^0.8.1:
+ version "0.8.2"
+ resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.2.tgz#364c5e409d3f4d6301d6c0b4c05bba50180aeb64"
+ integrity sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=
+ dependencies:
+ deep-is "~0.1.3"
+ fast-levenshtein "~2.0.4"
+ levn "~0.3.0"
+ prelude-ls "~1.1.2"
+ type-check "~0.3.2"
+ wordwrap "~1.0.0"
+
+os-homedir@^1.0.0:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3"
+ integrity sha1-/7xJiDNuDoM94MFox+8VISGqf7M=
+
+os-locale@^3.0.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-3.1.0.tgz#a802a6ee17f24c10483ab9935719cef4ed16bf1a"
+ integrity sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==
+ dependencies:
+ execa "^1.0.0"
+ lcid "^2.0.0"
+ mem "^4.0.0"
+
+os-tmpdir@^1.0.0:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274"
+ integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=
+
+osenv@^0.1.4:
+ version "0.1.5"
+ resolved "https://registry.yarnpkg.com/osenv/-/osenv-0.1.5.tgz#85cdfafaeb28e8677f416e287592b5f3f49ea410"
+ integrity sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==
+ dependencies:
+ os-homedir "^1.0.0"
+ os-tmpdir "^1.0.0"
+
+p-defer@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/p-defer/-/p-defer-1.0.0.tgz#9f6eb182f6c9aa8cd743004a7d4f96b196b0fb0c"
+ integrity sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=
+
+p-each-series@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/p-each-series/-/p-each-series-1.0.0.tgz#930f3d12dd1f50e7434457a22cd6f04ac6ad7f71"
+ integrity sha1-kw89Et0fUOdDRFeiLNbwSsatf3E=
+ dependencies:
+ p-reduce "^1.0.0"
+
+p-finally@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/p-finally/-/p-finally-1.0.0.tgz#3fbcfb15b899a44123b34b6dcc18b724336a2cae"
+ integrity sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=
+
+p-is-promise@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/p-is-promise/-/p-is-promise-2.1.0.tgz#918cebaea248a62cf7ffab8e3bca8c5f882fc42e"
+ integrity sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg==
+
+p-limit@^2.0.0:
+ version "2.2.0"
+ resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.2.0.tgz#417c9941e6027a9abcba5092dd2904e255b5fbc2"
+ integrity sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==
+ dependencies:
+ p-try "^2.0.0"
+
+p-locate@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-3.0.0.tgz#322d69a05c0264b25997d9f40cd8a891ab0064a4"
+ integrity sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==
+ dependencies:
+ p-limit "^2.0.0"
+
+p-reduce@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/p-reduce/-/p-reduce-1.0.0.tgz#18c2b0dd936a4690a529f8231f58a0fdb6a47dfa"
+ integrity sha1-GMKw3ZNqRpClKfgjH1ig/bakffo=
+
+p-try@^2.0.0:
+ version "2.2.0"
+ resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6"
+ integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==
+
+parse-json@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-4.0.0.tgz#be35f5425be1f7f6c747184f98a788cb99477ee0"
+ integrity sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=
+ dependencies:
+ error-ex "^1.3.1"
+ json-parse-better-errors "^1.0.1"
+
+parse5@4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/parse5/-/parse5-4.0.0.tgz#6d78656e3da8d78b4ec0b906f7c08ef1dfe3f608"
+ integrity sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==
+
+pascalcase@^0.1.1:
+ version "0.1.1"
+ resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14"
+ integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=
+
+path-exists@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515"
+ integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=
+
+path-is-absolute@^1.0.0:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f"
+ integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18=
+
+path-key@^2.0.0, path-key@^2.0.1:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40"
+ integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=
+
+path-parse@^1.0.6:
+ version "1.0.6"
+ resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c"
+ integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==
+
+path-type@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/path-type/-/path-type-3.0.0.tgz#cef31dc8e0a1a3bb0d105c0cd97cf3bf47f4e36f"
+ integrity sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==
+ dependencies:
+ pify "^3.0.0"
+
+performance-now@^2.1.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b"
+ integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=
+
+pify@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/pify/-/pify-3.0.0.tgz#e5a4acd2c101fdf3d9a4d07f0dbc4db49dd28176"
+ integrity sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=
+
+pify@^4.0.1:
+ version "4.0.1"
+ resolved "https://registry.yarnpkg.com/pify/-/pify-4.0.1.tgz#4b2cd25c50d598735c50292224fd8c6df41e3231"
+ integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==
+
+pirates@^4.0.1:
+ version "4.0.1"
+ resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.1.tgz#643a92caf894566f91b2b986d2c66950a8e2fb87"
+ integrity sha512-WuNqLTbMI3tmfef2TKxlQmAiLHKtFhlsCZnPIpuv2Ow0RDVO8lfy1Opf4NUzlMXLjPl+Men7AuVdX6TA+s+uGA==
+ dependencies:
+ node-modules-regexp "^1.0.0"
+
+pkg-dir@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-3.0.0.tgz#2749020f239ed990881b1f71210d51eb6523bea3"
+ integrity sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==
+ dependencies:
+ find-up "^3.0.0"
+
+pn@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/pn/-/pn-1.1.0.tgz#e2f4cef0e219f463c179ab37463e4e1ecdccbafb"
+ integrity sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA==
+
+posix-character-classes@^0.1.0:
+ version "0.1.1"
+ resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab"
+ integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=
+
+prelude-ls@~1.1.2:
+ version "1.1.2"
+ resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54"
+ integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=
+
+pretty-format@^24.8.0:
+ version "24.8.0"
+ resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-24.8.0.tgz#8dae7044f58db7cb8be245383b565a963e3c27f2"
+ integrity sha512-P952T7dkrDEplsR+TuY7q3VXDae5Sr7zmQb12JU/NDQa/3CH7/QW0yvqLcGN6jL+zQFKaoJcPc+yJxMTGmosqw==
+ dependencies:
+ "@jest/types" "^24.8.0"
+ ansi-regex "^4.0.0"
+ ansi-styles "^3.2.0"
+ react-is "^16.8.4"
+
+process-nextick-args@~2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa"
+ integrity sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==
+
+prompts@^2.0.1:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/prompts/-/prompts-2.1.0.tgz#bf90bc71f6065d255ea2bdc0fe6520485c1b45db"
+ integrity sha512-+x5TozgqYdOwWsQFZizE/Tra3fKvAoy037kOyU6cgz84n8f6zxngLOV4O32kTwt9FcLCxAqw0P/c8rOr9y+Gfg==
+ dependencies:
+ kleur "^3.0.2"
+ sisteransi "^1.0.0"
+
+psl@^1.1.24, psl@^1.1.28:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/psl/-/psl-1.2.0.tgz#df12b5b1b3a30f51c329eacbdef98f3a6e136dc6"
+ integrity sha512-GEn74ZffufCmkDDLNcl3uuyF/aSD6exEyh1v/ZSdAomB82t6G9hzJVRx0jBmLDW+VfZqks3aScmMw9DszwUalA==
+
+pump@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64"
+ integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==
+ dependencies:
+ end-of-stream "^1.1.0"
+ once "^1.3.1"
+
+punycode@^1.4.1:
+ version "1.4.1"
+ resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e"
+ integrity sha1-wNWmOycYgArY4esPpSachN1BhF4=
+
+punycode@^2.1.0, punycode@^2.1.1:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec"
+ integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==
+
+qs@~6.5.2:
+ version "6.5.2"
+ resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.2.tgz#cb3ae806e8740444584ef154ce8ee98d403f3e36"
+ integrity sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==
+
+rc@^1.2.7:
+ version "1.2.8"
+ resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.8.tgz#cd924bf5200a075b83c188cd6b9e211b7fc0d3ed"
+ integrity sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==
+ dependencies:
+ deep-extend "^0.6.0"
+ ini "~1.3.0"
+ minimist "^1.2.0"
+ strip-json-comments "~2.0.1"
+
+react-is@^16.8.4:
+ version "16.8.6"
+ resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.6.tgz#5bbc1e2d29141c9fbdfed456343fe2bc430a6a16"
+ integrity sha512-aUk3bHfZ2bRSVFFbbeVS4i+lNPZr3/WM5jT2J5omUVV1zzcs1nAaf3l51ctA5FFvCRbhrH0bdAsRRQddFJZPtA==
+
+read-pkg-up@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-4.0.0.tgz#1b221c6088ba7799601c808f91161c66e58f8978"
+ integrity sha512-6etQSH7nJGsK0RbG/2TeDzZFa8shjQ1um+SwQQ5cwKy0dhSXdOncEhb1CPpvQG4h7FyOV6EB6YlV0yJvZQNAkA==
+ dependencies:
+ find-up "^3.0.0"
+ read-pkg "^3.0.0"
+
+read-pkg@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-3.0.0.tgz#9cbc686978fee65d16c00e2b19c237fcf6e38389"
+ integrity sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=
+ dependencies:
+ load-json-file "^4.0.0"
+ normalize-package-data "^2.3.2"
+ path-type "^3.0.0"
+
+readable-stream@^2.0.1, readable-stream@^2.0.6:
+ version "2.3.6"
+ resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf"
+ integrity sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==
+ dependencies:
+ core-util-is "~1.0.0"
+ inherits "~2.0.3"
+ isarray "~1.0.0"
+ process-nextick-args "~2.0.0"
+ safe-buffer "~5.1.1"
+ string_decoder "~1.1.1"
+ util-deprecate "~1.0.1"
+
+realpath-native@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/realpath-native/-/realpath-native-1.1.0.tgz#2003294fea23fb0672f2476ebe22fcf498a2d65c"
+ integrity sha512-wlgPA6cCIIg9gKz0fgAPjnzh4yR/LnXovwuo9hvyGvx3h8nX4+/iLZplfUWasXpqD8BdnGnP5njOFjkUwPzvjA==
+ dependencies:
+ util.promisify "^1.0.0"
+
+regex-not@^1.0.0, regex-not@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c"
+ integrity sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==
+ dependencies:
+ extend-shallow "^3.0.2"
+ safe-regex "^1.1.0"
+
+remove-trailing-separator@^1.0.1:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef"
+ integrity sha1-wkvOKig62tW8P1jg1IJJuSN52O8=
+
+repeat-element@^1.1.2:
+ version "1.1.3"
+ resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.3.tgz#782e0d825c0c5a3bb39731f84efee6b742e6b1ce"
+ integrity sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==
+
+repeat-string@^1.6.1:
+ version "1.6.1"
+ resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637"
+ integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc=
+
+request-promise-core@1.1.2:
+ version "1.1.2"
+ resolved "https://registry.yarnpkg.com/request-promise-core/-/request-promise-core-1.1.2.tgz#339f6aababcafdb31c799ff158700336301d3346"
+ integrity sha512-UHYyq1MO8GsefGEt7EprS8UrXsm1TxEvFUX1IMTuSLU2Rh7fTIdFtl8xD7JiEYiWU2dl+NYAjCTksTehQUxPag==
+ dependencies:
+ lodash "^4.17.11"
+
+request-promise-native@^1.0.5:
+ version "1.0.7"
+ resolved "https://registry.yarnpkg.com/request-promise-native/-/request-promise-native-1.0.7.tgz#a49868a624bdea5069f1251d0a836e0d89aa2c59"
+ integrity sha512-rIMnbBdgNViL37nZ1b3L/VfPOpSi0TqVDQPAvO6U14lMzOLrt5nilxCQqtDKhZeDiW0/hkCXGoQjhgJd/tCh6w==
+ dependencies:
+ request-promise-core "1.1.2"
+ stealthy-require "^1.1.1"
+ tough-cookie "^2.3.3"
+
+request@^2.87.0:
+ version "2.88.0"
+ resolved "https://registry.yarnpkg.com/request/-/request-2.88.0.tgz#9c2fca4f7d35b592efe57c7f0a55e81052124fef"
+ integrity sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg==
+ dependencies:
+ aws-sign2 "~0.7.0"
+ aws4 "^1.8.0"
+ caseless "~0.12.0"
+ combined-stream "~1.0.6"
+ extend "~3.0.2"
+ forever-agent "~0.6.1"
+ form-data "~2.3.2"
+ har-validator "~5.1.0"
+ http-signature "~1.2.0"
+ is-typedarray "~1.0.0"
+ isstream "~0.1.2"
+ json-stringify-safe "~5.0.1"
+ mime-types "~2.1.19"
+ oauth-sign "~0.9.0"
+ performance-now "^2.1.0"
+ qs "~6.5.2"
+ safe-buffer "^5.1.2"
+ tough-cookie "~2.4.3"
+ tunnel-agent "^0.6.0"
+ uuid "^3.3.2"
+
+require-directory@^2.1.1:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42"
+ integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I=
+
+require-main-filename@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1"
+ integrity sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=
+
+require-main-filename@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b"
+ integrity sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==
+
+resolve-cwd@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-2.0.0.tgz#00a9f7387556e27038eae232caa372a6a59b665a"
+ integrity sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=
+ dependencies:
+ resolve-from "^3.0.0"
+
+resolve-from@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-3.0.0.tgz#b22c7af7d9d6881bc8b6e653335eebcb0a188748"
+ integrity sha1-six699nWiBvItuZTM17rywoYh0g=
+
+resolve-url@^0.2.1:
+ version "0.2.1"
+ resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a"
+ integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=
+
+resolve@1.1.7:
+ version "1.1.7"
+ resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b"
+ integrity sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs=
+
+resolve@^1.10.0, resolve@^1.3.2:
+ version "1.11.1"
+ resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.11.1.tgz#ea10d8110376982fef578df8fc30b9ac30a07a3e"
+ integrity sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw==
+ dependencies:
+ path-parse "^1.0.6"
+
+ret@~0.1.10:
+ version "0.1.15"
+ resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc"
+ integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==
+
+rimraf@^2.5.4, rimraf@^2.6.1, rimraf@^2.6.3:
+ version "2.6.3"
+ resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab"
+ integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==
+ dependencies:
+ glob "^7.1.3"
+
+rsvp@^4.8.4:
+ version "4.8.5"
+ resolved "https://registry.yarnpkg.com/rsvp/-/rsvp-4.8.5.tgz#c8f155311d167f68f21e168df71ec5b083113734"
+ integrity sha512-nfMOlASu9OnRJo1mbEk2cz0D56a1MBNrJ7orjRZQG10XDyuvwksKbuXNp6qa+kbn839HwjwhBzhFmdsaEAfauA==
+
+safe-buffer@^5.0.1, safe-buffer@^5.1.2:
+ version "5.2.0"
+ resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.0.tgz#b74daec49b1148f88c64b68d49b1e815c1f2f519"
+ integrity sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==
+
+safe-buffer@~5.1.0, safe-buffer@~5.1.1:
+ version "5.1.2"
+ resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"
+ integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==
+
+safe-regex@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-1.1.0.tgz#40a3669f3b077d1e943d44629e157dd48023bf2e"
+ integrity sha1-QKNmnzsHfR6UPURinhV91IAjvy4=
+ dependencies:
+ ret "~0.1.10"
+
+"safer-buffer@>= 2.1.2 < 3", safer-buffer@^2.0.2, safer-buffer@^2.1.0, safer-buffer@~2.1.0:
+ version "2.1.2"
+ resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a"
+ integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==
+
+sane@^4.0.3:
+ version "4.1.0"
+ resolved "https://registry.yarnpkg.com/sane/-/sane-4.1.0.tgz#ed881fd922733a6c461bc189dc2b6c006f3ffded"
+ integrity sha512-hhbzAgTIX8O7SHfp2c8/kREfEn4qO/9q8C9beyY6+tvZ87EpoZ3i1RIEvp27YBswnNbY9mWd6paKVmKbAgLfZA==
+ dependencies:
+ "@cnakazawa/watch" "^1.0.3"
+ anymatch "^2.0.0"
+ capture-exit "^2.0.0"
+ exec-sh "^0.3.2"
+ execa "^1.0.0"
+ fb-watchman "^2.0.0"
+ micromatch "^3.1.4"
+ minimist "^1.1.1"
+ walker "~1.0.5"
+
+sax@^1.2.4:
+ version "1.2.4"
+ resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9"
+ integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==
+
+"semver@2 || 3 || 4 || 5", semver@^5.3.0, semver@^5.4.1, semver@^5.5.0, semver@^5.6.0:
+ version "5.7.0"
+ resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.0.tgz#790a7cf6fea5459bac96110b29b60412dc8ff96b"
+ integrity sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==
+
+semver@^6.0.0:
+ version "6.2.0"
+ resolved "https://registry.yarnpkg.com/semver/-/semver-6.2.0.tgz#4d813d9590aaf8a9192693d6c85b9344de5901db"
+ integrity sha512-jdFC1VdUGT/2Scgbimf7FSx9iJLXoqfglSF+gJeuNWVpiE37OIbc1jywR/GJyFdz3mnkz2/id0L0J/cr0izR5A==
+
+set-blocking@^2.0.0, set-blocking@~2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7"
+ integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc=
+
+set-value@^2.0.0, set-value@^2.0.1:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/set-value/-/set-value-2.0.1.tgz#a18d40530e6f07de4228c7defe4227af8cad005b"
+ integrity sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==
+ dependencies:
+ extend-shallow "^2.0.1"
+ is-extendable "^0.1.1"
+ is-plain-object "^2.0.3"
+ split-string "^3.0.1"
+
+shebang-command@^1.2.0:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea"
+ integrity sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=
+ dependencies:
+ shebang-regex "^1.0.0"
+
+shebang-regex@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3"
+ integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=
+
+shellwords@^0.1.1:
+ version "0.1.1"
+ resolved "https://registry.yarnpkg.com/shellwords/-/shellwords-0.1.1.tgz#d6b9181c1a48d397324c84871efbcfc73fc0654b"
+ integrity sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww==
+
+signal-exit@^3.0.0, signal-exit@^3.0.2:
+ version "3.0.2"
+ resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d"
+ integrity sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=
+
+sisteransi@^1.0.0:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/sisteransi/-/sisteransi-1.0.2.tgz#ec57d64b6f25c4f26c0e2c7dd23f2d7f12f7e418"
+ integrity sha512-ZcYcZcT69nSLAR2oLN2JwNmLkJEKGooFMCdvOkFrToUt/WfcRWqhIg4P4KwY4dmLbuyXIx4o4YmPsvMRJYJd/w==
+
+slash@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/slash/-/slash-2.0.0.tgz#de552851a1759df3a8f206535442f5ec4ddeab44"
+ integrity sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==
+
+snapdragon-node@^2.0.1:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/snapdragon-node/-/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b"
+ integrity sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==
+ dependencies:
+ define-property "^1.0.0"
+ isobject "^3.0.0"
+ snapdragon-util "^3.0.1"
+
+snapdragon-util@^3.0.1:
+ version "3.0.1"
+ resolved "https://registry.yarnpkg.com/snapdragon-util/-/snapdragon-util-3.0.1.tgz#f956479486f2acd79700693f6f7b805e45ab56e2"
+ integrity sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==
+ dependencies:
+ kind-of "^3.2.0"
+
+snapdragon@^0.8.1:
+ version "0.8.2"
+ resolved "https://registry.yarnpkg.com/snapdragon/-/snapdragon-0.8.2.tgz#64922e7c565b0e14204ba1aa7d6964278d25182d"
+ integrity sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==
+ dependencies:
+ base "^0.11.1"
+ debug "^2.2.0"
+ define-property "^0.2.5"
+ extend-shallow "^2.0.1"
+ map-cache "^0.2.2"
+ source-map "^0.5.6"
+ source-map-resolve "^0.5.0"
+ use "^3.1.0"
+
+source-map-resolve@^0.5.0:
+ version "0.5.2"
+ resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.2.tgz#72e2cc34095543e43b2c62b2c4c10d4a9054f259"
+ integrity sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==
+ dependencies:
+ atob "^2.1.1"
+ decode-uri-component "^0.2.0"
+ resolve-url "^0.2.1"
+ source-map-url "^0.4.0"
+ urix "^0.1.0"
+
+source-map-support@^0.5.6:
+ version "0.5.12"
+ resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.12.tgz#b4f3b10d51857a5af0138d3ce8003b201613d599"
+ integrity sha512-4h2Pbvyy15EE02G+JOZpUCmqWJuqrs+sEkzewTm++BPi7Hvn/HwcqLAcNxYAyI0x13CpPPn+kMjl+hplXMHITQ==
+ dependencies:
+ buffer-from "^1.0.0"
+ source-map "^0.6.0"
+
+source-map-url@^0.4.0:
+ version "0.4.0"
+ resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3"
+ integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=
+
+source-map@^0.5.0, source-map@^0.5.6:
+ version "0.5.7"
+ resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc"
+ integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=
+
+source-map@^0.6.0, source-map@^0.6.1, source-map@~0.6.1:
+ version "0.6.1"
+ resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"
+ integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==
+
+spdx-correct@^3.0.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.0.tgz#fb83e504445268f154b074e218c87c003cd31df4"
+ integrity sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q==
+ dependencies:
+ spdx-expression-parse "^3.0.0"
+ spdx-license-ids "^3.0.0"
+
+spdx-exceptions@^2.1.0:
+ version "2.2.0"
+ resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz#2ea450aee74f2a89bfb94519c07fcd6f41322977"
+ integrity sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA==
+
+spdx-expression-parse@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz#99e119b7a5da00e05491c9fa338b7904823b41d0"
+ integrity sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==
+ dependencies:
+ spdx-exceptions "^2.1.0"
+ spdx-license-ids "^3.0.0"
+
+spdx-license-ids@^3.0.0:
+ version "3.0.5"
+ resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz#3694b5804567a458d3c8045842a6358632f62654"
+ integrity sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q==
+
+split-string@^3.0.1, split-string@^3.0.2:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2"
+ integrity sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==
+ dependencies:
+ extend-shallow "^3.0.0"
+
+sshpk@^1.7.0:
+ version "1.16.1"
+ resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.16.1.tgz#fb661c0bef29b39db40769ee39fa70093d6f6877"
+ integrity sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==
+ dependencies:
+ asn1 "~0.2.3"
+ assert-plus "^1.0.0"
+ bcrypt-pbkdf "^1.0.0"
+ dashdash "^1.12.0"
+ ecc-jsbn "~0.1.1"
+ getpass "^0.1.1"
+ jsbn "~0.1.0"
+ safer-buffer "^2.0.2"
+ tweetnacl "~0.14.0"
+
+stack-utils@^1.0.1:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/stack-utils/-/stack-utils-1.0.2.tgz#33eba3897788558bebfc2db059dc158ec36cebb8"
+ integrity sha512-MTX+MeG5U994cazkjd/9KNAapsHnibjMLnfXodlkXw76JEea0UiNzrqidzo1emMwk7w5Qhc9jd4Bn9TBb1MFwA==
+
+static-extend@^0.1.1:
+ version "0.1.2"
+ resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6"
+ integrity sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=
+ dependencies:
+ define-property "^0.2.5"
+ object-copy "^0.1.0"
+
+stealthy-require@^1.1.1:
+ version "1.1.1"
+ resolved "https://registry.yarnpkg.com/stealthy-require/-/stealthy-require-1.1.1.tgz#35b09875b4ff49f26a777e509b3090a3226bf24b"
+ integrity sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=
+
+string-length@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/string-length/-/string-length-2.0.0.tgz#d40dbb686a3ace960c1cffca562bf2c45f8363ed"
+ integrity sha1-1A27aGo6zpYMHP/KVivyxF+DY+0=
+ dependencies:
+ astral-regex "^1.0.0"
+ strip-ansi "^4.0.0"
+
+string-width@^1.0.1:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3"
+ integrity sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=
+ dependencies:
+ code-point-at "^1.0.0"
+ is-fullwidth-code-point "^1.0.0"
+ strip-ansi "^3.0.0"
+
+"string-width@^1.0.2 || 2", string-width@^2.0.0, string-width@^2.1.1:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e"
+ integrity sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==
+ dependencies:
+ is-fullwidth-code-point "^2.0.0"
+ strip-ansi "^4.0.0"
+
+string_decoder@~1.1.1:
+ version "1.1.1"
+ resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8"
+ integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==
+ dependencies:
+ safe-buffer "~5.1.0"
+
+strip-ansi@^3.0.0, strip-ansi@^3.0.1:
+ version "3.0.1"
+ resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf"
+ integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=
+ dependencies:
+ ansi-regex "^2.0.0"
+
+strip-ansi@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f"
+ integrity sha1-qEeQIusaw2iocTibY1JixQXuNo8=
+ dependencies:
+ ansi-regex "^3.0.0"
+
+strip-ansi@^5.0.0:
+ version "5.2.0"
+ resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae"
+ integrity sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==
+ dependencies:
+ ansi-regex "^4.1.0"
+
+strip-bom@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3"
+ integrity sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=
+
+strip-eof@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/strip-eof/-/strip-eof-1.0.0.tgz#bb43ff5598a6eb05d89b59fcd129c983313606bf"
+ integrity sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=
+
+strip-json-comments@~2.0.1:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a"
+ integrity sha1-PFMZQukIwml8DsNEhYwobHygpgo=
+
+supports-color@^5.3.0:
+ version "5.5.0"
+ resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f"
+ integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==
+ dependencies:
+ has-flag "^3.0.0"
+
+supports-color@^6.1.0:
+ version "6.1.0"
+ resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-6.1.0.tgz#0764abc69c63d5ac842dd4867e8d025e880df8f3"
+ integrity sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==
+ dependencies:
+ has-flag "^3.0.0"
+
+symbol-tree@^3.2.2:
+ version "3.2.4"
+ resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2"
+ integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==
+
+tar@^4:
+ version "4.4.10"
+ resolved "https://registry.yarnpkg.com/tar/-/tar-4.4.10.tgz#946b2810b9a5e0b26140cf78bea6b0b0d689eba1"
+ integrity sha512-g2SVs5QIxvo6OLp0GudTqEf05maawKUxXru104iaayWA09551tFCTI8f1Asb4lPfkBr91k07iL4c11XO3/b0tA==
+ dependencies:
+ chownr "^1.1.1"
+ fs-minipass "^1.2.5"
+ minipass "^2.3.5"
+ minizlib "^1.2.1"
+ mkdirp "^0.5.0"
+ safe-buffer "^5.1.2"
+ yallist "^3.0.3"
+
+test-exclude@^5.2.3:
+ version "5.2.3"
+ resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-5.2.3.tgz#c3d3e1e311eb7ee405e092dac10aefd09091eac0"
+ integrity sha512-M+oxtseCFO3EDtAaGH7iiej3CBkzXqFMbzqYAACdzKui4eZA+pq3tZEwChvOdNfa7xxy8BfbmgJSIr43cC/+2g==
+ dependencies:
+ glob "^7.1.3"
+ minimatch "^3.0.4"
+ read-pkg-up "^4.0.0"
+ require-main-filename "^2.0.0"
+
+throat@^4.0.0:
+ version "4.1.0"
+ resolved "https://registry.yarnpkg.com/throat/-/throat-4.1.0.tgz#89037cbc92c56ab18926e6ba4cbb200e15672a6a"
+ integrity sha1-iQN8vJLFarGJJua6TLsgDhVnKmo=
+
+tmpl@1.0.x:
+ version "1.0.4"
+ resolved "https://registry.yarnpkg.com/tmpl/-/tmpl-1.0.4.tgz#23640dd7b42d00433911140820e5cf440e521dd1"
+ integrity sha1-I2QN17QtAEM5ERQIIOXPRA5SHdE=
+
+to-fast-properties@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-2.0.0.tgz#dc5e698cbd079265bc73e0377681a4e4e83f616e"
+ integrity sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=
+
+to-object-path@^0.3.0:
+ version "0.3.0"
+ resolved "https://registry.yarnpkg.com/to-object-path/-/to-object-path-0.3.0.tgz#297588b7b0e7e0ac08e04e672f85c1f4999e17af"
+ integrity sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=
+ dependencies:
+ kind-of "^3.0.2"
+
+to-regex-range@^2.1.0:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-2.1.1.tgz#7c80c17b9dfebe599e27367e0d4dd5590141db38"
+ integrity sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=
+ dependencies:
+ is-number "^3.0.0"
+ repeat-string "^1.6.1"
+
+to-regex@^3.0.1, to-regex@^3.0.2:
+ version "3.0.2"
+ resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce"
+ integrity sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==
+ dependencies:
+ define-property "^2.0.2"
+ extend-shallow "^3.0.2"
+ regex-not "^1.0.2"
+ safe-regex "^1.1.0"
+
+tough-cookie@^2.3.3, tough-cookie@^2.3.4:
+ version "2.5.0"
+ resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.5.0.tgz#cd9fb2a0aa1d5a12b473bd9fb96fa3dcff65ade2"
+ integrity sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==
+ dependencies:
+ psl "^1.1.28"
+ punycode "^2.1.1"
+
+tough-cookie@~2.4.3:
+ version "2.4.3"
+ resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.4.3.tgz#53f36da3f47783b0925afa06ff9f3b165280f781"
+ integrity sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ==
+ dependencies:
+ psl "^1.1.24"
+ punycode "^1.4.1"
+
+tr46@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/tr46/-/tr46-1.0.1.tgz#a8b13fd6bfd2489519674ccde55ba3693b706d09"
+ integrity sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=
+ dependencies:
+ punycode "^2.1.0"
+
+trim-right@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/trim-right/-/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003"
+ integrity sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=
+
+tunnel-agent@^0.6.0:
+ version "0.6.0"
+ resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd"
+ integrity sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=
+ dependencies:
+ safe-buffer "^5.0.1"
+
+tweetnacl@^0.14.3, tweetnacl@~0.14.0:
+ version "0.14.5"
+ resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64"
+ integrity sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=
+
+type-check@~0.3.2:
+ version "0.3.2"
+ resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72"
+ integrity sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=
+ dependencies:
+ prelude-ls "~1.1.2"
+
+uglify-js@^3.1.4:
+ version "3.6.0"
+ resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.6.0.tgz#704681345c53a8b2079fb6cec294b05ead242ff5"
+ integrity sha512-W+jrUHJr3DXKhrsS7NUVxn3zqMOFn0hL/Ei6v0anCIMoKC93TjcflTagwIHLW7SfMFfiQuktQyFVCFHGUE0+yg==
+ dependencies:
+ commander "~2.20.0"
+ source-map "~0.6.1"
+
+union-value@^1.0.0:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847"
+ integrity sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==
+ dependencies:
+ arr-union "^3.1.0"
+ get-value "^2.0.6"
+ is-extendable "^0.1.1"
+ set-value "^2.0.1"
+
+unset-value@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559"
+ integrity sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=
+ dependencies:
+ has-value "^0.3.1"
+ isobject "^3.0.0"
+
+uri-js@^4.2.2:
+ version "4.2.2"
+ resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.2.2.tgz#94c540e1ff772956e2299507c010aea6c8838eb0"
+ integrity sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==
+ dependencies:
+ punycode "^2.1.0"
+
+urix@^0.1.0:
+ version "0.1.0"
+ resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72"
+ integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=
+
+use@^3.1.0:
+ version "3.1.1"
+ resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f"
+ integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==
+
+util-deprecate@~1.0.1:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
+ integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=
+
+util.promisify@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/util.promisify/-/util.promisify-1.0.0.tgz#440f7165a459c9a16dc145eb8e72f35687097030"
+ integrity sha512-i+6qA2MPhvoKLuxnJNpXAGhg7HphQOSUq2LKMZD0m15EiskXUkMvKdF4Uui0WYeCUGea+o2cw/ZuwehtfsrNkA==
+ dependencies:
+ define-properties "^1.1.2"
+ object.getownpropertydescriptors "^2.0.3"
+
+uuid@^3.3.2:
+ version "3.3.2"
+ resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.3.2.tgz#1b4af4955eb3077c501c23872fc6513811587131"
+ integrity sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==
+
+validate-npm-package-license@^3.0.1:
+ version "3.0.4"
+ resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a"
+ integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==
+ dependencies:
+ spdx-correct "^3.0.0"
+ spdx-expression-parse "^3.0.0"
+
+verror@1.10.0:
+ version "1.10.0"
+ resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400"
+ integrity sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=
+ dependencies:
+ assert-plus "^1.0.0"
+ core-util-is "1.0.2"
+ extsprintf "^1.2.0"
+
+w3c-hr-time@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/w3c-hr-time/-/w3c-hr-time-1.0.1.tgz#82ac2bff63d950ea9e3189a58a65625fedf19045"
+ integrity sha1-gqwr/2PZUOqeMYmlimViX+3xkEU=
+ dependencies:
+ browser-process-hrtime "^0.1.2"
+
+walker@^1.0.7, walker@~1.0.5:
+ version "1.0.7"
+ resolved "https://registry.yarnpkg.com/walker/-/walker-1.0.7.tgz#2f7f9b8fd10d677262b18a884e28d19618e028fb"
+ integrity sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=
+ dependencies:
+ makeerror "1.0.x"
+
+webidl-conversions@^4.0.2:
+ version "4.0.2"
+ resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-4.0.2.tgz#a855980b1f0b6b359ba1d5d9fb39ae941faa63ad"
+ integrity sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==
+
+whatwg-encoding@^1.0.1, whatwg-encoding@^1.0.3:
+ version "1.0.5"
+ resolved "https://registry.yarnpkg.com/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz#5abacf777c32166a51d085d6b4f3e7d27113ddb0"
+ integrity sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==
+ dependencies:
+ iconv-lite "0.4.24"
+
+whatwg-mimetype@^2.1.0, whatwg-mimetype@^2.2.0:
+ version "2.3.0"
+ resolved "https://registry.yarnpkg.com/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz#3d4b1e0312d2079879f826aff18dbeeca5960fbf"
+ integrity sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==
+
+whatwg-url@^6.4.1:
+ version "6.5.0"
+ resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-6.5.0.tgz#f2df02bff176fd65070df74ad5ccbb5a199965a8"
+ integrity sha512-rhRZRqx/TLJQWUpQ6bmrt2UV4f0HCQ463yQuONJqC6fO2VoEb1pTYddbe59SkYq87aoM5A3bdhMZiUiVws+fzQ==
+ dependencies:
+ lodash.sortby "^4.7.0"
+ tr46 "^1.0.1"
+ webidl-conversions "^4.0.2"
+
+whatwg-url@^7.0.0:
+ version "7.0.0"
+ resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-7.0.0.tgz#fde926fa54a599f3adf82dff25a9f7be02dc6edd"
+ integrity sha512-37GeVSIJ3kn1JgKyjiYNmSLP1yzbpb29jdmwBSgkD9h40/hyrR/OifpVUndji3tmwGgD8qpw7iQu3RSbCrBpsQ==
+ dependencies:
+ lodash.sortby "^4.7.0"
+ tr46 "^1.0.1"
+ webidl-conversions "^4.0.2"
+
+which-module@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a"
+ integrity sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=
+
+which@^1.2.9, which@^1.3.0:
+ version "1.3.1"
+ resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a"
+ integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==
+ dependencies:
+ isexe "^2.0.0"
+
+wide-align@^1.1.0:
+ version "1.1.3"
+ resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.3.tgz#ae074e6bdc0c14a431e804e624549c633b000457"
+ integrity sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==
+ dependencies:
+ string-width "^1.0.2 || 2"
+
+wordwrap@~0.0.2:
+ version "0.0.3"
+ resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107"
+ integrity sha1-o9XabNXAvAAI03I0u68b7WMFkQc=
+
+wordwrap@~1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb"
+ integrity sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=
+
+wrap-ansi@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85"
+ integrity sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=
+ dependencies:
+ string-width "^1.0.1"
+ strip-ansi "^3.0.1"
+
+wrappy@1:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
+ integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=
+
+write-file-atomic@2.4.1:
+ version "2.4.1"
+ resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-2.4.1.tgz#d0b05463c188ae804396fd5ab2a370062af87529"
+ integrity sha512-TGHFeZEZMnv+gBFRfjAcxL5bPHrsGKtnb4qsFAws7/vlh+QfwAaySIw4AXP9ZskTTh5GWu3FLuJhsWVdiJPGvg==
+ dependencies:
+ graceful-fs "^4.1.11"
+ imurmurhash "^0.1.4"
+ signal-exit "^3.0.2"
+
+ws@^5.2.0:
+ version "5.2.2"
+ resolved "https://registry.yarnpkg.com/ws/-/ws-5.2.2.tgz#dffef14866b8e8dc9133582514d1befaf96e980f"
+ integrity sha512-jaHFD6PFv6UgoIVda6qZllptQsMlDEJkTQcybzzXDYM1XO9Y8em691FGMPmM46WGyLU4z9KMgQN+qrux/nhlHA==
+ dependencies:
+ async-limiter "~1.0.0"
+
+xml-name-validator@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-3.0.0.tgz#6ae73e06de4d8c6e47f9fb181f78d648ad457c6a"
+ integrity sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==
+
+"y18n@^3.2.1 || ^4.0.0":
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.0.tgz#95ef94f85ecc81d007c264e190a120f0a3c8566b"
+ integrity sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==
+
+yallist@^3.0.0, yallist@^3.0.3:
+ version "3.0.3"
+ resolved "https://registry.yarnpkg.com/yallist/-/yallist-3.0.3.tgz#b4b049e314be545e3ce802236d6cd22cd91c3de9"
+ integrity sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==
+
+yargs-parser@^11.1.1:
+ version "11.1.1"
+ resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-11.1.1.tgz#879a0865973bca9f6bab5cbdf3b1c67ec7d3bcf4"
+ integrity sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ==
+ dependencies:
+ camelcase "^5.0.0"
+ decamelize "^1.2.0"
+
+yargs@^12.0.2:
+ version "12.0.5"
+ resolved "https://registry.yarnpkg.com/yargs/-/yargs-12.0.5.tgz#05f5997b609647b64f66b81e3b4b10a368e7ad13"
+ integrity sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw==
+ dependencies:
+ cliui "^4.0.0"
+ decamelize "^1.2.0"
+ find-up "^3.0.0"
+ get-caller-file "^1.0.1"
+ os-locale "^3.0.0"
+ require-directory "^2.1.1"
+ require-main-filename "^1.0.1"
+ set-blocking "^2.0.0"
+ string-width "^2.0.0"
+ which-module "^2.0.0"
+ y18n "^3.2.1 || ^4.0.0"
+ yargs-parser "^11.1.1"
diff --git a/devtools/client/netmonitor/test/ostrich-black.ttf b/devtools/client/netmonitor/test/ostrich-black.ttf
new file mode 100644
index 0000000000..a0ef8fe1c9
--- /dev/null
+++ b/devtools/client/netmonitor/test/ostrich-black.ttf
Binary files differ
diff --git a/devtools/client/netmonitor/test/ostrich-regular.ttf b/devtools/client/netmonitor/test/ostrich-regular.ttf
new file mode 100644
index 0000000000..9682c07350
--- /dev/null
+++ b/devtools/client/netmonitor/test/ostrich-regular.ttf
Binary files differ
diff --git a/devtools/client/netmonitor/test/service-workers/status-codes-service-worker.js b/devtools/client/netmonitor/test/service-workers/status-codes-service-worker.js
new file mode 100644
index 0000000000..282c02cfbb
--- /dev/null
+++ b/devtools/client/netmonitor/test/service-workers/status-codes-service-worker.js
@@ -0,0 +1,16 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+self.addEventListener("activate", event => {
+ // start controlling the already loaded page
+ event.waitUntil(self.clients.claim());
+});
+
+self.addEventListener("fetch", event => {
+ const response = new Response("Service worker response", {
+ statusText: "OK",
+ });
+ event.respondWith(response);
+});
diff --git a/devtools/client/netmonitor/test/service-workers/status-codes.html b/devtools/client/netmonitor/test/service-workers/status-codes.html
new file mode 100644
index 0000000000..2996b4a0e8
--- /dev/null
+++ b/devtools/client/netmonitor/test/service-workers/status-codes.html
@@ -0,0 +1,62 @@
+<!-- Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ -->
+
+<!doctype html>
+
+<html>
+ <head>
+ <meta charset="utf-8"/>
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <meta http-equiv="Expires" content="0" />
+ <title>Network Monitor test page</title>
+ </head>
+
+ <body>
+ <p>Status codes test</p>
+
+ <script type="text/javascript">
+ /* exported registerServiceWorker, unregisterServiceWorker, performRequests */
+ "use strict";
+
+ let swRegistration;
+
+ function registerServiceWorker() {
+ const sw = navigator.serviceWorker;
+ return sw.register("status-codes-service-worker.js")
+ .then(registration => {
+ swRegistration = registration;
+ console.log("Registered, scope is:", registration.scope);
+ return sw.ready;
+ }).then(() => {
+ // wait until the page is controlled
+ return new Promise(resolve => {
+ if (sw.controller) {
+ resolve();
+ } else {
+ sw.addEventListener("controllerchange", function() {
+ resolve();
+ }, {once: true});
+ }
+ });
+ }).catch(err => {
+ console.error("Registration failed");
+ });
+ }
+
+ function unregisterServiceWorker() {
+ return swRegistration.unregister();
+ }
+
+ function performRequests() {
+ return new Promise(function doXHR(done) {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", "test/200", true);
+ xhr.onreadystatechange = done;
+ xhr.send(null);
+ });
+ }
+ </script>
+ </body>
+
+</html>
diff --git a/devtools/client/netmonitor/test/sjs_content-type-test-server.sjs b/devtools/client/netmonitor/test/sjs_content-type-test-server.sjs
new file mode 100644
index 0000000000..6f3e79ebdf
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_content-type-test-server.sjs
@@ -0,0 +1,421 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+Cu.importGlobalProperties(["TextEncoder"]);
+
+function gzipCompressString(string, obs) {
+ const scs = Cc["@mozilla.org/streamConverters;1"].getService(
+ Ci.nsIStreamConverterService
+ );
+ const listener = Cc["@mozilla.org/network/stream-loader;1"].createInstance(
+ Ci.nsIStreamLoader
+ );
+ listener.init(obs);
+ const converter = scs.asyncConvertData(
+ "uncompressed",
+ "gzip",
+ listener,
+ null
+ );
+ const stringStream = Cc[
+ "@mozilla.org/io/string-input-stream;1"
+ ].createInstance(Ci.nsIStringInputStream);
+ stringStream.data = string;
+ converter.onStartRequest(null);
+ converter.onDataAvailable(null, stringStream, 0, string.length);
+ converter.onStopRequest(null, null);
+}
+
+function doubleGzipCompressString(string, observer) {
+ const observer2 = {
+ onStreamComplete(loader, context, status, length, result) {
+ const buffer = String.fromCharCode.apply(this, result);
+ gzipCompressString(buffer, observer);
+ },
+ };
+ gzipCompressString(string, observer2);
+}
+
+function handleRequest(request, response) {
+ response.processAsync();
+
+ const params = request.queryString.split("&");
+ const format = (params.filter(s => s.includes("fmt="))[0] || "").split(
+ "="
+ )[1];
+ const status =
+ (params.filter(s => s.includes("sts="))[0] || "").split("=")[1] || 200;
+ const cookies =
+ (params.filter(s => s.includes("cookies="))[0] || "").split("=")[1] || 0;
+ const cors = request.queryString.includes("cors=1");
+
+ let cachedCount = 0;
+ const cacheExpire = 60; // seconds
+
+ function setCacheHeaders() {
+ if (status != 304) {
+ response.setHeader(
+ "Cache-Control",
+ "no-cache, no-store, must-revalidate"
+ );
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Expires", "0");
+ return;
+ }
+ // Spice things up a little!
+ if (cachedCount % 2) {
+ response.setHeader("Cache-Control", "max-age=" + cacheExpire, false);
+ } else {
+ response.setHeader(
+ "Expires",
+ Date(Date.now() + cacheExpire * 1000),
+ false
+ );
+ }
+ cachedCount++;
+ }
+
+ function setCookieHeaders() {
+ if (cookies) {
+ response.setHeader(
+ "Set-Cookie",
+ "name1=value1; Domain=.foo.example.com",
+ true
+ );
+ response.setHeader(
+ "Set-Cookie",
+ "name2=value2; Domain=.example.com",
+ true
+ );
+ }
+ }
+
+ function setAllowOriginHeaders() {
+ if (cors) {
+ response.setHeader("Access-Control-Allow-Origin", "*", false);
+ }
+ }
+
+ let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+
+ timer.initWithCallback(
+ // eslint-disable-next-line complexity
+ () => {
+ // to avoid garbage collection
+ timer = null;
+ switch (format) {
+ case "txt": {
+ response.setStatusLine(request.httpVersion, status, "DA DA DA");
+ response.setHeader("Content-Type", "text/plain", false);
+ setCacheHeaders();
+
+ function convertToUtf8(str) {
+ return String.fromCharCode(...new TextEncoder().encode(str));
+ }
+
+ // This script must be evaluated as UTF-8 for this to write out the
+ // bytes of the string in UTF-8. If it's evaluated as Latin-1, the
+ // written bytes will be the result of UTF-8-encoding this string
+ // *twice*.
+ const data = "Братан, ты вообще качаешься?";
+ const stringOfUtf8Bytes = convertToUtf8(data);
+ response.write(stringOfUtf8Bytes);
+
+ response.finish();
+ break;
+ }
+ case "xml": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/xml; charset=utf-8", false);
+ setCacheHeaders();
+ response.write("<label value='greeting'>Hello XML!</label>");
+ response.finish();
+ break;
+ }
+ case "html": {
+ const content = (
+ params.filter(s => s.includes("res="))[0] || ""
+ ).split("=")[1];
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/html; charset=utf-8", false);
+ setAllowOriginHeaders();
+ setCacheHeaders();
+ setCookieHeaders();
+ response.write(content || "<p>Hello HTML!</p>");
+ response.finish();
+ break;
+ }
+ case "xhtml": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader(
+ "Content-Type",
+ "application/xhtml+xml; charset=utf-8",
+ false
+ );
+ setAllowOriginHeaders();
+ setCacheHeaders();
+ setCookieHeaders();
+ response.write("<p>Hello XHTML!</p>");
+ response.finish();
+ break;
+ }
+ case "html-long": {
+ const str = new Array(102400 /* 100 KB in bytes */).join(".");
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/html; charset=utf-8", false);
+ setCacheHeaders();
+ response.write("<p>" + str + "</p>");
+ response.finish();
+ break;
+ }
+ case "css": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/css; charset=utf-8", false);
+ setCacheHeaders();
+ response.write("body:pre { content: 'Hello CSS!' }");
+ response.finish();
+ break;
+ }
+ case "js": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader(
+ "Content-Type",
+ "application/javascript; charset=utf-8",
+ false
+ );
+ setCacheHeaders();
+ response.write("function() { return 'Hello JS!'; }");
+ response.finish();
+ break;
+ }
+ case "json": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader(
+ "Content-Type",
+ "application/json; charset=utf-8",
+ false
+ );
+ setCacheHeaders();
+ response.write('{ "greeting": "Hello JSON!" }');
+ response.finish();
+ break;
+ }
+ case "jsonp": {
+ const fun = (params.filter(s => s.includes("jsonp="))[0] || "").split(
+ "="
+ )[1];
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/json; charset=utf-8", false);
+ setCacheHeaders();
+ response.write(fun + '({ "greeting": "Hello JSONP!" })');
+ response.finish();
+ break;
+ }
+ case "jsonp2": {
+ const fun = (params.filter(s => s.includes("jsonp="))[0] || "").split(
+ "="
+ )[1];
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/json; charset=utf-8", false);
+ setCacheHeaders();
+ response.write(
+ " " + fun + ' ( { "greeting": "Hello weird JSONP!" } ) ; '
+ );
+ response.finish();
+ break;
+ }
+ case "json-b64": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/json; charset=utf-8", false);
+ setCacheHeaders();
+ response.write(btoa('{ "greeting": "This is a base 64 string." }'));
+ response.finish();
+ break;
+ }
+ case "json-long": {
+ const str = '{ "greeting": "Hello long string JSON!" },';
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/json; charset=utf-8", false);
+ setCacheHeaders();
+ response.write("[" + new Array(2048).join(str).slice(0, -1) + "]");
+ response.finish();
+ break;
+ }
+ case "json-malformed": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/json; charset=utf-8", false);
+ setCacheHeaders();
+ response.write('{ "greeting": "Hello malformed JSON!" },');
+ response.finish();
+ break;
+ }
+ case "json-text-mime": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader(
+ "Content-Type",
+ "text/plain; charset=utf-8",
+ false
+ );
+ setCacheHeaders();
+ response.write('{ "greeting": "Hello third-party JSON!" }');
+ response.finish();
+ break;
+ }
+ case "json-custom-mime": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader(
+ "Content-Type",
+ "text/x-bigcorp-json; charset=utf-8",
+ false
+ );
+ setCacheHeaders();
+ response.write('{ "greeting": "Hello oddly-named JSON!" }');
+ response.finish();
+ break;
+ }
+ case "json-valid-xssi-protection": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/json; charset=utf-8", false);
+ setCacheHeaders();
+ response.write(')]}\'\n{"greeting": "Hello good XSSI protection"}');
+ response.finish();
+ break;
+ }
+
+ case "font": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "font/woff", false);
+ setAllowOriginHeaders();
+ setCacheHeaders();
+ response.finish();
+ break;
+ }
+ case "image": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "image/png", false);
+ setCacheHeaders();
+ response.finish();
+ break;
+ }
+ case "application-ogg": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "application/ogg", false);
+ setCacheHeaders();
+ response.finish();
+ break;
+ }
+ case "audio": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "audio/ogg", false);
+ setCacheHeaders();
+ response.finish();
+ break;
+ }
+ case "video": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "video/webm", false);
+ setCacheHeaders();
+ response.finish();
+ break;
+ }
+ case "flash": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader(
+ "Content-Type",
+ "application/x-shockwave-flash",
+ false
+ );
+ setCacheHeaders();
+ response.finish();
+ break;
+ }
+ case "ws": {
+ response.setStatusLine(
+ request.httpVersion,
+ 101,
+ "Switching Protocols"
+ );
+ response.setHeader("Connection", "upgrade", false);
+ response.setHeader("Upgrade", "websocket", false);
+ setCacheHeaders();
+ response.finish();
+ break;
+ }
+ case "gzip": {
+ // Note: we're doing a double gzip encoding to test multiple
+ // converters in network monitor.
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/plain", false);
+ response.setHeader("Content-Encoding", "gzip\t ,gzip", false);
+ setCacheHeaders();
+
+ const observer = {
+ onStreamComplete(loader, context, statusl, length, result) {
+ const buffer = String.fromCharCode.apply(this, result);
+ response.setHeader("Content-Length", "" + buffer.length, false);
+ response.write(buffer);
+ response.finish();
+ },
+ };
+ const data = new Array(1000).join("Hello gzip!");
+ doubleGzipCompressString(data, observer);
+ break;
+ }
+ case "br": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "text/json", false);
+ response.setHeader("Content-Encoding", "br", false);
+ setCacheHeaders();
+ response.setHeader("Content-Length", "10", false);
+ // Use static data since we cannot encode brotli.
+ response.write("\x1b\x3f\x00\x00\x24\xb0\xe2\x99\x80\x12");
+ response.finish();
+ break;
+ }
+ case "hls-m3u8": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "application/x-mpegurl", false);
+ setCacheHeaders();
+ response.write("#EXTM3U\n");
+ response.finish();
+ break;
+ }
+ case "hls-m3u8-alt-mime-type": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader(
+ "Content-Type",
+ "application/vnd.apple.mpegurl",
+ false
+ );
+ setCacheHeaders();
+ response.write("#EXTM3U\n");
+ response.finish();
+ break;
+ }
+ case "mpeg-dash": {
+ response.setStatusLine(request.httpVersion, status, "OK");
+ response.setHeader("Content-Type", "video/vnd.mpeg.dash.mpd", false);
+ setCacheHeaders();
+ response.write('<?xml version="1.0" encoding="UTF-8"?>\n');
+ response.write(
+ '<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></MPD>\n'
+ );
+ response.finish();
+ break;
+ }
+ default: {
+ response.setStatusLine(request.httpVersion, 404, "Not Found");
+ response.setHeader("Content-Type", "text/html; charset=utf-8", false);
+ setCacheHeaders();
+ response.write("<blink>Not Found</blink>");
+ response.finish();
+ break;
+ }
+ }
+ },
+ 10,
+ Ci.nsITimer.TYPE_ONE_SHOT
+ ); // Make sure this request takes a few ms.
+}
diff --git a/devtools/client/netmonitor/test/sjs_cors-test-server.sjs b/devtools/client/netmonitor/test/sjs_cors-test-server.sjs
new file mode 100644
index 0000000000..3c3481e5c1
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_cors-test-server.sjs
@@ -0,0 +1,18 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.setStatusLine(request.httpVersion, 200, "Och Aye");
+
+ response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Expires", "0");
+
+ response.setHeader("Access-Control-Allow-Origin", "*", false);
+ response.setHeader("Access-Control-Allow-Headers", "content-type", false);
+
+ response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
+
+ response.write("Access-Control-Allow-Origin: *");
+}
diff --git a/devtools/client/netmonitor/test/sjs_hsts-test-server.sjs b/devtools/client/netmonitor/test/sjs_hsts-test-server.sjs
new file mode 100644
index 0000000000..8160508c51
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_hsts-test-server.sjs
@@ -0,0 +1,23 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Expires", "0");
+
+ if (request.queryString === "reset") {
+ // Reset the HSTS policy, prevent influencing other tests
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.setHeader("Strict-Transport-Security", "max-age=0");
+ response.write("Resetting HSTS");
+ } else if (request.scheme === "http") {
+ response.setStatusLine(request.httpVersion, 302, "Found");
+ response.setHeader("Location", "https://" + request.host + request.path);
+ } else {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.setHeader("Strict-Transport-Security", "max-age=100");
+ response.write("Page was accessed over HTTPS!");
+ }
+}
diff --git a/devtools/client/netmonitor/test/sjs_https-redirect-test-server.sjs b/devtools/client/netmonitor/test/sjs_https-redirect-test-server.sjs
new file mode 100644
index 0000000000..f0a5c95ab8
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_https-redirect-test-server.sjs
@@ -0,0 +1,19 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Expires", "0");
+
+ response.setHeader("Access-Control-Allow-Origin", "*", false);
+
+ if (request.scheme === "http") {
+ response.setStatusLine(request.httpVersion, 302, "Found");
+ response.setHeader("Location", "https://" + request.host + request.path);
+ } else {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.write("Page was accessed over HTTPS!");
+ }
+}
diff --git a/devtools/client/netmonitor/test/sjs_json-test-server.sjs b/devtools/client/netmonitor/test/sjs_json-test-server.sjs
new file mode 100644
index 0000000000..617ef04ae1
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_json-test-server.sjs
@@ -0,0 +1,28 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Expires", "0");
+
+ response.setHeader("Content-Type", "application/json; charset=utf-8", false);
+
+ // This server checks the name parameter from the request to decide which JSON object to
+ // return.
+ const params = request.queryString.split("&");
+ const name = (params.filter(s => s.includes("name="))[0] || "").split("=")[1];
+ switch (name) {
+ case "null":
+ response.write('{ "greeting": null }');
+ break;
+ case "nogrip":
+ response.write('{"obj": {"type": "string" }}');
+ break;
+ case "empty":
+ response.write("{}");
+ break;
+ }
+}
diff --git a/devtools/client/netmonitor/test/sjs_long-polling-server.sjs b/devtools/client/netmonitor/test/sjs_long-polling-server.sjs
new file mode 100644
index 0000000000..2c80149223
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_long-polling-server.sjs
@@ -0,0 +1,35 @@
+"use strict";
+
+const key = "blocked-response";
+function setResponse(response) {
+ setObjectState(key, response);
+}
+
+function getResponse() {
+ let response;
+ getObjectState(key, v => {
+ response = v;
+ });
+ return response;
+}
+
+function handleRequest(request, response) {
+ const { queryString } = request;
+ if (!queryString) {
+ // The default end point will return a blocked response.
+ // The response object will be stored and will be released
+ // when "?unblock" is called.
+ response.processAsync();
+ response.setHeader("Content-Type", "text/plain", false);
+ response.write("Begin...\n");
+ setResponse(response);
+ } else if (queryString == "unblock") {
+ // unblock the pending response
+ getResponse().finish();
+ setResponse(null);
+
+ // and return synchronously.
+ response.setHeader("Content-Type", "text/plain");
+ response.write("ok");
+ }
+}
diff --git a/devtools/client/netmonitor/test/sjs_method-test-server.sjs b/devtools/client/netmonitor/test/sjs_method-test-server.sjs
new file mode 100644
index 0000000000..4a820f3bcc
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_method-test-server.sjs
@@ -0,0 +1,35 @@
+/* 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 BinaryInputStream = Components.Constructor(
+ "@mozilla.org/binaryinputstream;1",
+ "nsIBinaryInputStream",
+ "setInputStream"
+);
+
+function handleRequest(request, response) {
+ response.setStatusLine(request.httpVersion, 200, "Och Aye");
+ response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
+
+ let body = "";
+ if (request.method == "POST") {
+ const bodyStream = new BinaryInputStream(request.bodyInputStream);
+
+ let avail = 0;
+ while ((avail = bodyStream.available()) > 0) {
+ body += String.fromCharCode.apply(
+ String,
+ bodyStream.readByteArray(avail)
+ );
+ }
+ }
+
+ const contentType = request.hasHeader("content-type")
+ ? request.getHeader("content-type")
+ : "";
+
+ const bodyOutput = [request.method, contentType, body].join("\n");
+ response.bodyOutputStream.write(bodyOutput, bodyOutput.length);
+}
diff --git a/devtools/client/netmonitor/test/sjs_search-test-server.sjs b/devtools/client/netmonitor/test/sjs_search-test-server.sjs
new file mode 100644
index 0000000000..6b1ef7990f
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_search-test-server.sjs
@@ -0,0 +1,10 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ response.setHeader("Content-Type", "text/xml; charset=utf-8", false);
+ response.setHeader("Set-Cookie", "name1=test;", true);
+ response.write("<label value='test'>Hello From XML!</label>");
+}
diff --git a/devtools/client/netmonitor/test/sjs_set-cookie-same-site.sjs b/devtools/client/netmonitor/test/sjs_set-cookie-same-site.sjs
new file mode 100644
index 0000000000..b21dcddbcd
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_set-cookie-same-site.sjs
@@ -0,0 +1,11 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.setStatusLine(request.httpVersion, 200, "Och Aye");
+
+ response.setHeader("Set-Cookie", "foo=bar; SameSite=Lax");
+
+ response.write("Hello world!");
+}
diff --git a/devtools/client/netmonitor/test/sjs_simple-test-server.sjs b/devtools/client/netmonitor/test/sjs_simple-test-server.sjs
new file mode 100644
index 0000000000..7396a87235
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_simple-test-server.sjs
@@ -0,0 +1,22 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.setStatusLine(request.httpVersion, 200, "Och Aye");
+
+ response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Expires", "0");
+
+ response.setHeaderNoCheck("Set-Cookie", "bob=true; Max-Age=10; HttpOnly");
+ response.setHeaderNoCheck("Set-Cookie", "tom=cool; Max-Age=10; HttpOnly");
+
+ response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
+
+ response.setHeaderNoCheck("Foo-Bar", "baz");
+ response.setHeaderNoCheck("Foo-Bar", "baz");
+ response.setHeaderNoCheck("Foo-Bar", "");
+
+ response.write("Hello world!");
+}
diff --git a/devtools/client/netmonitor/test/sjs_simple-unsorted-cookies-test-server.sjs b/devtools/client/netmonitor/test/sjs_simple-unsorted-cookies-test-server.sjs
new file mode 100644
index 0000000000..04519f6955
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_simple-unsorted-cookies-test-server.sjs
@@ -0,0 +1,20 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.setStatusLine(request.httpVersion, 200, "Och Aye");
+
+ response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Expires", "0");
+
+ response.setHeader("Set-Cookie", "tom=cool; Max-Age=10; HttpOnly", true);
+ response.setHeader("Set-Cookie", "bob=true; Max-Age=10; HttpOnly", true);
+ response.setHeader("Set-Cookie", "foo=bar; Max-Age=10; HttpOnly", true);
+ response.setHeader("Set-Cookie", "__proto__=2; Max-Age=10; HttpOnly", true);
+
+ response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
+ response.setHeader("Foo-Bar", "baz", false);
+ response.write("Hello world!");
+}
diff --git a/devtools/client/netmonitor/test/sjs_slow-script-server.sjs b/devtools/client/netmonitor/test/sjs_slow-script-server.sjs
new file mode 100644
index 0000000000..9e10310128
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_slow-script-server.sjs
@@ -0,0 +1,18 @@
+"use strict";
+
+let timer;
+
+const DELAY_MS = 2000;
+function handleRequest(request, response) {
+ response.processAsync();
+ timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+ timer.init(
+ () => {
+ response.setHeader("Content-Type", "text/javascript", false);
+ response.write("console.log('script loaded')\n");
+ response.finish();
+ },
+ DELAY_MS,
+ Ci.nsITimer.TYPE_ONE_SHOT
+ );
+}
diff --git a/devtools/client/netmonitor/test/sjs_slow-test-server.sjs b/devtools/client/netmonitor/test/sjs_slow-test-server.sjs
new file mode 100644
index 0000000000..9e996384e6
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_slow-test-server.sjs
@@ -0,0 +1,20 @@
+"use strict";
+
+let timer;
+
+const DELAY_MS = 1000;
+function handleRequest(request, response) {
+ response.processAsync();
+ timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+ timer.init(
+ () => {
+ response.setHeader("Content-Type", "text/html", false);
+ response.write(
+ "<body>Slow loading page for netmonitor test. You should never see this.</body>"
+ );
+ response.finish();
+ },
+ DELAY_MS,
+ Ci.nsITimer.TYPE_ONE_SHOT
+ );
+}
diff --git a/devtools/client/netmonitor/test/sjs_sorting-test-server.sjs b/devtools/client/netmonitor/test/sjs_sorting-test-server.sjs
new file mode 100644
index 0000000000..98cf232861
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_sorting-test-server.sjs
@@ -0,0 +1,36 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.processAsync();
+
+ const params = request.queryString.split("&");
+ const index = params.filter(s => s.includes("index="))[0].split("=")[1];
+
+ let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+ timer.initWithCallback(
+ () => {
+ // to avoid garbage collection
+ timer = null;
+ response.setStatusLine(
+ request.httpVersion,
+ index == 1 ? 101 : index * 100,
+ "Meh"
+ );
+
+ response.setHeader(
+ "Cache-Control",
+ "no-cache, no-store, must-revalidate"
+ );
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Expires", "0");
+
+ response.setHeader("Content-Type", "text/" + index, false);
+ response.write(new Array(index * 10).join(index)); // + 0.01 KB
+ response.finish();
+ },
+ 10,
+ Ci.nsITimer.TYPE_ONE_SHOT
+ ); // Make sure this request takes a few ms.
+}
diff --git a/devtools/client/netmonitor/test/sjs_sse-test-server.sjs b/devtools/client/netmonitor/test/sjs_sse-test-server.sjs
new file mode 100644
index 0000000000..bbfc7679b5
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_sse-test-server.sjs
@@ -0,0 +1,7 @@
+"use strict";
+function handleRequest(request, response) {
+ response.processAsync();
+ response.setHeader("Content-Type", "text/event-stream");
+ response.write("data: Why so serious?\n\n");
+ response.finish();
+}
diff --git a/devtools/client/netmonitor/test/sjs_status-codes-test-server.sjs b/devtools/client/netmonitor/test/sjs_status-codes-test-server.sjs
new file mode 100644
index 0000000000..a8ea9b5f8f
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_status-codes-test-server.sjs
@@ -0,0 +1,71 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ response.processAsync();
+
+ const params = request.queryString.split("&");
+ const status = params.filter(s => s.includes("sts="))[0].split("=")[1];
+ const cached = params.filter(s => s === "cached").length !== 0;
+
+ let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+ timer.initWithCallback(
+ () => {
+ // to avoid garbage collection
+ timer = null;
+ switch (status) {
+ case "100":
+ response.setStatusLine(
+ request.httpVersion,
+ 101,
+ "Switching Protocols"
+ );
+ break;
+ case "200":
+ response.setStatusLine(request.httpVersion, 202, "Created");
+ break;
+ case "300":
+ response.setStatusLine(request.httpVersion, 303, "See Other");
+ break;
+ case "304":
+ response.setStatusLine(request.httpVersion, 304, "Not Modified");
+ break;
+ case "400":
+ response.setStatusLine(request.httpVersion, 404, "Not Found");
+ break;
+ case "500":
+ response.setStatusLine(request.httpVersion, 501, "Not Implemented");
+ break;
+ case "ok":
+ response.setStatusLine(request.httpVersion, 200, "OK");
+ break;
+ case "redirect":
+ response.setStatusLine(request.httpVersion, 301, "Moved Permanently");
+ response.setHeader("Location", "http://example.com/redirected");
+ break;
+ }
+
+ if (!cached) {
+ response.setHeader(
+ "Cache-Control",
+ "no-cache, no-store, must-revalidate"
+ );
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Expires", "0");
+ } else {
+ response.setHeader(
+ "Cache-Control",
+ "no-transform,public,max-age=300,s-maxage=900"
+ );
+ response.setHeader("Expires", "Thu, 01 Dec 2100 20:00:00 GMT");
+ }
+
+ response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
+ response.write("Hello status code " + status + "!");
+ response.finish();
+ },
+ 10,
+ Ci.nsITimer.TYPE_ONE_SHOT
+ ); // Make sure this request takes a few ms.
+}
diff --git a/devtools/client/netmonitor/test/sjs_timings-test-server.sjs b/devtools/client/netmonitor/test/sjs_timings-test-server.sjs
new file mode 100644
index 0000000000..6446461039
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_timings-test-server.sjs
@@ -0,0 +1,45 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+const trailerServerTiming = [
+ { metric: "metric3", duration: "99789.11", description: "time3" },
+ { metric: "metric4", duration: "1112.13", description: "time4" },
+];
+
+const responseServerTiming = [
+ { metric: "metric1", duration: "123.4", description: "time1" },
+ { metric: "metric2", duration: "0", description: "time2" },
+];
+
+function handleRequest(request, response) {
+ const body = "c\r\ndata reached\r\n3\r\nhej\r\n0\r\n";
+
+ response.seizePower();
+ response.write("HTTP/1.1 200 OK\r\n");
+ response.write("Content-Type: text/plain\r\n");
+ response.write(createServerTimingHeader(responseServerTiming));
+ response.write("Transfer-Encoding: chunked\r\n");
+ response.write("\r\n");
+ response.write(body);
+ response.write(createServerTimingHeader(trailerServerTiming));
+ response.write("\r\n");
+ response.finish();
+}
+
+function createServerTimingHeader(headerData) {
+ let header = "";
+ for (let i = 0; i < headerData.length; i++) {
+ header +=
+ "Server-Timing: " +
+ headerData[i].metric +
+ ";" +
+ "dur=" +
+ headerData[i].duration +
+ ";" +
+ "desc=" +
+ headerData[i].description +
+ "\r\n";
+ }
+ return header;
+}
diff --git a/devtools/client/netmonitor/test/sjs_truncate-test-server.sjs b/devtools/client/netmonitor/test/sjs_truncate-test-server.sjs
new file mode 100644
index 0000000000..77ec88bf44
--- /dev/null
+++ b/devtools/client/netmonitor/test/sjs_truncate-test-server.sjs
@@ -0,0 +1,21 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+function handleRequest(request, response) {
+ const params = request.queryString.split("&");
+ const limit = (params.filter(s => s.includes("limit="))[0] || "").split(
+ "="
+ )[1];
+
+ response.setStatusLine(request.httpVersion, 200, "Och Aye");
+
+ response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Expires", "0");
+ response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
+
+ response.write("x".repeat(2 * parseInt(limit, 10)));
+
+ response.write("Hello world!");
+}
diff --git a/devtools/client/netmonitor/test/test-image.png b/devtools/client/netmonitor/test/test-image.png
new file mode 100644
index 0000000000..769c636340
--- /dev/null
+++ b/devtools/client/netmonitor/test/test-image.png
Binary files differ
diff --git a/devtools/client/netmonitor/test/xhr_bundle.js b/devtools/client/netmonitor/test/xhr_bundle.js
new file mode 100644
index 0000000000..00001de5a2
--- /dev/null
+++ b/devtools/client/netmonitor/test/xhr_bundle.js
@@ -0,0 +1,91 @@
+/******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // identity function for calling harmony imports with the correct context
+/******/ __webpack_require__.i = function(value) { return value; };
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, {
+/******/ configurable: false,
+/******/ enumerable: true,
+/******/ get: getter
+/******/ });
+/******/ }
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = 0);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function reallydoxhr() {
+ let z = new XMLHttpRequest();
+ z.open("get", "test-image.png", true);
+ z.send();
+}
+
+function doxhr() {
+ reallydoxhr();
+}
+
+window.doxhr = doxhr;
+
+
+/***/ })
+/******/ ]);
+//# sourceMappingURL=xhr_bundle.js.map \ No newline at end of file
diff --git a/devtools/client/netmonitor/test/xhr_bundle.js.map b/devtools/client/netmonitor/test/xhr_bundle.js.map
new file mode 100644
index 0000000000..c28ee2a8f9
--- /dev/null
+++ b/devtools/client/netmonitor/test/xhr_bundle.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack:///webpack/bootstrap 1f90f505700f55e4a0b4","webpack:///./xhr_original.js"],"names":[],"mappings":";AAAA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA,mDAA2C,cAAc;;AAEzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;;AAEA;AACA,8DAAsD,+DAA+D;;AAErH;AACA;;AAEA;AACA;;;;;;;;AChEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA","file":"xhr_bundle.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// identity function for calling harmony imports with the correct context\n \t__webpack_require__.i = function(value) { return value; };\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 1f90f505700f55e4a0b4","\"use strict\";\n\nfunction reallydoxhr() {\n let z = new XMLHttpRequest();\n z.open(\"get\", \"test-image.png\", true);\n z.send();\n}\n\nfunction doxhr() {\n reallydoxhr();\n}\n\nwindow.doxhr = doxhr;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./xhr_original.js\n// module id = 0\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file
diff --git a/devtools/client/netmonitor/test/xhr_original.js b/devtools/client/netmonitor/test/xhr_original.js
new file mode 100644
index 0000000000..8b480a0098
--- /dev/null
+++ b/devtools/client/netmonitor/test/xhr_original.js
@@ -0,0 +1,13 @@
+"use strict";
+
+function reallydoxhr() {
+ const z = new XMLHttpRequest();
+ z.open("get", "test-image.png", true);
+ z.send();
+}
+
+function doxhr() {
+ reallydoxhr();
+}
+
+window.doxhr = doxhr;
diff --git a/devtools/client/netmonitor/test/xpcshell/.eslintrc.js b/devtools/client/netmonitor/test/xpcshell/.eslintrc.js
new file mode 100644
index 0000000000..8611c174f5
--- /dev/null
+++ b/devtools/client/netmonitor/test/xpcshell/.eslintrc.js
@@ -0,0 +1,6 @@
+"use strict";
+
+module.exports = {
+ // Extend from the common devtools xpcshell eslintrc config.
+ extends: "../../../../.eslintrc.xpcshell.js",
+};
diff --git a/devtools/client/netmonitor/test/xpcshell/test_doc-utils.js b/devtools/client/netmonitor/test/xpcshell/test_doc-utils.js
new file mode 100644
index 0000000000..7cd71662d6
--- /dev/null
+++ b/devtools/client/netmonitor/test/xpcshell/test_doc-utils.js
@@ -0,0 +1,62 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Test for doc-utils
+
+"use strict";
+
+function run_test() {
+ const { require } = ChromeUtils.importESModule(
+ "resource://devtools/shared/loader/Loader.sys.mjs"
+ );
+ const MDN_URL = "https://developer.mozilla.org/docs/";
+ const GTM_PARAMS_NM =
+ "?utm_source=mozilla" +
+ "&utm_medium=devtools-netmonitor&utm_campaign=default";
+ const GTM_PARAMS_WC =
+ "?utm_source=mozilla" +
+ "&utm_medium=devtools-webconsole&utm_campaign=default";
+ const USER_DOC_URL = "https://firefox-source-docs.mozilla.org/devtools-user/";
+
+ const {
+ getHeadersURL,
+ getHTTPStatusCodeURL,
+ getNetMonitorTimingsURL,
+ getPerformanceAnalysisURL,
+ getFilterBoxURL,
+ } = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+
+ info("Checking for supported headers");
+ equal(
+ getHeadersURL("Accept"),
+ `${MDN_URL}Web/HTTP/Headers/Accept${GTM_PARAMS_NM}`
+ );
+ info("Checking for unsupported headers");
+ equal(getHeadersURL("Width"), null);
+
+ info("Checking for supported status code");
+ equal(
+ getHTTPStatusCodeURL("200", "webconsole"),
+ `${MDN_URL}Web/HTTP/Status/200${GTM_PARAMS_WC}`
+ );
+ info("Checking for unsupported status code");
+ equal(
+ getHTTPStatusCodeURL("999", "webconsole"),
+ `${MDN_URL}Web/HTTP/Status${GTM_PARAMS_WC}`
+ );
+
+ equal(
+ getNetMonitorTimingsURL(),
+ `${USER_DOC_URL}network_monitor/request_details/#network-monitor-request-details-timings-tab`
+ );
+
+ equal(
+ getPerformanceAnalysisURL(),
+ `${USER_DOC_URL}network_monitor/performance_analysis/`
+ );
+
+ equal(
+ getFilterBoxURL(),
+ `${USER_DOC_URL}network_monitor/request_list/#filtering-by-properties`
+ );
+}
diff --git a/devtools/client/netmonitor/test/xpcshell/test_request-utils-fetchNetworkUpdatePacket.js b/devtools/client/netmonitor/test/xpcshell/test_request-utils-fetchNetworkUpdatePacket.js
new file mode 100644
index 0000000000..6b7a66f5ad
--- /dev/null
+++ b/devtools/client/netmonitor/test/xpcshell/test_request-utils-fetchNetworkUpdatePacket.js
@@ -0,0 +1,54 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Test devtools/client/netmonitor/src/utils/request-utils.js function
+// |fetchNetworkUpdatePacket|
+
+"use strict";
+
+const { require } = ChromeUtils.importESModule(
+ "resource://devtools/shared/loader/Loader.sys.mjs"
+);
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+function run_test() {
+ let fetchedNetworkUpdateTypes = [];
+ async function mockConnectorRequestData(id, updateType) {
+ fetchedNetworkUpdateTypes.push(updateType);
+ return updateType;
+ }
+
+ const updateTypes = ["requestHeaders", "responseHeaders"];
+ const request = {
+ id: "foo",
+ requestHeadersAvailable: true,
+ responseHeadersAvailable: true,
+ };
+
+ info(
+ "Testing that the expected network update packets were fetched from the server"
+ );
+ fetchNetworkUpdatePacket(mockConnectorRequestData, request, updateTypes);
+ equal(fetchedNetworkUpdateTypes.length, 2, "Two network request updates");
+ equal(
+ fetchedNetworkUpdateTypes[0],
+ "requestHeaders",
+ "Request headers updates"
+ );
+ equal(
+ fetchedNetworkUpdateTypes[1],
+ "responseHeaders",
+ " Response headers updates"
+ );
+
+ // clear the fetch updates for next test
+ fetchedNetworkUpdateTypes = [];
+
+ info(
+ "Testing that no network updates were fetched when no `request` is provided"
+ );
+ fetchNetworkUpdatePacket(mockConnectorRequestData, undefined, updateTypes);
+ equal(fetchedNetworkUpdateTypes.length, 0, "No network request updates");
+}
diff --git a/devtools/client/netmonitor/test/xpcshell/test_request-utils-js-getFormattedProtocol.js b/devtools/client/netmonitor/test/xpcshell/test_request-utils-js-getFormattedProtocol.js
new file mode 100644
index 0000000000..07ead52893
--- /dev/null
+++ b/devtools/client/netmonitor/test/xpcshell/test_request-utils-js-getFormattedProtocol.js
@@ -0,0 +1,235 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Test devtools/client/netmonitor/src/utils/request-utils.js function
+// |getFormattedProtocol|
+
+"use strict";
+
+const { require } = ChromeUtils.importESModule(
+ "resource://devtools/shared/loader/Loader.sys.mjs"
+);
+const {
+ getFormattedProtocol,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+function run_test() {
+ const http_1p1_value_http1p1 = {
+ httpVersion: "HTTP/1.1",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "http/1.1",
+ },
+ ],
+ },
+ };
+
+ const http_1p1_value_http_no_slash_1p1 = {
+ httpVersion: "HTTP/1.1",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "http1.1",
+ },
+ ],
+ },
+ };
+
+ const http_1p1_value_http1p11 = {
+ httpVersion: "HTTP/1.1",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "http/1.11",
+ },
+ ],
+ },
+ };
+
+ const http_2p0_value_h2 = {
+ httpVersion: "HTTP/2.0",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "h2",
+ },
+ ],
+ },
+ };
+
+ const http_1p1_value_h1 = {
+ httpVersion: "HTTP/1.1",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "h1",
+ },
+ ],
+ },
+ };
+
+ const http_1p1_value_h2 = {
+ httpVersion: "HTTP/1.1",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "h2",
+ },
+ ],
+ },
+ };
+
+ const http_1p1_value_empty_string = {
+ httpVersion: "HTTP/1.1",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "",
+ },
+ ],
+ },
+ };
+
+ const http_2p0_value_empty_string = {
+ httpVersion: "HTTP/2.0",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "",
+ },
+ ],
+ },
+ };
+
+ const http_2p0_value_2p0 = {
+ httpVersion: "HTTP/2.0",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "HTTP/2.0",
+ },
+ ],
+ },
+ };
+
+ const http_3p0_value_h3 = {
+ httpVersion: "HTTP/3.0",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "h3",
+ },
+ ],
+ },
+ };
+
+ const http_3p0_value_h3p0 = {
+ httpVersion: "HTTP/3.0",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "h3.0",
+ },
+ ],
+ },
+ };
+
+ const http_3p0_value_http_3p0 = {
+ httpVersion: "HTTP/3.0",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "http/3.0",
+ },
+ ],
+ },
+ };
+
+ const http_3p0_value_3p0 = {
+ httpVersion: "HTTP/3.0",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "3.0",
+ },
+ ],
+ },
+ };
+
+ const http_4p0_value_h4 = {
+ httpVersion: "HTTP/4.0",
+ responseHeaders: {
+ headers: [
+ {
+ name: "X-Firefox-Spdy",
+ value: "h4",
+ },
+ ],
+ },
+ };
+
+ info("Testing httpValue:HTTP/1.1, value:http/1.1");
+ equal(getFormattedProtocol(http_1p1_value_http1p1), "HTTP/1.1");
+
+ info("Testing httpValue:HTTP/1.1, value:http1.1");
+ equal(
+ getFormattedProtocol(http_1p1_value_http_no_slash_1p1),
+ "HTTP/1.1+http1.1"
+ );
+
+ info("Testing httpValue:HTTP/1.1, value:http/1.11");
+ equal(getFormattedProtocol(http_1p1_value_http1p11), "HTTP/1.1+http/1.11");
+
+ info("Testing httpValue:HTTP/2.0, value:h2");
+ equal(getFormattedProtocol(http_2p0_value_h2), "HTTP/2.0");
+
+ info("Testing httpValue:HTTP/1.1, value:h1");
+ equal(getFormattedProtocol(http_1p1_value_h1), "HTTP/1.1+h1");
+
+ info("Testing httpValue:HTTP/1.1, value:h2");
+ equal(getFormattedProtocol(http_1p1_value_h2), "HTTP/1.1+h2");
+
+ info("Testing httpValue:HTTP/1.1, value:http1.1");
+ equal(
+ getFormattedProtocol(http_1p1_value_http_no_slash_1p1),
+ "HTTP/1.1+http1.1"
+ );
+
+ info("Testing httpValue:HTTP/1.1, value:''");
+ equal(getFormattedProtocol(http_1p1_value_empty_string), "HTTP/1.1");
+
+ info("Testing httpValue:HTTP/2.0, value:''");
+ equal(getFormattedProtocol(http_2p0_value_empty_string), "HTTP/2.0");
+
+ info("Testing httpValue:HTTP/2.0, value:HTTP/2.0");
+ equal(getFormattedProtocol(http_2p0_value_2p0), "HTTP/2.0+HTTP/2.0");
+
+ info("Testing httpValue:HTTP/3.0, value:h3");
+ equal(getFormattedProtocol(http_3p0_value_h3), "HTTP/3.0");
+
+ info("Testing httpValue:HTTP/3.0, value:h3.0");
+ equal(getFormattedProtocol(http_3p0_value_h3p0), "HTTP/3.0");
+
+ info("Testing httpValue:HTTP/3.0, value:http/3.0");
+ equal(getFormattedProtocol(http_3p0_value_http_3p0), "HTTP/3.0+http/3.0");
+
+ info("Testing httpValue:HTTP/3.0, value:3.0");
+ equal(getFormattedProtocol(http_3p0_value_3p0), "HTTP/3.0+3.0");
+
+ info("Testing httpValue:HTTP/4.0, value:h4");
+ equal(getFormattedProtocol(http_4p0_value_h4), "HTTP/4.0");
+}
diff --git a/devtools/client/netmonitor/test/xpcshell/test_request-utils-parseJSON.js b/devtools/client/netmonitor/test/xpcshell/test_request-utils-parseJSON.js
new file mode 100644
index 0000000000..78fd722522
--- /dev/null
+++ b/devtools/client/netmonitor/test/xpcshell/test_request-utils-parseJSON.js
@@ -0,0 +1,78 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Test devtools/client/netmonitor/src/utils/request-utils.js function
+// |parseJSON| ensure that it correctly handles plain JSON, Base 64
+// encoded JSON, and JSON that has XSSI protection prepended to it
+
+"use strict";
+
+const { require } = ChromeUtils.importESModule(
+ "resource://devtools/shared/loader/Loader.sys.mjs"
+);
+const {
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+function run_test() {
+ const validJSON = '{"item":{"subitem":true},"seconditem":"bar"}';
+ const base64JSON = btoa(validJSON);
+ const parsedJSON = { item: { subitem: true }, seconditem: "bar" };
+ const googleStyleXSSI = ")]}'\n";
+ const facebookStyleXSSI = "for (;;);";
+ const notRealXSSIPrevention = "sdgijsdjg";
+ const while1XSSIPrevention = "while(1)";
+
+ const parsedValidJSON = parseJSON(validJSON);
+ info(JSON.stringify(parsedValidJSON));
+ ok(
+ parsedValidJSON.json.item.subitem == parsedJSON.item.subitem &&
+ parsedValidJSON.json.seconditem == parsedJSON.seconditem,
+ "plain JSON is parsed correctly"
+ );
+
+ const parsedBase64JSON = parseJSON(base64JSON);
+ ok(
+ parsedBase64JSON.json.item.subitem === parsedJSON.item.subitem &&
+ parsedBase64JSON.json.seconditem === parsedJSON.seconditem,
+ "base64 encoded JSON is parsed correctly"
+ );
+
+ const parsedGoogleStyleXSSIJSON = parseJSON(googleStyleXSSI + validJSON);
+ ok(
+ parsedGoogleStyleXSSIJSON.strippedChars === googleStyleXSSI &&
+ parsedGoogleStyleXSSIJSON.error === void 0 &&
+ parsedGoogleStyleXSSIJSON.json.item.subitem === parsedJSON.item.subitem &&
+ parsedGoogleStyleXSSIJSON.json.seconditem === parsedJSON.seconditem,
+ "Google style XSSI sequence correctly removed and returned"
+ );
+
+ const parsedFacebookStyleXSSIJSON = parseJSON(facebookStyleXSSI + validJSON);
+ ok(
+ parsedFacebookStyleXSSIJSON.strippedChars === facebookStyleXSSI &&
+ parsedFacebookStyleXSSIJSON.error === void 0 &&
+ parsedFacebookStyleXSSIJSON.json.item.subitem ===
+ parsedJSON.item.subitem &&
+ parsedFacebookStyleXSSIJSON.json.seconditem === parsedJSON.seconditem,
+ "Facebook style XSSI sequence correctly removed and returned"
+ );
+
+ const parsedWhileXSSIJSON = parseJSON(while1XSSIPrevention + validJSON);
+ ok(
+ parsedWhileXSSIJSON.strippedChars === while1XSSIPrevention &&
+ parsedWhileXSSIJSON.error === void 0 &&
+ parsedWhileXSSIJSON.json.item.subitem === parsedJSON.item.subitem &&
+ parsedWhileXSSIJSON.json.seconditem === parsedJSON.seconditem,
+ "While XSSI sequence correctly removed and returned"
+ );
+ const parsedInvalidJson = parseJSON(notRealXSSIPrevention + validJSON);
+ ok(
+ !parsedInvalidJson.json && !parsedInvalidJson.strippedChars,
+ "Parsed invalid JSON does not return a data object or strippedChars"
+ );
+ equal(
+ parsedInvalidJson.error.name,
+ "SyntaxError",
+ "Parsing invalid JSON yeilds a SyntaxError"
+ );
+}
diff --git a/devtools/client/netmonitor/test/xpcshell/xpcshell.ini b/devtools/client/netmonitor/test/xpcshell/xpcshell.ini
new file mode 100644
index 0000000000..a2120e3c9c
--- /dev/null
+++ b/devtools/client/netmonitor/test/xpcshell/xpcshell.ini
@@ -0,0 +1,10 @@
+[DEFAULT]
+tags = devtools
+head =
+firefox-appdir = browser
+skip-if = toolkit == 'android'
+
+[test_doc-utils.js]
+[test_request-utils-fetchNetworkUpdatePacket.js]
+[test_request-utils-js-getFormattedProtocol.js]
+[test_request-utils-parseJSON.js]