From b8157dfaafc42deb3b9824ab6aab1c3e11636d76 Mon Sep 17 00:00:00 2001 From: Victor Porof Date: Fri, 5 Jul 2019 11:29:32 +0200 Subject: [PATCH] Bug 1561435 - Format remaining devtools/, a=automatic-formatting, CLOSED TREE # ignore-this-changeset Differential Revision: https://phabricator.services.mozilla.com/D35894 --HG-- extra : source : 4722b924e08478f5337ab509718bd66906bf472f extra : amend_source : a5baa1aab21639fdba44537e3a10b179b0073cb4 --- .prettierignore | 6 - .../platform/tests/unit/test_nsjsinspector.js | 24 +- devtools/shared/DevToolsUtils.js | 118 ++++--- devtools/shared/Loader.jsm | 43 ++- devtools/shared/Parser.jsm | 39 ++- devtools/shared/ThreadSafeDevToolsUtils.js | 27 +- devtools/shared/adb/adb-addon.js | 21 +- devtools/shared/adb/adb-binary.js | 93 +++-- devtools/shared/adb/adb-device.js | 4 +- devtools/shared/adb/adb-process.js | 48 ++- devtools/shared/adb/adb-runtime.js | 10 +- devtools/shared/adb/adb-socket.js | 8 +- devtools/shared/adb/adb.js | 33 +- devtools/shared/adb/commands/list-devices.js | 26 +- .../adb/commands/prepare-tcp-connection.js | 19 +- devtools/shared/adb/commands/shell.js | 8 +- devtools/shared/adb/commands/track-devices.js | 9 +- devtools/shared/adb/test/test_adb.js | 208 ++++++----- devtools/shared/async-storage.js | 162 +++++---- devtools/shared/base-loader.js | 131 ++++--- devtools/shared/builtin-modules.js | 36 +- devtools/shared/client/connection-manager.js | 69 ++-- devtools/shared/client/debugger-client.js | 165 ++++++--- .../shared/client/deprecated-thread-client.js | 66 ++-- devtools/shared/client/environment-client.js | 6 +- devtools/shared/client/event-source.js | 5 +- devtools/shared/client/long-string-client.js | 5 +- devtools/shared/client/object-client.js | 329 +++++++++++------- .../shared/client/property-iterator-client.js | 38 +- .../shared/client/symbol-iterator-client.js | 27 +- devtools/shared/client/thread-client.js | 7 +- devtools/shared/content-observer.js | 18 +- devtools/shared/css/color.js | 260 +++++++++----- devtools/shared/css/constants.js | 14 +- .../css/generated/generate-properties-db.js | 20 +- devtools/shared/css/lexer.js | 297 +++++++++++----- devtools/shared/css/parsing-utils.js | 141 +++++--- devtools/shared/css/properties-db.js | 7 +- devtools/shared/discovery/discovery.js | 53 +-- .../discovery/tests/unit/test_discovery.js | 21 +- devtools/shared/dom-node-filter-constants.js | 2 +- devtools/shared/event-emitter.js | 23 +- devtools/shared/execution-point-utils.js | 18 +- devtools/shared/fronts/actor-registry.js | 60 ++-- devtools/shared/fronts/addon/addons.js | 7 +- .../addon/webextension-inspected-window.js | 10 +- devtools/shared/fronts/animation.js | 36 +- devtools/shared/fronts/array-buffer.js | 5 +- devtools/shared/fronts/changes.js | 7 +- devtools/shared/fronts/css-properties.js | 82 +++-- devtools/shared/fronts/device.js | 9 +- devtools/shared/fronts/emulation.js | 5 +- devtools/shared/fronts/framerate.js | 5 +- devtools/shared/fronts/highlighters.js | 5 +- devtools/shared/fronts/inspector.js | 113 +++--- .../shared/fronts/inspector/rule-rewriter.js | 126 ++++--- devtools/shared/fronts/layout.js | 8 +- devtools/shared/fronts/memory.js | 29 +- devtools/shared/fronts/node.js | 49 ++- devtools/shared/fronts/perf.js | 5 +- .../shared/fronts/performance-recording.js | 43 ++- devtools/shared/fronts/performance.js | 29 +- devtools/shared/fronts/preference.js | 7 +- devtools/shared/fronts/reflow.js | 7 +- devtools/shared/fronts/root.js | 31 +- devtools/shared/fronts/screenshot.js | 7 +- devtools/shared/fronts/source.js | 5 +- devtools/shared/fronts/storage.js | 5 +- devtools/shared/fronts/string.js | 21 +- devtools/shared/fronts/styles.js | 17 +- devtools/shared/fronts/stylesheets.js | 29 +- devtools/shared/fronts/targets/addon.js | 34 +- .../shared/fronts/targets/browsing-context.js | 17 +- .../shared/fronts/targets/content-process.js | 14 +- .../shared/fronts/targets/target-mixin.js | 43 ++- devtools/shared/fronts/targets/worker.js | 12 +- devtools/shared/fronts/webconsole.js | 21 +- devtools/shared/fronts/websocket.js | 13 +- .../shared/fronts/worker/push-subscription.js | 10 +- .../worker/service-worker-registration.js | 16 +- .../shared/fronts/worker/service-worker.js | 9 +- devtools/shared/generate-uuid.js | 5 +- devtools/shared/heapsnapshot/CensusUtils.js | 31 +- .../shared/heapsnapshot/DominatorTreeNode.js | 85 +++-- .../shared/heapsnapshot/HeapAnalysesClient.js | 22 +- .../shared/heapsnapshot/HeapAnalysesWorker.js | 155 +++++---- .../heapsnapshot/HeapSnapshotFileUtils.js | 11 +- .../shared/heapsnapshot/census-tree-node.js | 67 ++-- .../shared/heapsnapshot/tests/unit/Census.jsm | 31 +- .../shared/heapsnapshot/tests/unit/Match.jsm | 46 ++- .../tests/unit/dominator-tree-worker.js | 7 +- .../tests/unit/head_heapsnapshot.js | 221 ++++++++---- .../tests/unit/heap-snapshot-worker.js | 18 +- ...ominatorTreeNode_LabelAndShallowSize_01.js | 5 +- ...ominatorTreeNode_LabelAndShallowSize_02.js | 5 +- ...ominatorTreeNode_LabelAndShallowSize_03.js | 7 +- ...ominatorTreeNode_LabelAndShallowSize_04.js | 6 +- ...ominatorTreeNode_attachShortestPaths_01.js | 58 +-- ...minatorTreeNode_getNodeByIdAlongPath_01.js | 16 +- .../unit/test_DominatorTreeNode_insert_01.js | 9 +- .../unit/test_DominatorTreeNode_insert_02.js | 9 +- .../unit/test_DominatorTreeNode_insert_03.js | 9 +- ...t_DominatorTreeNode_partialTraversal_01.js | 51 +-- .../tests/unit/test_DominatorTree_03.js | 11 +- .../tests/unit/test_DominatorTree_04.js | 7 +- .../tests/unit/test_DominatorTree_05.js | 44 ++- .../tests/unit/test_DominatorTree_06.js | 23 +- ...st_HeapAnalyses_computeDominatorTree_01.js | 7 +- ...st_HeapAnalyses_getCensusIndividuals_01.js | 51 ++- .../test_HeapAnalyses_getDominatorTree_01.js | 55 ++- ...HeapAnalyses_getImmediatelyDominated_01.js | 40 ++- .../test_HeapAnalyses_takeCensusDiff_01.js | 33 +- .../test_HeapAnalyses_takeCensusDiff_02.js | 19 +- .../unit/test_HeapAnalyses_takeCensus_03.js | 15 +- .../unit/test_HeapAnalyses_takeCensus_04.js | 64 ++-- .../unit/test_HeapAnalyses_takeCensus_05.js | 33 +- .../unit/test_HeapAnalyses_takeCensus_06.js | 22 +- .../unit/test_HeapAnalyses_takeCensus_07.js | 14 +- ...st_HeapSnapshot_computeShortestPaths_01.js | 54 ++- ...st_HeapSnapshot_computeShortestPaths_02.js | 4 +- .../unit/test_HeapSnapshot_deepStack_01.js | 17 +- .../unit/test_HeapSnapshot_takeCensus_02.js | 21 +- .../unit/test_HeapSnapshot_takeCensus_04.js | 16 +- .../unit/test_HeapSnapshot_takeCensus_05.js | 16 +- .../unit/test_HeapSnapshot_takeCensus_06.js | 68 ++-- .../unit/test_HeapSnapshot_takeCensus_07.js | 89 +++-- .../unit/test_HeapSnapshot_takeCensus_08.js | 4 +- .../unit/test_HeapSnapshot_takeCensus_09.js | 42 ++- .../unit/test_HeapSnapshot_takeCensus_10.js | 12 +- .../unit/test_HeapSnapshot_takeCensus_11.js | 14 +- .../unit/test_HeapSnapshot_takeCensus_12.js | 21 +- .../tests/unit/test_ReadHeapSnapshot.js | 4 +- .../test_ReadHeapSnapshot_with_allocations.js | 4 +- .../tests/unit/test_SaveHeapSnapshot.js | 104 ++++-- .../tests/unit/test_census-tree-node-01.js | 16 +- .../tests/unit/test_census-tree-node-02.js | 14 +- .../tests/unit/test_census-tree-node-03.js | 6 +- .../tests/unit/test_census-tree-node-04.js | 8 +- .../tests/unit/test_census-tree-node-05.js | 20 +- .../tests/unit/test_census-tree-node-06.js | 6 +- .../tests/unit/test_census-tree-node-07.js | 2 +- .../tests/unit/test_census-tree-node-10.js | 12 +- .../tests/unit/test_census_diff_01.js | 64 ++-- .../tests/unit/test_census_diff_02.js | 12 +- .../tests/unit/test_census_diff_04.js | 20 +- .../tests/unit/test_census_diff_05.js | 14 +- .../tests/unit/test_census_diff_06.js | 86 +++-- .../tests/unit/test_census_filtering_02.js | 8 +- .../tests/unit/test_census_filtering_03.js | 4 +- .../tests/unit/test_census_filtering_05.js | 19 +- .../tests/unit/test_deduplicatePaths_01.js | 40 +-- .../unit/test_getCensusIndividuals_01.js | 13 +- .../tests/unit/test_getReportLeaves_01.js | 31 +- devtools/shared/indentation.js | 9 +- devtools/shared/indexed-db.js | 6 +- devtools/shared/inspector/css-logic.js | 63 +++- devtools/shared/inspector/utils.js | 8 +- devtools/shared/l10n.js | 48 ++- devtools/shared/layout/dom-matrix-2d.js | 116 +++--- devtools/shared/layout/utils.js | 68 ++-- devtools/shared/multi-e10s-helper.js | 5 +- .../shared/performance/recording-utils.js | 12 +- .../test_perf-utils-allocations-to-samples.js | 72 ++-- devtools/shared/platform/cache-entry.js | 163 ++++----- devtools/shared/platform/clipboard.js | 23 +- devtools/shared/platform/stack.js | 2 +- devtools/shared/protocol/Actor.js | 12 +- devtools/shared/protocol/Pool.js | 2 +- devtools/shared/protocol/lazy-pool.js | 8 +- .../shared/qrcode/tests/unit/test_encode.js | 20 +- devtools/shared/screenshot/capture.js | 41 ++- devtools/shared/screenshot/save.js | 45 ++- devtools/shared/security/auth.js | 40 +-- devtools/shared/security/cert.js | 7 +- devtools/shared/security/prompt.js | 88 +++-- devtools/shared/security/socket.js | 237 ++++++++----- .../shared/security/tests/unit/head_dbg.js | 25 +- .../shared/security/tests/unit/testactors.js | 15 +- devtools/shared/specs/accessibility.js | 8 +- devtools/shared/specs/actor-registry.js | 6 +- devtools/shared/specs/addon/addons.js | 2 +- devtools/shared/specs/addon/webextension.js | 6 +- devtools/shared/specs/animation.js | 4 +- devtools/shared/specs/array-buffer.js | 2 +- devtools/shared/specs/changes.js | 10 +- devtools/shared/specs/device.js | 7 +- devtools/shared/specs/environment.js | 2 +- devtools/shared/specs/frame.js | 2 +- devtools/shared/specs/index.js | 19 +- devtools/shared/specs/inspector.js | 20 +- devtools/shared/specs/memory.js | 2 +- devtools/shared/specs/node.js | 4 +- devtools/shared/specs/perf.js | 7 +- devtools/shared/specs/preference.js | 2 +- devtools/shared/specs/reflow.js | 6 +- devtools/shared/specs/root.js | 8 +- devtools/shared/specs/screenshot.js | 11 +- devtools/shared/specs/source.js | 7 +- devtools/shared/specs/storage.js | 27 +- devtools/shared/specs/string.js | 4 +- devtools/shared/specs/styles.js | 16 +- devtools/shared/specs/stylesheets.js | 2 +- devtools/shared/specs/symbol.js | 4 +- devtools/shared/specs/targets/addon.js | 2 +- .../shared/specs/targets/browsing-context.js | 11 +- .../shared/specs/targets/chrome-window.js | 13 +- .../shared/specs/targets/content-process.js | 6 +- devtools/shared/specs/targets/frame.js | 12 +- .../shared/specs/targets/parent-process.js | 8 +- devtools/shared/specs/targets/webextension.js | 13 +- devtools/shared/specs/targets/worker.js | 2 +- devtools/shared/specs/thread.js | 8 +- devtools/shared/specs/timeline.js | 12 +- devtools/shared/specs/webconsole.js | 15 +- .../worker/service-worker-registration.js | 1 - .../shared/specs/worker/service-worker.js | 1 - devtools/shared/system.js | 32 +- devtools/shared/task.js | 48 +-- .../shared/test-helpers/allocation-tracker.js | 24 +- .../browser_allocation_tracker.js | 46 ++- .../browser/browser_l10n_localizeMarkup.js | 51 ++- devtools/shared/tests/unit/head_devtools.js | 17 +- devtools/shared/tests/unit/test_assert.js | 21 +- .../tests/unit/test_console_filtering.js | 26 +- .../tests/unit/test_console_save-file.js | 10 +- .../tests/unit/test_css-properties-db.js | 70 ++-- devtools/shared/tests/unit/test_csslexer.js | 76 ++-- .../shared/tests/unit/test_debugger_client.js | 5 +- .../tests/unit/test_eventemitter_basic.js | 51 ++- .../tests/unit/test_eventemitter_static.js | 101 ++++-- .../shared/tests/unit/test_executeSoon.js | 11 +- devtools/shared/tests/unit/test_fetch-bom.js | 15 +- .../shared/tests/unit/test_fetch-chrome.js | 22 +- devtools/shared/tests/unit/test_fetch-file.js | 39 ++- devtools/shared/tests/unit/test_fetch-http.js | 21 +- .../shared/tests/unit/test_fetch-resource.js | 22 +- devtools/shared/tests/unit/test_flatten.js | 4 +- .../shared/tests/unit/test_indentation.js | 43 ++- .../tests/unit/test_invisible_loader.js | 12 +- devtools/shared/tests/unit/test_isSet.js | 5 +- .../tests/unit/test_pluralForm-english.js | 7 +- .../tests/unit/test_pluralForm-makeGetter.js | 2 +- .../shared/tests/unit/test_prettifyCSS.js | 140 +++----- devtools/shared/tests/unit/test_require.js | 47 ++- .../shared/tests/unit/test_require_lazy.js | 4 +- .../shared/tests/unit/test_require_raw.js | 13 +- devtools/shared/tests/unit/test_sprintfjs.js | 37 +- devtools/shared/tests/unit/test_stack.js | 2 +- devtools/shared/transport/child-transport.js | 5 +- devtools/shared/transport/local-transport.js | 124 ++++--- devtools/shared/transport/packets.js | 73 ++-- devtools/shared/transport/stream-utils.js | 28 +- .../shared/transport/tests/unit/head_dbg.js | 25 +- .../transport/tests/unit/test_bulk_error.js | 48 +-- .../tests/unit/test_client_server_bulk.js | 248 +++++++------ .../transport/tests/unit/test_dbgsocket.js | 20 +- .../unit/test_dbgsocket_connection_drop.js | 2 +- .../tests/unit/test_delimited_read.js | 7 +- .../transport/tests/unit/test_packet.js | 3 +- .../shared/transport/tests/unit/test_queue.js | 92 ++--- .../tests/unit/test_transport_bulk.js | 90 ++--- .../tests/unit/testactors-no-bulk.js | 4 +- .../shared/transport/tests/unit/testactors.js | 15 +- devtools/shared/transport/transport.js | 67 ++-- .../shared/transport/websocket-transport.js | 4 +- devtools/shared/transport/worker-transport.js | 24 +- devtools/shared/wasm-source-map.js | 43 ++- .../shared/webconsole/js-property-provider.js | 134 ++++--- devtools/shared/webconsole/network-helper.js | 139 +++++--- .../browser/browser_commands_registration.js | 48 ++- .../browser/browser_network_longstring.js | 33 +- .../shared/webconsole/test/browser/head.js | 10 +- devtools/shared/webconsole/test/common.js | 36 +- .../webconsole/test/console-test-worker.js | 2 +- .../test/unit/test_js_property_provider.js | 154 +++++--- .../test/unit/test_network_helper.js | 40 ++- .../unit/test_security-info-certificate.js | 70 ++-- .../test/unit/test_security-info-parser.js | 14 +- .../test_security-info-protocol-version.js | 21 +- .../test/unit/test_security-info-state.js | 35 +- .../unit/test_security-info-static-hpkp.js | 5 +- .../test_security-info-weakness-reasons.js | 15 +- .../webconsole/test/unit/test_throttle.js | 50 ++- devtools/shared/webconsole/throttle.js | 143 +++++--- devtools/shared/worker/helper.js | 9 +- devtools/shared/worker/loader.js | 87 ++--- .../worker/tests/browser/browser_worker-01.js | 31 +- .../worker/tests/browser/browser_worker-02.js | 35 +- .../worker/tests/browser/browser_worker-03.js | 6 +- devtools/shared/worker/worker.js | 66 +++- .../startup/AboutDebuggingRegistration.jsm | 8 +- .../AboutDevToolsToolboxRegistration.jsm | 8 +- devtools/startup/DevToolsShim.jsm | 45 ++- devtools/startup/DevToolsStartup.jsm | 285 ++++++++++----- .../AboutDevToolsRegistration.jsm | 9 +- .../startup/aboutdevtools/aboutdevtools.js | 244 +++++++------ devtools/startup/aboutdevtools/subscribe.js | 226 ++++++------ .../test/browser_aboutdevtools_closes_page.js | 7 +- .../browser_aboutdevtools_enables_devtools.js | 12 +- .../browser_aboutdevtools_focus_owner_tab.js | 25 +- .../browser_aboutdevtools_reuse_existing.js | 11 +- devtools/startup/aboutdevtools/test/head.js | 6 +- .../browser/browser_shim_disable_devtools.js | 62 +++- .../startup/tests/unit/test_devtools_shim.js | 17 +- 304 files changed, 7063 insertions(+), 4270 deletions(-) diff --git a/.prettierignore b/.prettierignore index ad2e97b0ff63..06b09cd70718 100644 --- a/.prettierignore +++ b/.prettierignore @@ -39,12 +39,6 @@ testing/marionette/prefs/marionette.js toolkit/components/telemetry/datareporting-prefs.js toolkit/components/telemetry/healthreport-prefs.js -# Ignore all devtools directories for now, except the debugger. -devtools/docs/** -devtools/platform/** -devtools/shared/** -devtools/startup/** - # Ignore testing pref files which aren't parsed normally. testing/profiles/**/user.js diff --git a/devtools/platform/tests/unit/test_nsjsinspector.js b/devtools/platform/tests/unit/test_nsjsinspector.js index d08edfcb4ab8..a5e63c0cdf69 100644 --- a/devtools/platform/tests/unit/test_nsjsinspector.js +++ b/devtools/platform/tests/unit/test_nsjsinspector.js @@ -7,11 +7,11 @@ var gCount = 0; const MAX = 10; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); var inspector = Cc["@mozilla.org/jsinspector;1"].getService(Ci.nsIJSInspector); // Emulate 10 simultaneously-debugged windows from 3 separate client connections. -var requestor = (count) => ({ +var requestor = count => ({ url: "http://foo/bar/" + count, connection: "conn" + (count % 3), }); @@ -23,7 +23,7 @@ function run_test() { function test_nesting() { Assert.equal(inspector.eventLoopNestLevel, 0); - Services.tm.dispatchToMainThread({ run: enterEventLoop}); + Services.tm.dispatchToMainThread({ run: enterEventLoop }); Assert.equal(inspector.enterNestedEventLoop(requestor(gCount)), 0); Assert.equal(inspector.eventLoopNestLevel, 0); @@ -32,28 +32,32 @@ function test_nesting() { function enterEventLoop() { if (gCount++ < MAX) { - Services.tm.dispatchToMainThread({ run: enterEventLoop}); + Services.tm.dispatchToMainThread({ run: enterEventLoop }); Object.create(requestor(gCount)); Assert.equal(inspector.eventLoopNestLevel, gCount); Assert.equal(inspector.lastNestRequestor.url, requestor(gCount - 1).url); - Assert.equal(inspector.lastNestRequestor.connection, - requestor(gCount - 1).connection); + Assert.equal( + inspector.lastNestRequestor.connection, + requestor(gCount - 1).connection + ); Assert.equal(inspector.enterNestedEventLoop(requestor(gCount)), gCount); } else { Assert.equal(gCount, MAX + 1); - Services.tm.dispatchToMainThread({ run: exitEventLoop}); + Services.tm.dispatchToMainThread({ run: exitEventLoop }); } } function exitEventLoop() { if (inspector.lastNestRequestor != null) { Assert.equal(inspector.lastNestRequestor.url, requestor(gCount - 1).url); - Assert.equal(inspector.lastNestRequestor.connection, - requestor(gCount - 1).connection); + Assert.equal( + inspector.lastNestRequestor.connection, + requestor(gCount - 1).connection + ); if (gCount-- > 1) { - Services.tm.dispatchToMainThread({ run: exitEventLoop}); + Services.tm.dispatchToMainThread({ run: exitEventLoop }); } Assert.equal(inspector.exitNestedEventLoop(), gCount); diff --git a/devtools/shared/DevToolsUtils.js b/devtools/shared/DevToolsUtils.js index 4666667cc595..37a4e83bd644 100644 --- a/devtools/shared/DevToolsUtils.js +++ b/devtools/shared/DevToolsUtils.js @@ -11,10 +11,17 @@ var { Ci, Cc, Cu, components } = require("chrome"); var Services = require("Services"); var flags = require("./flags"); -var {getStack, callFunctionWithAsyncStack} = require("devtools/shared/platform/stack"); +var { + getStack, + callFunctionWithAsyncStack, +} = require("devtools/shared/platform/stack"); -loader.lazyRequireGetter(this, "FileUtils", - "resource://gre/modules/FileUtils.jsm", true); +loader.lazyRequireGetter( + this, + "FileUtils", + "resource://gre/modules/FileUtils.jsm", + true +); // Using this name lets the eslint plugin know about lazy defines in // this file. @@ -37,7 +44,7 @@ for (const key of Object.keys(ThreadSafeDevToolsUtils)) { exports.isCPOW = function(debuggerObject) { try { return Cu.isCrossProcessWrapper(debuggerObject.unsafeDereference()); - } catch (e) { } + } catch (e) {} return false; }; @@ -310,8 +317,9 @@ exports.isSafeJSObject = function(obj) { return false; } - if (Cu.getGlobalForObject(obj) == - Cu.getGlobalForObject(exports.isSafeJSObject)) { + if ( + Cu.getGlobalForObject(obj) == Cu.getGlobalForObject(exports.isSafeJSObject) + ) { // obj is not a cross-compartment wrapper. return true; } @@ -399,7 +407,7 @@ DevToolsUtils.defineLazyGetter(this, "AppConstants", () => { /** * No operation. The empty function. */ -exports.noop = function() { }; +exports.noop = function() {}; let assertionFailureCount = 0; @@ -434,9 +442,10 @@ function reallyAssert(condition, message) { * If assertions are not enabled, then this function is a no-op. */ Object.defineProperty(exports, "assert", { - get: () => (AppConstants.DEBUG_JS_MODULES || flags.testing) - ? reallyAssert - : exports.noop, + get: () => + AppConstants.DEBUG_JS_MODULES || flags.testing + ? reallyAssert + : exports.noop, }); /** @@ -503,13 +512,18 @@ DevToolsUtils.defineLazyGetter(this, "NetworkHelper", () => { * without relying on caching when we can (not for eval, etc.): * http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/ */ -function mainThreadFetch(urlIn, aOptions = { loadFromCache: true, - policy: Ci.nsIContentPolicy.TYPE_OTHER, - window: null, - charset: null, - principal: null, - cacheKey: 0 }) { - return new Promise((resolve, reject) =>{ +function mainThreadFetch( + urlIn, + aOptions = { + loadFromCache: true, + policy: Ci.nsIContentPolicy.TYPE_OTHER, + window: null, + charset: null, + principal: null, + cacheKey: 0, + } +) { + return new Promise((resolve, reject) => { // Create a channel. const url = urlIn.split(" -> ").pop(); let channel; @@ -527,16 +541,19 @@ function mainThreadFetch(urlIn, aOptions = { loadFromCache: true, // When loading from cache, the cacheKey allows us to target a specific // SHEntry and offer ways to restore POST requests from cache. - if (aOptions.loadFromCache && - aOptions.cacheKey != 0 && channel instanceof Ci.nsICacheInfoChannel) { + if ( + aOptions.loadFromCache && + aOptions.cacheKey != 0 && + channel instanceof Ci.nsICacheInfoChannel + ) { channel.cacheKey = aOptions.cacheKey; } if (aOptions.window) { // Respect private browsing. - channel.loadGroup = aOptions.window.docShell - .QueryInterface(Ci.nsIDocumentLoader) - .loadGroup; + channel.loadGroup = aOptions.window.docShell.QueryInterface( + Ci.nsIDocumentLoader + ).loadGroup; } const onResponse = (stream, status, request) => { @@ -560,16 +577,26 @@ function mainThreadFetch(urlIn, aOptions = { loadFromCache: true, // implementation of the "decode" algorithm // (https://encoding.spec.whatwg.org/#decode) exposed to JS. let bomCharset = null; - if (available >= 3 && source.codePointAt(0) == 0xef && - source.codePointAt(1) == 0xbb && source.codePointAt(2) == 0xbf) { + if ( + available >= 3 && + source.codePointAt(0) == 0xef && + source.codePointAt(1) == 0xbb && + source.codePointAt(2) == 0xbf + ) { bomCharset = "UTF-8"; source = source.slice(3); - } else if (available >= 2 && source.codePointAt(0) == 0xfe && - source.codePointAt(1) == 0xff) { + } else if ( + available >= 2 && + source.codePointAt(0) == 0xfe && + source.codePointAt(1) == 0xff + ) { bomCharset = "UTF-16BE"; source = source.slice(2); - } else if (available >= 2 && source.codePointAt(0) == 0xff && - source.codePointAt(1) == 0xfe) { + } else if ( + available >= 2 && + source.codePointAt(0) == 0xff && + source.codePointAt(1) == 0xfe + ) { bomCharset = "UTF-16LE"; source = source.slice(2); } @@ -600,7 +627,10 @@ function mainThreadFetch(urlIn, aOptions = { loadFromCache: true, }); } catch (ex) { const uri = request.originalURI; - if (ex.name === "NS_BASE_STREAM_CLOSED" && uri instanceof Ci.nsIFileURL) { + if ( + ex.name === "NS_BASE_STREAM_CLOSED" && + uri instanceof Ci.nsIFileURL + ) { // Empty files cause NS_BASE_STREAM_CLOSED exception. Use OS.File to // differentiate between empty files and other errors (bug 1170864). // This can be removed when bug 982654 is fixed. @@ -642,7 +672,11 @@ function mainThreadFetch(urlIn, aOptions = { loadFromCache: true, * @param {Object} options - The options object passed to @method fetch. * @return {nsIChannel} - The newly created channel. Throws on failure. */ -function newChannelForURL(url, { policy, window, principal }, recursing = false) { +function newChannelForURL( + url, + { policy, window, principal }, + recursing = false +) { const securityFlags = Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL; let uri; @@ -679,8 +713,7 @@ function newChannelForURL(url, { policy, window, principal }, recursing = false) // and it may not be correct. let prin = principal; if (!prin) { - prin = Services.scriptSecurityManager - .createCodebasePrincipal(uri, {}); + prin = Services.scriptSecurityManager.createCodebasePrincipal(uri, {}); } channelOptions.loadingPrincipal = prin; @@ -698,8 +731,11 @@ function newChannelForURL(url, { policy, window, principal }, recursing = false) // can throw NS_ERROR_UNKNOWN_PROTOCOL if the external protocol isn't // supported by Windows, so we also need to handle the exception here if // parsing the URL above doesn't throw. - return newChannelForURL("file://" + url, { policy, window, principal }, - /* recursing */ true); + return newChannelForURL( + "file://" + url, + { policy, window, principal }, + /* recursing */ true + ); } } @@ -748,7 +784,7 @@ exports.openFileStream = function(filePath) { exports.saveFileStream = function(filePath, istream) { return new Promise((resolve, reject) => { const ostream = FileUtils.openSafeFileOutputStream(filePath); - NetUtil.asyncCopy(istream, ostream, (status) => { + NetUtil.asyncCopy(istream, ostream, status => { if (!components.isSuccessCode(status)) { reject(new Error(`Could not save "${filePath}"`)); return; @@ -782,7 +818,7 @@ exports.showSaveFileDialog = function(parentWindow, suggestedFilename) { fp.appendFilters(fp.filterAll); return new Promise((resolve, reject) => { - fp.open((result) => { + fp.open(result => { if (result == Ci.nsIFilePicker.returnCancel) { reject(); } else { @@ -800,14 +836,16 @@ exports.showSaveFileDialog = function(parentWindow, suggestedFilename) { function errorOnFlag(exports, name) { Object.defineProperty(exports, name, { get: () => { - const msg = `Cannot get the flag ${name}. ` + - `Use the "devtools/shared/flags" module instead`; + const msg = + `Cannot get the flag ${name}. ` + + `Use the "devtools/shared/flags" module instead`; console.error(msg); throw new Error(msg); }, set: () => { - const msg = `Cannot set the flag ${name}. ` + - `Use the "devtools/shared/flags" module instead`; + const msg = + `Cannot set the flag ${name}. ` + + `Use the "devtools/shared/flags" module instead`; console.error(msg); throw new Error(msg); }, diff --git a/devtools/shared/Loader.jsm b/devtools/shared/Loader.jsm index 25cf650943f6..62edb3877879 100644 --- a/devtools/shared/Loader.jsm +++ b/devtools/shared/Loader.jsm @@ -9,14 +9,22 @@ */ var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -var { Loader, Require, resolveURI, unload } = - ChromeUtils.import("resource://devtools/shared/base-loader.js"); -var { requireRawId } = ChromeUtils.import("resource://devtools/shared/loader-plugin-raw.jsm"); +var { Loader, Require, resolveURI, unload } = ChromeUtils.import( + "resource://devtools/shared/base-loader.js" +); +var { requireRawId } = ChromeUtils.import( + "resource://devtools/shared/loader-plugin-raw.jsm" +); -this.EXPORTED_SYMBOLS = ["DevToolsLoader", "devtools", "BuiltinProvider", - "require", "loader", - // Export StructuredCloneHolder for its use from builtin-modules - "StructuredCloneHolder"]; +this.EXPORTED_SYMBOLS = [ + "DevToolsLoader", + "devtools", + "BuiltinProvider", + "require", + "loader", + // Export StructuredCloneHolder for its use from builtin-modules + "StructuredCloneHolder", +]; /** * Providers are different strategies for loading the devtools. @@ -31,9 +39,9 @@ BuiltinProvider.prototype = { load: function() { const paths = { // ⚠ DISCUSSION ON DEV-DEVELOPER-TOOLS REQUIRED BEFORE MODIFYING ⚠ - "devtools": "resource://devtools", + devtools: "resource://devtools", // ⚠ DISCUSSION ON DEV-DEVELOPER-TOOLS REQUIRED BEFORE MODIFYING ⚠ - "acorn": "resource://devtools/shared/acorn", + acorn: "resource://devtools/shared/acorn", // ⚠ DISCUSSION ON DEV-DEVELOPER-TOOLS REQUIRED BEFORE MODIFYING ⚠ "acorn/util/walk": "resource://devtools/shared/acorn/walk.js", // ⚠ DISCUSSION ON DEV-DEVELOPER-TOOLS REQUIRED BEFORE MODIFYING ⚠ @@ -171,7 +179,9 @@ DevToolsLoader.prototype = { this.require = Require(this._provider.loader, { id: "devtools" }); // Fetch custom pseudo modules and globals - const { modules, globals } = this.require("devtools/shared/builtin-modules"); + const { modules, globals } = this.require( + "devtools/shared/builtin-modules" + ); // When creating a Loader for the browser toolbox, we have to use // Promise-backend.js, as a Loader module. Instead of Promise.jsm which @@ -193,7 +203,10 @@ DevToolsLoader.prototype = { // Register custom globals to the current loader instance globals.loader.id = this.id; - Object.defineProperties(loader.globals, Object.getOwnPropertyDescriptors(globals)); + Object.defineProperties( + loader.globals, + Object.getOwnPropertyDescriptors(globals) + ); // Expose lazy helpers on loader this.lazyGetter = globals.loader.lazyGetter; @@ -206,8 +219,12 @@ DevToolsLoader.prototype = { // created for objects in the recording/replaying process. if (globals.isReplaying) { const oldHook = this._provider.loader.requireHook; - const ReplayInspector = this.require("devtools/server/actors/replay/inspector"); - this._provider.loader.requireHook = ReplayInspector.wrapRequireHook(oldHook); + const ReplayInspector = this.require( + "devtools/server/actors/replay/inspector" + ); + this._provider.loader.requireHook = ReplayInspector.wrapRequireHook( + oldHook + ); } }, diff --git a/devtools/shared/Parser.jsm b/devtools/shared/Parser.jsm index 77a6f458495a..a70878af0967 100644 --- a/devtools/shared/Parser.jsm +++ b/devtools/shared/Parser.jsm @@ -9,8 +9,11 @@ const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); const { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm"); const DevToolsUtils = require("devtools/shared/DevToolsUtils"); -ChromeUtils.defineModuleGetter(this, - "Reflect", "resource://gre/modules/reflect.jsm"); +ChromeUtils.defineModuleGetter( + this, + "Reflect", + "resource://gre/modules/reflect.jsm" +); this.EXPORTED_SYMBOLS = ["Parser", "ParserHelpers", "SyntaxTreeVisitor"]; @@ -141,8 +144,13 @@ SyntaxTreesPool.prototype = { * @see SyntaxTree.prototype.getIdentifierAt */ getIdentifierAt({ line, column, scriptIndex, ignoreLiterals }) { - return this._call("getIdentifierAt", - scriptIndex, line, column, ignoreLiterals)[0]; + return this._call( + "getIdentifierAt", + scriptIndex, + line, + column, + ignoreLiterals + )[0]; }, /** @@ -232,7 +240,9 @@ SyntaxTreesPool.prototype = { // Language features may be added, in which case the recursive methods // need to be updated. If an exception is thrown here, file a bug. DevToolsUtils.reportException( - `Syntax tree visitor for ${this._url}`, e); + `Syntax tree visitor for ${this._url}`, + e + ); } } this._cache.set(requestId, results); @@ -442,8 +452,10 @@ var ParserHelpers = { const { loc: parentLocation, type: parentType } = node._parent; const { loc: nodeLocation } = node; if (!nodeLocation) { - if (parentType == "FunctionDeclaration" || - parentType == "FunctionExpression") { + if ( + parentType == "FunctionDeclaration" || + parentType == "FunctionExpression" + ) { // e.g. "function foo() {}" or "{ bar: function foo() {} }" // The location is unavailable for the identifier node "foo". const loc = Cu.cloneInto(parentLocation, {}); @@ -516,8 +528,12 @@ var ParserHelpers = { */ nodeContainsPoint(node, line, column) { const { start: s, end: e } = this.getNodeLocation(node); - return s.line == line && e.line == line && - s.column <= column && e.column >= column; + return ( + s.line == line && + e.line == line && + s.column <= column && + e.column >= column + ); }, /** @@ -708,8 +724,9 @@ var ParserHelpers = { // directly as an evaluation string. Otherwise, construct the property // access chain, since the value might have changed. if (!this._getObjectExpressionPropertyKeyForValue(node)) { - const propertyChain = - this._getObjectExpressionPropertyChain(node._parent); + const propertyChain = this._getObjectExpressionPropertyChain( + node._parent + ); const propertyLeaf = node.name; return [...propertyChain, propertyLeaf].join("."); } diff --git a/devtools/shared/ThreadSafeDevToolsUtils.js b/devtools/shared/ThreadSafeDevToolsUtils.js index 8d93d0463689..cc6300016797 100644 --- a/devtools/shared/ThreadSafeDevToolsUtils.js +++ b/devtools/shared/ThreadSafeDevToolsUtils.js @@ -81,7 +81,9 @@ exports.isCPOW = function() { * Report that |who| threw an exception, |exception|. */ exports.reportException = function reportException(who, exception) { - const msg = `${who} threw an exception: ${exports.safeErrorString(exception)}`; + const msg = `${who} threw an exception: ${exports.safeErrorString( + exception + )}`; dump(msg + "\n"); if (typeof console !== "undefined" && console && console.error) { @@ -142,8 +144,12 @@ exports.safeErrorString = function(error) { // Append additional line and column number information to the output, // since it might not be part of the stringified error. - if (typeof error.lineNumber == "number" && typeof error.columnNumber == "number") { - errorString += "Line: " + error.lineNumber + ", column: " + error.columnNumber; + if ( + typeof error.lineNumber == "number" && + typeof error.columnNumber == "number" + ) { + errorString += + "Line: " + error.lineNumber + ", column: " + error.columnNumber; } return errorString; @@ -174,9 +180,11 @@ exports.zip = function(a, b) { return b; } const pairs = []; - for (let i = 0, aLength = a.length, bLength = b.length; - i < aLength || i < bLength; - i++) { + for ( + let i = 0, aLength = a.length, bLength = b.length; + i < aLength || i < bLength; + i++ + ) { pairs.push([a[i], b[i]]); } return pairs; @@ -219,8 +227,7 @@ exports.compose = function compose(...funcs) { return (...args) => { const initialValue = funcs[funcs.length - 1](...args); const leftFuncs = funcs.slice(0, -1); - return leftFuncs.reduceRight((composed, f) => f(composed), - initialValue); + return leftFuncs.reduceRight((composed, f) => f(composed), initialValue); }; }; @@ -311,7 +318,7 @@ exports.flatten = function(lists) { * promise in the list of given promises to be rejected. */ exports.settleAll = values => { - if (values === null || typeof (values[Symbol.iterator]) != "function") { + if (values === null || typeof values[Symbol.iterator] != "function") { throw new Error("settleAll() expects an iterable."); } @@ -353,7 +360,7 @@ exports.settleAll = values => { checkForCompletion(); }; - if (value && typeof (value.then) == "function") { + if (value && typeof value.then == "function") { value.then(resolver, rejecter); } else { // Given value is not a promise, forward it as a resolution value. diff --git a/devtools/shared/adb/adb-addon.js b/devtools/shared/adb/adb-addon.js index 16852d2dc2d1..c5806f072a15 100644 --- a/devtools/shared/adb/adb-addon.js +++ b/devtools/shared/adb/adb-addon.js @@ -4,7 +4,7 @@ "use strict"; -const {AddonManager} = require("resource://gre/modules/AddonManager.jsm"); +const { AddonManager } = require("resource://gre/modules/AddonManager.jsm"); const Services = require("Services"); const EventEmitter = require("devtools/shared/event-emitter"); @@ -44,10 +44,8 @@ class ADBAddon extends EventEmitter { this._status = ADB_ADDON_STATES.UNKNOWN; const addonsListener = {}; - addonsListener.onEnabled = - addonsListener.onDisabled = - addonsListener.onInstalled = - addonsListener.onUninstalled = () => this.updateInstallStatus(); + addonsListener.onEnabled = addonsListener.onDisabled = addonsListener.onInstalled = addonsListener.onUninstalled = () => + this.updateInstallStatus(); AddonManager.addAddonListener(addonsListener); this.updateInstallStatus(); @@ -109,7 +107,9 @@ class ADBAddon extends EventEmitter { */ async install(source) { if (!source) { - throw new Error("Missing mandatory `source` parameter for adb-addon.install"); + throw new Error( + "Missing mandatory `source` parameter for adb-addon.install" + ); } const addon = await this._getAddon(); @@ -121,10 +121,9 @@ class ADBAddon extends EventEmitter { if (addon && addon.userDisabled) { await addon.enable(); } else { - const install = await AddonManager.getInstallForURL( - this._getXpiLink(), - {telemetryInfo: {source}} - ); + const install = await AddonManager.getInstallForURL(this._getXpiLink(), { + telemetryInfo: { source }, + }); install.addListener(this); install.install(); } @@ -199,7 +198,7 @@ class ADBAddon extends EventEmitter { } // Expected AddonManager install listener. - onInstallEnded({addon}) { + onInstallEnded({ addon }) { addon.enable(); } } diff --git a/devtools/shared/adb/adb-binary.js b/devtools/shared/adb/adb-binary.js index 78f3ec42ca36..960fd72732b5 100644 --- a/devtools/shared/adb/adb-binary.js +++ b/devtools/shared/adb/adb-binary.js @@ -7,12 +7,24 @@ const { dumpn } = require("devtools/shared/DevToolsUtils"); loader.lazyImporter(this, "OS", "resource://gre/modules/osfile.jsm"); -loader.lazyImporter(this, "ExtensionParent", "resource://gre/modules/ExtensionParent.jsm"); +loader.lazyImporter( + this, + "ExtensionParent", + "resource://gre/modules/ExtensionParent.jsm" +); loader.lazyRequireGetter(this, "Services"); -loader.lazyRequireGetter(this, "FileUtils", - "resource://gre/modules/FileUtils.jsm", true); -loader.lazyRequireGetter(this, "NetUtil", - "resource://gre/modules/NetUtil.jsm", true); +loader.lazyRequireGetter( + this, + "FileUtils", + "resource://gre/modules/FileUtils.jsm", + true +); +loader.lazyRequireGetter( + this, + "NetUtil", + "resource://gre/modules/NetUtil.jsm", + true +); loader.lazyGetter(this, "UNPACKED_ROOT_PATH", () => { return OS.Path.join(OS.Constants.Path.localProfileDir, "adb"); }); @@ -35,18 +47,24 @@ const MANIFEST = "manifest.json"; */ async function readFromExtension(fileUri) { return new Promise(resolve => { - NetUtil.asyncFetch({ - uri: fileUri, - loadUsingSystemPrincipal: true, - }, (input) => { - try { - const string = NetUtil.readInputStreamToString(input, input.available()); - resolve(JSON.parse(string)); - } catch (e) { - dumpn(`Could not read ${fileUri} in the extension: ${e}`); - resolve(null); + NetUtil.asyncFetch( + { + uri: fileUri, + loadUsingSystemPrincipal: true, + }, + input => { + try { + const string = NetUtil.readInputStreamToString( + input, + input.available() + ); + resolve(JSON.parse(string)); + } catch (e) { + dumpn(`Could not read ${fileUri} in the extension: ${e}`); + resolve(null); + } } - }); + ); }); } @@ -67,21 +85,24 @@ async function unpackFile(file) { const basePath = file.substring(file.lastIndexOf("/") + 1); const filePath = OS.Path.join(UNPACKED_ROOT_PATH, basePath); await new Promise((resolve, reject) => { - NetUtil.asyncFetch({ - uri: policy.getURL(file), - loadUsingSystemPrincipal: true, - }, (input) => { - try { - // Since we have to use NetUtil to read, probably it's okay to use for - // writing, rather than bouncing to OS.File...? - const outputFile = new FileUtils.File(filePath); - const output = FileUtils.openAtomicFileOutputStream(outputFile); - NetUtil.asyncCopy(input, output, resolve); - } catch (e) { - dumpn(`Could not unpack file ${file} in the extension: ${e}`); - reject(e); + NetUtil.asyncFetch( + { + uri: policy.getURL(file), + loadUsingSystemPrincipal: true, + }, + input => { + try { + // Since we have to use NetUtil to read, probably it's okay to use for + // writing, rather than bouncing to OS.File...? + const outputFile = new FileUtils.File(filePath); + const output = FileUtils.openAtomicFileOutputStream(outputFile); + NetUtil.asyncCopy(input, output, resolve); + } catch (e) { + dumpn(`Could not unpack file ${file} in the extension: ${e}`); + reject(e); + } } - }); + ); }); // Mark binaries as executable. await OS.File.setPermissions(filePath, { unixMode: 0o744 }); @@ -172,7 +193,7 @@ async function isManifestUnpacked() { * Uses OS.File since this is a local file. */ async function getManifestFromUnpacked() { - if (!await isManifestUnpacked()) { + if (!(await isManifestUnpacked())) { throw new Error("Manifest doesn't exist at unpacked path"); } @@ -182,8 +203,7 @@ async function getManifestFromUnpacked() { let data; try { data = JSON.parse(json); - } catch (e) { - } + } catch (e) {} return data; } @@ -191,7 +211,7 @@ async function getManifestFromUnpacked() { * Check state of binary unpacking, including the location and manifest. */ async function isUnpacked() { - if (!await isManifestUnpacked()) { + if (!(await isManifestUnpacked())) { dumpn("Needs unpacking, no manifest found"); return false; } @@ -201,7 +221,7 @@ async function isUnpacked() { if (manifestInExtension.version != unpackedManifest.version) { dumpn( `Needs unpacking, extension version ${manifestInExtension.version} != ` + - `unpacked version ${unpackedManifest.version}` + `unpacked version ${unpackedManifest.version}` ); return false; } @@ -217,8 +237,7 @@ async function isUnpacked() { * File object for the binary. */ async function getFileForBinary() { - if (!await isUnpacked() && - !await extractFiles()) { + if (!(await isUnpacked()) && !(await extractFiles())) { return null; } diff --git a/devtools/shared/adb/adb-device.js b/devtools/shared/adb/adb-device.js index d2f56a69f262..4fbc7e56e9e0 100644 --- a/devtools/shared/adb/adb-device.js +++ b/devtools/shared/adb/adb-device.js @@ -33,7 +33,9 @@ class AdbDevice { // Filter to lines with "firefox-debugger-socket" let socketInfos = rawSocketInfo.split(/\r?\n/); - socketInfos = socketInfos.filter(l => l.includes("firefox-debugger-socket")); + socketInfos = socketInfos.filter(l => + l.includes("firefox-debugger-socket") + ); // It's possible to have multiple lines with the same path, so de-dupe them const socketPaths = new Set(); diff --git a/devtools/shared/adb/adb-process.js b/devtools/shared/adb/adb-process.js index ef55f5107b7f..25a1a281f4b0 100644 --- a/devtools/shared/adb/adb-process.js +++ b/devtools/shared/adb/adb-process.js @@ -10,8 +10,18 @@ const EventEmitter = require("devtools/shared/event-emitter"); const { getFileForBinary } = require("./adb-binary"); const { setTimeout } = require("resource://gre/modules/Timer.jsm"); -loader.lazyRequireGetter(this, "runCommand", "devtools/shared/adb/commands/index", true); -loader.lazyRequireGetter(this, "check", "devtools/shared/adb/adb-running-checker", true); +loader.lazyRequireGetter( + this, + "runCommand", + "devtools/shared/adb/commands/index", + true +); +loader.lazyRequireGetter( + this, + "check", + "devtools/shared/adb/adb-running-checker", + true +); // Waits until a predicate returns true or re-tries the predicate calls // |retry| times, we wait for 100ms between each calls. @@ -51,18 +61,23 @@ class AdbProcess extends EventEmitter { async _runProcess(process, params) { return new Promise((resolve, reject) => { - process.runAsync(params, params.length, { - observe(subject, topic, data) { - switch (topic) { - case "process-finished": - resolve(); - break; - case "process-failed": - reject(); - break; - } + process.runAsync( + params, + params.length, + { + observe(subject, topic, data) { + switch (topic) { + case "process-finished": + resolve(); + break; + case "process-failed": + reject(); + break; + } + }, }, - }, false); + false + ); }); } @@ -85,7 +100,9 @@ class AdbProcess extends EventEmitter { dumpn("Didn't find ADB process running, restarting"); this._didRunInitially = true; - const process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess); + const process = Cc["@mozilla.org/process/util;1"].createInstance( + Ci.nsIProcess + ); // FIXME: Bug 1481691 - We should avoid extracting files every time. const adbFile = await this._getAdbFile(); @@ -98,8 +115,7 @@ class AdbProcess extends EventEmitter { try { await this._runProcess(process, params); isStarted = await waitUntil(check); - } catch (e) { - } + } catch (e) {} if (isStarted) { onSuccessfulStart(); diff --git a/devtools/shared/adb/adb-runtime.js b/devtools/shared/adb/adb-runtime.js index cb2a7d49a18b..bda33353dc37 100644 --- a/devtools/shared/adb/adb-runtime.js +++ b/devtools/shared/adb/adb-runtime.js @@ -4,7 +4,9 @@ "use strict"; -const { RuntimeTypes } = require("devtools/client/webide/modules/runtime-types"); +const { + RuntimeTypes, +} = require("devtools/client/webide/modules/runtime-types"); const { prepareTCPConnection } = require("devtools/shared/adb/commands/index"); const { shell } = require("devtools/shared/adb/commands/index"); @@ -94,9 +96,9 @@ class AdbRuntime { // If using path base socket, it is "/data/data/..."" // Until Fennec 62 only supports path based UNIX domain socket, but // Fennec 63+ supports both path based and abstract socket. - return this._socketPath.startsWith("@") ? - this._socketPath.substr(1).split("/")[0] : - this._socketPath.split("/")[3]; + return this._socketPath.startsWith("@") + ? this._socketPath.substr(1).split("/")[0] + : this._socketPath.split("/")[3]; } } exports.AdbRuntime = AdbRuntime; diff --git a/devtools/shared/adb/adb-socket.js b/devtools/shared/adb/adb-socket.js index bf67a61fd1da..6330a6cc30fd 100644 --- a/devtools/shared/adb/adb-socket.js +++ b/devtools/shared/adb/adb-socket.js @@ -8,8 +8,9 @@ const { Cu } = require("chrome"); const { dumpn } = require("devtools/shared/DevToolsUtils"); function createTCPSocket(location, port, options) { - const { TCPSocket } = - Cu.getGlobalForObject(Cu.import("resource://gre/modules/Services.jsm", {})); + const { TCPSocket } = Cu.getGlobalForObject( + Cu.import("resource://gre/modules/Services.jsm", {}) + ); return new TCPSocket(location, port, options); } @@ -63,8 +64,7 @@ class AdbSocket { } close() { - if (this.s.readyState === "open" || - this.s.readyState === "connecting") { + if (this.s.readyState === "open" || this.s.readyState === "connecting") { this.s.close(); } } diff --git a/devtools/shared/adb/adb.js b/devtools/shared/adb/adb.js index 1f103a9f0ad5..b57d05e394d6 100644 --- a/devtools/shared/adb/adb.js +++ b/devtools/shared/adb/adb.js @@ -4,15 +4,25 @@ "use strict"; -const { clearInterval, setInterval } = require("resource://gre/modules/Timer.jsm"); +const { + clearInterval, + setInterval, +} = require("resource://gre/modules/Timer.jsm"); const EventEmitter = require("devtools/shared/event-emitter"); const { adbProcess } = require("devtools/shared/adb/adb-process"); const { adbAddon } = require("devtools/shared/adb/adb-addon"); const AdbDevice = require("devtools/shared/adb/adb-device"); const { AdbRuntime } = require("devtools/shared/adb/adb-runtime"); -const { TrackDevicesCommand } = require("devtools/shared/adb/commands/track-devices"); -loader.lazyRequireGetter(this, "check", "devtools/shared/adb/adb-running-checker", true); +const { + TrackDevicesCommand, +} = require("devtools/shared/adb/commands/track-devices"); +loader.lazyRequireGetter( + this, + "check", + "devtools/shared/adb/adb-running-checker", + true +); // Duration in milliseconds of the runtime polling. We resort to polling here because we // have no event to know when a runtime started on an already discovered ADB device. @@ -37,8 +47,14 @@ class Adb extends EventEmitter { this._onNoDevicesDetected = this._onNoDevicesDetected.bind(this); this._trackDevicesCommand.on("device-connected", this._onDeviceConnected); - this._trackDevicesCommand.on("device-disconnected", this._onDeviceDisconnected); - this._trackDevicesCommand.on("no-devices-detected", this._onNoDevicesDetected); + this._trackDevicesCommand.on( + "device-disconnected", + this._onDeviceDisconnected + ); + this._trackDevicesCommand.on( + "no-devices-detected", + this._onNoDevicesDetected + ); adbAddon.on("update", this._updateAdbProcess); } @@ -87,7 +103,10 @@ class Adb extends EventEmitter { // Device runtimes are detected by running a shell command and checking for // "firefox-debugger-socket" in the list of currently running processes. - this._timer = setInterval(this.updateRuntimes.bind(this), UPDATE_RUNTIMES_INTERVAL); + this._timer = setInterval( + this.updateRuntimes.bind(this), + UPDATE_RUNTIMES_INTERVAL + ); } async _stopTracking() { @@ -138,7 +157,7 @@ class Adb extends EventEmitter { } async _getDeviceRuntimes(device) { - const socketPaths = [...await device.getRuntimeSocketPaths()]; + const socketPaths = [...(await device.getRuntimeSocketPaths())]; const runtimes = []; for (const socketPath of socketPaths) { const runtime = new AdbRuntime(device, socketPath); diff --git a/devtools/shared/adb/commands/list-devices.js b/devtools/shared/adb/commands/list-devices.js index bff26622edd3..ed2d586673e7 100644 --- a/devtools/shared/adb/commands/list-devices.js +++ b/devtools/shared/adb/commands/list-devices.js @@ -13,19 +13,17 @@ const { dumpn } = require("devtools/shared/DevToolsUtils"); const listDevices = function() { dumpn("listDevices"); - return this.runCommand("host:devices").then( - function onSuccess(data) { - const lines = data.split("\n"); - const res = []; - lines.forEach(function(line) { - if (line.length == 0) { - return; - } - const [ device ] = line.split("\t"); - res.push(device); - }); - return res; - } - ); + return this.runCommand("host:devices").then(function onSuccess(data) { + const lines = data.split("\n"); + const res = []; + lines.forEach(function(line) { + if (line.length == 0) { + return; + } + const [device] = line.split("\t"); + res.push(device); + }); + return res; + }); }; exports.listDevices = listDevices; diff --git a/devtools/shared/adb/commands/prepare-tcp-connection.js b/devtools/shared/adb/commands/prepare-tcp-connection.js index f41501db98e0..7efd23df6adf 100644 --- a/devtools/shared/adb/commands/prepare-tcp-connection.js +++ b/devtools/shared/adb/commands/prepare-tcp-connection.js @@ -5,7 +5,9 @@ "use strict"; const { dumpn } = require("devtools/shared/DevToolsUtils"); -const { ConnectionManager } = require("devtools/shared/client/connection-manager"); +const { + ConnectionManager, +} = require("devtools/shared/client/connection-manager"); const { runCommand } = require("./run-command"); // sends adb forward deviceId, localPort and devicePort @@ -14,20 +16,21 @@ const forwardPort = function(deviceId, localPort, devicePort) { // Send "host-serial::", // with set to "forward:;" // See https://android.googlesource.com/platform/system/core/+/jb-dev/adb/SERVICES.TXT - return runCommand(`host-serial:${ deviceId }:forward:${ localPort };${ devicePort }`) - .then(function onSuccess(data) { - return data; - }); + return runCommand( + `host-serial:${deviceId}:forward:${localPort};${devicePort}` + ).then(function onSuccess(data) { + return data; + }); }; // Prepare TCP connection for provided device id and socket path. // The returned value is a port number of localhost for the connection. const prepareTCPConnection = async function(deviceId, socketPath) { const port = ConnectionManager.getFreeTCPPort(); - const local = `tcp:${ port }`; + const local = `tcp:${port}`; const remote = socketPath.startsWith("@") - ? `localabstract:${ socketPath.substring(1) }` - : `localfilesystem:${ socketPath }`; + ? `localabstract:${socketPath.substring(1)}` + : `localfilesystem:${socketPath}`; await forwardPort(deviceId, local, remote); return port; }; diff --git a/devtools/shared/adb/commands/shell.js b/devtools/shared/adb/commands/shell.js index 1e5ed63ad071..5e4120391bf0 100644 --- a/devtools/shared/adb/commands/shell.js +++ b/devtools/shared/adb/commands/shell.js @@ -65,11 +65,13 @@ const shell = async function(deviceId, command) { break; } ignoreResponseCode = true; - // eslint-disable-next-lined no-fallthrough + // eslint-disable-next-lined no-fallthrough case "decode-shell": const decoder = new TextDecoder(); - const text = new Uint8Array(client.getBuffer(data), - ignoreResponseCode ? 4 : 0); + const text = new Uint8Array( + client.getBuffer(data), + ignoreResponseCode ? 4 : 0 + ); stdout += decoder.decode(text); break; default: diff --git a/devtools/shared/adb/commands/track-devices.js b/devtools/shared/adb/commands/track-devices.js index 3c9c5dbfd829..372ab25aa03e 100644 --- a/devtools/shared/adb/commands/track-devices.js +++ b/devtools/shared/adb/commands/track-devices.js @@ -110,7 +110,10 @@ class TrackDevicesCommand extends EventEmitter { }); // Fire events if needed. - const deviceIds = new Set([...this._devices.keys(), ...newDevices.keys()]); + const deviceIds = new Set([ + ...this._devices.keys(), + ...newDevices.keys(), + ]); for (const deviceId of deviceIds) { const currentStatus = this._devices.get(deviceId); const newStatus = newDevices.get(deviceId); @@ -137,7 +140,9 @@ class TrackDevicesCommand extends EventEmitter { } _fireConnectionEventIfNeeded(deviceId, currentStatus, newStatus) { - const isCurrentOnline = !!(currentStatus && currentStatus !== ADB_STATUS_OFFLINE); + const isCurrentOnline = !!( + currentStatus && currentStatus !== ADB_STATUS_OFFLINE + ); const isNewOnline = !!(newStatus && newStatus !== ADB_STATUS_OFFLINE); if (isCurrentOnline === isNewOnline) { diff --git a/devtools/shared/adb/test/test_adb.js b/devtools/shared/adb/test/test_adb.js index e21a7ac5c06c..b013ecfb13d3 100644 --- a/devtools/shared/adb/test/test_adb.js +++ b/devtools/shared/adb/test/test_adb.js @@ -3,7 +3,9 @@ "use strict"; -const { ExtensionTestUtils } = ChromeUtils.import("resource://testing-common/ExtensionXPCShellUtils.jsm"); +const { ExtensionTestUtils } = ChromeUtils.import( + "resource://testing-common/ExtensionXPCShellUtils.jsm" +); const { NetUtil } = require("resource://gre/modules/NetUtil.jsm"); const { getFileForBinary } = require("devtools/shared/adb/adb-binary"); const { check } = require("devtools/shared/adb/adb-running-checker"); @@ -11,30 +13,16 @@ const { adbProcess } = require("devtools/shared/adb/adb-process"); const { TrackDevicesCommand } = require("devtools/shared/adb/commands/index"); const ADB_JSON = { - "Linux": { - "x86": [ - "linux/adb", - ], - "x86_64": [ - "linux64/adb", - ], + Linux: { + x86: ["linux/adb"], + x86_64: ["linux64/adb"], }, - "Darwin": { - "x86_64": [ - "mac64/adb", - ], + Darwin: { + x86_64: ["mac64/adb"], }, - "WINNT": { - "x86": [ - "win32/adb.exe", - "win32/AdbWinApi.dll", - "win32/AdbWinUsbApi.dll", - ], - "x86_64": [ - "win32/adb.exe", - "win32/AdbWinApi.dll", - "win32/AdbWinUsbApi.dll", - ], + WINNT: { + x86: ["win32/adb.exe", "win32/AdbWinApi.dll", "win32/AdbWinUsbApi.dll"], + x86_64: ["win32/adb.exe", "win32/AdbWinApi.dll", "win32/AdbWinUsbApi.dll"], }, }; let extension_version = 1.0; @@ -43,8 +31,9 @@ ExtensionTestUtils.init(this); function readAdbMockContent() { const adbMockFile = do_get_file("adb.py", false); - const s = Cc["@mozilla.org/network/file-input-stream;1"] - .createInstance(Ci.nsIFileInputStream); + const s = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); s.init(adbMockFile, -1, -1, false); try { return NetUtil.readInputStreamToString(s, s.available()); @@ -152,92 +141,97 @@ add_task(async function testExtract() { await extension.unload(); }); -add_task({ - skip_if: () => mozinfo.os == "win", // bug 1482008 -}, async function testStartAndStop() { - const extension = ExtensionTestUtils.loadExtension({ - manifest: { - version: (extension_version++).toString(), - applications: { - gecko: { id: "adb@mozilla.org" }, +add_task( + { + skip_if: () => mozinfo.os == "win", // bug 1482008 + }, + async function testStartAndStop() { + const extension = ExtensionTestUtils.loadExtension({ + manifest: { + version: (extension_version++).toString(), + applications: { + gecko: { id: "adb@mozilla.org" }, + }, }, - }, - files: { - "adb.json": JSON.stringify(ADB_JSON), - "linux/adb": adbMock, - "linux64/adb": adbMock, - "mac64/adb": adbMock, - "win32/adb.exe": adbMock, - "win32/AdbWinApi.dll": "dummy", - "win32/AdbWinUsbApi.dll": "dummy", - }, - }); - - await extension.startup(); - - // Call start() once and call stop() afterwards. - await adbProcess.start(); - ok(adbProcess.ready); - ok(await check(), "adb is now running"); - - await adbProcess.stop(); - ok(!adbProcess.ready); - ok(!(await check()), "adb is no longer running"); - - // Call start() twice and call stop() afterwards. - await adbProcess.start(); - await adbProcess.start(); - ok(adbProcess.ready); - ok(await check(), "adb is now running"); - - await adbProcess.stop(); - ok(!adbProcess.ready); - ok(!(await check()), "adb is no longer running"); - - await extension.unload(); -}); - -add_task({ - skip_if: () => mozinfo.os == "win", // bug 1482008 -}, async function testTrackDevices() { - const extension = ExtensionTestUtils.loadExtension({ - manifest: { - version: (extension_version++).toString(), - applications: { - gecko: { id: "adb@mozilla.org" }, + files: { + "adb.json": JSON.stringify(ADB_JSON), + "linux/adb": adbMock, + "linux64/adb": adbMock, + "mac64/adb": adbMock, + "win32/adb.exe": adbMock, + "win32/AdbWinApi.dll": "dummy", + "win32/AdbWinUsbApi.dll": "dummy", }, - }, - files: { - "adb.json": JSON.stringify(ADB_JSON), - "linux/adb": adbMock, - "linux64/adb": adbMock, - "mac64/adb": adbMock, - "win32/adb.exe": adbMock, - "win32/AdbWinApi.dll": "dummy", - "win32/AdbWinUsbApi.dll": "dummy", - }, - }); - - await extension.startup(); - - await adbProcess.start(); - ok(adbProcess.ready); - - ok(await check(), "adb is now running"); - - const receivedDeviceId = await new Promise(resolve => { - const trackDevicesCommand = new TrackDevicesCommand(); - trackDevicesCommand.on("device-connected", deviceId => { - resolve(deviceId); }); - trackDevicesCommand.run(); - }); - equal(receivedDeviceId, "1234567890"); + await extension.startup(); - await adbProcess.stop(); - ok(!adbProcess.ready); + // Call start() once and call stop() afterwards. + await adbProcess.start(); + ok(adbProcess.ready); + ok(await check(), "adb is now running"); - await extension.unload(); -}); + await adbProcess.stop(); + ok(!adbProcess.ready); + ok(!(await check()), "adb is no longer running"); + // Call start() twice and call stop() afterwards. + await adbProcess.start(); + await adbProcess.start(); + ok(adbProcess.ready); + ok(await check(), "adb is now running"); + + await adbProcess.stop(); + ok(!adbProcess.ready); + ok(!(await check()), "adb is no longer running"); + + await extension.unload(); + } +); + +add_task( + { + skip_if: () => mozinfo.os == "win", // bug 1482008 + }, + async function testTrackDevices() { + const extension = ExtensionTestUtils.loadExtension({ + manifest: { + version: (extension_version++).toString(), + applications: { + gecko: { id: "adb@mozilla.org" }, + }, + }, + files: { + "adb.json": JSON.stringify(ADB_JSON), + "linux/adb": adbMock, + "linux64/adb": adbMock, + "mac64/adb": adbMock, + "win32/adb.exe": adbMock, + "win32/AdbWinApi.dll": "dummy", + "win32/AdbWinUsbApi.dll": "dummy", + }, + }); + + await extension.startup(); + + await adbProcess.start(); + ok(adbProcess.ready); + + ok(await check(), "adb is now running"); + + const receivedDeviceId = await new Promise(resolve => { + const trackDevicesCommand = new TrackDevicesCommand(); + trackDevicesCommand.on("device-connected", deviceId => { + resolve(deviceId); + }); + trackDevicesCommand.run(); + }); + + equal(receivedDeviceId, "1234567890"); + + await adbProcess.stop(); + ok(!adbProcess.ready); + + await extension.unload(); + } +); diff --git a/devtools/shared/async-storage.js b/devtools/shared/async-storage.js index f590bd798c3c..732febe6a814 100644 --- a/devtools/shared/async-storage.js +++ b/devtools/shared/async-storage.js @@ -73,70 +73,90 @@ function withStore(type, onsuccess, onerror) { function getItem(itemKey) { return new Promise((resolve, reject) => { let req; - withStore("readonly", (store) => { - store.transaction.oncomplete = function onComplete() { - let value = req.result; - if (value === undefined) { - value = null; - } - resolve(value); - }; - req = store.get(itemKey); - req.onerror = function getItemOnError() { - reject("Error in asyncStorage.getItem(): ", req.error.name); - }; - }, reject); + withStore( + "readonly", + store => { + store.transaction.oncomplete = function onComplete() { + let value = req.result; + if (value === undefined) { + value = null; + } + resolve(value); + }; + req = store.get(itemKey); + req.onerror = function getItemOnError() { + reject("Error in asyncStorage.getItem(): ", req.error.name); + }; + }, + reject + ); }); } function setItem(itemKey, value) { return new Promise((resolve, reject) => { - withStore("readwrite", (store) => { - store.transaction.oncomplete = resolve; - const req = store.put(value, itemKey); - req.onerror = function setItemOnError() { - reject("Error in asyncStorage.setItem(): ", req.error.name); - }; - }, reject); + withStore( + "readwrite", + store => { + store.transaction.oncomplete = resolve; + const req = store.put(value, itemKey); + req.onerror = function setItemOnError() { + reject("Error in asyncStorage.setItem(): ", req.error.name); + }; + }, + reject + ); }); } function removeItem(itemKey) { return new Promise((resolve, reject) => { - withStore("readwrite", (store) => { - store.transaction.oncomplete = resolve; - const req = store.delete(itemKey); - req.onerror = function removeItemOnError() { - reject("Error in asyncStorage.removeItem(): ", req.error.name); - }; - }, reject); + withStore( + "readwrite", + store => { + store.transaction.oncomplete = resolve; + const req = store.delete(itemKey); + req.onerror = function removeItemOnError() { + reject("Error in asyncStorage.removeItem(): ", req.error.name); + }; + }, + reject + ); }); } function clear() { return new Promise((resolve, reject) => { - withStore("readwrite", (store) => { - store.transaction.oncomplete = resolve; - const req = store.clear(); - req.onerror = function clearOnError() { - reject("Error in asyncStorage.clear(): ", req.error.name); - }; - }, reject); + withStore( + "readwrite", + store => { + store.transaction.oncomplete = resolve; + const req = store.clear(); + req.onerror = function clearOnError() { + reject("Error in asyncStorage.clear(): ", req.error.name); + }; + }, + reject + ); }); } function length() { return new Promise((resolve, reject) => { let req; - withStore("readonly", (store) => { - store.transaction.oncomplete = function onComplete() { - resolve(req.result); - }; - req = store.count(); - req.onerror = function lengthOnError() { - reject("Error in asyncStorage.length(): ", req.error.name); - }; - }, reject); + withStore( + "readonly", + store => { + store.transaction.oncomplete = function onComplete() { + resolve(req.result); + }; + req = store.count(); + req.onerror = function lengthOnError() { + reject("Error in asyncStorage.length(): ", req.error.name); + }; + }, + reject + ); }); } @@ -148,33 +168,37 @@ function key(n) { } let req; - withStore("readonly", (store) => { - store.transaction.oncomplete = function onComplete() { - const cursor = req.result; - resolve(cursor ? cursor.key : null); - }; - let advanced = false; - req = store.openCursor(); - req.onsuccess = function keyOnSuccess() { - const cursor = req.result; - if (!cursor) { - // this means there weren"t enough keys - return; - } - if (n === 0 || advanced) { - // Either 1) we have the first key, return it if that's what they - // wanted, or 2) we"ve got the nth key. - return; - } + withStore( + "readonly", + store => { + store.transaction.oncomplete = function onComplete() { + const cursor = req.result; + resolve(cursor ? cursor.key : null); + }; + let advanced = false; + req = store.openCursor(); + req.onsuccess = function keyOnSuccess() { + const cursor = req.result; + if (!cursor) { + // this means there weren"t enough keys + return; + } + if (n === 0 || advanced) { + // Either 1) we have the first key, return it if that's what they + // wanted, or 2) we"ve got the nth key. + return; + } - // Otherwise, ask the cursor to skip ahead n records - advanced = true; - cursor.advance(n); - }; - req.onerror = function keyOnError() { - reject("Error in asyncStorage.key(): ", req.error.name); - }; - }, reject); + // Otherwise, ask the cursor to skip ahead n records + advanced = true; + cursor.advance(n); + }; + req.onerror = function keyOnError() { + reject("Error in asyncStorage.key(): ", req.error.name); + }; + }, + reject + ); }); } diff --git a/devtools/shared/base-loader.js b/devtools/shared/base-loader.js index 623533461eda..21ad0dc5df68 100644 --- a/devtools/shared/base-loader.js +++ b/devtools/shared/base-loader.js @@ -13,14 +13,25 @@ const { Constructor: CC, manager: Cm } = Components; const systemPrincipal = CC("@mozilla.org/systemprincipal;1", "nsIPrincipal")(); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); -const { normalize, dirname } = ChromeUtils.import("resource://gre/modules/osfile/ospath_unix.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +const { normalize, dirname } = ChromeUtils.import( + "resource://gre/modules/osfile/ospath_unix.jsm" +); -XPCOMUtils.defineLazyServiceGetter(this, "resProto", - "@mozilla.org/network/protocol;1?name=resource", - "nsIResProtocolHandler"); +XPCOMUtils.defineLazyServiceGetter( + this, + "resProto", + "@mozilla.org/network/protocol;1?name=resource", + "nsIResProtocolHandler" +); -ChromeUtils.defineModuleGetter(this, "NetUtil", "resource://gre/modules/NetUtil.jsm"); +ChromeUtils.defineModuleGetter( + this, + "NetUtil", + "resource://gre/modules/NetUtil.jsm" +); const { defineLazyGetter } = XPCOMUtils; @@ -58,8 +69,8 @@ function readURI(uri) { const stream = NetUtil.newChannel({ uri: NetUtil.newURI(uri, "UTF-8"), - loadUsingSystemPrincipal: true} - ).open(); + loadUsingSystemPrincipal: true, + }).open(); const count = stream.available(); const data = NetUtil.readInputStreamToString(stream, count, { charset: "UTF-8", @@ -74,7 +85,9 @@ function readURI(uri) { function join(base, ...paths) { // If this is an absolute URL, we need to normalize only the path portion, // or we wind up stripping too many slashes and producing invalid URLs. - const match = /^((?:resource|file|chrome)\:\/\/[^\/]*|jar:[^!]+!)(.*)/.exec(base); + const match = /^((?:resource|file|chrome)\:\/\/[^\/]*|jar:[^!]+!)(.*)/.exec( + base + ); if (match) { return match[1] + normalize([match[2], ...paths].join("/")); } @@ -100,8 +113,8 @@ function Sandbox(options) { wantComponents: false, sandboxName: options.name, sandboxPrototype: "prototype" in options ? options.prototype : {}, - invisibleToDebugger: "invisibleToDebugger" in options ? - options.invisibleToDebugger : false, + invisibleToDebugger: + "invisibleToDebugger" in options ? options.invisibleToDebugger : false, freshCompartment: options.freshCompartment || false, }; @@ -169,7 +182,10 @@ function load(loader, module) { descriptors.define = define; } if ("DOMParser" in globals) { - descriptors.DOMParser = Object.getOwnPropertyDescriptor(globals, "DOMParser"); + descriptors.DOMParser = Object.getOwnPropertyDescriptor( + globals, + "DOMParser" + ); } Object.defineProperties(sandbox, descriptors); } else { @@ -188,12 +204,19 @@ function load(loader, module) { // loadSubScript sometime throws string errors, which includes no stack. // At least provide the current stack by re-throwing a real Error object. if (typeof error == "string") { - if (error.startsWith("Error creating URI") || - error.startsWith("Error opening input stream (invalid filename?)")) { - throw new Error(`Module \`${module.id}\` is not found at ${module.uri}`); + if ( + error.startsWith("Error creating URI") || + error.startsWith("Error opening input stream (invalid filename?)") + ) { + throw new Error( + `Module \`${module.id}\` is not found at ${module.uri}` + ); } - throw new Error(`Error while loading module \`${module.id}\` at ${module.uri}:` + - "\n" + error); + throw new Error( + `Error while loading module \`${module.id}\` at ${module.uri}:` + + "\n" + + error + ); } // Otherwise just re-throw everything else which should have a stack throw error; @@ -246,8 +269,8 @@ function resolve(id, base) { function compileMapping(paths) { // Make mapping array that is sorted from longest path to shortest path. const mapping = Object.keys(paths) - .sort((a, b) => b.length - a.length) - .map(path => [path, paths[path]]); + .sort((a, b) => b.length - a.length) + .map(path => [path, paths[path]]); const PATTERN = /([.\\?+*(){}[\]^$])/g; const escapeMeta = str => str.replace(PATTERN, "\\$1"); @@ -326,7 +349,7 @@ function lazyRequire(obj, moduleId, ...args) { for (let props of args) { if (typeof props !== "object") { - props = {[props]: props}; + props = { [props]: props }; } for (const [fromName, toName] of Object.entries(props)) { @@ -355,15 +378,16 @@ function lazyRequireModule(obj, moduleId, prop = moduleId) { // of `require` that is allowed to load only a modules that are associated // with it during link time. function Require(loader, requirer) { - const { - modules, mapping, mappingCache, requireHook, - } = loader; + const { modules, mapping, mappingCache, requireHook } = loader; function require(id) { if (!id) { // Throw if `id` is not passed. - throw Error("You must provide a module name when calling require() from " - + requirer.id, requirer.uri); + throw Error( + "You must provide a module name when calling require() from " + + requirer.id, + requirer.uri + ); } if (requireHook) { @@ -432,8 +456,11 @@ function Require(loader, requirer) { function getRequirements(id) { if (!id) { // Throw if `id` is not passed. - throw Error("you must provide a module name when calling require() from " - + requirer.id, requirer.uri); + throw Error( + "you must provide a module name when calling require() from " + + requirer.id, + requirer.uri + ); } let requirement, uri; @@ -459,8 +486,15 @@ function Require(loader, requirer) { // Throw if `uri` can not be resolved. if (!uri) { - throw Error("Module: Can not resolve '" + id + "' module required by " + - requirer.id + " located at " + requirer.uri, requirer.uri); + throw Error( + "Module: Can not resolve '" + + id + + "' module required by " + + requirer.id + + " located at " + + requirer.uri, + requirer.uri + ); } return { uri: uri, requirement: requirement }; @@ -488,8 +522,12 @@ function Require(loader, requirer) { function Module(id, uri) { return Object.create(null, { id: { enumerable: true, value: id }, - exports: { enumerable: true, writable: true, value: Object.create(null), - configurable: true }, + exports: { + enumerable: true, + writable: true, + value: Object.create(null), + configurable: true, + }, uri: { value: uri }, }); } @@ -545,9 +583,15 @@ function Loader(options) { let modules = { "@loader/unload": destructor, "@loader/options": options, - "chrome": { Cc, Ci, Cu, Cr, Cm, - CC: bind(CC, Components), components: Components, - ChromeWorker, + chrome: { + Cc, + Ci, + Cu, + Cr, + Cm, + CC: bind(CC, Components), + components: Components, + ChromeWorker, }, }; @@ -586,8 +630,11 @@ function Loader(options) { // the sandbox directly. Note that this will not work for callers who // depend on being able to add globals after the loader was created. for (const name of getOwnIdentifiers(globals)) { - Object.defineProperty(sharedGlobalSandbox, name, - Object.getOwnPropertyDescriptor(globals, name)); + Object.defineProperty( + sharedGlobalSandbox, + name, + Object.getOwnPropertyDescriptor(globals, name) + ); } } @@ -606,9 +653,15 @@ function Loader(options) { // Map of module sandboxes indexed by module URIs. sandboxes: { enumerable: false, value: {} }, // Whether the modules loaded should be ignored by the debugger - invisibleToDebugger: { enumerable: false, - value: options.invisibleToDebugger || false }, - requireHook: { enumerable: false, writable: true, value: options.requireHook }, + invisibleToDebugger: { + enumerable: false, + value: options.invisibleToDebugger || false, + }, + requireHook: { + enumerable: false, + writable: true, + value: options.requireHook, + }, }; return Object.create(null, returnObj); diff --git a/devtools/shared/builtin-modules.js b/devtools/shared/builtin-modules.js index fccd37d9ca0c..e2bfa9dd697f 100644 --- a/devtools/shared/builtin-modules.js +++ b/devtools/shared/builtin-modules.js @@ -165,11 +165,18 @@ function defineLazyServiceGetter(object, name, contract, interfaceName) { * An object which acts on behalf of the module to be imported until * the module has been imported. */ -function defineLazyModuleGetter(object, name, resource, symbol, - preLambda, postLambda, proxy) { +function defineLazyModuleGetter( + object, + name, + resource, + symbol, + preLambda, + postLambda, + proxy +) { proxy = proxy || {}; - if (typeof (preLambda) === "function") { + if (typeof preLambda === "function") { preLambda.apply(proxy); } @@ -178,7 +185,7 @@ function defineLazyModuleGetter(object, name, resource, symbol, try { ChromeUtils.import(resource, temp); - if (typeof (postLambda) === "function") { + if (typeof postLambda === "function") { postLambda.apply(proxy); } } catch (ex) { @@ -247,13 +254,17 @@ defineLazyGetter(exports.modules, "Debugger", () => { if (global.Debugger) { return global.Debugger; } - const { addDebuggerToGlobal } = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm"); + const { addDebuggerToGlobal } = ChromeUtils.import( + "resource://gre/modules/jsdebugger.jsm" + ); addDebuggerToGlobal(global); return global.Debugger; }); defineLazyGetter(exports.modules, "ChromeDebugger", () => { - const { addDebuggerToGlobal } = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm"); + const { addDebuggerToGlobal } = ChromeUtils.import( + "resource://gre/modules/jsdebugger.jsm" + ); addDebuggerToGlobal(debuggerSandbox); return debuggerSandbox.Debugger; }); @@ -265,7 +276,9 @@ defineLazyGetter(exports.modules, "RecordReplayControl", () => { if (global.RecordReplayControl) { return global.RecordReplayControl; } - const { addDebuggerToGlobal } = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm"); + const { addDebuggerToGlobal } = ChromeUtils.import( + "resource://gre/modules/jsdebugger.jsm" + ); addDebuggerToGlobal(global); return global.RecordReplayControl; }); @@ -279,7 +292,10 @@ defineLazyGetter(exports.modules, "InspectorUtils", () => { }); defineLazyGetter(exports.modules, "Timer", () => { - const {setTimeout, clearTimeout} = require("resource://gre/modules/Timer.jsm"); + const { + setTimeout, + clearTimeout, + } = require("resource://gre/modules/Timer.jsm"); // Do not return Cu.import result, as DevTools loader would freeze Timer.jsm globals... return { setTimeout, @@ -377,7 +393,9 @@ lazyGlobal("WebSocket", () => { return Services.appShell.hiddenDOMWindow.WebSocket; }); lazyGlobal("indexedDB", () => { - return require("devtools/shared/indexed-db").createDevToolsIndexedDB(indexedDB); + return require("devtools/shared/indexed-db").createDevToolsIndexedDB( + indexedDB + ); }); lazyGlobal("isReplaying", () => { return exports.modules.Debugger.recordReplayProcessKind() == "Middleman"; diff --git a/devtools/shared/client/connection-manager.js b/devtools/shared/client/connection-manager.js index 61c7ca5f7273..5c0bf7b0883d 100644 --- a/devtools/shared/client/connection-manager.js +++ b/devtools/shared/client/connection-manager.js @@ -6,7 +6,7 @@ "use strict"; -const {Cc, Ci, Cr} = require("chrome"); +const { Cc, Ci, Cr } = require("chrome"); const EventEmitter = require("devtools/shared/event-emitter"); const { DebuggerServer } = require("devtools/server/main"); const { DebuggerClient } = require("devtools/shared/client/debugger-client"); @@ -100,8 +100,9 @@ var ConnectionManager = { return [...this._connections]; }, getFreeTCPPort: function() { - const serv = Cc["@mozilla.org/network/server-socket;1"] - .createInstance(Ci.nsIServerSocket); + const serv = Cc["@mozilla.org/network/server-socket;1"].createInstance( + Ci.nsIServerSocket + ); serv.init(-1, true, -1); const port = serv.port; serv.close(); @@ -251,8 +252,10 @@ Connection.prototype = { return; } clearTimeout(this._timeoutID); - if (this.status == Connection.Status.CONNECTED || - this.status == Connection.Status.CONNECTING) { + if ( + this.status == Connection.Status.CONNECTED || + this.status == Connection.Status.CONNECTING + ) { this.log("disconnecting"); this._setStatus(Connection.Status.DISCONNECTING); if (this._client) { @@ -309,26 +312,32 @@ Connection.prototype = { }, _clientConnect: function() { - this._getTransport().then(transport => { - if (!transport) { - return; + this._getTransport().then( + transport => { + if (!transport) { + return; + } + this._client = new DebuggerClient(transport); + this._client.once("closed", this._onDisconnected); + this._client.connect().then(this._onConnected); + }, + e => { + // If we're continuously trying to connect, we expect the connection to be + // rejected a couple times, so don't log these. + if ( + !this.keepConnecting || + e.result !== Cr.NS_ERROR_CONNECTION_REFUSED + ) { + console.error(e); + } + // In some cases, especially on Mac, the openOutputStream call in + // DebuggerClient.socketConnect may throw NS_ERROR_NOT_INITIALIZED. + // It occurs when we connect agressively to the simulator, + // and keep trying to open a socket to the server being started in + // the simulator. + this._onDisconnected(); } - this._client = new DebuggerClient(transport); - this._client.once("closed", this._onDisconnected); - this._client.connect().then(this._onConnected); - }, e => { - // If we're continuously trying to connect, we expect the connection to be - // rejected a couple times, so don't log these. - if (!this.keepConnecting || e.result !== Cr.NS_ERROR_CONNECTION_REFUSED) { - console.error(e); - } - // In some cases, especially on Mac, the openOutputStream call in - // DebuggerClient.socketConnect may throw NS_ERROR_NOT_INITIALIZED. - // It occurs when we connect agressively to the simulator, - // and keep trying to open a socket to the server being started in - // the simulator. - this._onDisconnected(); - }); + ); }, get status() { @@ -360,9 +369,11 @@ Connection.prototype = { this.log("disconnected (unexpected)"); break; case Connection.Status.CONNECTING: - this.log("connection error. Possible causes: USB port not connected, port not " + - "forwarded (adb forward), wrong host or port, remote debugging not " + - "enabled on the device."); + this.log( + "connection error. Possible causes: USB port not connected, port not " + + "forwarded (adb forward), wrong host or port, remote debugging not " + + "enabled on the device." + ); break; default: this.log("disconnected"); @@ -377,7 +388,9 @@ Connection.prototype = { }, _onTimeout: function() { - this.log("connection timeout. Possible causes: didn't click on 'accept' (prompt)."); + this.log( + "connection timeout. Possible causes: didn't click on 'accept' (prompt)." + ); this.emit(Connection.Events.TIMEOUT); this.disconnect(); }, diff --git a/devtools/shared/client/debugger-client.js b/devtools/shared/client/debugger-client.js index cfa9b6d273f8..467344fb08f5 100644 --- a/devtools/shared/client/debugger-client.js +++ b/devtools/shared/client/debugger-client.js @@ -7,7 +7,10 @@ const promise = require("devtools/shared/deprecated-sync-thenables"); const DevToolsUtils = require("devtools/shared/DevToolsUtils"); -const { getStack, callFunctionWithAsyncStack } = require("devtools/shared/platform/stack"); +const { + getStack, + callFunctionWithAsyncStack, +} = require("devtools/shared/platform/stack"); const EventEmitter = require("devtools/shared/event-emitter"); const { ThreadStateTypes, @@ -15,12 +18,30 @@ const { UnsolicitedPauses, } = require("./constants"); -loader.lazyRequireGetter(this, "Authentication", "devtools/shared/security/auth"); -loader.lazyRequireGetter(this, "DebuggerSocket", "devtools/shared/security/socket", true); +loader.lazyRequireGetter( + this, + "Authentication", + "devtools/shared/security/auth" +); +loader.lazyRequireGetter( + this, + "DebuggerSocket", + "devtools/shared/security/socket", + true +); loader.lazyRequireGetter(this, "EventEmitter", "devtools/shared/event-emitter"); -loader.lazyRequireGetter(this, "RootFront", "devtools/shared/fronts/root", true); -loader.lazyRequireGetter(this, "ObjectClient", "devtools/shared/client/object-client"); +loader.lazyRequireGetter( + this, + "RootFront", + "devtools/shared/fronts/root", + true +); +loader.lazyRequireGetter( + this, + "ObjectClient", + "devtools/shared/client/object-client" +); loader.lazyRequireGetter(this, "Front", "devtools/shared/protocol", true); /** @@ -46,7 +67,7 @@ function DebuggerClient(transport) { * the connection's root actor. */ this.mainRoot = null; - this.expectReply("root", (packet) => { + this.expectReply("root", packet => { this.mainRoot = new RootFront(this, packet); // Root Front is a special case, managing itself as it doesn't have any parent. @@ -98,22 +119,25 @@ DebuggerClient.requester = function(packetSkeleton, config = {}) { outgoingPacket = before.call(this, outgoingPacket); } - return this.request(outgoingPacket, DevToolsUtils.makeInfallible((response) => { - if (after) { - const { from } = response; - response = after.call(this, response); - if (!response.from) { - response.from = from; + return this.request( + outgoingPacket, + DevToolsUtils.makeInfallible(response => { + if (after) { + const { from } = response; + response = after.call(this, response); + if (!response.from) { + response.from = from; + } } - } - // The callback is always the last parameter. - const thisCallback = args[maxPosition + 1]; - if (thisCallback) { - thisCallback(response); - } - return response; - }, "DebuggerClient.requester request callback")); + // The callback is always the last parameter. + const thisCallback = args[maxPosition + 1]; + if (thisCallback) { + thisCallback(response); + } + return response; + }, "DebuggerClient.requester request callback") + ); }, "DebuggerClient.requester"); }; @@ -294,9 +318,14 @@ DebuggerClient.prototype = { }; if (this._closed) { - const msg = "'" + type + "' request packet to " + - "'" + packet.to + "' " + - "can't be sent as the connection is closed."; + const msg = + "'" + + type + + "' request packet to " + + "'" + + packet.to + + "' " + + "can't be sent as the connection is closed."; const resp = { error: "connectionClosed", message: msg }; return promise.reject(safeOnResponse(resp)); } @@ -531,24 +560,28 @@ DebuggerClient.prototype = { if (!packet.from) { DevToolsUtils.reportException( "onPacket", - new Error("Server did not specify an actor, dropping packet: " + - JSON.stringify(packet))); + new Error( + "Server did not specify an actor, dropping packet: " + + JSON.stringify(packet) + ) + ); return; } // Check for "forwardingCancelled" here instead of using a front to handle it. // This is necessary because we might receive this event while the client is closing, // and the fronts have already been removed by that point. - if (this.mainRoot && - packet.from == this.mainRoot.actorID && - packet.type == "forwardingCancelled") { + if ( + this.mainRoot && + packet.from == this.mainRoot.actorID && + packet.type == "forwardingCancelled" + ) { this.purgeRequests(packet.prefix); return; } // support older browsers for Fx69+ for using the old thread client - if (!this.traits.hasThreadFront && - packet.from.includes("context")) { + if (!this.traits.hasThreadFront && packet.from.includes("context")) { this.sendToDeprecatedThreadClient(packet); return; } @@ -565,8 +598,10 @@ DebuggerClient.prototype = { // See if we have a handler function waiting for a reply from this // actor. (Don't count unsolicited notifications or pauses as // replies.) - if (this._activeRequests.has(packet.from) && - !(packet.type in UnsolicitedNotifications)) { + if ( + this._activeRequests.has(packet.from) && + !(packet.type in UnsolicitedNotifications) + ) { activeRequest = this._activeRequests.get(packet.from); this._activeRequests.delete(packet.from); } @@ -585,8 +620,11 @@ DebuggerClient.prototype = { if (activeRequest) { const emitReply = () => activeRequest.emit("json-reply", packet); if (activeRequest.stack) { - callFunctionWithAsyncStack(emitReply, activeRequest.stack, - "DevTools RDP"); + callFunctionWithAsyncStack( + emitReply, + activeRequest.stack, + "DevTools RDP" + ); } else { emitReply(); } @@ -611,9 +649,13 @@ DebuggerClient.prototype = { // See if we have a handler function waiting for a reply from this // actor. (Don't count unsolicited notifications or pauses as // replies.) - if (this._activeRequests.has(packet.from) && - !(packet.type == ThreadStateTypes.paused && - packet.why.type in UnsolicitedPauses)) { + if ( + this._activeRequests.has(packet.from) && + !( + packet.type == ThreadStateTypes.paused && + packet.why.type in UnsolicitedPauses + ) + ) { activeRequest = this._activeRequests.get(packet.from); this._activeRequests.delete(packet.from); } @@ -624,9 +666,11 @@ DebuggerClient.prototype = { this._attemptNextRequest(packet.from); // Packets that indicate thread state changes get special treatment. - if (packet.type in ThreadStateTypes && - deprecatedThreadClient && - typeof deprecatedThreadClient._onThreadState == "function") { + if ( + packet.type in ThreadStateTypes && + deprecatedThreadClient && + typeof deprecatedThreadClient._onThreadState == "function" + ) { deprecatedThreadClient._onThreadState(packet); } @@ -677,8 +721,11 @@ DebuggerClient.prototype = { if (!actor) { DevToolsUtils.reportException( "onBulkPacket", - new Error("Server did not specify an actor, dropping bulk packet: " + - JSON.stringify(packet))); + new Error( + "Server did not specify an actor, dropping bulk packet: " + + JSON.stringify(packet) + ) + ); return; } @@ -751,11 +798,19 @@ DebuggerClient.prototype = { // to expectReply, so that there is no request object. let msg; if (request.request) { - msg = "'" + request.request.type + "' " + type + " request packet" + - " to '" + request.actor + "' " + - "can't be sent as the connection just closed."; + msg = + "'" + + request.request.type + + "' " + + type + + " request packet" + + " to '" + + request.actor + + "' " + + "can't be sent as the connection just closed."; } else { - msg = "server side packet can't be received as the connection just closed."; + msg = + "server side packet can't be received as the connection just closed."; } const packet = { error: "connectionClosed", message: msg }; request.emit("json-reply", packet); @@ -838,14 +893,16 @@ DebuggerClient.prototype = { return Promise.resolve(); } - return DevToolsUtils.settleAll(requests).catch(() => { - // One of the requests might have failed, but ignore that situation here and pipe - // both success and failure through the same path. The important part is just that - // we waited. - }).then(() => { - // Repeat, more requests may have started in response to those we just waited for - return this.waitForRequestsToSettle(); - }); + return DevToolsUtils.settleAll(requests) + .catch(() => { + // One of the requests might have failed, but ignore that situation here and pipe + // both success and failure through the same path. The important part is just that + // we waited. + }) + .then(() => { + // Repeat, more requests may have started in response to those we just waited for + return this.waitForRequestsToSettle(); + }); }, /** diff --git a/devtools/shared/client/deprecated-thread-client.js b/devtools/shared/client/deprecated-thread-client.js index 2bb54a7c0f06..c73ee6c133ac 100644 --- a/devtools/shared/client/deprecated-thread-client.js +++ b/devtools/shared/client/deprecated-thread-client.js @@ -5,9 +5,12 @@ "use strict"; -const {arg, DebuggerClient} = require("devtools/shared/client/debugger-client"); +const { + arg, + DebuggerClient, +} = require("devtools/shared/client/debugger-client"); const EventEmitter = require("devtools/shared/event-emitter"); -const {ThreadStateTypes} = require("devtools/shared/client/constants"); +const { ThreadStateTypes } = require("devtools/shared/client/constants"); loader.lazyRequireGetter( this, @@ -78,36 +81,39 @@ ThreadClient.prototype = { * than proceeding forwards. This parameter has no effect if the * server does not support rewinding. */ - _doResume: DebuggerClient.requester({ - type: "resume", - resumeLimit: arg(0), - rewind: arg(1), - }, { - before: function(packet) { - this._assertPaused("resume"); - - // Put the client in a tentative "resuming" state so we can prevent - // further requests that should only be sent in the paused state. - this._previousState = this._state; - this._state = "resuming"; - - return packet; + _doResume: DebuggerClient.requester( + { + type: "resume", + resumeLimit: arg(0), + rewind: arg(1), }, - after: function(response) { - if (response.error && this._state == "resuming") { - // There was an error resuming, update the state to the new one - // reported by the server, if given (only on wrongState), otherwise - // reset back to the previous state. - if (response.state) { - this._state = ThreadStateTypes[response.state]; - } else { - this._state = this._previousState; + { + before: function(packet) { + this._assertPaused("resume"); + + // Put the client in a tentative "resuming" state so we can prevent + // further requests that should only be sent in the paused state. + this._previousState = this._state; + this._state = "resuming"; + + return packet; + }, + after: function(response) { + if (response.error && this._state == "resuming") { + // There was an error resuming, update the state to the new one + // reported by the server, if given (only on wrongState), otherwise + // reset back to the previous state. + if (response.state) { + this._state = ThreadStateTypes[response.state]; + } else { + this._state = this._previousState; + } } - } - delete this._previousState; - return response; - }, - }), + delete this._previousState; + return response; + }, + } + ), /** * Reconfigure the thread actor. diff --git a/devtools/shared/client/environment-client.js b/devtools/shared/client/environment-client.js index d0e3fdde553c..35140e7f453b 100644 --- a/devtools/shared/client/environment-client.js +++ b/devtools/shared/client/environment-client.js @@ -4,7 +4,10 @@ "use strict"; -const {arg, DebuggerClient} = require("devtools/shared/client/debugger-client"); +const { + arg, + DebuggerClient, +} = require("devtools/shared/client/debugger-client"); /** * Environment clients are used to manipulate the lexical environment actors. @@ -22,7 +25,6 @@ function EnvironmentClient(client, form) { exports.EnvironmentClient = EnvironmentClient; EnvironmentClient.prototype = { - get actor() { return this._form.actor; }, diff --git a/devtools/shared/client/event-source.js b/devtools/shared/client/event-source.js index 742bdced70e0..3b6da9544897 100644 --- a/devtools/shared/client/event-source.js +++ b/devtools/shared/client/event-source.js @@ -86,8 +86,9 @@ function eventSource(proto) { if (!listener) { this._listeners[name] = []; } else { - this._listeners[name] = - this._listeners[name].filter(l => l.key != listener); + this._listeners[name] = this._listeners[name].filter( + l => l.key != listener + ); } }; diff --git a/devtools/shared/client/long-string-client.js b/devtools/shared/client/long-string-client.js index 2c5998eccc43..f3ca26645c4e 100644 --- a/devtools/shared/client/long-string-client.js +++ b/devtools/shared/client/long-string-client.js @@ -4,7 +4,10 @@ "use strict"; -const {arg, DebuggerClient} = require("devtools/shared/client/debugger-client"); +const { + arg, + DebuggerClient, +} = require("devtools/shared/client/debugger-client"); /** * A LongStringClient provides a way to access "very long" strings from the * debugger server. diff --git a/devtools/shared/client/object-client.js b/devtools/shared/client/object-client.js index f27aa9693571..54651f71354c 100644 --- a/devtools/shared/client/object-client.js +++ b/devtools/shared/client/object-client.js @@ -4,9 +4,20 @@ "use strict"; -const {arg, DebuggerClient} = require("devtools/shared/client/debugger-client"); -loader.lazyRequireGetter(this, "PropertyIteratorClient", "devtools/shared/client/property-iterator-client"); -loader.lazyRequireGetter(this, "SymbolIteratorClient", "devtools/shared/client/symbol-iterator-client"); +const { + arg, + DebuggerClient, +} = require("devtools/shared/client/debugger-client"); +loader.lazyRequireGetter( + this, + "PropertyIteratorClient", + "devtools/shared/client/property-iterator-client" +); +loader.lazyRequireGetter( + this, + "SymbolIteratorClient", + "devtools/shared/client/symbol-iterator-client" +); /** * Grip clients are used to retrieve information about the relevant object. @@ -46,16 +57,21 @@ ObjectClient.prototype = { type: "threadGrip", }), - getDefinitionSite: DebuggerClient.requester({ - type: "definitionSite", - }, { - before: function(packet) { - if (this._grip.class != "Function") { - throw new Error("getDefinitionSite is only valid for function grips."); - } - return packet; + getDefinitionSite: DebuggerClient.requester( + { + type: "definitionSite", }, - }), + { + before: function(packet) { + if (this._grip.class != "Function") { + throw new Error( + "getDefinitionSite is only valid for function grips." + ); + } + return packet; + }, + } + ), /** * Request the names of a function's formal parameters. @@ -65,16 +81,21 @@ ObjectClient.prototype = { * { parameterNames:[, ...] } * where each is the name of a parameter. */ - getParameterNames: DebuggerClient.requester({ - type: "parameterNames", - }, { - before: function(packet) { - if (this._grip.class !== "Function") { - throw new Error("getParameterNames is only valid for function grips."); - } - return packet; + getParameterNames: DebuggerClient.requester( + { + type: "parameterNames", }, - }), + { + before: function(packet) { + if (this._grip.class !== "Function") { + throw new Error( + "getParameterNames is only valid for function grips." + ); + } + return packet; + }, + } + ), /** * Request the names of the properties defined on the object and not its @@ -113,17 +134,25 @@ ObjectClient.prototype = { * before dispatching them. * @param onResponse function Called with the client instance. */ - enumProperties: DebuggerClient.requester({ - type: "enumProperties", - options: arg(0), - }, { - after: function(response) { - if (response.iterator) { - return { iterator: new PropertyIteratorClient(this._client, response.iterator) }; - } - return response; + enumProperties: DebuggerClient.requester( + { + type: "enumProperties", + options: arg(0), }, - }), + { + after: function(response) { + if (response.iterator) { + return { + iterator: new PropertyIteratorClient( + this._client, + response.iterator + ), + }; + } + return response; + }, + } + ), /** * Request a PropertyIteratorClient instance to enumerate entries in a @@ -131,48 +160,63 @@ ObjectClient.prototype = { * * @param onResponse function Called with the request's response. */ - enumEntries: DebuggerClient.requester({ - type: "enumEntries", - }, { - before: function(packet) { - if (!["Map", "WeakMap", "Set", "WeakSet", "Storage"].includes(this._grip.class)) { - throw new Error("enumEntries is only valid for Map/Set/Storage-like grips."); - } - return packet; + enumEntries: DebuggerClient.requester( + { + type: "enumEntries", }, - after: function(response) { - if (response.iterator) { - return { - iterator: new PropertyIteratorClient(this._client, response.iterator), - }; - } - return response; - }, - }), + { + before: function(packet) { + if ( + !["Map", "WeakMap", "Set", "WeakSet", "Storage"].includes( + this._grip.class + ) + ) { + throw new Error( + "enumEntries is only valid for Map/Set/Storage-like grips." + ); + } + return packet; + }, + after: function(response) { + if (response.iterator) { + return { + iterator: new PropertyIteratorClient( + this._client, + response.iterator + ), + }; + } + return response; + }, + } + ), /** * Request a SymbolIteratorClient instance to enumerate symbols in an object. * * @param onResponse function Called with the request's response. */ - enumSymbols: DebuggerClient.requester({ - type: "enumSymbols", - }, { - before: function(packet) { - if (this._grip.type !== "object") { - throw new Error("enumSymbols is only valid for objects grips."); - } - return packet; + enumSymbols: DebuggerClient.requester( + { + type: "enumSymbols", }, - after: function(response) { - if (response.iterator) { - return { - iterator: new SymbolIteratorClient(this._client, response.iterator), - }; - } - return response; - }, - }), + { + before: function(packet) { + if (this._grip.type !== "object") { + throw new Error("enumSymbols is only valid for objects grips."); + } + return packet; + }, + after: function(response) { + if (response.iterator) { + return { + iterator: new SymbolIteratorClient(this._client, response.iterator), + }; + } + return response; + }, + } + ), /** * Request the property descriptor of the object's specified property. @@ -234,98 +278,121 @@ ObjectClient.prototype = { * * @param onResponse function Called with the request's response. */ - getScope: DebuggerClient.requester({ - type: "scope", - }, { - before: function(packet) { - if (this._grip.class !== "Function") { - throw new Error("scope is only valid for function grips."); - } - return packet; + getScope: DebuggerClient.requester( + { + type: "scope", }, - }), + { + before: function(packet) { + if (this._grip.class !== "Function") { + throw new Error("scope is only valid for function grips."); + } + return packet; + }, + } + ), /** * Request the promises directly depending on the current promise. */ - getDependentPromises: DebuggerClient.requester({ - type: "dependentPromises", - }, { - before: function(packet) { - if (this._grip.class !== "Promise") { - throw new Error("getDependentPromises is only valid for promise " + - "grips."); - } - return packet; + getDependentPromises: DebuggerClient.requester( + { + type: "dependentPromises", }, - }), + { + before: function(packet) { + if (this._grip.class !== "Promise") { + throw new Error( + "getDependentPromises is only valid for promise " + "grips." + ); + } + return packet; + }, + } + ), /** * Request the stack to the promise's allocation point. */ - getPromiseAllocationStack: DebuggerClient.requester({ - type: "allocationStack", - }, { - before: function(packet) { - if (this._grip.class !== "Promise") { - throw new Error("getAllocationStack is only valid for promise grips."); - } - return packet; + getPromiseAllocationStack: DebuggerClient.requester( + { + type: "allocationStack", }, - }), + { + before: function(packet) { + if (this._grip.class !== "Promise") { + throw new Error( + "getAllocationStack is only valid for promise grips." + ); + } + return packet; + }, + } + ), /** * Request the stack to the promise's fulfillment point. */ - getPromiseFulfillmentStack: DebuggerClient.requester({ - type: "fulfillmentStack", - }, { - before: function(packet) { - if (this._grip.class !== "Promise") { - throw new Error("getPromiseFulfillmentStack is only valid for " + - "promise grips."); - } - return packet; + getPromiseFulfillmentStack: DebuggerClient.requester( + { + type: "fulfillmentStack", }, - }), + { + before: function(packet) { + if (this._grip.class !== "Promise") { + throw new Error( + "getPromiseFulfillmentStack is only valid for " + "promise grips." + ); + } + return packet; + }, + } + ), /** * Request the stack to the promise's rejection point. */ - getPromiseRejectionStack: DebuggerClient.requester({ - type: "rejectionStack", - }, { - before: function(packet) { - if (this._grip.class !== "Promise") { - throw new Error("getPromiseRejectionStack is only valid for " + - "promise grips."); - } - return packet; + getPromiseRejectionStack: DebuggerClient.requester( + { + type: "rejectionStack", }, - }), + { + before: function(packet) { + if (this._grip.class !== "Promise") { + throw new Error( + "getPromiseRejectionStack is only valid for " + "promise grips." + ); + } + return packet; + }, + } + ), /** * Request the target and handler internal slots of a proxy. */ - getProxySlots: DebuggerClient.requester({ - type: "proxySlots", - }, { - before: function(packet) { - if (this._grip.class !== "Proxy") { - throw new Error("getProxySlots is only valid for proxy grips."); - } - return packet; + getProxySlots: DebuggerClient.requester( + { + type: "proxySlots", }, - after: function(response) { - // Before Firefox 68 (bug 1392760), the proxySlots request didn't exist. - // The proxy target and handler were directly included in the grip. - if (response.error === "unrecognizedPacketType") { - const {proxyTarget, proxyHandler} = this._grip; - return {proxyTarget, proxyHandler}; - } - return response; - }, - }), + { + before: function(packet) { + if (this._grip.class !== "Proxy") { + throw new Error("getProxySlots is only valid for proxy grips."); + } + return packet; + }, + after: function(response) { + // Before Firefox 68 (bug 1392760), the proxySlots request didn't exist. + // The proxy target and handler were directly included in the grip. + if (response.error === "unrecognizedPacketType") { + const { proxyTarget, proxyHandler } = this._grip; + return { proxyTarget, proxyHandler }; + } + return response; + }, + } + ), }; module.exports = ObjectClient; diff --git a/devtools/shared/client/property-iterator-client.js b/devtools/shared/client/property-iterator-client.js index f7593ce34220..ef72d8771ec8 100644 --- a/devtools/shared/client/property-iterator-client.js +++ b/devtools/shared/client/property-iterator-client.js @@ -4,7 +4,10 @@ "use strict"; -const {arg, DebuggerClient} = require("devtools/shared/client/debugger-client"); +const { + arg, + DebuggerClient, +} = require("devtools/shared/client/debugger-client"); /** * A PropertyIteratorClient provides a way to access to property names and @@ -46,10 +49,13 @@ PropertyIteratorClient.prototype = { * @param callback Function * The function called when we receive the property names. */ - names: DebuggerClient.requester({ - type: "names", - indexes: arg(0), - }, {}), + names: DebuggerClient.requester( + { + type: "names", + indexes: arg(0), + }, + {} + ), /** * Get a set of following property value(s). @@ -61,11 +67,14 @@ PropertyIteratorClient.prototype = { * @param callback Function * The function called when we receive the property values. */ - slice: DebuggerClient.requester({ - type: "slice", - start: arg(0), - count: arg(1), - }, {}), + slice: DebuggerClient.requester( + { + type: "slice", + start: arg(0), + count: arg(1), + }, + {} + ), /** * Get all the property values. @@ -73,9 +82,12 @@ PropertyIteratorClient.prototype = { * @param callback Function * The function called when we receive the property values. */ - all: DebuggerClient.requester({ - type: "all", - }, {}), + all: DebuggerClient.requester( + { + type: "all", + }, + {} + ), }; module.exports = PropertyIteratorClient; diff --git a/devtools/shared/client/symbol-iterator-client.js b/devtools/shared/client/symbol-iterator-client.js index 4d8b79aa6f25..da56c233d6aa 100644 --- a/devtools/shared/client/symbol-iterator-client.js +++ b/devtools/shared/client/symbol-iterator-client.js @@ -4,7 +4,10 @@ "use strict"; -const {arg, DebuggerClient} = require("devtools/shared/client/debugger-client"); +const { + arg, + DebuggerClient, +} = require("devtools/shared/client/debugger-client"); /** * A SymbolIteratorClient provides a way to access to symbols @@ -44,11 +47,14 @@ SymbolIteratorClient.prototype = { * @param callback Function * The function called when we receive the symbols. */ - slice: DebuggerClient.requester({ - type: "slice", - start: arg(0), - count: arg(1), - }, {}), + slice: DebuggerClient.requester( + { + type: "slice", + start: arg(0), + count: arg(1), + }, + {} + ), /** * Get all the symbols. @@ -56,9 +62,12 @@ SymbolIteratorClient.prototype = { * @param callback Function * The function called when we receive the symbols. */ - all: DebuggerClient.requester({ - type: "all", - }, {}), + all: DebuggerClient.requester( + { + type: "all", + }, + {} + ), }; module.exports = SymbolIteratorClient; diff --git a/devtools/shared/client/thread-client.js b/devtools/shared/client/thread-client.js index 864cd06dec04..550369acd994 100644 --- a/devtools/shared/client/thread-client.js +++ b/devtools/shared/client/thread-client.js @@ -6,7 +6,10 @@ "use strict"; const { ThreadStateTypes } = require("devtools/shared/client/constants"); -const { FrontClassWithSpec, registerFront } = require("devtools/shared/protocol"); +const { + FrontClassWithSpec, + registerFront, +} = require("devtools/shared/protocol"); const { threadSpec } = require("devtools/shared/specs/thread"); loader.lazyRequireGetter( @@ -198,7 +201,7 @@ class ThreadClient extends FrontClassWithSpec(threadSpec) { async getSources() { let sources = []; try { - ({sources} = await super.sources()); + ({ sources } = await super.sources()); } catch (e) { // we may have closed the connection console.log(`getSources failed. Connection may have closed: ${e}`); diff --git a/devtools/shared/content-observer.js b/devtools/shared/content-observer.js index 7ebb89ffbf03..30578e805d87 100644 --- a/devtools/shared/content-observer.js +++ b/devtools/shared/content-observer.js @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {Ci} = require("chrome"); +const { Ci } = require("chrome"); const Services = require("Services"); const EventEmitter = require("devtools/shared/event-emitter"); @@ -28,9 +28,13 @@ ContentObserver.prototype = { */ startListening: function() { Services.obs.addObserver( - this._onContentGlobalCreated, "content-document-global-created"); + this._onContentGlobalCreated, + "content-document-global-created" + ); Services.obs.addObserver( - this._onInnerWindowDestroyed, "inner-window-destroyed"); + this._onInnerWindowDestroyed, + "inner-window-destroyed" + ); }, /** @@ -38,9 +42,13 @@ ContentObserver.prototype = { */ stopListening: function() { Services.obs.removeObserver( - this._onContentGlobalCreated, "content-document-global-created"); + this._onContentGlobalCreated, + "content-document-global-created" + ); Services.obs.removeObserver( - this._onInnerWindowDestroyed, "inner-window-destroyed"); + this._onInnerWindowDestroyed, + "inner-window-destroyed" + ); }, /** diff --git a/devtools/shared/css/color.js b/devtools/shared/css/color.js index 7e04f3d66a56..b51d412346a3 100644 --- a/devtools/shared/css/color.js +++ b/devtools/shared/css/color.js @@ -5,11 +5,21 @@ "use strict"; const Services = require("Services"); -const {getCSSLexer} = require("devtools/shared/css/lexer"); -const {cssColors} = require("devtools/shared/css/color-db"); +const { getCSSLexer } = require("devtools/shared/css/lexer"); +const { cssColors } = require("devtools/shared/css/color-db"); -loader.lazyRequireGetter(this, "CSS_ANGLEUNIT", "devtools/shared/css/constants", true); -loader.lazyRequireGetter(this, "getAngleValueInDegrees", "devtools/shared/css/parsing-utils", true); +loader.lazyRequireGetter( + this, + "CSS_ANGLEUNIT", + "devtools/shared/css/constants", + true +); +loader.lazyRequireGetter( + this, + "getAngleValueInDegrees", + "devtools/shared/css/parsing-utils", + true +); const COLOR_UNIT_PREF = "devtools.defaultColorUnit"; @@ -83,11 +93,11 @@ module.exports.colorUtils = { * Values used in COLOR_UNIT_PREF */ CssColor.COLORUNIT = { - "authored": "authored", - "hex": "hex", - "name": "name", - "rgb": "rgb", - "hsl": "hsl", + authored: "authored", + hex: "hex", + name: "name", + rgb: "rgb", + hsl: "hsl", }; CssColor.prototype = { @@ -106,8 +116,8 @@ CssColor.prototype = { // Specifically exclude the case where the color is // case-insensitive. This makes it so that "#000" isn't // considered "upper case" for the purposes of color cycling. - this._colorUnitUppercase = (color === color.toUpperCase()) && - (color !== color.toLowerCase()); + this._colorUnitUppercase = + color === color.toUpperCase() && color !== color.toLowerCase(); }, get colorUnit() { @@ -131,8 +141,10 @@ CssColor.prototype = { * @param {String} color The color to use */ setAuthoredUnitFromColor: function(color) { - if (Services.prefs.getCharPref(COLOR_UNIT_PREF) === - CssColor.COLORUNIT.authored) { + if ( + Services.prefs.getCharPref(COLOR_UNIT_PREF) === + CssColor.COLORUNIT.authored + ) { this._colorUnit = classifyColor(color); this._setColorUnitUppercase(color); } @@ -195,7 +207,7 @@ CssColor.prototype = { if (tuple.a !== 1) { return this.hex; } - const {r, g, b} = tuple; + const { r, g, b } = tuple; return rgbToColorName(r, g, b) || this.hex; }, @@ -209,9 +221,11 @@ CssColor.prototype = { } let hex = this.longHex; - if (hex.charAt(1) == hex.charAt(2) && - hex.charAt(3) == hex.charAt(4) && - hex.charAt(5) == hex.charAt(6)) { + if ( + hex.charAt(1) == hex.charAt(2) && + hex.charAt(3) == hex.charAt(4) && + hex.charAt(5) == hex.charAt(6) + ) { hex = "#" + hex.charAt(1) + hex.charAt(3) + hex.charAt(5); } return hex; @@ -224,12 +238,18 @@ CssColor.prototype = { } let alphaHex = this.longAlphaHex; - if (alphaHex.charAt(1) == alphaHex.charAt(2) && - alphaHex.charAt(3) == alphaHex.charAt(4) && - alphaHex.charAt(5) == alphaHex.charAt(6) && - alphaHex.charAt(7) == alphaHex.charAt(8)) { - alphaHex = "#" + alphaHex.charAt(1) + alphaHex.charAt(3) + - alphaHex.charAt(5) + alphaHex.charAt(7); + if ( + alphaHex.charAt(1) == alphaHex.charAt(2) && + alphaHex.charAt(3) == alphaHex.charAt(4) && + alphaHex.charAt(5) == alphaHex.charAt(6) && + alphaHex.charAt(7) == alphaHex.charAt(8) + ) { + alphaHex = + "#" + + alphaHex.charAt(1) + + alphaHex.charAt(3) + + alphaHex.charAt(5) + + alphaHex.charAt(7); } return alphaHex; }, @@ -244,8 +264,12 @@ CssColor.prototype = { } const tuple = this.getRGBATuple(); - return "#" + ((1 << 24) + (tuple.r << 16) + (tuple.g << 8) + - (tuple.b << 0)).toString(16).substr(-6); + return ( + "#" + + ((1 << 24) + (tuple.r << 16) + (tuple.g << 8) + (tuple.b << 0)) + .toString(16) + .substr(-6) + ); }, get longAlphaHex() { @@ -256,9 +280,15 @@ CssColor.prototype = { const tuple = this.highResTuple; - return "#" + ((1 << 24) + (tuple.r << 16) + (tuple.g << 8) + - (tuple.b << 0)).toString(16).substr(-6) + - Math.round(tuple.a).toString(16).padStart(2, "0"); + return ( + "#" + + ((1 << 24) + (tuple.r << 16) + (tuple.g << 8) + (tuple.b << 0)) + .toString(16) + .substr(-6) + + Math.round(tuple.a) + .toString(16) + .padStart(2, "0") + ); }, get rgb() { @@ -287,10 +317,17 @@ CssColor.prototype = { return this.authored; } const components = this.getRGBATuple(); - return "rgba(" + components.r + ", " + - components.g + ", " + - components.b + ", " + - components.a + ")"; + return ( + "rgba(" + + components.r + + ", " + + components.g + + ", " + + components.b + + ", " + + components.a + + ")" + ); }, get hsl() { @@ -407,8 +444,10 @@ CssColor.prototype = { color = this.rgb; } - if (this._colorUnitUppercase && - this.colorUnit != CssColor.COLORUNIT.authored) { + if ( + this._colorUnitUppercase && + this.colorUnit != CssColor.COLORUNIT.authored + ) { color = color.toUpperCase(); } @@ -432,7 +471,7 @@ CssColor.prototype = { * appropriate. */ _getHSLATuple: function() { - const {r, g, b, a} = colorToRGBA(this.authored, this.cssColor4); + const { r, g, b, a } = colorToRGBA(this.authored, this.cssColor4); const [h, s, l] = rgbToHsl([r, g, b]); @@ -450,7 +489,7 @@ CssColor.prototype = { return this.authored; } - const {r, g, b} = this.getRGBATuple(); + const { r, g, b } = this.getRGBATuple(); const [h, s, l] = rgbToHsl([r, g, b]); if (maybeAlpha !== undefined) { return "hsla(" + h + ", " + s + "%, " + l + "%, " + maybeAlpha + ")"; @@ -647,7 +686,10 @@ function hslToRGB([h, s, l]) { * name was not a valid color */ function hexToRGBA(name, highResolution) { - let r, g, b, a = 1; + let r, + g, + b, + a = 1; if (name.length === 3) { // short hex string (e.g. F0C) @@ -685,7 +727,7 @@ function hexToRGBA(name, highResolution) { if (!highResolution) { a = Math.round(a * 10) / 10; } - return {r, g, b, a}; + return { r, g, b, a }; } /** @@ -722,8 +764,10 @@ function getToken(lexer) { while (true) { const token = lexer.nextToken(); - if (!token || (token.tokenType !== "comment" && - token.tokenType !== "whitespace")) { + if ( + !token || + (token.tokenType !== "comment" && token.tokenType !== "whitespace") + ) { lexer._currentToken = token; return token; } @@ -767,9 +811,9 @@ function expectSymbol(lexer, symbol) { } const COLOR_COMPONENT_TYPE = { - "integer": "integer", - "number": "number", - "percentage": "percentage", + integer: "integer", + number: "number", + percentage: "percentage", }; /** @@ -935,10 +979,16 @@ function parseHsl(lexer) { // version of parseColorComponent function for them. No need to check the // separator after 'lightness'. It will be checked in opacity value parsing. const separatorBeforeAlpha = hasComma ? commaSeparator : "/"; - if (parseColorComponent(lexer, COLOR_COMPONENT_TYPE.percentage, - hasComma ? commaSeparator : "", hsl) && - parseColorComponent(lexer, COLOR_COMPONENT_TYPE.percentage, "", hsl) && - parseColorOpacityAndCloseParen(lexer, separatorBeforeAlpha, a)) { + if ( + parseColorComponent( + lexer, + COLOR_COMPONENT_TYPE.percentage, + hasComma ? commaSeparator : "", + hsl + ) && + parseColorComponent(lexer, COLOR_COMPONENT_TYPE.percentage, "", hsl) && + parseColorOpacityAndCloseParen(lexer, separatorBeforeAlpha, a) + ) { return [...hslToRGB(hsl), ...a]; } @@ -980,18 +1030,32 @@ function parseOldStyleHsl(lexer, hasAlpha) { // The saturation and lightness are , so reuse the // version of parseColorComponent function for them. The opacity is if (hasAlpha) { - if (parseColorComponent(lexer, COLOR_COMPONENT_TYPE.percentage, - commaSeparator, hsl) && - parseColorComponent(lexer, COLOR_COMPONENT_TYPE.percentage, - commaSeparator, hsl) && - parseColorComponent(lexer, COLOR_COMPONENT_TYPE.number, - closeParen, a)) { + if ( + parseColorComponent( + lexer, + COLOR_COMPONENT_TYPE.percentage, + commaSeparator, + hsl + ) && + parseColorComponent( + lexer, + COLOR_COMPONENT_TYPE.percentage, + commaSeparator, + hsl + ) && + parseColorComponent(lexer, COLOR_COMPONENT_TYPE.number, closeParen, a) + ) { return [...hslToRGB(hsl), ...a]; } - } else if (parseColorComponent(lexer, COLOR_COMPONENT_TYPE.percentage, - commaSeparator, hsl) && - parseColorComponent(lexer, COLOR_COMPONENT_TYPE.percentage, - closeParen, hsl)) { + } else if ( + parseColorComponent( + lexer, + COLOR_COMPONENT_TYPE.percentage, + commaSeparator, + hsl + ) && + parseColorComponent(lexer, COLOR_COMPONENT_TYPE.percentage, closeParen, hsl) + ) { return [...hslToRGB(hsl), 1]; } @@ -1022,9 +1086,10 @@ function parseRgb(lexer) { return null; } unGetToken(lexer); - const type = (token.tokenType === "percentage") ? - COLOR_COMPONENT_TYPE.percentage : - COLOR_COMPONENT_TYPE.number; + const type = + token.tokenType === "percentage" + ? COLOR_COMPONENT_TYPE.percentage + : COLOR_COMPONENT_TYPE.number; // Parse R. if (!parseColorComponent(lexer, type, "", rgba)) { @@ -1036,9 +1101,11 @@ function parseRgb(lexer) { // No need to check the separator after 'B'. It will be checked in 'A' values // parsing. const separatorBeforeAlpha = hasComma ? commaSeparator : "/"; - if (parseColorComponent(lexer, type, hasComma ? commaSeparator : "", rgba) && - parseColorComponent(lexer, type, "", rgba) && - parseColorOpacityAndCloseParen(lexer, separatorBeforeAlpha, rgba)) { + if ( + parseColorComponent(lexer, type, hasComma ? commaSeparator : "", rgba) && + parseColorComponent(lexer, type, "", rgba) && + parseColorOpacityAndCloseParen(lexer, separatorBeforeAlpha, rgba) + ) { if (type === COLOR_COMPONENT_TYPE.percentage) { rgba[0] = Math.round(255 * rgba[0]); rgba[1] = Math.round(255 * rgba[1]); @@ -1070,27 +1137,33 @@ function parseOldStyleRgb(lexer, hasAlpha) { const rgba = []; const token = getToken(lexer); - if (token.tokenType !== "percentage" && - (token.tokenType !== "number" || !token.isInteger)) { + if ( + token.tokenType !== "percentage" && + (token.tokenType !== "number" || !token.isInteger) + ) { return null; } unGetToken(lexer); - const type = (token.tokenType === "percentage") ? - COLOR_COMPONENT_TYPE.percentage : - COLOR_COMPONENT_TYPE.integer; + const type = + token.tokenType === "percentage" + ? COLOR_COMPONENT_TYPE.percentage + : COLOR_COMPONENT_TYPE.integer; // Parse R. G, B and A. if (hasAlpha) { - if (!parseColorComponent(lexer, type, commaSeparator, rgba) || - !parseColorComponent(lexer, type, commaSeparator, rgba) || - !parseColorComponent(lexer, type, commaSeparator, rgba) || - !parseColorComponent(lexer, COLOR_COMPONENT_TYPE.number, - closeParen, rgba)) { + if ( + !parseColorComponent(lexer, type, commaSeparator, rgba) || + !parseColorComponent(lexer, type, commaSeparator, rgba) || + !parseColorComponent(lexer, type, commaSeparator, rgba) || + !parseColorComponent(lexer, COLOR_COMPONENT_TYPE.number, closeParen, rgba) + ) { return null; } - } else if (!parseColorComponent(lexer, type, commaSeparator, rgba) || - !parseColorComponent(lexer, type, commaSeparator, rgba) || - !parseColorComponent(lexer, type, closeParen, rgba)) { + } else if ( + !parseColorComponent(lexer, type, commaSeparator, rgba) || + !parseColorComponent(lexer, type, commaSeparator, rgba) || + !parseColorComponent(lexer, type, closeParen, rgba) + ) { return null; } @@ -1120,11 +1193,11 @@ function colorToRGBA(name, useCssColor4ColorFunction = false) { if (name in cssColors) { const result = cssColors[name]; - return {r: result[0], g: result[1], b: result[2], a: result[3]}; + return { r: result[0], g: result[1], b: result[2], a: result[3] }; } else if (name === "transparent") { - return {r: 0, g: 0, b: 0, a: 0}; + return { r: 0, g: 0, b: 0, a: 0 }; } else if (name === "currentcolor") { - return {r: 0, g: 0, b: 0, a: 1}; + return { r: 0, g: 0, b: 0, a: 1 }; } const lexer = getCSSLexer(name); @@ -1142,8 +1215,11 @@ function colorToRGBA(name, useCssColor4ColorFunction = false) { } const expectedFunctions = ["rgba", "rgb", "hsla", "hsl"]; - if (!func || func.tokenType !== "function" || - !expectedFunctions.includes(func.text)) { + if ( + !func || + func.tokenType !== "function" || + !expectedFunctions.includes(func.text) + ) { return null; } @@ -1151,8 +1227,10 @@ function colorToRGBA(name, useCssColor4ColorFunction = false) { let vals; if (!useCssColor4ColorFunction) { - const hasAlpha = (func.text === "rgba" || func.text === "hsla"); - vals = hsl ? parseOldStyleHsl(lexer, hasAlpha) : parseOldStyleRgb(lexer, hasAlpha); + const hasAlpha = func.text === "rgba" || func.text === "hsla"; + vals = hsl + ? parseOldStyleHsl(lexer, hasAlpha) + : parseOldStyleRgb(lexer, hasAlpha); } else { vals = hsl ? parseHsl(lexer) : parseRgb(lexer); } @@ -1164,7 +1242,7 @@ function colorToRGBA(name, useCssColor4ColorFunction = false) { return null; } - return {r: vals[0], g: vals[1], b: vals[2], a: vals[3]}; + return { r: vals[0], g: vals[1], b: vals[2], a: vals[3] }; } /** @@ -1188,8 +1266,10 @@ function isValidCSSColor(name, useCssColor4ColorFunction = false) { function calculateLuminance(rgba) { for (let i = 0; i < 3; i++) { rgba[i] /= 255; - rgba[i] = (rgba[i] < 0.03928) ? (rgba[i] / 12.92) : - Math.pow(((rgba[i] + 0.055) / 1.055), 2.4); + rgba[i] = + rgba[i] < 0.03928 + ? rgba[i] / 12.92 + : Math.pow((rgba[i] + 0.055) / 1.055, 2.4); } return 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2]; } @@ -1204,9 +1284,9 @@ function calculateLuminance(rgba) { * @return {Array} * An array with combined [r,g,b,a] colors. */ -function blendColors(foregroundColor, backgroundColor = [ 255, 255, 255, 1 ]) { - const [ fgR, fgG, fgB, fgA ] = foregroundColor; - const [ bgR, bgG, bgB, bgA ] = backgroundColor; +function blendColors(foregroundColor, backgroundColor = [255, 255, 255, 1]) { + const [fgR, fgG, fgB, fgA] = foregroundColor; + const [bgR, bgG, bgB, bgA] = backgroundColor; if (fgA === 1) { return foregroundColor; } @@ -1241,5 +1321,5 @@ function calculateContrastRatio(backgroundColor, textColor) { const textLuminance = calculateLuminance(textColor); const ratio = (textLuminance + 0.05) / (backgroundLuminance + 0.05); - return (ratio > 1.0) ? ratio : (1 / ratio); + return ratio > 1.0 ? ratio : 1 / ratio; } diff --git a/devtools/shared/css/constants.js b/devtools/shared/css/constants.js index 82a075bdd0c6..e3879971c536 100644 --- a/devtools/shared/css/constants.js +++ b/devtools/shared/css/constants.js @@ -8,10 +8,10 @@ * All CSS types that properties can support. */ exports.CSS_ANGLEUNIT = { - "deg": "deg", - "rad": "rad", - "grad": "grad", - "turn": "turn", + deg: "deg", + rad: "rad", + grad: "grad", + turn: "turn", }; /** @@ -19,9 +19,9 @@ exports.CSS_ANGLEUNIT = { * Kept for backwards compatibility. Remove after Firefox 70. */ exports.CSS_TYPES = { - "color": 2, - "gradient": 4, - "timing-function": 10, + color: 2, + gradient: 4, + "timing-function": 10, }; /** diff --git a/devtools/shared/css/generated/generate-properties-db.js b/devtools/shared/css/generated/generate-properties-db.js index 1387c0bb54ee..9febd5707da5 100644 --- a/devtools/shared/css/generated/generate-properties-db.js +++ b/devtools/shared/css/generated/generate-properties-db.js @@ -9,8 +9,10 @@ * as known by the platform. It is run from ./mach_commands.py by running * `mach devtools-css-db`. */ -var {require} = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); -var {generateCssProperties} = require("devtools/server/actors/css-properties"); +var { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); +var { + generateCssProperties, +} = require("devtools/server/actors/css-properties"); const InspectorUtils = require("InspectorUtils"); // xpcshell can output extra information, so place some delimiter text between @@ -18,11 +20,13 @@ const InspectorUtils = require("InspectorUtils"); dump("DEVTOOLS_CSS_DB_DELIMITER"); // Output JSON -dump(JSON.stringify({ - cssProperties: cssProperties(), - preferences: preferences(), - pseudoElements: pseudoElements(), -})); +dump( + JSON.stringify({ + cssProperties: cssProperties(), + preferences: preferences(), + pseudoElements: pseudoElements(), + }) +); dump("DEVTOOLS_CSS_DB_DELIMITER"); @@ -53,7 +57,7 @@ function cssProperties() { function preferences() { const prefs = InspectorUtils.getCSSPropertyPrefs(); const result = []; - for (const {name, pref} of prefs) { + for (const { name, pref } of prefs) { result.push([name, pref]); } return result; diff --git a/devtools/shared/css/lexer.js b/devtools/shared/css/lexer.js index 1feac2bd9f06..ae5cbdbc76ae 100644 --- a/devtools/shared/css/lexer.js +++ b/devtools/shared/css/lexer.js @@ -133,14 +133,14 @@ const NUMBER_SIGN = "#".charCodeAt(0); const PERCENT_SIGN = "%".charCodeAt(0); const PLUS_SIGN = "+".charCodeAt(0); const QUESTION_MARK = "?".charCodeAt(0); -const QUOTATION_MARK = "\"".charCodeAt(0); +const QUOTATION_MARK = '"'.charCodeAt(0); const REVERSE_SOLIDUS = "\\".charCodeAt(0); const RIGHT_PARENTHESIS = ")".charCodeAt(0); const SOLIDUS = "/".charCodeAt(0); const TILDE = "~".charCodeAt(0); const VERTICAL_LINE = "|".charCodeAt(0); -const UCS2_REPLACEMENT_CHAR = 0xFFFD; +const UCS2_REPLACEMENT_CHAR = 0xfffd; const kImpliedEOFCharacters = [ UCS2_REPLACEMENT_CHAR, @@ -160,7 +160,7 @@ const kImpliedEOFCharacters = [ * @return {Number} the character or its replacement */ function ensureValidChar(c) { - if (c >= 0x00110000 || (c & 0xFFF800) == 0xD800) { + if (c >= 0x00110000 || (c & 0xfff800) == 0xd800) { // Out of range or a surrogate. return UCS2_REPLACEMENT_CHAR; } @@ -175,7 +175,7 @@ function ensureValidChar(c) { * the input string. */ function stringToCodes(str) { - return Array.prototype.map.call(str, (c) => c.charCodeAt(0)); + return Array.prototype.map.call(str, c => c.charCodeAt(0)); } const IS_HEX_DIGIT = 0x01; @@ -204,38 +204,150 @@ const SUIJX = S | U | I | J | X; /* eslint-disable indent, indent-legacy, no-multi-spaces, comma-spacing, spaced-comment */ const gLexTable = [ -// 00 01 02 03 04 05 06 07 - 0, S, S, S, S, S, S, S, -// 08 TAB LF 0B FF CR 0E 0F - S, SH, V, S, V, V, S, S, -// 10 11 12 13 14 15 16 17 - S, S, S, S, S, S, S, S, -// 18 19 1A 1B 1C 1D 1E 1F - S, S, S, S, S, S, S, S, -//SPC ! " # $ % & ' - SH, SU, 0, SU, SU, SU, SU, 0, -// ( ) * + , - . / - S, S, SU, SU, SU, SUI, SU, SU, -// 0 1 2 3 4 5 6 7 - SUIX, SUIX, SUIX, SUIX, SUIX, SUIX, SUIX, SUIX, -// 8 9 : ; < = > ? - SUIX, SUIX, SU, SU, SU, SU, SU, SU, -// @ A B C D E F G - SU,SUIJX,SUIJX,SUIJX,SUIJX,SUIJX,SUIJX, SUIJ, -// H I J K L M N O - SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, -// P Q R S T U V W - SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, -// X Y Z [ \ ] ^ _ - SUIJ, SUIJ, SUIJ, SU, J, SU, SU, SUIJ, -// ` a b c d e f g - SU,SUIJX,SUIJX,SUIJX,SUIJX,SUIJX,SUIJX, SUIJ, -// h i j k l m n o - SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, -// p q r s t u v w - SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, SUIJ, -// x y z { | } ~ 7F - SUIJ, SUIJ, SUIJ, SU, SU, SU, SU, S, + // 00 01 02 03 04 05 06 07 + 0, + S, + S, + S, + S, + S, + S, + S, + // 08 TAB LF 0B FF CR 0E 0F + S, + SH, + V, + S, + V, + V, + S, + S, + // 10 11 12 13 14 15 16 17 + S, + S, + S, + S, + S, + S, + S, + S, + // 18 19 1A 1B 1C 1D 1E 1F + S, + S, + S, + S, + S, + S, + S, + S, + //SPC ! " # $ % & ' + SH, + SU, + 0, + SU, + SU, + SU, + SU, + 0, + // ( ) * + , - . / + S, + S, + SU, + SU, + SU, + SUI, + SU, + SU, + // 0 1 2 3 4 5 6 7 + SUIX, + SUIX, + SUIX, + SUIX, + SUIX, + SUIX, + SUIX, + SUIX, + // 8 9 : ; < = > ? + SUIX, + SUIX, + SU, + SU, + SU, + SU, + SU, + SU, + // @ A B C D E F G + SU, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJ, + // H I J K L M N O + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + // P Q R S T U V W + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + // X Y Z [ \ ] ^ _ + SUIJ, + SUIJ, + SUIJ, + SU, + J, + SU, + SU, + SUIJ, + // ` a b c d e f g + SU, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJX, + SUIJ, + // h i j k l m n o + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + // p q r s t u v w + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + SUIJ, + // x y z { | } ~ 7F + SUIJ, + SUIJ, + SUIJ, + SU, + SU, + SU, + SU, + S, ]; /* eslint-enable indent, indent-legacy, no-multi-spaces, comma-spacing, spaced-comment */ @@ -304,16 +416,18 @@ function IsIdentStart(ch) { * identifier. */ function StartsIdent(aFirstChar, aSecondChar) { - return IsIdentStart(aFirstChar) || - (aFirstChar == HYPHEN_MINUS && (aSecondChar == HYPHEN_MINUS || - IsIdentStart(aSecondChar))); + return ( + IsIdentStart(aFirstChar) || + (aFirstChar == HYPHEN_MINUS && + (aSecondChar == HYPHEN_MINUS || IsIdentStart(aSecondChar))) + ); } /** * True if 'ch' is a decimal digit. */ function IsDigit(ch) { - return (ch >= DIGIT_ZERO) && (ch <= DIGIT_NINE); + return ch >= DIGIT_ZERO && ch <= DIGIT_NINE; } /** @@ -351,12 +465,18 @@ function HexDigitValue(ch) { */ function MatchOperatorType(ch) { switch (ch) { - case TILDE: return eCSSToken_Includes; - case VERTICAL_LINE: return eCSSToken_Dashmatch; - case CIRCUMFLEX_ACCENT: return eCSSToken_Beginsmatch; - case DOLLAR_SIGN: return eCSSToken_Endsmatch; - case ASTERISK: return eCSSToken_Containsmatch; - default: return eCSSToken_Symbol; + case TILDE: + return eCSSToken_Includes; + case VERTICAL_LINE: + return eCSSToken_Dashmatch; + case CIRCUMFLEX_ACCENT: + return eCSSToken_Beginsmatch; + case DOLLAR_SIGN: + return eCSSToken_Endsmatch; + case ASTERISK: + return eCSSToken_Containsmatch; + default: + return eCSSToken_Symbol; } } @@ -428,16 +548,23 @@ Scanner.prototype = { let eofChars = this.mEOFCharacters; - if (aPreserveBackslash && - (eofChars & (eEOFCharacters_DropBackslash | - eEOFCharacters_ReplacementChar)) != 0) { - eofChars &= ~(eEOFCharacters_DropBackslash | - eEOFCharacters_ReplacementChar); + if ( + aPreserveBackslash && + (eofChars & + (eEOFCharacters_DropBackslash | eEOFCharacters_ReplacementChar)) != + 0 + ) { + eofChars &= ~( + eEOFCharacters_DropBackslash | eEOFCharacters_ReplacementChar + ); result += "\\"; } - if ((eofChars & eEOFCharacters_DropBackslash) != 0 && - result.length > 0 && result.endsWith("\\")) { + if ( + (eofChars & eEOFCharacters_DropBackslash) != 0 && + result.length > 0 && + result.endsWith("\\") + ) { result = result.slice(0, -1); } @@ -525,7 +652,7 @@ Scanner.prototype = { case eCSSToken_Dimension: resultToken.text = constructText(); - /* Fall through. */ + /* Fall through. */ case eCSSToken_Number: case eCSSToken_Percentage: resultToken.number = token.mNumber; @@ -595,9 +722,11 @@ Scanner.prototype = { */ AdvanceLine: function() { // Advance over \r\n as a unit. - if (this.mBuffer.charCodeAt(this.mOffset) == CARRIAGE_RETURN && - this.mOffset + 1 < this.mCount && - this.mBuffer.charCodeAt(this.mOffset + 1) == LINE_FEED) { + if ( + this.mBuffer.charCodeAt(this.mOffset) == CARRIAGE_RETURN && + this.mOffset + 1 < this.mCount && + this.mBuffer.charCodeAt(this.mOffset + 1) == LINE_FEED + ) { this.mOffset += 2; } else { this.mOffset += 1; @@ -616,7 +745,8 @@ Scanner.prototype = { SkipWhitespace: function() { for (;;) { const ch = this.Peek(); - if (!IsWhitespace(ch)) { // EOF counts as non-whitespace + if (!IsWhitespace(ch)) { + // EOF counts as non-whitespace break; } if (IsVertSpace(ch)) { @@ -760,8 +890,10 @@ Scanner.prototype = { for (;;) { // Consume runs of unescaped characters in one go. let n = this.mOffset; - while (n < this.mCount && IsOpenCharClass(this.mBuffer.charCodeAt(n), - aClass)) { + while ( + n < this.mCount && + IsOpenCharClass(this.mBuffer.charCodeAt(n), aClass) + ) { n++; } if (n > this.mOffset) { @@ -849,8 +981,9 @@ Scanner.prototype = { const ch = this.Peek(); if (IsIdentChar(ch) || ch == REVERSE_SOLIDUS) { - const type = - StartsIdent(ch, this.Peek(1)) ? eCSSToken_ID : eCSSToken_Hash; + const type = StartsIdent(ch, this.Peek(1)) + ? eCSSToken_ID + : eCSSToken_Hash; aToken.mIdent.length = 0; if (this.GatherText(IS_IDCHAR, aToken.mIdent)) { aToken.mType = type; @@ -891,13 +1024,13 @@ Scanner.prototype = { // Sign of the exponent. let expSign = 1; - aToken.mHasSign = (c == PLUS_SIGN || c == HYPHEN_MINUS); + aToken.mHasSign = c == PLUS_SIGN || c == HYPHEN_MINUS; if (aToken.mHasSign) { this.Advance(); c = this.Peek(); } - let gotDot = (c == FULL_STOP); + let gotDot = c == FULL_STOP; if (!gotDot) { // Scan the integer part of the mantissa. @@ -907,7 +1040,7 @@ Scanner.prototype = { c = this.Peek(); } while (IsDigit(c)); - gotDot = (c == FULL_STOP) && IsDigit(this.Peek(1)); + gotDot = c == FULL_STOP && IsDigit(this.Peek(1)); } if (gotDot) { @@ -928,9 +1061,11 @@ Scanner.prototype = { if (c == LATIN_SMALL_LETTER_E || c == LATIN_CAPITAL_LETTER_E) { const expSignChar = this.Peek(1); const nextChar = this.Peek(2); - if (IsDigit(expSignChar) || - ((expSignChar == HYPHEN_MINUS || expSignChar == PLUS_SIGN) && - IsDigit(nextChar))) { + if ( + IsDigit(expSignChar) || + ((expSignChar == HYPHEN_MINUS || expSignChar == PLUS_SIGN) && + IsDigit(nextChar)) + ) { gotE = true; if (expSignChar == HYPHEN_MINUS) { expSign = -1; @@ -1009,9 +1144,11 @@ Scanner.prototype = { const ch = this.Peek(); if (ch == -1) { - this.AddEOFCharacters(aStop == QUOTATION_MARK ? - eEOFCharacters_DoubleQuote : - eEOFCharacters_SingleQuote); + this.AddEOFCharacters( + aStop == QUOTATION_MARK + ? eEOFCharacters_DoubleQuote + : eEOFCharacters_SingleQuote + ); break; // EOF ends a string token with no error. } if (ch == aStop) { @@ -1073,7 +1210,7 @@ Scanner.prototype = { } else { haveQues = true; low = low * 16 + 0x0; - high = high * 16 + 0xF; + high = high * 16 + 0xf; } i++; @@ -1219,8 +1356,10 @@ Scanner.prototype = { aToken.mType = eCSSToken_Whitespace; return true; } - if (ch == SOLIDUS && // !IsSVGMode() && - this.Peek(1) == ASTERISK) { + if ( + ch == SOLIDUS && // !IsSVGMode() && + this.Peek(1) == ASTERISK + ) { this.SkipComment(); aToken.mType = eCSSToken_Comment; return true; @@ -1282,10 +1421,12 @@ Scanner.prototype = { } // the other HTML-comment token - if (ch == LESS_THAN_SIGN && - this.Peek(1) == EXCLAMATION_MARK && - this.Peek(2) == HYPHEN_MINUS && - this.Peek(3) == HYPHEN_MINUS) { + if ( + ch == LESS_THAN_SIGN && + this.Peek(1) == EXCLAMATION_MARK && + this.Peek(2) == HYPHEN_MINUS && + this.Peek(3) == HYPHEN_MINUS + ) { this.Advance(4); aToken.mType = eCSSToken_HTMLComment; aToken.mIdent = stringToCodes("$/, "").trim(); + text = trimmed + .replace(/^$/, "") + .trim(); } const originalText = text; @@ -357,8 +380,12 @@ function prettifyCSS(text, ruleCount) { break; } - if (token.tokenType === "symbol" && token.text === "," && - isInSelector && !isInAtRuleDefinition) { + if ( + token.tokenType === "symbol" && + token.text === "," && + isInSelector && + !isInAtRuleDefinition + ) { break; } @@ -437,8 +464,12 @@ function prettifyCSS(text, ruleCount) { // "Early" bail-out if the text does not appear to be minified. // Here we ignore the case where whitespace appears at the end of // the text. - if (pushbackToken && token && token.tokenType === "whitespace" && - /\n/g.test(text.substring(token.startOffset, token.endOffset))) { + if ( + pushbackToken && + token && + token.tokenType === "whitespace" && + /\n/g.test(text.substring(token.startOffset, token.endOffset)) + ) { return { result: originalText, mappings: [] }; } diff --git a/devtools/shared/inspector/utils.js b/devtools/shared/inspector/utils.js index ba0ad99ac035..3bd6b8edff0b 100644 --- a/devtools/shared/inspector/utils.js +++ b/devtools/shared/inspector/utils.js @@ -12,9 +12,11 @@ function truncateString(str, maxLength) { return str; } - return str.substring(0, Math.ceil(maxLength / 2)) + - "…" + - str.substring(str.length - Math.floor(maxLength / 2)); + return ( + str.substring(0, Math.ceil(maxLength / 2)) + + "…" + + str.substring(str.length - Math.floor(maxLength / 2)) + ); } exports.truncateString = truncateString; diff --git a/devtools/shared/l10n.js b/devtools/shared/l10n.js index 00c9080db34e..a2cb83fc4ed3 100644 --- a/devtools/shared/l10n.js +++ b/devtools/shared/l10n.js @@ -26,14 +26,26 @@ const propertiesMap = {}; // file. In the webpack case this results in just the locale property // files being included in the pack; and in the devtools case this is // a wordy no-op. -const reqShared = require.context("raw!devtools/shared/locales/", - true, /^.*\.properties$/); -const reqClient = require.context("raw!devtools/client/locales/", - true, /^.*\.properties$/); -const reqStartup = require.context("raw!devtools/startup/locales/", - true, /^.*\.properties$/); -const reqGlobal = require.context("raw!toolkit/locales/", - true, /^.*\.properties$/); +const reqShared = require.context( + "raw!devtools/shared/locales/", + true, + /^.*\.properties$/ +); +const reqClient = require.context( + "raw!devtools/client/locales/", + true, + /^.*\.properties$/ +); +const reqStartup = require.context( + "raw!devtools/startup/locales/", + true, + /^.*\.properties$/ +); +const reqGlobal = require.context( + "raw!toolkit/locales/", + true, + /^.*\.properties$/ +); // Map used to memoize Number formatters. const numberFormatters = new Map(); @@ -160,7 +172,7 @@ LocalizationHelper.prototype = { */ numberWithDecimals: function(number, decimals = 0) { // Do not show decimals for integers. - if (number === (number|0)) { + if (number === (number | 0)) { return getNumberFormatter(0).format(number); } @@ -175,8 +187,8 @@ LocalizationHelper.prototype = { // Convert the localized number to a number again. const localizedNumber = localized * 1; // Check if this number is now equal to an integer. - if (localizedNumber === (localizedNumber|0)) { - // If it is, remove the fraction part. + if (localizedNumber === (localizedNumber | 0)) { + // If it is, remove the fraction part. return getNumberFormatter(0).format(localizedNumber); } @@ -241,7 +253,9 @@ function localizeMarkup(root) { } } -const sharedL10N = new LocalizationHelper("devtools/shared/locales/shared.properties"); +const sharedL10N = new LocalizationHelper( + "devtools/shared/locales/shared.properties" +); /** * A helper for having the same interface as LocalizationHelper, but for more @@ -260,8 +274,10 @@ function MultiLocalizationHelper(...stringBundleNames) { Object.getOwnPropertyNames(LocalizationHelper.prototype) .map(name => ({ name: name, - descriptor: Object.getOwnPropertyDescriptor(LocalizationHelper.prototype, - name), + descriptor: Object.getOwnPropertyDescriptor( + LocalizationHelper.prototype, + name + ), })) .filter(({ descriptor }) => descriptor.value instanceof Function) .forEach(method => { @@ -281,4 +297,6 @@ function MultiLocalizationHelper(...stringBundleNames) { exports.LocalizationHelper = LocalizationHelper; exports.localizeMarkup = localizeMarkup; exports.MultiLocalizationHelper = MultiLocalizationHelper; -Object.defineProperty(exports, "ELLIPSIS", { get: () => sharedL10N.getStr("ellipsis") }); +Object.defineProperty(exports, "ELLIPSIS", { + get: () => sharedL10N.getStr("ellipsis"), +}); diff --git a/devtools/shared/layout/dom-matrix-2d.js b/devtools/shared/layout/dom-matrix-2d.js index fa51a4fd8ffb..f6e3e730672d 100644 --- a/devtools/shared/layout/dom-matrix-2d.js +++ b/devtools/shared/layout/dom-matrix-2d.js @@ -17,11 +17,7 @@ * @return {Array} * The new matrix. */ -const scale = (sx = 1, sy = sx) => [ - sx, 0, 0, - 0, sy, 0, - 0, 0, 1, -]; +const scale = (sx = 1, sy = sx) => [sx, 0, 0, 0, sy, 0, 0, 0, 1]; exports.scale = scale; /** @@ -37,11 +33,7 @@ exports.scale = scale; * @return {Array} * The new matrix. */ -const translate = (tx = 0, ty = tx) => [ - 1, 0, tx, - 0, 1, ty, - 0, 0, 1, -]; +const translate = (tx = 0, ty = tx) => [1, 0, tx, 0, 1, ty, 0, 0, 1]; exports.translate = translate; /** @@ -51,11 +43,7 @@ exports.translate = translate; * @return {Array} * The new matrix. */ -const reflectAboutY = () => [ - -1, 0, 0, - 0, 1, 0, - 0, 0, 1, -]; +const reflectAboutY = () => [-1, 0, 0, 0, 1, 0, 0, 0, 1]; exports.reflectAboutY = reflectAboutY; /** @@ -72,11 +60,7 @@ const rotate = (angle = 0) => { const cos = Math.cos(angle); const sin = Math.sin(angle); - return [ - cos, sin, 0, - -sin, cos, 0, - 0, 0, 1, - ]; + return [cos, sin, 0, -sin, cos, 0, 0, 0, 1]; }; exports.rotate = rotate; @@ -86,11 +70,7 @@ exports.rotate = rotate; * @return {Array} * The new matrix. */ -const identity = () => [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, -]; +const identity = () => [1, 0, 0, 0, 1, 0, 0, 0, 1]; exports.identity = identity; /** @@ -116,11 +96,7 @@ const multiply = (M1, M2) => { const c32 = M1[6] * M2[1] + M1[7] * M2[4] + M1[8] * M2[7]; const c33 = M1[6] * M2[2] + M1[7] * M2[5] + M1[8] * M2[8]; - return [ - c11, c12, c13, - c21, c22, c23, - c31, c32, c33, - ]; + return [c11, c12, c13, c21, c22, c23, c31, c32, c33]; }; exports.multiply = multiply; @@ -148,10 +124,16 @@ exports.apply = apply; * @return {Boolean} * `true` if the matrix passed is a identity matrix, `false` otherwise. */ -const isIdentity = (M) => - M[0] === 1 && M[1] === 0 && M[2] === 0 && - M[3] === 0 && M[4] === 1 && M[5] === 0 && - M[6] === 0 && M[7] === 0 && M[8] === 1; +const isIdentity = M => + M[0] === 1 && + M[1] === 0 && + M[2] === 0 && + M[3] === 0 && + M[4] === 1 && + M[5] === 0 && + M[6] === 0 && + M[7] === 0 && + M[8] === 1; exports.isIdentity = isIdentity; /** @@ -171,15 +153,29 @@ exports.isIdentity = isIdentity; const getBasis = (u, v) => { const uLength = Math.abs(Math.sqrt(u[0] ** 2 + u[1] ** 2)); const vLength = Math.abs(Math.sqrt(v[0] ** 2 + v[1] ** 2)); - const basis = - [ u[0] / uLength, v[0] / vLength, 0, - u[1] / uLength, v[1] / vLength, 0, - 0, 0, 1 ]; + const basis = [ + u[0] / uLength, + v[0] / vLength, + 0, + u[1] / uLength, + v[1] / vLength, + 0, + 0, + 0, + 1, + ]; const determinant = 1 / (basis[0] * basis[4] - basis[1] * basis[3]); - const invertedBasis = - [ basis[4] / determinant, -basis[1] / determinant, 0, - -basis[3] / determinant, basis[0] / determinant, 0, - 0, 0, 1 ]; + const invertedBasis = [ + basis[4] / determinant, + -basis[1] / determinant, + 0, + -basis[3] / determinant, + basis[0] / determinant, + 0, + 0, + 0, + 1, + ]; return { basis, invertedBasis, uLength, vLength }; }; exports.getBasis = getBasis; @@ -216,14 +212,11 @@ exports.changeMatrixBase = changeMatrixBase; * The transformation matrix. */ function getNodeTransformationMatrix(node, ancestor = node.parentElement) { - const { a, b, c, d, e, f } = ancestor.getTransformToParent() - .multiply(node.getTransformToAncestor(ancestor)); + const { a, b, c, d, e, f } = ancestor + .getTransformToParent() + .multiply(node.getTransformToAncestor(ancestor)); - return [ - a, c, e, - b, d, f, - 0, 0, 1, - ]; + return [a, c, e, b, d, f, 0, 0, 1]; } exports.getNodeTransformationMatrix = getNodeTransformationMatrix; @@ -249,28 +242,16 @@ function getWritingModeMatrix(size, style) { // This is the initial value. No further adjustment needed. break; case "vertical-rl": - currentMatrix = multiply( - translate(width, 0), - rotate(-Math.PI / 2) - ); + currentMatrix = multiply(translate(width, 0), rotate(-Math.PI / 2)); break; case "vertical-lr": - currentMatrix = multiply( - reflectAboutY(), - rotate(-Math.PI / 2) - ); + currentMatrix = multiply(reflectAboutY(), rotate(-Math.PI / 2)); break; case "sideways-rl": - currentMatrix = multiply( - translate(width, 0), - rotate(-Math.PI / 2) - ); + currentMatrix = multiply(translate(width, 0), rotate(-Math.PI / 2)); break; case "sideways-lr": - currentMatrix = multiply( - rotate(Math.PI / 2), - translate(-height, 0) - ); + currentMatrix = multiply(rotate(Math.PI / 2), translate(-height, 0)); break; default: console.error(`Unexpected writing-mode: ${writingMode}`); @@ -310,10 +291,7 @@ exports.getWritingModeMatrix = getWritingModeMatrix; * The matching 6 element CSS transform function. */ function getCSSMatrixTransform(M) { - const [ - a, c, e, - b, d, f, - ] = M; + const [a, c, e, b, d, f] = M; return `matrix(${a}, ${b}, ${c}, ${d}, ${e}, ${f})`; } exports.getCSSMatrixTransform = getCSSMatrixTransform; diff --git a/devtools/shared/layout/utils.js b/devtools/shared/layout/utils.js index 058f4f2164c9..cd1343a42fff 100644 --- a/devtools/shared/layout/utils.js +++ b/devtools/shared/layout/utils.js @@ -8,13 +8,18 @@ const { Ci, Cc } = require("chrome"); const nodeFilterConstants = require("devtools/shared/dom-node-filter-constants"); const SHEET_TYPE = { - "agent": "AGENT_SHEET", - "user": "USER_SHEET", - "author": "AUTHOR_SHEET", + agent: "AGENT_SHEET", + user: "USER_SHEET", + author: "AUTHOR_SHEET", }; // eslint-disable-next-line no-unused-vars -loader.lazyRequireGetter(this, "setIgnoreLayoutChanges", "devtools/server/actors/reflow", true); +loader.lazyRequireGetter( + this, + "setIgnoreLayoutChanges", + "devtools/server/actors/reflow", + true +); exports.setIgnoreLayoutChanges = (...args) => this.setIgnoreLayoutChanges(...args); @@ -47,12 +52,12 @@ const isTopWindow = win => win && win.top === win; exports.isTopWindow = isTopWindow; /** - * Check a window is part of the boundary window given. - * - * @param {DOMWindow} boundaryWindow - * @param {DOMWindow} win - * @return {Boolean} - */ + * Check a window is part of the boundary window given. + * + * @param {DOMWindow} boundaryWindow + * @param {DOMWindow} win + * @return {Boolean} + */ function isWindowIncluded(boundaryWindow, win) { if (win === boundaryWindow) { return true; @@ -76,7 +81,7 @@ exports.isWindowIncluded = isWindowIncluded; * @return {DOMNode} * The element in which the window is embedded. */ -const getFrameElement = (win) => +const getFrameElement = win => isTopWindow(win) ? null : utilsFor(win).containerElement; exports.getFrameElement = getFrameElement; @@ -151,7 +156,7 @@ exports.getFrameOffsets = getFrameOffsets; * An array of objects that have the same structure as quads returned by * getBoxQuads. An empty array if the node has no quads or is invalid. */ -function getAdjustedQuads(boundaryWindow, node, region, {ignoreZoom} = {}) { +function getAdjustedQuads(boundaryWindow, node, region, { ignoreZoom } = {}) { if (!node || !node.getBoxQuads) { return []; } @@ -323,10 +328,10 @@ function getNodeBounds(boundaryWindow, node) { const height = node.offsetHeight * scale; return { - p1: {x: xOffset, y: yOffset}, - p2: {x: xOffset + width, y: yOffset}, - p3: {x: xOffset + width, y: yOffset + height}, - p4: {x: xOffset, y: yOffset + height}, + p1: { x: xOffset, y: yOffset }, + p2: { x: xOffset + width, y: yOffset }, + p3: { x: xOffset + width, y: yOffset + height }, + p4: { x: xOffset, y: yOffset + height }, top: yOffset, right: xOffset + width, bottom: yOffset + height, @@ -350,8 +355,9 @@ function safelyGetContentWindow(frame) { return frame.contentWindow; } - const walker = Cc["@mozilla.org/inspector/deep-tree-walker;1"] - .createInstance(Ci.inIDeepTreeWalker); + const walker = Cc["@mozilla.org/inspector/deep-tree-walker;1"].createInstance( + Ci.inIDeepTreeWalker + ); walker.showSubDocuments = true; walker.showDocumentsAsNodes = true; walker.init(frame, nodeFilterConstants.SHOW_ALL); @@ -409,8 +415,10 @@ function isNodeConnected(node) { } try { - return !(node.compareDocumentPosition(node.ownerDocument.documentElement) & - node.DOCUMENT_POSITION_DISCONNECTED); + return !( + node.compareDocumentPosition(node.ownerDocument.documentElement) & + node.DOCUMENT_POSITION_DISCONNECTED + ); } catch (e) { // "can't access dead object" error return false; @@ -466,7 +474,7 @@ exports.getBindingParent = getBindingParent; * @return {Boolean} * */ -const isAnonymous = (node) => getRootBindingParent(node) !== node; +const isAnonymous = node => getRootBindingParent(node) !== node; exports.isAnonymous = isAnonymous; /** @@ -476,7 +484,7 @@ exports.isAnonymous = isAnonymous; * @return {Boolean} * */ -const hasBindingParent = (node) => !!getBindingParent(node); +const hasBindingParent = node => !!getBindingParent(node); /** * Determine whether a node is native anonymous content (as opposed @@ -488,7 +496,7 @@ const hasBindingParent = (node) => !!getBindingParent(node); * @return {Boolean} * */ -const isNativeAnonymous = (node) => +const isNativeAnonymous = node => hasBindingParent(node) && !(isXBLAnonymous(node) || isShadowAnonymous(node)); exports.isNativeAnonymous = isNativeAnonymous; @@ -508,7 +516,7 @@ function isXBLAnonymous(node) { return false; } - const anonNodes = [...node.ownerDocument.getAnonymousNodes(parent) || []]; + const anonNodes = [...(node.ownerDocument.getAnonymousNodes(parent) || [])]; return anonNodes.indexOf(node) > -1; } exports.isXBLAnonymous = isXBLAnonymous; @@ -528,7 +536,10 @@ function isShadowAnonymous(node) { // If there is a shadowRoot and this is part of it then this // is not native anonymous - return parent.openOrClosedShadowRoot && parent.openOrClosedShadowRoot.contains(node); + return ( + parent.openOrClosedShadowRoot && + parent.openOrClosedShadowRoot.contains(node) + ); } exports.isShadowAnonymous = isShadowAnonymous; @@ -539,7 +550,9 @@ exports.isShadowAnonymous = isShadowAnonymous; * @return {Boolean} */ function isTemplateElement(node) { - return node.ownerGlobal && node instanceof node.ownerGlobal.HTMLTemplateElement; + return ( + node.ownerGlobal && node instanceof node.ownerGlobal.HTMLTemplateElement + ); } exports.isTemplateElement = isTemplateElement; @@ -593,7 +606,8 @@ function isDirectShadowHostChild(node) { isMarkerPseudoElement(node) || isBeforePseudoElement(node) || isAfterPseudoElement(node) || - isNativeAnonymous(node)) { + isNativeAnonymous(node) + ) { return false; } diff --git a/devtools/shared/multi-e10s-helper.js b/devtools/shared/multi-e10s-helper.js index 05d1247ef7f4..f3f6d08adec8 100644 --- a/devtools/shared/multi-e10s-helper.js +++ b/devtools/shared/multi-e10s-helper.js @@ -8,7 +8,8 @@ const Services = require("Services"); const { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm"); XPCOMUtils.defineLazyServiceGetter( - this, "swm", + this, + "swm", "@mozilla.org/serviceworkers/manager;1", "nsIServiceWorkerManager" ); @@ -52,7 +53,7 @@ function removeMultiE10sListener(listener) { function isMultiE10s() { const isE10s = Services.appinfo.browserTabsRemoteAutostart; const processCount = Services.appinfo.maxWebProcessCount; - const multiE10s = isE10s && processCount > 1; + const multiE10s = isE10s && processCount > 1; const isNewSWImplementation = swm.isParentInterceptEnabled(); // When can we debug Service Workers? diff --git a/devtools/shared/performance/recording-utils.js b/devtools/shared/performance/recording-utils.js index b677ec4f8293..dfc511079130 100644 --- a/devtools/shared/performance/recording-utils.js +++ b/devtools/shared/performance/recording-utils.js @@ -12,8 +12,9 @@ function mapRecordingOptions(type, options) { if (type === "profiler") { return { entries: options.bufferSize, - interval: options.sampleFrequency ? (1000 / options.sampleFrequency) - : void 0, + interval: options.sampleFrequency + ? 1000 / options.sampleFrequency + : void 0, }; } @@ -289,7 +290,7 @@ function allocationsWithSchema(data) { * A profile with version 2. */ function deflateProfile(profile) { - profile.threads = profile.threads.map((thread) => { + profile.threads = profile.threads.map(thread => { const uniqueStacks = new UniqueStacks(); return deflateThread(thread, uniqueStacks); }); @@ -561,8 +562,9 @@ UniqueStacks.prototype.getOrAddFrameIndex = function(frame) { const implementationIndex = this.getOrAddStringIndex(frame.implementation); // Super dumb. - const hash = `${locationIndex} ${implementationIndex || ""} ` + - `${frame.line || ""} ${frame.category || ""}`; + const hash = + `${locationIndex} ${implementationIndex || ""} ` + + `${frame.line || ""} ${frame.category || ""}`; let index = frameHash[hash]; if (index !== undefined) { diff --git a/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js b/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js index 9c4769515f7a..953ae425898b 100644 --- a/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js +++ b/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js @@ -10,9 +10,15 @@ */ add_task(function() { - const { getProfileThreadFromAllocations } = require("devtools/shared/performance/recording-utils"); + const { + getProfileThreadFromAllocations, + } = require("devtools/shared/performance/recording-utils"); const output = getProfileThreadFromAllocations(TEST_DATA); - equal(output.toSource(), EXPECTED_OUTPUT.toSource(), "The output is correct."); + equal( + output.toSource(), + EXPECTED_OUTPUT.toSource(), + "The output is correct." + ); }); var TEST_DATA = { @@ -20,19 +26,22 @@ var TEST_DATA = { timestamps: [50, 100, 150, 200, 250], sizes: [0, 0, 100, 200, 300], frames: [ - null, { + null, + { source: "A", line: 1, column: 2, functionDisplayName: "x", parent: 0, - }, { + }, + { source: "B", line: 3, column: 4, functionDisplayName: "y", parent: 1, - }, { + }, + { source: "C", line: 5, column: 6, @@ -45,53 +54,40 @@ var TEST_DATA = { var EXPECTED_OUTPUT = { name: "allocations", samples: { - "schema": { - "stack": 0, - "time": 1, - "size": 2, + schema: { + stack: 0, + time: 1, + size: 2, }, - data: [ - [ 1, 150, 100 ], - [ 2, 200, 200 ], - [ 3, 250, 300 ], - ], + data: [[1, 150, 100], [2, 200, 200], [3, 250, 300]], }, stackTable: { - "schema": { - "prefix": 0, - "frame": 1, + schema: { + prefix: 0, + frame: 1, }, - "data": [ + data: [ null, // x (A:1:2) - [ null, 1 ], + [null, 1], // x (A:1:2) > y (B:3:4) - [ 1, 2 ], + [1, 2], // x (A:1:2) > y (B:3:4) > C:5:6 - [ 2, 3 ], + [2, 3], ], }, frameTable: { - "schema": { - "location": 0, - "implementation": 1, - "optimizations": 2, - "line": 3, - "category": 4, + schema: { + location: 0, + implementation: 1, + optimizations: 2, + line: 3, + category: 4, }, - data: [ - null, - [ 0 ], - [ 1 ], - [ 2 ], - ], + data: [null, [0], [1], [2]], }, - "stringTable": [ - "x (A:1:2)", - "y (B:3:4)", - "C:5:6", - ], + stringTable: ["x (A:1:2)", "y (B:3:4)", "C:5:6"], }; diff --git a/devtools/shared/platform/cache-entry.js b/devtools/shared/platform/cache-entry.js index 16d837a5e965..158a15b8da0c 100644 --- a/devtools/shared/platform/cache-entry.js +++ b/devtools/shared/platform/cache-entry.js @@ -4,46 +4,49 @@ * 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"; +"use strict"; - const Services = require("Services"); - const {Ci} = require("chrome"); - loader.lazyRequireGetter(this, "NetworkHelper", - "devtools/shared/webconsole/network-helper"); +const Services = require("Services"); +const { Ci } = require("chrome"); +loader.lazyRequireGetter( + this, + "NetworkHelper", + "devtools/shared/webconsole/network-helper" +); - /** - * Module to fetch cache objects from CacheStorageService - * and return them as an object. - */ - exports.CacheEntry = { +/** + * Module to fetch cache objects from CacheStorageService + * and return them as an object. + */ +exports.CacheEntry = { /** * Flag for cache session being initialized. */ - isCacheSessionInitialized: false, + isCacheSessionInitialized: false, /** * Cache session object. */ - cacheSession: null, + cacheSession: null, /** * Initializes our cache session / cache storage session. */ - initializeCacheSession: function(request) { - try { - const cacheService = Services.cache2; - if (cacheService) { - let loadContext = NetworkHelper.getRequestLoadContext(request); - if (!loadContext) { // Get default load context if we can't fetch. - loadContext = Services.loadContextInfo.default; - } - this.cacheSession = - cacheService.diskCacheStorage(loadContext, false); - this.isCacheSessionInitialized = true; - } - } catch (e) { - this.isCacheSessionInitialized = false; - } - }, + initializeCacheSession: function(request) { + try { + const cacheService = Services.cache2; + if (cacheService) { + let loadContext = NetworkHelper.getRequestLoadContext(request); + if (!loadContext) { + // Get default load context if we can't fetch. + loadContext = Services.loadContextInfo.default; + } + this.cacheSession = cacheService.diskCacheStorage(loadContext, false); + this.isCacheSessionInitialized = true; + } + } catch (e) { + this.isCacheSessionInitialized = false; + } + }, /** * Parses a cache descriptor returned from the backend into a @@ -51,32 +54,32 @@ * * @param Object descriptor The descriptor from the backend. */ - parseCacheDescriptor: function(descriptor) { - const descriptorObj = {}; - try { - if (descriptor.storageDataSize) { - descriptorObj.dataSize = descriptor.storageDataSize; - } - } catch (e) { + parseCacheDescriptor: function(descriptor) { + const descriptorObj = {}; + try { + if (descriptor.storageDataSize) { + descriptorObj.dataSize = descriptor.storageDataSize; + } + } catch (e) { // We just need to handle this in case it's a js file of 0B. - } - if (descriptor.expirationTime) { - descriptorObj.expires = descriptor.expirationTime; - } - if (descriptor.fetchCount) { - descriptorObj.fetchCount = descriptor.fetchCount; - } - if (descriptor.lastFetched) { - descriptorObj.lastFetched = descriptor.lastFetched; - } - if (descriptor.lastModified) { - descriptorObj.lastModified = descriptor.lastModified; - } - if (descriptor.deviceID) { - descriptorObj.device = descriptor.deviceID; - } - return descriptorObj; - }, + } + if (descriptor.expirationTime) { + descriptorObj.expires = descriptor.expirationTime; + } + if (descriptor.fetchCount) { + descriptorObj.fetchCount = descriptor.fetchCount; + } + if (descriptor.lastFetched) { + descriptorObj.lastFetched = descriptor.lastFetched; + } + if (descriptor.lastModified) { + descriptorObj.lastModified = descriptor.lastModified; + } + if (descriptor.deviceID) { + descriptorObj.device = descriptor.deviceID; + } + return descriptorObj; + }, /** * Does the fetch for the cache descriptor from the session. @@ -86,32 +89,32 @@ * @param Function onCacheDescriptorAvailable * callback function. */ - getCacheEntry: function(request, onCacheDescriptorAvailable) { - if (!this.isCacheSessionInitialized) { - this.initializeCacheSession(request); - } - if (this.cacheSession) { - const uri = NetworkHelper.nsIURL(request.URI.spec); - this.cacheSession.asyncOpenURI( - uri, + getCacheEntry: function(request, onCacheDescriptorAvailable) { + if (!this.isCacheSessionInitialized) { + this.initializeCacheSession(request); + } + if (this.cacheSession) { + const uri = NetworkHelper.nsIURL(request.URI.spec); + this.cacheSession.asyncOpenURI( + uri, "", Ci.nsICacheStorage.OPEN_SECRETLY, - { - onCacheEntryCheck: (entry, appcache) => { - return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; - }, - onCacheEntryAvailable: (descriptor, isnew, appcache, status) => { - if (descriptor) { - const descriptorObj = this.parseCacheDescriptor(descriptor); - onCacheDescriptorAvailable(descriptorObj); - } else { - onCacheDescriptorAvailable(null); - } - }, - } - ); - } else { - onCacheDescriptorAvailable(null); - } - }, - }; + { + onCacheEntryCheck: (entry, appcache) => { + return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; + }, + onCacheEntryAvailable: (descriptor, isnew, appcache, status) => { + if (descriptor) { + const descriptorObj = this.parseCacheDescriptor(descriptor); + onCacheDescriptorAvailable(descriptorObj); + } else { + onCacheDescriptorAvailable(null); + } + }, + } + ); + } else { + onCacheDescriptorAvailable(null); + } + }, +}; diff --git a/devtools/shared/platform/clipboard.js b/devtools/shared/platform/clipboard.js index 9e882e018ebe..d9d471c504c5 100644 --- a/devtools/shared/platform/clipboard.js +++ b/devtools/shared/platform/clipboard.js @@ -6,10 +6,11 @@ "use strict"; -const {Cc, Ci} = require("chrome"); +const { Cc, Ci } = require("chrome"); const Services = require("Services"); -const clipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"] - .getService(Ci.nsIClipboardHelper); +const clipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"].getService( + Ci.nsIClipboardHelper +); function copyString(string) { clipboardHelper.copyString(string); @@ -23,22 +24,22 @@ function copyString(string) { function getText() { const flavor = "text/unicode"; - const xferable = Cc["@mozilla.org/widget/transferable;1"] - .createInstance(Ci.nsITransferable); + const xferable = Cc["@mozilla.org/widget/transferable;1"].createInstance( + Ci.nsITransferable + ); if (!xferable) { - throw new Error("Couldn't get the clipboard data due to an internal error " + - "(couldn't create a Transferable object)."); + throw new Error( + "Couldn't get the clipboard data due to an internal error " + + "(couldn't create a Transferable object)." + ); } xferable.init(null); xferable.addDataFlavor(flavor); // Get the data into our transferable. - Services.clipboard.getData( - xferable, - Services.clipboard.kGlobalClipboard - ); + Services.clipboard.getData(xferable, Services.clipboard.kGlobalClipboard); const data = {}; try { diff --git a/devtools/shared/platform/stack.js b/devtools/shared/platform/stack.js index 3b46c056232a..245ff507eb4f 100644 --- a/devtools/shared/platform/stack.js +++ b/devtools/shared/platform/stack.js @@ -39,7 +39,7 @@ function getNthPathExcluding(n, substr) { if (!stack[n]) { n = 0; } - return (stack[n] || ""); + return stack[n] || ""; } /** diff --git a/devtools/shared/protocol/Actor.js b/devtools/shared/protocol/Actor.js index cb8c1277829a..83b134a42c3a 100644 --- a/devtools/shared/protocol/Actor.js +++ b/devtools/shared/protocol/Actor.js @@ -55,8 +55,10 @@ class Actor extends Pool { _sendEvent(name, request, ...args) { if (!this.actorID) { - console.error(`Tried to send a '${name}' event on an already destroyed actor` + - ` '${this.typeName}'`); + console.error( + `Tried to send a '${name}' event on an already destroyed actor` + + ` '${this.typeName}'` + ); return; } let packet; @@ -86,8 +88,10 @@ class Actor extends Pool { } writeError(error, typeName, method) { - console.error(`Error while calling actor '${typeName}'s method '${method}'`, - error.message); + console.error( + `Error while calling actor '${typeName}'s method '${method}'`, + error.message + ); if (error.stack) { console.error(error.stack); } diff --git a/devtools/shared/protocol/Pool.js b/devtools/shared/protocol/Pool.js index 6ea34f245698..eac6d8eec9c7 100644 --- a/devtools/shared/protocol/Pool.js +++ b/devtools/shared/protocol/Pool.js @@ -119,7 +119,7 @@ class Pool extends EventEmitter { } // Generator that yields each non-self child of the pool. - * poolChildren() { + *poolChildren() { if (!this.__poolMap) { return; } diff --git a/devtools/shared/protocol/lazy-pool.js b/devtools/shared/protocol/lazy-pool.js index 20742f716e7d..9874d458d87c 100644 --- a/devtools/shared/protocol/lazy-pool.js +++ b/devtools/shared/protocol/lazy-pool.js @@ -163,7 +163,9 @@ LazyActor.prototype = { // Fetch the actor constructor } catch (e) { throw new Error( - `Unable to load actor module '${options.id}'\n${e.message}\n${e.stack}\n` + `Unable to load actor module '${options.id}'\n${e.message}\n${ + e.stack + }\n` ); } }, @@ -183,7 +185,9 @@ LazyActor.prototype = { const constructor = module[options.constructorName]; if (!constructor) { throw new Error( - `Unable to find actor constructor named '${this.name}'. (Is it exported?)` + `Unable to find actor constructor named '${ + this.name + }'. (Is it exported?)` ); } return constructor; diff --git a/devtools/shared/qrcode/tests/unit/test_encode.js b/devtools/shared/qrcode/tests/unit/test_encode.js index 39814e6f80b4..b8430130dccc 100644 --- a/devtools/shared/qrcode/tests/unit/test_encode.js +++ b/devtools/shared/qrcode/tests/unit/test_encode.js @@ -12,15 +12,17 @@ const QR = require("devtools/shared/qrcode/index"); function run_test() { const imgData = QR.encodeToDataURI("HELLO", "L"); - Assert.equal(imgData.src, - "data:image/gif;base64,R0lGODdhOgA6AIAAAAAAAP///ywAAAAAOgA6AAAC" + - "/4yPqcvtD6OctNqLs968+w+G4gKU5nkaKKquLuW+QVy2tAkDTj3rfQts8CRDko" + - "+HPPoYRUgy9YsyldDm44mLWhHYZM6W7WaDqyCRGkZDySxpRGw2sqvLt1q5w/fo" + - "XyE6vnUQOJUHBlinMGh046V1F5PDqNcoqcgBOWKBKbK2N+aY+Ih49VkmqMcl2l" + - "dkhZUK1umE6jZXJ2ZJaujZaRqH4bpb2uZrJxvIt4Ebe9qoYYrJOsw8apz2bCut" + - "m9kqDcw52uuImyr5Oh1KXH1jrn2anuunywtODU/o2c6teceW39ZcLFg/fNMo1b" + - "t3jVw2dwTPwJq1KYG3gAklCgu37yGxeScYKyiCc+7DR34hPVQiuQ7UhJMagyEb" + - "lymmzJk0a9q8iTOnzp0NCgAAOw=="); + Assert.equal( + imgData.src, + "data:image/gif;base64,R0lGODdhOgA6AIAAAAAAAP///ywAAAAAOgA6AAAC" + + "/4yPqcvtD6OctNqLs968+w+G4gKU5nkaKKquLuW+QVy2tAkDTj3rfQts8CRDko" + + "+HPPoYRUgy9YsyldDm44mLWhHYZM6W7WaDqyCRGkZDySxpRGw2sqvLt1q5w/fo" + + "XyE6vnUQOJUHBlinMGh046V1F5PDqNcoqcgBOWKBKbK2N+aY+Ih49VkmqMcl2l" + + "dkhZUK1umE6jZXJ2ZJaujZaRqH4bpb2uZrJxvIt4Ebe9qoYYrJOsw8apz2bCut" + + "m9kqDcw52uuImyr5Oh1KXH1jrn2anuunywtODU/o2c6teceW39ZcLFg/fNMo1b" + + "t3jVw2dwTPwJq1KYG3gAklCgu37yGxeScYKyiCc+7DR34hPVQiuQ7UhJMagyEb" + + "lymmzJk0a9q8iTOnzp0NCgAAOw==" + ); Assert.equal(imgData.width, 58); Assert.equal(imgData.height, 58); } diff --git a/devtools/shared/screenshot/capture.js b/devtools/shared/screenshot/capture.js index 133eb2f16385..ee064d839a86 100644 --- a/devtools/shared/screenshot/capture.js +++ b/devtools/shared/screenshot/capture.js @@ -19,7 +19,7 @@ loader.lazyRequireGetter(this, "getRect", "devtools/shared/layout/utils", true); */ function simulateCameraFlash(document) { const window = document.defaultView; - const frames = Cu.cloneInto({ opacity: [ 0, 1 ] }, window); + const frames = Cu.cloneInto({ opacity: [0, 1] }, window); document.documentElement.animate(frames, CONTAINER_FLASHING_DURATION); } @@ -88,7 +88,10 @@ function createScreenshotDataURL(document, args) { height -= scrollbarHeight.value; } - const canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas"); + const canvas = document.createElementNS( + "http://www.w3.org/1999/xhtml", + "canvas" + ); const ctx = canvas.getContext("2d"); const ratio = args.dpr ? args.dpr : window.devicePixelRatio; canvas.width = width * ratio; @@ -126,20 +129,24 @@ function getFilename(defaultName) { } const date = new Date(); - let dateString = date.getFullYear() + "-" + (date.getMonth() + 1) + - "-" + date.getDate(); - dateString = dateString.split("-").map(function(part) { - if (part.length == 1) { - part = "0" + part; - } - return part; - }).join("-"); + let dateString = + date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(); + dateString = dateString + .split("-") + .map(function(part) { + if (part.length == 1) { + part = "0" + part; + } + return part; + }) + .join("-"); - const timeString = date.toTimeString().replace(/:/g, ".").split(" ")[0]; - return L10N.getFormatStr( - "screenshotGeneratedFilename", - dateString, - timeString - ) + ".png"; + const timeString = date + .toTimeString() + .replace(/:/g, ".") + .split(" ")[0]; + return ( + L10N.getFormatStr("screenshotGeneratedFilename", dateString, timeString) + + ".png" + ); } - diff --git a/devtools/shared/screenshot/save.js b/devtools/shared/screenshot/save.js index 8483891d7020..8a7b4ff9b4b4 100644 --- a/devtools/shared/screenshot/save.js +++ b/devtools/shared/screenshot/save.js @@ -72,13 +72,15 @@ const screenshotCommandParams = [ */ function formatHelpField(param) { const padding = " ".repeat(5); - return Object.entries(param).map(([key, value]) => { - if (key === "name") { - const name = `${padding}--${value}`; - return name; - } - return `${padding.repeat(2)}${key}: ${value}`; - }).join("\n"); + return Object.entries(param) + .map(([key, value]) => { + if (key === "name") { + const name = `${padding}--${value}`; + return name; + } + return `${padding.repeat(2)}${key}: ${value}`; + }) + .join("\n"); } /** @@ -131,7 +133,9 @@ function saveScreenshot(window, args = {}, value) { */ function simulateCameraShutter(window) { if (Services.prefs.getBoolPref("devtools.screenshot.audio.enabled")) { - const audioCamera = new window.Audio("resource://devtools/client/themes/audio/shutter.wav"); + const audioCamera = new window.Audio( + "resource://devtools/client/themes/audio/shutter.wav" + ); audioCamera.play(); } } @@ -149,8 +153,7 @@ function simulateCameraShutter(window) { * Response messages from processing the screenshot. */ async function save(args, image) { - const fileNeeded = args.filename || - !args.clipboard || args.file; + const fileNeeded = args.filename || !args.clipboard || args.file; const results = []; if (args.clipboard) { @@ -177,21 +180,31 @@ async function save(args, image) { */ function saveToClipboard(base64URI) { try { - const imageTools = Cc["@mozilla.org/image/tools;1"] - .getService(Ci.imgITools); + const imageTools = Cc["@mozilla.org/image/tools;1"].getService( + Ci.imgITools + ); const base64Data = base64URI.replace("data:image/png;base64,", ""); const image = atob(base64Data); - const img = imageTools.decodeImageFromBuffer(image, image.length, "image/png"); + const img = imageTools.decodeImageFromBuffer( + image, + image.length, + "image/png" + ); - const transferable = Cc["@mozilla.org/widget/transferable;1"] - .createInstance(Ci.nsITransferable); + const transferable = Cc[ + "@mozilla.org/widget/transferable;1" + ].createInstance(Ci.nsITransferable); transferable.init(null); transferable.addDataFlavor("image/png"); transferable.setTransferData("image/png", img, -1); - Services.clipboard.setData(transferable, null, Services.clipboard.kGlobalClipboard); + Services.clipboard.setData( + transferable, + null, + Services.clipboard.kGlobalClipboard + ); return L10N.getStr("screenshotCopied"); } catch (ex) { console.error(ex); diff --git a/devtools/shared/security/auth.js b/devtools/shared/security/auth.js index 6c175b155569..51422d2e3338 100644 --- a/devtools/shared/security/auth.js +++ b/devtools/shared/security/auth.js @@ -11,12 +11,9 @@ var Services = require("Services"); var defer = require("devtools/shared/defer"); var DevToolsUtils = require("devtools/shared/DevToolsUtils"); var { dumpn, dumpv } = DevToolsUtils; -loader.lazyRequireGetter(this, "prompt", - "devtools/shared/security/prompt"); -loader.lazyRequireGetter(this, "cert", - "devtools/shared/security/cert"); -loader.lazyRequireGetter(this, "asyncStorage", - "devtools/shared/async-storage"); +loader.lazyRequireGetter(this, "prompt", "devtools/shared/security/prompt"); +loader.lazyRequireGetter(this, "cert", "devtools/shared/security/cert"); +loader.lazyRequireGetter(this, "asyncStorage", "devtools/shared/async-storage"); /** * A simple enum-like object with keys mirrored to values. @@ -36,8 +33,7 @@ function createEnum(obj) { * centralize the common actions available, while still allowing embedders to * present their UI in whatever way they choose. */ -var AuthenticationResult = exports.AuthenticationResult = createEnum({ - +var AuthenticationResult = (exports.AuthenticationResult = createEnum({ /** * Close all listening sockets, and disable them from opening again. */ @@ -64,8 +60,7 @@ var AuthenticationResult = exports.AuthenticationResult = createEnum({ * identify the client in the future, such as the cert used during OOB_CERT. */ ALLOW_PERSIST: null, - -}); +})); /** * An |Authenticator| implements an authentication mechanism via various hooks @@ -86,13 +81,12 @@ var Authenticators = {}; * no cryptographic properties at work here, so it is up to the user to be sure * that the client can be trusted. */ -var Prompt = Authenticators.Prompt = {}; +var Prompt = (Authenticators.Prompt = {}); Prompt.mode = "PROMPT"; Prompt.Client = function() {}; Prompt.Client.prototype = { - mode: Prompt.mode, /** @@ -140,12 +134,10 @@ Prompt.Client.prototype = { * @return A promise can be used if there is async behavior. */ authenticate() {}, - }; Prompt.Server = function() {}; Prompt.Server.prototype = { - mode: Prompt.mode, /** @@ -236,7 +228,6 @@ Prompt.Server.prototype = { * A promise that will be resolved to the above is also allowed. */ allowConnection: prompt.Server.defaultAllowConnection, - }; /** @@ -257,13 +248,12 @@ Prompt.Server.prototype = { * * See docs/wifi.md for details of the authentication design. */ -var OOBCert = Authenticators.OOBCert = {}; +var OOBCert = (Authenticators.OOBCert = {}); OOBCert.mode = "OOB_CERT"; OOBCert.Client = function() {}; OOBCert.Client.prototype = { - mode: OOBCert.mode, /** @@ -300,9 +290,9 @@ OOBCert.Client.prototype = { // Client verifies that Server's cert matches hash(ServerCert) from the // advertisement dumpv("Validate server cert hash"); - const serverCert = socket.securityInfo - .QueryInterface(Ci.nsITransportSecurityInfo) - .serverCert; + const serverCert = socket.securityInfo.QueryInterface( + Ci.nsITransportSecurityInfo + ).serverCert; const advertisedCert = cert; if (serverCert.sha256Fingerprint != advertisedCert.sha256) { dumpn("Server cert hash doesn't match advertisement"); @@ -345,7 +335,7 @@ OOBCert.Client.prototype = { }; transport.hooks = { - onPacket: async (packet) => { + onPacket: async packet => { closeDialog(); const { authResult } = packet; switch (authResult) { @@ -411,8 +401,9 @@ OOBCert.Client.prototype = { _createRandom() { // 16 bytes / 128 bits const length = 16; - const rng = Cc["@mozilla.org/security/random-generator;1"] - .createInstance(Ci.nsIRandomGenerator); + const rng = Cc["@mozilla.org/security/random-generator;1"].createInstance( + Ci.nsIRandomGenerator + ); const bytes = rng.generateRandomBytes(length); return bytes.map(byte => byte.toString(16)).join(""); }, @@ -436,12 +427,10 @@ OOBCert.Client.prototype = { * * close: Function to hide the notification */ sendOOB: prompt.Client.defaultSendOOB, - }; OOBCert.Server = function() {}; OOBCert.Server.prototype = { - mode: OOBCert.mode, /** @@ -638,7 +627,6 @@ OOBCert.Server.prototype = { * A promise that will be resolved to the above is also allowed. */ receiveOOB: prompt.Server.defaultReceiveOOB, - }; exports.Authenticators = { diff --git a/devtools/shared/security/cert.js b/devtools/shared/security/cert.js index f6fca8db4629..314921ebc218 100644 --- a/devtools/shared/security/cert.js +++ b/devtools/shared/security/cert.js @@ -12,14 +12,14 @@ var DevToolsUtils = require("devtools/shared/DevToolsUtils"); DevToolsUtils.defineLazyGetter(this, "localCertService", () => { // Ensure PSM is initialized to support TLS sockets Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports); - return Cc["@mozilla.org/security/local-cert-service;1"] - .getService(Ci.nsILocalCertService); + return Cc["@mozilla.org/security/local-cert-service;1"].getService( + Ci.nsILocalCertService + ); }); const localCertName = "devtools"; exports.local = { - /** * Get or create a new self-signed X.509 cert to represent this device for * DevTools purposes over a secure transport, like TLS. @@ -62,5 +62,4 @@ exports.local = { }); return deferred.promise; }, - }; diff --git a/devtools/shared/security/prompt.js b/devtools/shared/security/prompt.js index 5c79e85a7d92..b6b2be99f908 100644 --- a/devtools/shared/security/prompt.js +++ b/devtools/shared/security/prompt.js @@ -1,21 +1,27 @@ /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ /* vim: set ft=javascript ts=2 et sw=2 tw=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/. */ + * 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"; var Services = require("Services"); var DevToolsUtils = require("devtools/shared/DevToolsUtils"); -loader.lazyRequireGetter(this, "AuthenticationResult", - "devtools/shared/security/auth", true); +loader.lazyRequireGetter( + this, + "AuthenticationResult", + "devtools/shared/security/auth", + true +); -const {LocalizationHelper} = require("devtools/shared/l10n"); -const L10N = new LocalizationHelper("devtools/shared/locales/debugger.properties"); +const { LocalizationHelper } = require("devtools/shared/l10n"); +const L10N = new LocalizationHelper( + "devtools/shared/locales/debugger.properties" +); -var Client = exports.Client = {}; -var Server = exports.Server = {}; +var Client = (exports.Client = {}); +var Server = (exports.Server = {}); /** * During OOB_CERT authentication, a notification dialog like this is used to @@ -60,14 +66,20 @@ Client.defaultSendOOB = ({ authResult, oob }) => { const windowListener = { onOpenWindow(xulWindow) { const win = xulWindow.docShell.domWindow; - win.addEventListener("load", function() { - if (win.document.documentElement.getAttribute("id") != "commonDialog") { - return; - } - // Found the window - promptWindow = win; - Services.wm.removeListener(windowListener); - }, {once: true}); + win.addEventListener( + "load", + function() { + if ( + win.document.documentElement.getAttribute("id") != "commonDialog" + ) { + return; + } + // Found the window + promptWindow = win; + Services.wm.removeListener(windowListener); + }, + { once: true } + ); }, onCloseWindow() {}, }; @@ -75,8 +87,9 @@ Client.defaultSendOOB = ({ authResult, oob }) => { // nsIPrompt is typically a blocking API, so |executeSoon| to get around this DevToolsUtils.executeSoon(() => { - prompt.confirmEx(null, title, msg, flags, null, null, null, null, - { value: false }); + prompt.confirmEx(null, title, msg, flags, null, null, null, null, { + value: false, + }); }); return { @@ -118,21 +131,35 @@ Server.defaultAllowConnection = ({ client, server }) => { const title = L10N.getStr("remoteIncomingPromptTitle"); const header = L10N.getStr("remoteIncomingPromptHeader"); const clientEndpoint = `${client.host}:${client.port}`; - const clientMsg = - L10N.getFormatStr("remoteIncomingPromptClientEndpoint", clientEndpoint); + const clientMsg = L10N.getFormatStr( + "remoteIncomingPromptClientEndpoint", + clientEndpoint + ); const serverEndpoint = `${server.host}:${server.port}`; - const serverMsg = - L10N.getFormatStr("remoteIncomingPromptServerEndpoint", serverEndpoint); + const serverMsg = L10N.getFormatStr( + "remoteIncomingPromptServerEndpoint", + serverEndpoint + ); const footer = L10N.getStr("remoteIncomingPromptFooter"); const msg = `${header}\n\n${clientMsg}\n${serverMsg}\n\n${footer}`; const disableButton = L10N.getStr("remoteIncomingPromptDisable"); const prompt = Services.prompt; - const flags = prompt.BUTTON_POS_0 * prompt.BUTTON_TITLE_OK + - prompt.BUTTON_POS_1 * prompt.BUTTON_TITLE_CANCEL + - prompt.BUTTON_POS_2 * prompt.BUTTON_TITLE_IS_STRING + - prompt.BUTTON_POS_1_DEFAULT; - const result = prompt.confirmEx(null, title, msg, flags, null, null, - disableButton, null, { value: false }); + const flags = + prompt.BUTTON_POS_0 * prompt.BUTTON_TITLE_OK + + prompt.BUTTON_POS_1 * prompt.BUTTON_TITLE_CANCEL + + prompt.BUTTON_POS_2 * prompt.BUTTON_TITLE_IS_STRING + + prompt.BUTTON_POS_1_DEFAULT; + const result = prompt.confirmEx( + null, + title, + msg, + flags, + null, + null, + disableButton, + null, + { value: false } + ); if (result === 0) { return AuthenticationResult.ALLOW; } @@ -169,7 +196,10 @@ Server.defaultReceiveOOB = () => { // Re-create original object from token input = input.value.trim(); let sha256 = input.substring(0, 64); - sha256 = sha256.replace(/\w{2}/g, "$&:").slice(0, -1).toUpperCase(); + sha256 = sha256 + .replace(/\w{2}/g, "$&:") + .slice(0, -1) + .toUpperCase(); const k = input.substring(64); return { sha256, k }; }; diff --git a/devtools/shared/security/socket.js b/devtools/shared/security/socket.js index d274e54ffabd..fe8766cb9a03 100644 --- a/devtools/shared/security/socket.js +++ b/devtools/shared/security/socket.js @@ -16,20 +16,40 @@ var promise = require("promise"); var defer = require("devtools/shared/defer"); var DevToolsUtils = require("devtools/shared/DevToolsUtils"); var { dumpn, dumpv } = DevToolsUtils; -loader.lazyRequireGetter(this, "WebSocketServer", - "devtools/server/socket/websocket-server"); -loader.lazyRequireGetter(this, "DebuggerTransport", - "devtools/shared/transport/transport", true); -loader.lazyRequireGetter(this, "WebSocketDebuggerTransport", - "devtools/shared/transport/websocket-transport"); -loader.lazyRequireGetter(this, "discovery", - "devtools/shared/discovery/discovery"); -loader.lazyRequireGetter(this, "cert", - "devtools/shared/security/cert"); -loader.lazyRequireGetter(this, "Authenticators", - "devtools/shared/security/auth", true); -loader.lazyRequireGetter(this, "AuthenticationResult", - "devtools/shared/security/auth", true); +loader.lazyRequireGetter( + this, + "WebSocketServer", + "devtools/server/socket/websocket-server" +); +loader.lazyRequireGetter( + this, + "DebuggerTransport", + "devtools/shared/transport/transport", + true +); +loader.lazyRequireGetter( + this, + "WebSocketDebuggerTransport", + "devtools/shared/transport/websocket-transport" +); +loader.lazyRequireGetter( + this, + "discovery", + "devtools/shared/discovery/discovery" +); +loader.lazyRequireGetter(this, "cert", "devtools/shared/security/cert"); +loader.lazyRequireGetter( + this, + "Authenticators", + "devtools/shared/security/auth", + true +); +loader.lazyRequireGetter( + this, + "AuthenticationResult", + "devtools/shared/security/auth", + true +); loader.lazyRequireGetter(this, "EventEmitter", "devtools/shared/event-emitter"); DevToolsUtils.defineLazyGetter(this, "nsFile", () => { @@ -37,18 +57,21 @@ DevToolsUtils.defineLazyGetter(this, "nsFile", () => { }); DevToolsUtils.defineLazyGetter(this, "socketTransportService", () => { - return Cc["@mozilla.org/network/socket-transport-service;1"] - .getService(Ci.nsISocketTransportService); + return Cc["@mozilla.org/network/socket-transport-service;1"].getService( + Ci.nsISocketTransportService + ); }); DevToolsUtils.defineLazyGetter(this, "certOverrideService", () => { - return Cc["@mozilla.org/security/certoverride;1"] - .getService(Ci.nsICertOverrideService); + return Cc["@mozilla.org/security/certoverride;1"].getService( + Ci.nsICertOverrideService + ); }); DevToolsUtils.defineLazyGetter(this, "nssErrorsService", () => { - return Cc["@mozilla.org/nss_errors_service;1"] - .getService(Ci.nsINSSErrorsService); + return Cc["@mozilla.org/nss_errors_service;1"].getService( + Ci.nsINSSErrorsService + ); }); var DebuggerSocket = {}; @@ -75,7 +98,7 @@ var DebuggerSocket = {}; DebuggerSocket.connect = async function(settings) { // Default to PROMPT |Authenticator| instance if not supplied if (!settings.authenticator) { - settings.authenticator = new (Authenticators.get().Client)(); + settings.authenticator = new (Authenticators.get()).Client(); } _validateSettings(settings); // eslint-disable-next-line no-shadow @@ -211,13 +234,15 @@ var _attemptTransport = async function(settings) { // The |Authenticator| examines the connection as well and may determine it // should be dropped. - alive = alive && authenticator.validateConnection({ - host: settings.host, - port: settings.port, - encryption: settings.encryption, - cert: settings.cert, - socket: s, - }); + alive = + alive && + authenticator.validateConnection({ + host: settings.host, + port: settings.port, + encryption: settings.encryption, + cert: settings.cert, + socket: s, + }); let transport; if (alive) { @@ -274,24 +299,28 @@ var _attemptConnect = async function({ host, port, encryption }) { // specify a client cert programmatically, we need to access the transport's // nsISSLSocketControl interface, which is not accessible until the transport // has connected. - s.setEventSink({ - onTransportStatus(transport, status) { - if (status != Ci.nsISocketTransport.STATUS_CONNECTING_TO) { - return; - } - if (encryption) { - const sslSocketControl = - transport.securityInfo.QueryInterface(Ci.nsISSLSocketControl); - sslSocketControl.clientCert = clientCert; - } - try { - input = s.openInputStream(0, 0, 0); - } catch (e) { - deferred.reject(e); - } - deferred.resolve({ s, input, output }); + s.setEventSink( + { + onTransportStatus(transport, status) { + if (status != Ci.nsISocketTransport.STATUS_CONNECTING_TO) { + return; + } + if (encryption) { + const sslSocketControl = transport.securityInfo.QueryInterface( + Ci.nsISSLSocketControl + ); + sslSocketControl.clientCert = clientCert; + } + try { + input = s.openInputStream(0, 0, 0); + } catch (e) { + deferred.reject(e); + } + deferred.resolve({ s, input, output }); + }, }, - }, Services.tm.currentThread); + Services.tm.currentThread + ); // openOutputStream may throw NS_ERROR_NOT_INITIALIZED if we hit some race // where the nsISocketTransport gets shutdown in between its instantiation and @@ -322,26 +351,31 @@ var _attemptConnect = async function({ host, port, encryption }) { */ function _isInputAlive(input) { const deferred = defer(); - input.asyncWait({ - onInputStreamReady(stream) { - try { - stream.available(); - deferred.resolve({ alive: true }); - } catch (e) { + input.asyncWait( + { + onInputStreamReady(stream) { try { - // getErrorClass may throw if you pass a non-NSS error - const errorClass = nssErrorsService.getErrorClass(e.result); - if (errorClass === Ci.nsINSSErrorsService.ERROR_CLASS_BAD_CERT) { - deferred.resolve({ certError: true }); - } else { + stream.available(); + deferred.resolve({ alive: true }); + } catch (e) { + try { + // getErrorClass may throw if you pass a non-NSS error + const errorClass = nssErrorsService.getErrorClass(e.result); + if (errorClass === Ci.nsINSSErrorsService.ERROR_CLASS_BAD_CERT) { + deferred.resolve({ certError: true }); + } else { + deferred.reject(e); + } + } catch (nssErr) { deferred.reject(e); } - } catch (nssErr) { - deferred.reject(e); } - } + }, }, - }, 0, 0, Services.tm.currentThread); + 0, + 0, + Services.tm.currentThread + ); return deferred.promise; } @@ -353,11 +387,17 @@ function _isInputAlive(input) { function _storeCertOverride(s, host, port) { // eslint-disable-next-line no-shadow const cert = s.securityInfo.QueryInterface(Ci.nsITransportSecurityInfo) - .serverCert; - const overrideBits = Ci.nsICertOverrideService.ERROR_UNTRUSTED | - Ci.nsICertOverrideService.ERROR_MISMATCH; - certOverrideService.rememberValidityOverride(host, port, cert, overrideBits, - true /* temporary */); + .serverCert; + const overrideBits = + Ci.nsICertOverrideService.ERROR_UNTRUSTED | + Ci.nsICertOverrideService.ERROR_MISMATCH; + certOverrideService.rememberValidityOverride( + host, + port, + cert, + overrideBits, + true /* temporary */ + ); } /** @@ -396,7 +436,8 @@ function SocketListener(debuggerServer, socketOptions) { // Set socket options with default value this._socketOptions = { - authenticator: socketOptions.authenticator || new (Authenticators.get().Server)(), + authenticator: + socketOptions.authenticator || new (Authenticators.get()).Server(), discoverable: !!socketOptions.discoverable, encryption: !!socketOptions.encryption, portOrPath: socketOptions.portOrPath || null, @@ -476,13 +517,19 @@ SocketListener.prototype = { await self._setAdditionalSocketOptions(); self._socket.asyncListen(self); dumpn("Socket listening on: " + (self.port || self.portOrPath)); - })().then(() => { - this._advertise(); - }).catch(e => { - dumpn("Could not start debugging listener on '" + this.portOrPath + - "': " + e); - this.close(); - }); + })() + .then(() => { + this._advertise(); + }) + .catch(e => { + dumpn( + "Could not start debugging listener on '" + + this.portOrPath + + "': " + + e + ); + this.close(); + }); }, _advertise: function() { @@ -502,11 +549,13 @@ SocketListener.prototype = { _createSocketInstance: function() { if (this.encryption) { - return Cc["@mozilla.org/network/tls-server-socket;1"] - .createInstance(Ci.nsITLSServerSocket); + return Cc["@mozilla.org/network/tls-server-socket;1"].createInstance( + Ci.nsITLSServerSocket + ); } - return Cc["@mozilla.org/network/server-socket;1"] - .createInstance(Ci.nsIServerSocket); + return Cc["@mozilla.org/network/server-socket;1"].createInstance( + Ci.nsIServerSocket + ); }, async _setAdditionalSocketOptions() { @@ -578,16 +627,18 @@ SocketListener.prototype = { // nsIServerSocketListener implementation - onSocketAccepted: - DevToolsUtils.makeInfallible(function(socket, socketTransport) { + onSocketAccepted: DevToolsUtils.makeInfallible(function( + socket, + socketTransport + ) { const connection = new ServerSocketConnection(this, socketTransport); connection.once("allowed", this.onAllowedConnection.bind(this)); - }, "SocketListener.onSocketAccepted"), + }, + "SocketListener.onSocketAccepted"), onStopListening: function(socket, status) { dumpn("onStopListening, status: " + status); }, - }; // Client must complete TLS handshake within this window (ms) @@ -609,7 +660,6 @@ function ServerSocketConnection(listener, socketTransport) { } ServerSocketConnection.prototype = { - get authentication() { return this._listener.authenticator.mode; }, @@ -684,7 +734,11 @@ ServerSocketConnection.prototype = { const output = this._socketTransport.openOutputStream(0, 0, 0); if (this._listener.webSocket) { - const socket = await WebSocketServer.accept(this._socketTransport, input, output); + const socket = await WebSocketServer.accept( + this._socketTransport, + input, + output + ); this._transport = new WebSocketDebuggerTransport(socket); } else { this._transport = new DebuggerTransport(input, output); @@ -708,8 +762,9 @@ ServerSocketConnection.prototype = { if (!this._socketTransport || !this._socketTransport.securityInfo) { return; } - const connectionInfo = this._socketTransport.securityInfo - .QueryInterface(Ci.nsITLSServerConnectionInfo); + const connectionInfo = this._socketTransport.securityInfo.QueryInterface( + Ci.nsITLSServerConnectionInfo + ); connectionInfo.setSecurityObserver(observer); }, @@ -725,8 +780,10 @@ ServerSocketConnection.prototype = { return; } this._setSecurityObserver(this); - this._handshakeTimeout = setTimeout(this._onHandshakeTimeout.bind(this), - HANDSHAKE_TIMEOUT); + this._handshakeTimeout = setTimeout( + this._onHandshakeTimeout.bind(this), + HANDSHAKE_TIMEOUT + ); }, _awaitTLSHandshake() { @@ -795,8 +852,9 @@ ServerSocketConnection.prototype = { break; } } - dumpn("Debugging connection denied on " + this.address + - " (" + errorName + ")"); + dumpn( + "Debugging connection denied on " + this.address + " (" + errorName + ")" + ); if (this._transport) { this._transport.hooks = null; this._transport.close(result); @@ -823,7 +881,6 @@ ServerSocketConnection.prototype = { this._transport = null; this._clientCert = null; }, - }; exports.DebuggerSocket = DebuggerSocket; diff --git a/devtools/shared/security/tests/unit/head_dbg.js b/devtools/shared/security/tests/unit/head_dbg.js index 8a11b07f5c0d..3c467b1eeb78 100644 --- a/devtools/shared/security/tests/unit/head_dbg.js +++ b/devtools/shared/security/tests/unit/head_dbg.js @@ -5,8 +5,9 @@ /* exported defer, DebuggerClient, initTestDebuggerServer */ -const { loader, require } = - ChromeUtils.import("resource://devtools/shared/Loader.jsm"); +const { loader, require } = ChromeUtils.import( + "resource://devtools/shared/Loader.jsm" +); const defer = require("devtools/shared/defer"); const Services = require("Services"); const xpcInspector = require("xpcInspector"); @@ -14,7 +15,12 @@ const { DebuggerServer } = require("devtools/server/main"); const { DebuggerClient } = require("devtools/shared/client/debugger-client"); // We need to require lazily since will be crashed if we load SocketListener too early // in xpc shell test due to SocketListener loads PSM module. -loader.lazyRequireGetter(this, "SocketListener", "devtools/shared/security/socket", true); +loader.lazyRequireGetter( + this, + "SocketListener", + "devtools/shared/security/socket", + true +); // We do not want to log packets by default, because in some tests, // we can be sending large amounts of data. The test harness has @@ -53,9 +59,16 @@ var listener = { let string; try { message.QueryInterface(Ci.nsIScriptError); - dump(message.sourceName + ":" + message.lineNumber + ": " + - scriptErrorFlagsToKind(message.flags) + ": " + - message.errorMessage + "\n"); + dump( + message.sourceName + + ":" + + message.lineNumber + + ": " + + scriptErrorFlagsToKind(message.flags) + + ": " + + message.errorMessage + + "\n" + ); string = message.errorMessage; } catch (ex) { // Be a little paranoid with message, as the whole goal here is to lose diff --git a/devtools/shared/security/tests/unit/testactors.js b/devtools/shared/security/tests/unit/testactors.js index 1e15bb75f437..beff34bb0591 100644 --- a/devtools/shared/security/tests/unit/testactors.js +++ b/devtools/shared/security/tests/unit/testactors.js @@ -2,11 +2,16 @@ http://creativecommons.org/publicdomain/zero/1.0/ */ "use strict"; -const { LazyPool, createExtraActors } = require("devtools/shared/protocol/lazy-pool"); +const { + LazyPool, + createExtraActors, +} = require("devtools/shared/protocol/lazy-pool"); const { RootActor } = require("devtools/server/actors/root"); const { ThreadActor } = require("devtools/server/actors/thread"); const { DebuggerServer } = require("devtools/server/main"); -const { ActorRegistry } = require("devtools/server/actors/utils/actor-registry"); +const { + ActorRegistry, +} = require("devtools/server/actors/utils/actor-registry"); const promise = require("promise"); var gTestGlobals = []; @@ -106,13 +111,13 @@ TestTargetActor.prototype = { onDetach: function(request) { if (!this._attached) { - return { "error": "wrongState" }; + return { error: "wrongState" }; } return { type: "detached" }; }, }; TestTargetActor.prototype.requestTypes = { - "attach": TestTargetActor.prototype.onAttach, - "detach": TestTargetActor.prototype.onDetach, + attach: TestTargetActor.prototype.onAttach, + detach: TestTargetActor.prototype.onDetach, }; diff --git a/devtools/shared/specs/accessibility.js b/devtools/shared/specs/accessibility.js index 38a6eb48701e..f20379b7eb9d 100644 --- a/devtools/shared/specs/accessibility.js +++ b/devtools/shared/specs/accessibility.js @@ -77,7 +77,7 @@ const accessibleSpec = generateActorSpec({ type: "shortcutChange", shortcut: Arg(0, "string"), }, - "reorder": { + reorder: { type: "reorder", childCount: Arg(0, "number"), walker: Arg(1, "nullable:accessiblewalker"), @@ -90,7 +90,7 @@ const accessibleSpec = generateActorSpec({ type: "indexInParentChange", indexInParent: Arg(0, "number"), }, - "audited": { + audited: { type: "audited", audit: Arg(0, "nullable:json"), }, @@ -210,10 +210,10 @@ const accessibilitySpec = generateActorSpec({ typeName: "accessibility", events: { - "init": { + init: { type: "init", }, - "shutdown": { + shutdown: { type: "shutdown", }, "can-be-disabled-change": { diff --git a/devtools/shared/specs/actor-registry.js b/devtools/shared/specs/actor-registry.js index 65fc99a031ab..e70f3f4f752b 100644 --- a/devtools/shared/specs/actor-registry.js +++ b/devtools/shared/specs/actor-registry.js @@ -3,11 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { - Arg, - RetVal, - generateActorSpec, -} = require("devtools/shared/protocol"); +const { Arg, RetVal, generateActorSpec } = require("devtools/shared/protocol"); const actorActorSpec = generateActorSpec({ typeName: "actorActor", diff --git a/devtools/shared/specs/addon/addons.js b/devtools/shared/specs/addon/addons.js index 6246b9d1f0e9..2f955a30ce8d 100644 --- a/devtools/shared/specs/addon/addons.js +++ b/devtools/shared/specs/addon/addons.js @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {Arg, RetVal, generateActorSpec} = require("devtools/shared/protocol"); +const { Arg, RetVal, generateActorSpec } = require("devtools/shared/protocol"); const addonsSpec = generateActorSpec({ typeName: "addons", diff --git a/devtools/shared/specs/addon/webextension.js b/devtools/shared/specs/addon/webextension.js index d18a7645b873..506639135753 100644 --- a/devtools/shared/specs/addon/webextension.js +++ b/devtools/shared/specs/addon/webextension.js @@ -3,19 +3,19 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {RetVal, generateActorSpec} = require("devtools/shared/protocol"); +const { RetVal, generateActorSpec } = require("devtools/shared/protocol"); const webExtensionSpec = generateActorSpec({ typeName: "webExtension", methods: { reload: { - request: { }, + request: {}, response: { addon: RetVal("json") }, }, connect: { - request: { }, + request: {}, response: { form: RetVal("json") }, }, }, diff --git a/devtools/shared/specs/animation.js b/devtools/shared/specs/animation.js index 05be4f96e446..660409351e55 100644 --- a/devtools/shared/specs/animation.js +++ b/devtools/shared/specs/animation.js @@ -25,7 +25,7 @@ const animationPlayerSpec = generateActorSpec({ typeName: "animationplayer", events: { - "changed": { + changed: { type: "changed", state: Arg(0, "json"), }, @@ -62,7 +62,7 @@ const animationsSpec = generateActorSpec({ typeName: "animations", events: { - "mutations": { + mutations: { type: "mutations", changes: Arg(0, "array:animationMutationChange"), }, diff --git a/devtools/shared/specs/array-buffer.js b/devtools/shared/specs/array-buffer.js index 531bfaadc398..31ef31eeab4c 100644 --- a/devtools/shared/specs/array-buffer.js +++ b/devtools/shared/specs/array-buffer.js @@ -4,7 +4,7 @@ "use strict"; const protocol = require("devtools/shared/protocol"); -const {Arg, RetVal, generateActorSpec} = protocol; +const { Arg, RetVal, generateActorSpec } = protocol; const arrayBufferSpec = generateActorSpec({ typeName: "arraybuffer", diff --git a/devtools/shared/specs/changes.js b/devtools/shared/specs/changes.js index cc678c5e668b..2b5f5bbe708b 100644 --- a/devtools/shared/specs/changes.js +++ b/devtools/shared/specs/changes.js @@ -4,11 +4,7 @@ "use strict"; -const { - Arg, - generateActorSpec, - RetVal, -} = require("devtools/shared/protocol"); +const { Arg, generateActorSpec, RetVal } = require("devtools/shared/protocol"); const changesSpec = generateActorSpec({ typeName: "changes", @@ -28,12 +24,12 @@ const changesSpec = generateActorSpec({ }, methods: { - "allChanges": { + allChanges: { response: { changes: RetVal("array:json"), }, }, - "start": {}, // no arguments, no response + start: {}, // no arguments, no response }, }); diff --git a/devtools/shared/specs/device.js b/devtools/shared/specs/device.js index 551149d7c34b..c621d679b914 100644 --- a/devtools/shared/specs/device.js +++ b/devtools/shared/specs/device.js @@ -15,8 +15,11 @@ const deviceSpec = generateActorSpec({ }, methods: { - getDescription: {request: {}, response: { value: RetVal("json")}}, - screenshotToDataURL: {request: {}, response: { value: RetVal("longstring")}}, + getDescription: { request: {}, response: { value: RetVal("json") } }, + screenshotToDataURL: { + request: {}, + response: { value: RetVal("longstring") }, + }, }, }); diff --git a/devtools/shared/specs/environment.js b/devtools/shared/specs/environment.js index ef81e1f36664..83a85d6fe2fa 100644 --- a/devtools/shared/specs/environment.js +++ b/devtools/shared/specs/environment.js @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {Arg, RetVal, generateActorSpec} = require("devtools/shared/protocol"); +const { Arg, RetVal, generateActorSpec } = require("devtools/shared/protocol"); const environmentSpec = generateActorSpec({ typeName: "environment", diff --git a/devtools/shared/specs/frame.js b/devtools/shared/specs/frame.js index bd3fa5a5fc9d..c389cb760cb9 100644 --- a/devtools/shared/specs/frame.js +++ b/devtools/shared/specs/frame.js @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {generateActorSpec, RetVal} = require("devtools/shared/protocol"); +const { generateActorSpec, RetVal } = require("devtools/shared/protocol"); const frameSpec = generateActorSpec({ typeName: "frame", diff --git a/devtools/shared/specs/index.js b/devtools/shared/specs/index.js index 90ebb3f08637..8353218f8af1 100644 --- a/devtools/shared/specs/index.js +++ b/devtools/shared/specs/index.js @@ -11,7 +11,7 @@ // Declare in which spec module and front module a set of types are defined. // This array should be sorted by `spec` attribute. -const Types = exports.__TypesForTests = [ +const Types = (exports.__TypesForTests = [ { types: ["accessible", "accessiblewalker", "accessibility"], spec: "devtools/shared/specs/accessibility", @@ -177,7 +177,14 @@ const Types = exports.__TypesForTests = [ front: "devtools/shared/fronts/source", }, { - types: ["cookies", "localStorage", "sessionStorage", "Cache", "indexedDB", "storage"], + types: [ + "cookies", + "localStorage", + "sessionStorage", + "Cache", + "indexedDB", + "storage", + ], spec: "devtools/shared/specs/storage", front: "devtools/shared/fronts/storage", }, @@ -282,7 +289,7 @@ const Types = exports.__TypesForTests = [ spec: "devtools/shared/specs/worker/service-worker-registration", front: "devtools/shared/fronts/worker/service-worker-registration", }, -]; +]); const lazySpecs = new Map(); const lazyFronts = new Map(); @@ -310,7 +317,8 @@ function lazyLoadSpec(type) { require(modulePath); } catch (e) { throw new Error( - `Unable to load lazy spec module '${modulePath}' for type '${type}'`); + `Unable to load lazy spec module '${modulePath}' for type '${type}'` + ); } lazySpecs.delete(type); return true; @@ -335,7 +343,8 @@ function lazyLoadFront(type) { } catch (e) { throw new Error( `Unable to load lazy front module '${modulePath}' for type '${type}'. - Error: ${e}`); + Error: ${e}` + ); } lazyFronts.delete(type); return true; diff --git a/devtools/shared/specs/inspector.js b/devtools/shared/specs/inspector.js index 0d1f421b8e57..28dbb32e835a 100644 --- a/devtools/shared/specs/inspector.js +++ b/devtools/shared/specs/inspector.js @@ -30,9 +30,11 @@ var nodeArrayMethod = { start: Option(1, "domnode"), whatToShow: Option(1), }, - response: RetVal(types.addDictType("domtraversalarray", { - nodes: "array:domnode", - })), + response: RetVal( + types.addDictType("domtraversalarray", { + nodes: "array:domnode", + }) + ), }; var traversalMethod = { @@ -85,7 +87,7 @@ const walkerSpec = generateActorSpec({ // clients know when the browser window gets resized. This may be useful // for refreshing a DOM node's styles for example, since those may depend on // media-queries. - "resize": { + resize: { type: "resize", }, }, @@ -100,7 +102,7 @@ const walkerSpec = generateActorSpec({ }, cancelPick: {}, highlight: { - request: {node: Arg(0, "nullable:domnode")}, + request: { node: Arg(0, "nullable:domnode") }, }, document: { request: { node: Arg(0, "nullable:domnode") }, @@ -409,15 +411,15 @@ const inspectorSpec = generateActorSpec({ }, }, getImageDataFromURL: { - request: {url: Arg(0), maxDim: Arg(1, "nullable:number")}, + request: { url: Arg(0), maxDim: Arg(1, "nullable:number") }, response: RetVal("imageData"), }, resolveRelativeURL: { - request: {url: Arg(0, "string"), node: Arg(1, "nullable:domnode")}, - response: {value: RetVal("string")}, + request: { url: Arg(0, "string"), node: Arg(1, "nullable:domnode") }, + response: { value: RetVal("string") }, }, pickColorFromPage: { - request: {options: Arg(0, "nullable:json")}, + request: { options: Arg(0, "nullable:json") }, response: {}, }, cancelPickColorFromPage: { diff --git a/devtools/shared/specs/memory.js b/devtools/shared/specs/memory.js index 8720d738ab1b..acf9d5dee380 100644 --- a/devtools/shared/specs/memory.js +++ b/devtools/shared/specs/memory.js @@ -40,7 +40,7 @@ const memorySpec = generateActorSpec({ // Same data as the data from `getAllocations` -- only fired if // `autoDrain` set during `startRecordingAllocations`. - "allocations": { + allocations: { type: "allocations", data: Arg(0, "json"), }, diff --git a/devtools/shared/specs/node.js b/devtools/shared/specs/node.js index 17400e0a149e..691aef253994 100644 --- a/devtools/shared/specs/node.js +++ b/devtools/shared/specs/node.js @@ -105,7 +105,7 @@ const nodeSpec = generateActorSpec({ response: {}, }, getImageData: { - request: {maxDim: Arg(0, "nullable:number")}, + request: { maxDim: Arg(0, "nullable:number") }, response: RetVal("imageData"), }, getEventListenerInfo: { @@ -121,7 +121,7 @@ const nodeSpec = generateActorSpec({ response: {}, }, getFontFamilyDataURL: { - request: {font: Arg(0, "string"), fillStyle: Arg(1, "nullable:string")}, + request: { font: Arg(0, "string"), fillStyle: Arg(1, "nullable:string") }, response: RetVal("imageData"), }, getClosestBackgroundColor: { diff --git a/devtools/shared/specs/perf.js b/devtools/shared/specs/perf.js index 4f1a06cd4b3e..1d94eb4e11f4 100644 --- a/devtools/shared/specs/perf.js +++ b/devtools/shared/specs/perf.js @@ -3,7 +3,12 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { Arg, Option, RetVal, generateActorSpec } = require("devtools/shared/protocol"); +const { + Arg, + Option, + RetVal, + generateActorSpec, +} = require("devtools/shared/protocol"); const perfDescription = { typeName: "perf", diff --git a/devtools/shared/specs/preference.js b/devtools/shared/specs/preference.js index 2988265b6542..c5e8e3943d4a 100644 --- a/devtools/shared/specs/preference.js +++ b/devtools/shared/specs/preference.js @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {Arg, RetVal, generateActorSpec} = require("devtools/shared/protocol"); +const { Arg, RetVal, generateActorSpec } = require("devtools/shared/protocol"); const preferenceSpec = generateActorSpec({ typeName: "preference", diff --git a/devtools/shared/specs/reflow.js b/devtools/shared/specs/reflow.js index f6e82d144d9d..e8c036bba63e 100644 --- a/devtools/shared/specs/reflow.js +++ b/devtools/shared/specs/reflow.js @@ -4,7 +4,7 @@ "use strict"; -const {Arg, generateActorSpec} = require("devtools/shared/protocol"); +const { Arg, generateActorSpec } = require("devtools/shared/protocol"); const reflowSpec = generateActorSpec({ typeName: "reflow", @@ -25,8 +25,8 @@ const reflowSpec = generateActorSpec({ }, methods: { - start: {oneway: true}, - stop: {oneway: true}, + start: { oneway: true }, + stop: { oneway: true }, }, }); diff --git a/devtools/shared/specs/root.js b/devtools/shared/specs/root.js index 670c0b8c17a7..7964a13327b7 100644 --- a/devtools/shared/specs/root.js +++ b/devtools/shared/specs/root.js @@ -3,7 +3,13 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { types, generateActorSpec, RetVal, Arg, Option } = require("devtools/shared/protocol"); +const { + types, + generateActorSpec, + RetVal, + Arg, + Option, +} = require("devtools/shared/protocol"); types.addDictType("root.listWorkers", { workers: "array:workerTarget", diff --git a/devtools/shared/specs/screenshot.js b/devtools/shared/specs/screenshot.js index d688d3f7f7df..acadd976f8ad 100644 --- a/devtools/shared/specs/screenshot.js +++ b/devtools/shared/specs/screenshot.js @@ -3,7 +3,12 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {RetVal, Arg, generateActorSpec, types} = require("devtools/shared/protocol"); +const { + RetVal, + Arg, + generateActorSpec, + types, +} = require("devtools/shared/protocol"); types.addDictType("screenshot.args", { fullpage: "nullable:boolean", @@ -23,10 +28,10 @@ const screenshotSpec = generateActorSpec({ args: Arg(0, "screenshot.args"), }, response: { - value: RetVal("json")}, + value: RetVal("json"), + }, }, }, }); exports.screenshotSpec = screenshotSpec; - diff --git a/devtools/shared/specs/source.js b/devtools/shared/specs/source.js index b732fd2fe15d..7cff8e7dc6cf 100644 --- a/devtools/shared/specs/source.js +++ b/devtools/shared/specs/source.js @@ -3,7 +3,12 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { Arg, RetVal, generateActorSpec, types } = require("devtools/shared/protocol"); +const { + Arg, + RetVal, + generateActorSpec, + types, +} = require("devtools/shared/protocol"); const longstringType = types.getType("longstring"); const arraybufferType = types.getType("arraybuffer"); diff --git a/devtools/shared/specs/storage.js b/devtools/shared/specs/storage.js index 4d329fbefc92..0ff5626a3996 100644 --- a/devtools/shared/specs/storage.js +++ b/devtools/shared/specs/storage.js @@ -87,7 +87,8 @@ const editRemoveMethods = { createStorageSpec({ typeName: "cookies", storeObjectType: "cookiestoreobject", - methods: Object.assign({}, + methods: Object.assign( + {}, editRemoveMethods, { addItem: { @@ -96,7 +97,8 @@ createStorageSpec({ }, response: {}, }, - }, { + }, + { removeAll: { request: { host: Arg(0, "string"), @@ -104,7 +106,8 @@ createStorageSpec({ }, response: {}, }, - }, { + }, + { removeAllSessionCookies: { request: { host: Arg(0, "string"), @@ -123,7 +126,8 @@ types.addDictType("storageobject", { }); // Common methods for local/session storage -const storageMethods = Object.assign({}, +const storageMethods = Object.assign( + {}, editRemoveMethods, { addItem: { @@ -164,8 +168,8 @@ createStorageSpec({ }); types.addDictType("cacheobject", { - "url": "string", - "status": "string", + url: "string", + status: "string", }); // Array of Cache store objects @@ -264,10 +268,13 @@ types.addDictType("storeUpdateObject", { }); // Generate a type definition for an object with actors for all storage types. -types.addDictType("storelist", Object.keys(childSpecs).reduce((obj, type) => { - obj[type] = type; - return obj; -}, {})); +types.addDictType( + "storelist", + Object.keys(childSpecs).reduce((obj, type) => { + obj[type] = type; + return obj; + }, {}) +); exports.childSpecs = childSpecs; diff --git a/devtools/shared/specs/string.js b/devtools/shared/specs/string.js index fcb6b99b2443..7809bf4a380f 100644 --- a/devtools/shared/specs/string.js +++ b/devtools/shared/specs/string.js @@ -4,7 +4,7 @@ "use strict"; const protocol = require("devtools/shared/protocol"); -const {Arg, RetVal, generateActorSpec} = protocol; +const { Arg, RetVal, generateActorSpec } = protocol; const promise = require("promise"); const longStringSpec = generateActorSpec({ @@ -78,7 +78,7 @@ protocol.types.addType("longstring", { if (context instanceof protocol.Actor) { throw Error("Passing a longstring as an argument isn't supported."); } - if (typeof (value) === "string") { + if (typeof value === "string") { return new SimpleStringFront(value); } return stringActorType.read(value, context, detail); diff --git a/devtools/shared/specs/styles.js b/devtools/shared/specs/styles.js index de39df7ae914..3542d6ad9aa1 100644 --- a/devtools/shared/specs/styles.js +++ b/devtools/shared/specs/styles.js @@ -17,7 +17,7 @@ types.addActorType("domstylerule"); /** * DOM Nodes returned by the style actor will be owned by the DOM walker * for the connection. - */ + */ types.addLifetime("walker", "walker"); /** @@ -144,11 +144,13 @@ const pageStyleSpec = generateActorSpec({ property: Arg(1, "string"), filter: Option(2, "string"), }, - response: RetVal(types.addDictType("matchedselectorresponse", { - rules: "array:domstylerule", - sheets: "array:stylesheet", - matched: "array:matchedselector", - })), + response: RetVal( + types.addDictType("matchedselectorresponse", { + rules: "array:domstylerule", + sheets: "array:stylesheet", + matched: "array:matchedselector", + }) + ), }, getRule: { request: { @@ -169,7 +171,7 @@ const pageStyleSpec = generateActorSpec({ response: RetVal("appliedStylesReturn"), }, isPositionEditable: { - request: { node: Arg(0, "domnode")}, + request: { node: Arg(0, "domnode") }, response: { value: RetVal("boolean") }, }, getLayout: { diff --git a/devtools/shared/specs/stylesheets.js b/devtools/shared/specs/stylesheets.js index a6e175e437f5..11ca02d86a07 100644 --- a/devtools/shared/specs/stylesheets.js +++ b/devtools/shared/specs/stylesheets.js @@ -47,7 +47,7 @@ const styleSheetSpec = generateActorSpec({ methods: { toggleDisabled: { - response: { disabled: RetVal("boolean")}, + response: { disabled: RetVal("boolean") }, }, getText: { response: { diff --git a/devtools/shared/specs/symbol.js b/devtools/shared/specs/symbol.js index 7961c4592fec..300ae1db827e 100644 --- a/devtools/shared/specs/symbol.js +++ b/devtools/shared/specs/symbol.js @@ -4,9 +4,7 @@ "use strict"; -const { - generateActorSpec, -} = require("devtools/shared/protocol"); +const { generateActorSpec } = require("devtools/shared/protocol"); const symbolSpec = generateActorSpec({ typeName: "symbol", diff --git a/devtools/shared/specs/targets/addon.js b/devtools/shared/specs/targets/addon.js index e71072c3dc34..90ab36053f40 100644 --- a/devtools/shared/specs/targets/addon.js +++ b/devtools/shared/specs/targets/addon.js @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {RetVal, generateActorSpec} = require("devtools/shared/protocol"); +const { RetVal, generateActorSpec } = require("devtools/shared/protocol"); const addonTargetSpec = generateActorSpec({ typeName: "addonTarget", diff --git a/devtools/shared/specs/targets/browsing-context.js b/devtools/shared/specs/targets/browsing-context.js index be4d43b21537..37563219fae0 100644 --- a/devtools/shared/specs/targets/browsing-context.js +++ b/devtools/shared/specs/targets/browsing-context.js @@ -3,7 +3,12 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { types, generateActorSpec, RetVal, Option } = require("devtools/shared/protocol"); +const { + types, + generateActorSpec, + RetVal, + Option, +} = require("devtools/shared/protocol"); types.addDictType("browsingContextTarget.attach", { type: "string", @@ -148,7 +153,9 @@ const browsingContextTargetSpecPrototype = { }, }; -const browsingContextTargetSpec = generateActorSpec(browsingContextTargetSpecPrototype); +const browsingContextTargetSpec = generateActorSpec( + browsingContextTargetSpecPrototype +); exports.browsingContextTargetSpecPrototype = browsingContextTargetSpecPrototype; exports.browsingContextTargetSpec = browsingContextTargetSpec; diff --git a/devtools/shared/specs/targets/chrome-window.js b/devtools/shared/specs/targets/chrome-window.js index cae7c4762d17..31aae450c891 100644 --- a/devtools/shared/specs/targets/chrome-window.js +++ b/devtools/shared/specs/targets/chrome-window.js @@ -5,13 +5,14 @@ const { generateActorSpec } = require("devtools/shared/protocol"); const { extend } = require("devtools/shared/extend"); -const { browsingContextTargetSpecPrototype } = require("devtools/shared/specs/targets/browsing-context"); - -const chromeWindowTargetSpec = generateActorSpec(extend( +const { browsingContextTargetSpecPrototype, - { +} = require("devtools/shared/specs/targets/browsing-context"); + +const chromeWindowTargetSpec = generateActorSpec( + extend(browsingContextTargetSpecPrototype, { typeName: "chromeWindowTarget", - } -)); + }) +); exports.chromeWindowTargetSpec = chromeWindowTargetSpec; diff --git a/devtools/shared/specs/targets/content-process.js b/devtools/shared/specs/targets/content-process.js index aa95dd5db38e..05a94d5776f2 100644 --- a/devtools/shared/specs/targets/content-process.js +++ b/devtools/shared/specs/targets/content-process.js @@ -3,7 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {types, RetVal, generateActorSpec} = require("devtools/shared/protocol"); +const { + types, + RetVal, + generateActorSpec, +} = require("devtools/shared/protocol"); types.addDictType("contentProcessTarget.workers", { error: "nullable:string", diff --git a/devtools/shared/specs/targets/frame.js b/devtools/shared/specs/targets/frame.js index 1aac143af264..6b9f4ef44c63 100644 --- a/devtools/shared/specs/targets/frame.js +++ b/devtools/shared/specs/targets/frame.js @@ -5,11 +5,15 @@ const { generateActorSpec } = require("devtools/shared/protocol"); const { extend } = require("devtools/shared/extend"); -const { browsingContextTargetSpecPrototype } = require("devtools/shared/specs/targets/browsing-context"); +const { + browsingContextTargetSpecPrototype, +} = require("devtools/shared/specs/targets/browsing-context"); // Bug 1467560: Update `generateActorSpec` support extension more naturally -const frameTargetSpec = generateActorSpec(extend(browsingContextTargetSpecPrototype, { - typeName: "frameTarget", -})); +const frameTargetSpec = generateActorSpec( + extend(browsingContextTargetSpecPrototype, { + typeName: "frameTarget", + }) +); exports.frameTargetSpec = frameTargetSpec; diff --git a/devtools/shared/specs/targets/parent-process.js b/devtools/shared/specs/targets/parent-process.js index 8fe9224239ef..b74d64698314 100644 --- a/devtools/shared/specs/targets/parent-process.js +++ b/devtools/shared/specs/targets/parent-process.js @@ -5,7 +5,9 @@ const { generateActorSpec } = require("devtools/shared/protocol"); const { extend } = require("devtools/shared/extend"); -const { browsingContextTargetSpecPrototype } = require("devtools/shared/specs/targets/browsing-context"); +const { + browsingContextTargetSpecPrototype, +} = require("devtools/shared/specs/targets/browsing-context"); const parentProcessTargetSpecPrototype = extend( browsingContextTargetSpecPrototype, @@ -14,7 +16,9 @@ const parentProcessTargetSpecPrototype = extend( } ); -const parentProcessTargetSpec = generateActorSpec(parentProcessTargetSpecPrototype); +const parentProcessTargetSpec = generateActorSpec( + parentProcessTargetSpecPrototype +); exports.parentProcessTargetSpecPrototype = parentProcessTargetSpecPrototype; exports.parentProcessTargetSpec = parentProcessTargetSpec; diff --git a/devtools/shared/specs/targets/webextension.js b/devtools/shared/specs/targets/webextension.js index 680cd8fe7b74..bf55ec2c7baf 100644 --- a/devtools/shared/specs/targets/webextension.js +++ b/devtools/shared/specs/targets/webextension.js @@ -5,13 +5,14 @@ const { generateActorSpec } = require("devtools/shared/protocol"); const { extend } = require("devtools/shared/extend"); -const { parentProcessTargetSpecPrototype } = require("devtools/shared/specs/targets/parent-process"); - -const webExtensionTargetSpec = generateActorSpec(extend( +const { parentProcessTargetSpecPrototype, - { +} = require("devtools/shared/specs/targets/parent-process"); + +const webExtensionTargetSpec = generateActorSpec( + extend(parentProcessTargetSpecPrototype, { typeName: "webExtensionTarget", - } -)); + }) +); exports.webExtensionTargetSpec = webExtensionTargetSpec; diff --git a/devtools/shared/specs/targets/worker.js b/devtools/shared/specs/targets/worker.js index 42ff45a86f1d..dacf7c84b26e 100644 --- a/devtools/shared/specs/targets/worker.js +++ b/devtools/shared/specs/targets/worker.js @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {Arg, RetVal, generateActorSpec} = require("devtools/shared/protocol"); +const { Arg, RetVal, generateActorSpec } = require("devtools/shared/protocol"); const workerTargetSpec = generateActorSpec({ typeName: "workerTarget", diff --git a/devtools/shared/specs/thread.js b/devtools/shared/specs/thread.js index 49443020672b..7f984b3a244d 100644 --- a/devtools/shared/specs/thread.js +++ b/devtools/shared/specs/thread.js @@ -3,7 +3,13 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {Arg, Option, RetVal, generateActorSpec, types} = require("devtools/shared/protocol"); +const { + Arg, + Option, + RetVal, + generateActorSpec, + types, +} = require("devtools/shared/protocol"); types.addDictType("available-breakpoint-group", { name: "string", diff --git a/devtools/shared/specs/timeline.js b/devtools/shared/specs/timeline.js index 806821b0d16b..b0f777f59290 100644 --- a/devtools/shared/specs/timeline.js +++ b/devtools/shared/specs/timeline.js @@ -20,9 +20,9 @@ const { * serialization redundancy. */ types.addType("array-of-numbers-as-strings", { - write: (v) => v.join(","), + write: v => v.join(","), // In Gecko <= 37, `v` is an array; do not transform in this case. - read: (v) => typeof v === "string" ? v.split(",") : v, + read: v => (typeof v === "string" ? v.split(",") : v), }); const timelineSpec = generateActorSpec({ @@ -43,7 +43,7 @@ const timelineSpec = generateActorSpec({ * at most, when profile markers are found. The timestamps on each marker * are relative to when recording was started. */ - "markers": { + markers: { type: "markers", markers: Arg(0, "json"), endTime: Arg(1, "number"), @@ -54,7 +54,7 @@ const timelineSpec = generateActorSpec({ * when the recording started. The `delta` timestamp on this measurement is * relative to when recording was started. */ - "memory": { + memory: { type: "memory", delta: Arg(0, "number"), measurement: Arg(1, "json"), @@ -65,7 +65,7 @@ const timelineSpec = generateActorSpec({ * "markers", if this was enabled when the recording started. All ticks * are timestamps with a zero epoch. */ - "ticks": { + ticks: { type: "ticks", delta: Arg(0, "number"), timestamps: Arg(1, "array-of-numbers-as-strings"), @@ -76,7 +76,7 @@ const timelineSpec = generateActorSpec({ * JS stack frames. The `delta` timestamp on this frames packet is * relative to when recording was started. */ - "frames": { + frames: { type: "frames", delta: Arg(0, "number"), frames: Arg(1, "json"), diff --git a/devtools/shared/specs/webconsole.js b/devtools/shared/specs/webconsole.js index b4e21d218ee2..d00b95588db7 100644 --- a/devtools/shared/specs/webconsole.js +++ b/devtools/shared/specs/webconsole.js @@ -4,7 +4,13 @@ "use strict"; -const {types, generateActorSpec, RetVal, Option, Arg} = require("devtools/shared/protocol"); +const { + types, + generateActorSpec, + RetVal, + Option, + Arg, +} = require("devtools/shared/protocol"); types.addDictType("console.traits", { evaluateJSAsync: "boolean", @@ -88,8 +94,7 @@ const webconsoleSpecPrototype = { inspectObject: { objectActor: Option(0, "json"), }, - lastPrivateContextExited: { - }, + lastPrivateContextExited: {}, documentEvent: { name: Option(0, "string"), time: Option(0, "string"), @@ -194,8 +199,8 @@ const webconsoleSpecPrototype = { response: RetVal("console.autocomplete"), }, /** - * Clear the cache of messages (page errors and console API calls) expects no response. - */ + * Clear the cache of messages (page errors and console API calls) expects no response. + */ clearMessagesCache: { oneway: true, }, diff --git a/devtools/shared/specs/worker/service-worker-registration.js b/devtools/shared/specs/worker/service-worker-registration.js index 199400a02eed..bc2c29e43f3e 100644 --- a/devtools/shared/specs/worker/service-worker-registration.js +++ b/devtools/shared/specs/worker/service-worker-registration.js @@ -34,4 +34,3 @@ const serviceWorkerRegistrationSpec = generateActorSpec({ }); exports.serviceWorkerRegistrationSpec = serviceWorkerRegistrationSpec; - diff --git a/devtools/shared/specs/worker/service-worker.js b/devtools/shared/specs/worker/service-worker.js index 53f664222607..fec9e93a1347 100644 --- a/devtools/shared/specs/worker/service-worker.js +++ b/devtools/shared/specs/worker/service-worker.js @@ -10,4 +10,3 @@ const serviceWorkerSpec = generateActorSpec({ }); exports.serviceWorkerSpec = serviceWorkerSpec; - diff --git a/devtools/shared/system.js b/devtools/shared/system.js index c5e0279f5ff7..73146b2fddf5 100644 --- a/devtools/shared/system.js +++ b/devtools/shared/system.js @@ -7,19 +7,23 @@ const { Cc, Ci } = require("chrome"); loader.lazyRequireGetter(this, "Services"); loader.lazyRequireGetter(this, "DebuggerServer", "devtools/server/main", true); -loader.lazyRequireGetter(this, "AppConstants", - "resource://gre/modules/AppConstants.jsm", true); +loader.lazyRequireGetter( + this, + "AppConstants", + "resource://gre/modules/AppConstants.jsm", + true +); loader.lazyGetter(this, "hostname", () => { try { // On some platforms (Linux according to try), this service does not exist and fails. - return Cc["@mozilla.org/network/dns-service;1"] - .getService(Ci.nsIDNSService).myHostName; + return Cc["@mozilla.org/network/dns-service;1"].getService(Ci.nsIDNSService) + .myHostName; } catch (e) { return ""; } }); loader.lazyGetter(this, "endianness", () => { - if ((new Uint32Array((new Uint8Array([1, 2, 3, 4])).buffer))[0] === 0x04030201) { + if (new Uint32Array(new Uint8Array([1, 2, 3, 4]).buffer)[0] === 0x04030201) { return "LE"; } return "BE"; @@ -43,13 +47,7 @@ function getSystemInfo() { const appInfo = Services.appinfo; const win = Services.wm.getMostRecentWindow(DebuggerServer.chromeWindowType); const [processor, compiler] = appInfo.XPCOMABI.split("-"); - let dpi, - useragent, - width, - height, - physicalWidth, - physicalHeight, - brandName; + let dpi, useragent, width, height, physicalWidth, physicalHeight, brandName; const appid = appInfo.ID; const apptype = APP_MAP[appid]; const geckoVersion = appInfo.platformVersion; @@ -59,7 +57,9 @@ function getSystemInfo() { const os = appInfo.OS; version = appInfo.version; - const bundle = Services.strings.createBundle("chrome://branding/locale/brand.properties"); + const bundle = Services.strings.createBundle( + "chrome://branding/locale/brand.properties" + ); if (bundle) { brandName = bundle.GetStringFromName("brandFullName"); } else { @@ -77,7 +77,6 @@ function getSystemInfo() { } const info = { - /** * Information from nsIXULAppInfo, regarding * the application itself. @@ -184,8 +183,9 @@ function getProfileLocation() { // nsXREDirProvider never gets initialised and so the profile service // crashes on initialisation. const profd = Services.dirsvc.get("ProfD", Ci.nsIFile); - const profservice = Cc["@mozilla.org/toolkit/profile-service;1"] - .getService(Ci.nsIToolkitProfileService); + const profservice = Cc["@mozilla.org/toolkit/profile-service;1"].getService( + Ci.nsIToolkitProfileService + ); if (profservice.currentProfile) { return profservice.currentProfile.name; } diff --git a/devtools/shared/task.js b/devtools/shared/task.js index 0574ecab618a..23fddb9a0e74 100644 --- a/devtools/shared/task.js +++ b/devtools/shared/task.js @@ -91,8 +91,12 @@ const defer = require("devtools/shared/defer"); // The following error types are considered programmer errors, which should be // reported (possibly redundantly) so as to let programmers fix their code. -const ERRORS_TO_REPORT = ["EvalError", "RangeError", "ReferenceError", - "TypeError"]; +const ERRORS_TO_REPORT = [ + "EvalError", + "RangeError", + "ReferenceError", + "TypeError", +]; /** * The Task currently being executed @@ -199,7 +203,7 @@ var Task = { * @return A function that starts the task function and returns its promise. */ async: function(task) { - if (typeof (task) != "function") { + if (typeof task != "function") { throw new TypeError("task argument must be a function"); } @@ -221,13 +225,14 @@ var Task = { function createAsyncFunction(task) { const asyncFunction = function() { let result = task; - if (task && typeof (task) == "function") { + if (task && typeof task == "function") { if (task.isAsyncFunction) { throw new TypeError( "Cannot use an async function in place of a promise. " + - "You should either invoke the async function first " + - "or use 'Task.spawn' instead of 'Task.async' to start " + - "the Task and return its promise."); + "You should either invoke the async function first " + + "or use 'Task.spawn' instead of 'Task.async' to start " + + "the Task and return its promise." + ); } try { @@ -264,7 +269,7 @@ function createAsyncFunction(task) { */ function TaskImpl(iterator) { if (gMaintainStack) { - this._stack = (new Error()).stack; + this._stack = new Error().stack; } this.deferred = defer(); this._iterator = iterator; @@ -307,8 +312,9 @@ TaskImpl.prototype = { if (this._isStarGenerator) { try { - const result = sendResolved ? this._iterator.next(sendValue) - : this._iterator.throw(sendValue); + const result = sendResolved + ? this._iterator.next(sendValue) + : this._iterator.throw(sendValue); if (result.done) { // The generator function returned. @@ -323,8 +329,9 @@ TaskImpl.prototype = { } } else { try { - const yielded = sendResolved ? this._iterator.send(sendValue) - : this._iterator.throw(sendValue); + const yielded = sendResolved + ? this._iterator.send(sendValue) + : this._iterator.throw(sendValue); this._handleResultValue(yielded); } catch (ex) { if (ex instanceof Task.Result) { @@ -379,12 +386,11 @@ TaskImpl.prototype = { value = Task.spawn(value); } - if (value && typeof (value.then) == "function") { + if (value && typeof value.then == "function") { // We have a promise object now. When fulfilled, call again into this // function to continue the task, with either a resolution or rejection // condition. - value.then(this._run.bind(this, true), - this._run.bind(this, false)); + value.then(this._run.bind(this, true), this._run.bind(this, false)); } else { // If our task yielded a value that is not a promise, just continue and // pass it directly as the result of the yield statement. @@ -404,9 +410,11 @@ TaskImpl.prototype = { if (exception && typeof exception == "object" && "stack" in exception) { let stack = exception.stack; - if (gMaintainStack && - exception._capturedTaskStack != this._stack && - typeof stack == "string") { + if ( + gMaintainStack && + exception._capturedTaskStack != this._stack && + typeof stack == "string" + ) { // Rewrite the stack for more readability. const bottomStack = this._stack; @@ -422,8 +430,7 @@ TaskImpl.prototype = { stack = "Not available"; } - if ("name" in exception && - ERRORS_TO_REPORT.includes(exception.name)) { + if ("name" in exception && ERRORS_TO_REPORT.includes(exception.name)) { // We suspect that the exception is a programmer error, so we now // display it using dump(). Note that we do not use Cu.reportError as // we assume that this is a programming error, so we do not want end @@ -454,7 +461,6 @@ TaskImpl.prototype = { }; Task.Debugging = { - /** * Control stack rewriting. * diff --git a/devtools/shared/test-helpers/allocation-tracker.js b/devtools/shared/test-helpers/allocation-tracker.js index 75d68b241e40..510fdbd29b49 100644 --- a/devtools/shared/test-helpers/allocation-tracker.js +++ b/devtools/shared/test-helpers/allocation-tracker.js @@ -39,7 +39,9 @@ const { Cu } = require("chrome"); const ChromeUtils = require("ChromeUtils"); const global = Cu.getGlobalForObject(this); -const {addDebuggerToGlobal} = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm"); +const { addDebuggerToGlobal } = ChromeUtils.import( + "resource://gre/modules/jsdebugger.jsm" +); addDebuggerToGlobal(global); /** @@ -84,7 +86,9 @@ exports.allocationTracker = function({ const ref = g.unsafeDereference(); const location = Cu.getRealmLocation(ref); const accept = !!location.match(/devtools/i); - dump("TRACKER NEW GLOBAL: " + (accept ? "+" : "-") + " : " + location + "\n"); + dump( + "TRACKER NEW GLOBAL: " + (accept ? "+" : "-") + " : " + location + "\n" + ); return accept; }; } @@ -203,13 +207,21 @@ exports.allocationTracker = function({ }); return { src, count: item.count, lines }; }); - dump("DEVTOOLS ALLOCATION: Javascript object allocations: " + allocations.length + - "\n" + JSON.stringify(allocationList, null, 2) + "\n"); + dump( + "DEVTOOLS ALLOCATION: Javascript object allocations: " + + allocations.length + + "\n" + + JSON.stringify(allocationList, null, 2) + + "\n" + ); }, logCount() { - dump("DEVTOOLS ALLOCATION: Javascript object allocations: " + - this.countAllocations() + "\n"); + dump( + "DEVTOOLS ALLOCATION: Javascript object allocations: " + + this.countAllocations() + + "\n" + ); }, countAllocations() { diff --git a/devtools/shared/test-helpers/browser_allocation_tracker.js b/devtools/shared/test-helpers/browser_allocation_tracker.js index 0d1ec9d4a305..c3ec3117e260 100644 --- a/devtools/shared/test-helpers/browser_allocation_tracker.js +++ b/devtools/shared/test-helpers/browser_allocation_tracker.js @@ -6,12 +6,15 @@ // Load the tracker in a dedicated loader using invisibleToDebugger and freshCompartment // so that it can inspect any other module/compartment, even DevTools, chrome, // and this script! -const { DevToolsLoader } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); +const { DevToolsLoader } = ChromeUtils.import( + "resource://devtools/shared/Loader.jsm" +); const loader = new DevToolsLoader(); loader.invisibleToDebugger = true; loader.freshCompartment = true; -const { allocationTracker } = - loader.require("chrome://mochitests/content/browser/devtools/shared/test-helpers/allocation-tracker"); +const { allocationTracker } = loader.require( + "chrome://mochitests/content/browser/devtools/shared/test-helpers/allocation-tracker" +); add_task(async function() { // Use a sandbox to allocate test javascript object in order to avoid any @@ -22,26 +25,37 @@ add_task(async function() { const before = tracker.stillAllocatedObjects(); /* eslint-disable no-undef */ - Cu.evalInSandbox("let list; new " + function() { - list = []; - for (let i = 0; i < 1000; i++) { - list.push({}); - } - }, global, undefined, "test-file.js", 1); + Cu.evalInSandbox( + "let list; new " + + function() { + list = []; + for (let i = 0; i < 1000; i++) { + list.push({}); + } + }, + global, + undefined, + "test-file.js", + 1 + ); /* eslint-enable no-undef */ const allocations = tracker.countAllocations(); - ok(allocations > 1000, - `At least 1000 objects are reported as created (${allocations})`); + ok( + allocations > 1000, + `At least 1000 objects are reported as created (${allocations})` + ); // Uncomment this and comment the call to `countAllocations` to debug the allocations. // The call to `countAllocations` will reset the allocation record. // tracker.logAllocationSites(); const afterCreation = tracker.stillAllocatedObjects(); - ok(afterCreation - before > 1000, + ok( + afterCreation - before > 1000, `At least 1000 more objects are reported still allocated (${before}` + - ` + ${afterCreation - before} -> ${afterCreation})`); + ` + ${afterCreation - before} -> ${afterCreation})` + ); Cu.evalInSandbox("list = null;", global, undefined, "test-file.js", 7); @@ -49,9 +63,11 @@ add_task(async function() { Cu.forceCC(); const afterGC = tracker.stillAllocatedObjects(); - ok(afterCreation - afterGC > 1000, + ok( + afterCreation - afterGC > 1000, `At least 1000 less objects are reported still allocated (${afterCreation}` + - ` -(${afterGC - afterCreation})-> ${afterGC})`); + ` -(${afterGC - afterCreation})-> ${afterGC})` + ); tracker.stop(); }); diff --git a/devtools/shared/tests/browser/browser_l10n_localizeMarkup.js b/devtools/shared/tests/browser/browser_l10n_localizeMarkup.js index 575f7d93eaa6..9a6fd8f76659 100644 --- a/devtools/shared/tests/browser/browser_l10n_localizeMarkup.js +++ b/devtools/shared/tests/browser/browser_l10n_localizeMarkup.js @@ -10,19 +10,26 @@ const HTML_NS = "http://www.w3.org/1999/xhtml"; add_task(async function() { info("Check that the strings used for this test are still valid"); - const STARTUP_L10N = - new LocalizationHelper("devtools/client/locales/startup.properties"); - const TOOLBOX_L10N = - new LocalizationHelper("devtools/client/locales/toolbox.properties"); + const STARTUP_L10N = new LocalizationHelper( + "devtools/client/locales/startup.properties" + ); + const TOOLBOX_L10N = new LocalizationHelper( + "devtools/client/locales/toolbox.properties" + ); const str1 = STARTUP_L10N.getStr("inspector.label"); const str2 = STARTUP_L10N.getStr("inspector.accesskey"); const str3 = TOOLBOX_L10N.getStr("toolbox.defaultTitle"); - ok(str1 && str2 && str3, "If this failed, strings should be updated in the test"); + ok( + str1 && str2 && str3, + "If this failed, strings should be updated in the test" + ); info("Create the test markup"); const div = document.createElementNS(HTML_NS, "div"); - div.setAttribute("data-localization-bundle", - "devtools/client/locales/startup.properties"); + div.setAttribute( + "data-localization-bundle", + "devtools/client/locales/startup.properties" + ); const div0 = document.createElementNS(HTML_NS, "div"); div0.setAttribute("id", "d0"); div0.setAttribute("data-localization", "content=inspector.someInvalidKey"); @@ -34,13 +41,17 @@ add_task(async function() { div1.append("Text will disappear"); const div2 = document.createElementNS(HTML_NS, "div"); div2.setAttribute("id", "d2"); - div2.setAttribute("data-localization", - "content=inspector.label;title=inspector.accesskey"); + div2.setAttribute( + "data-localization", + "content=inspector.label;title=inspector.accesskey" + ); div.appendChild(div2); const div3 = document.createElementNS(HTML_NS, "div"); div3.setAttribute("id", "d3"); - div3.setAttribute("data-localization", - "content=inspector.label;title=inspector.accesskey"); + div3.setAttribute( + "data-localization", + "content=inspector.label;title=inspector.accesskey" + ); div.appendChild(div3); const div4 = document.createElementNS(HTML_NS, "div"); div4.setAttribute("id", "d4"); @@ -48,8 +59,10 @@ add_task(async function() { div.appendChild(div4); div4.append("Some content"); const toolboxDiv = document.createElementNS(HTML_NS, "div"); - toolboxDiv.setAttribute("data-localization-bundle", - "devtools/client/locales/toolbox.properties"); + toolboxDiv.setAttribute( + "data-localization-bundle", + "devtools/client/locales/toolbox.properties" + ); div.appendChild(toolboxDiv); const div5 = document.createElementNS(HTML_NS, "div"); div5.setAttribute("id", "d5"); @@ -65,6 +78,14 @@ add_task(async function() { is(div3.innerHTML, str1, "The content of #d3 is localized"); is(div3.getAttribute("title"), str2, "The title of #d3 is localized"); is(div4.innerHTML, "Some content", "The content of #d4 is not replaced"); - is(div4.getAttribute("aria-label"), str1, "The aria-label of #d4 is localized"); - is(div5.innerHTML, str3, "The content of #d5 is localized with another bundle"); + is( + div4.getAttribute("aria-label"), + str1, + "The aria-label of #d4 is localized" + ); + is( + div5.innerHTML, + str3, + "The content of #d5 is localized with another bundle" + ); }); diff --git a/devtools/shared/tests/unit/head_devtools.js b/devtools/shared/tests/unit/head_devtools.js index 49753eccfc03..5bd90927bfae 100644 --- a/devtools/shared/tests/unit/head_devtools.js +++ b/devtools/shared/tests/unit/head_devtools.js @@ -5,7 +5,9 @@ "use strict"; -const { require, DevToolsLoader } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); +const { require, DevToolsLoader } = ChromeUtils.import( + "resource://devtools/shared/Loader.jsm" +); const Services = require("Services"); const DevToolsUtils = require("devtools/shared/DevToolsUtils"); @@ -29,9 +31,16 @@ var listener = { let string; try { message.QueryInterface(Ci.nsIScriptError); - dump(message.sourceName + ":" + message.lineNumber + ": " + - scriptErrorFlagsToKind(message.flags) + ": " + - message.errorMessage + "\n"); + dump( + message.sourceName + + ":" + + message.lineNumber + + ": " + + scriptErrorFlagsToKind(message.flags) + + ": " + + message.errorMessage + + "\n" + ); string = message.errorMessage; } catch (ex) { // Be a little paranoid with message, as the whole goal here is to lose diff --git a/devtools/shared/tests/unit/test_assert.js b/devtools/shared/tests/unit/test_assert.js index 7956961c2f7f..5ff9423edb5a 100644 --- a/devtools/shared/tests/unit/test_assert.js +++ b/devtools/shared/tests/unit/test_assert.js @@ -17,20 +17,27 @@ function run_test() { } catch (e) { // If you catch assertion failures in practice, I will hunt you down. I get // email notifications every time it happens. - ok(false, "Should not get an error for an assertion that should not fail. Got " - + DevToolsUtils.safeErrorString(e)); + ok( + false, + "Should not get an error for an assertion that should not fail. Got " + + DevToolsUtils.safeErrorString(e) + ); } let assertionFailed = false; try { assert(false, "this assertion should fail"); } catch (e) { - ok(e.message.startsWith("Assertion failure:"), - "Should be an assertion failure error"); + ok( + e.message.startsWith("Assertion failure:"), + "Should be an assertion failure error" + ); assertionFailed = true; } - ok(assertionFailed, - "The assertion should have failed, which should throw an error when assertions " + - "are enabled."); + ok( + assertionFailed, + "The assertion should have failed, which should throw an error when assertions " + + "are enabled." + ); } diff --git a/devtools/shared/tests/unit/test_console_filtering.js b/devtools/shared/tests/unit/test_console_filtering.js index 1807912472f7..986230f09e5d 100644 --- a/devtools/shared/tests/unit/test_console_filtering.js +++ b/devtools/shared/tests/unit/test_console_filtering.js @@ -4,7 +4,9 @@ "use strict"; const { console, ConsoleAPI } = require("resource://gre/modules/Console.jsm"); -const { ConsoleAPIListener } = require("devtools/server/actors/webconsole/listeners/console-api"); +const { + ConsoleAPIListener, +} = require("devtools/server/actors/webconsole/listeners/console-api"); var seenMessages = 0; var seenTypes = 0; @@ -33,8 +35,10 @@ registerCleanupFunction(() => { policy.active = false; }); -function createFakeAddonWindow({addonId} = {}) { - const uuidGen = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator); +function createFakeAddonWindow({ addonId } = {}) { + const uuidGen = Cc["@mozilla.org/uuid-generator;1"].getService( + Ci.nsIUUIDGenerator + ); const uuid = uuidGen.generateUUID().number.slice(1, -1); if (policy) { @@ -51,14 +55,16 @@ function createFakeAddonWindow({addonId} = {}) { policy.active = true; const baseURI = Services.io.newURI(`moz-extension://${uuid}/`); - const principal = Services.scriptSecurityManager - .createCodebasePrincipal(baseURI, {}); + const principal = Services.scriptSecurityManager.createCodebasePrincipal( + baseURI, + {} + ); const chromeWebNav = Services.appShell.createWindowlessBrowser(true); const { docShell } = chromeWebNav; docShell.createAboutBlankContentViewer(principal, principal); const addonWindow = docShell.contentViewer.DOMDocument.defaultView; - return {addonWindow, chromeWebNav}; + return { addonWindow, chromeWebNav }; } /** @@ -74,7 +80,9 @@ function run_test() { // console2 - WebExtension page's console messages tagged // by 'originAttributes.addonId' are filtered correctly. - const {addonWindow, chromeWebNav} = createFakeAddonWindow({addonId: "bar"}); + const { addonWindow, chromeWebNav } = createFakeAddonWindow({ + addonId: "bar", + }); const console2 = addonWindow.console; // console - Plain console object (messages are tagged with window ids @@ -104,7 +112,7 @@ function run_test() { listener.destroy(); - listener = new ConsoleAPIListener(null, callback, {addonId: "foo"}); + listener = new ConsoleAPIListener(null, callback, { addonId: "foo" }); listener.init(); messages = listener.getCachedMessages(); @@ -124,7 +132,7 @@ function run_test() { listener.destroy(); - listener = new ConsoleAPIListener(null, callback, {addonId: "bar"}); + listener = new ConsoleAPIListener(null, callback, { addonId: "bar" }); listener.init(); messages = listener.getCachedMessages(); diff --git a/devtools/shared/tests/unit/test_console_save-file.js b/devtools/shared/tests/unit/test_console_save-file.js index 67c9df3cb75f..09475358710d 100644 --- a/devtools/shared/tests/unit/test_console_save-file.js +++ b/devtools/shared/tests/unit/test_console_save-file.js @@ -5,7 +5,10 @@ // Tests for DevToolsUtils.saveFileStream file: -const { FileUtils } = ChromeUtils.import("resource://gre/modules/FileUtils.jsm", {}); +const { FileUtils } = ChromeUtils.import( + "resource://gre/modules/FileUtils.jsm", + {} +); /** * Tests that a file is properly saved using the saveFileStream function @@ -28,8 +31,9 @@ add_task(async function test_save_file() { * @return nsIInputStream */ function convertToInputStream(content) { - const converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Ci.nsIScriptableUnicodeConverter); + const converter = Cc[ + "@mozilla.org/intl/scriptableunicodeconverter" + ].createInstance(Ci.nsIScriptableUnicodeConverter); converter.charset = "UTF-8"; return converter.convertToInputStream(content); } diff --git a/devtools/shared/tests/unit/test_css-properties-db.js b/devtools/shared/tests/unit/test_css-properties-db.js index 38a022be3c5b..b4b86c60d057 100644 --- a/devtools/shared/tests/unit/test_css-properties-db.js +++ b/devtools/shared/tests/unit/test_css-properties-db.js @@ -19,27 +19,40 @@ "use strict"; -const {PSEUDO_ELEMENTS, CSS_PROPERTIES, PREFERENCES} = require("devtools/shared/css/generated/properties-db"); -const {generateCssProperties} = require("devtools/server/actors/css-properties"); -const {Preferences} = require("resource://gre/modules/Preferences.jsm"); +const { + PSEUDO_ELEMENTS, + CSS_PROPERTIES, + PREFERENCES, +} = require("devtools/shared/css/generated/properties-db"); +const { + generateCssProperties, +} = require("devtools/server/actors/css-properties"); +const { Preferences } = require("resource://gre/modules/Preferences.jsm"); const InspectorUtils = require("InspectorUtils"); function run_test() { - const propertiesErrorMessage = "If this assertion fails, then the client side CSS " + - "properties list in devtools is out of sync with the " + - "CSS properties on the platform. To fix this " + - "assertion run `mach devtools-css-db` to re-generate " + - "the client side properties."; + const propertiesErrorMessage = + "If this assertion fails, then the client side CSS " + + "properties list in devtools is out of sync with the " + + "CSS properties on the platform. To fix this " + + "assertion run `mach devtools-css-db` to re-generate " + + "the client side properties."; // Check that the platform and client match for pseudo elements. - deepEqual(PSEUDO_ELEMENTS, InspectorUtils.getCSSPseudoElementNames(), - "The pseudo elements match on the client and platform. " + - propertiesErrorMessage); + deepEqual( + PSEUDO_ELEMENTS, + InspectorUtils.getCSSPseudoElementNames(), + "The pseudo elements match on the client and platform. " + + propertiesErrorMessage + ); const prefs = InspectorUtils.getCSSPropertyPrefs(); - deepEqual(PREFERENCES, prefs.map(({name, pref}) => [name, pref]), - "The preferences match on the client and platform. " + - propertiesErrorMessage); + deepEqual( + PREFERENCES, + prefs.map(({ name, pref }) => [name, pref]), + "The preferences match on the client and platform. " + + propertiesErrorMessage + ); /** * Check that the platform and client match for the details on their CSS properties. @@ -57,8 +70,12 @@ function run_test() { if (deepEqual) { ok(true, `The static database and platform match for "${propertyName}".`); } else { - ok(false, `The static database and platform do not match for ` + ` - "${propertyName}". ${propertiesErrorMessage}`); + ok( + false, + `The static database and platform do not match for ` + + ` + "${propertyName}". ${propertiesErrorMessage}` + ); } } @@ -72,17 +89,26 @@ function run_test() { .filter(name => name && !name.includes("-moz-osx-")); if (mismatches.length === 0) { - ok(true, "No client and platform CSS property database mismatches were found."); + ok( + true, + "No client and platform CSS property database mismatches were found." + ); } mismatches.forEach(propertyName => { if (getPreference(propertyName) === false) { - ok(true, `The static database and platform do not agree on the property ` + - `"${propertyName}" This is ok because it is currently disabled through ` + - `a preference.`); + ok( + true, + `The static database and platform do not agree on the property ` + + `"${propertyName}" This is ok because it is currently disabled through ` + + `a preference.` + ); } else { - ok(false, `The static database and platform do not agree on the property ` + - `"${propertyName}" ${propertiesErrorMessage}`); + ok( + false, + `The static database and platform do not agree on the property ` + + `"${propertyName}" ${propertiesErrorMessage}` + ); } }); } diff --git a/devtools/shared/tests/unit/test_csslexer.js b/devtools/shared/tests/unit/test_csslexer.js index 847a0e68f2f8..3606baa7681b 100644 --- a/devtools/shared/tests/unit/test_csslexer.js +++ b/devtools/shared/tests/unit/test_csslexer.js @@ -36,19 +36,35 @@ function test_lexer(cssText, tokenTypes) { var LEX_TESTS = [ ["simple", ["ident:simple"]], - ["simple: { hi; }", - ["ident:simple", "symbol::", - "whitespace", "symbol:{", - "whitespace", "ident:hi", - "symbol:;", "whitespace", - "symbol:}"]], + [ + "simple: { hi; }", + [ + "ident:simple", + "symbol::", + "whitespace", + "symbol:{", + "whitespace", + "ident:hi", + "symbol:;", + "whitespace", + "symbol:}", + ], + ], ["/* whatever */", ["comment"]], ["'string'", ["string:string"]], ['"string"', ["string:string"]], - ["rgb(1,2,3)", ["function:rgb", "number", - "symbol:,", "number", - "symbol:,", "number", - "symbol:)"]], + [ + "rgb(1,2,3)", + [ + "function:rgb", + "number", + "symbol:,", + "number", + "symbol:,", + "number", + "symbol:)", + ], + ], ["@media", ["at:media"]], ["#hibob", ["id:hibob"]], ["#123", ["hash:123"]], @@ -56,8 +72,7 @@ var LEX_TESTS = [ ["23%", ["percentage"]], ["url(http://example.com)", ["url:http://example.com"]], ["url('http://example.com')", ["url:http://example.com"]], - ["url( 'http://example.com' )", - ["url:http://example.com"]], + ["url( 'http://example.com' )", ["url:http://example.com"]], // In CSS Level 3, this is an ordinary URL, not a BAD_URL. ["url(http://example.com", ["url:http://example.com"]], ["url(http://example.com @", ["bad_url:http://example.com"]], @@ -72,9 +87,18 @@ var LEX_TESTS = [ // URANGE may be on the way out, and it isn't used by devutils, so // let's skip it. - ["", ["htmlcomment", "whitespace", "ident:html", - "whitespace", "ident:comment", "whitespace", - "htmlcomment"]], + [ + "", + [ + "htmlcomment", + "whitespace", + "ident:html", + "whitespace", + "ident:comment", + "whitespace", + "htmlcomment", + ], + ], // earlier versions of CSS had "bad comment" tokens, but in level 3, // unterminated comments are just comments. @@ -107,8 +131,12 @@ function test_lexer_linecol(cssText, locations) { equal(i, locations.length); } -function test_lexer_eofchar(cssText, argText, expectedAppend, - expectedNoAppend) { +function test_lexer_eofchar( + cssText, + argText, + expectedAppend, + expectedNoAppend +) { const lexer = jsLexer.getCSSLexer(cssText); while (lexer.nextToken()) { // Nothing. @@ -126,26 +154,28 @@ function test_lexer_eofchar(cssText, argText, expectedAppend, var LINECOL_TESTS = [ ["simple", ["ident:0:0", ":0:6"]], ["\n stuff", ["whitespace:0:0", "ident:1:4", ":1:9"]], - ['"string with \\\nnewline" \r\n', ["string:0:0", "whitespace:1:8", - ":2:0"]], + [ + '"string with \\\nnewline" \r\n', + ["string:0:0", "whitespace:1:8", ":2:0"], + ], ]; var EOFCHAR_TESTS = [ ["hello", "hello"], ["hello \\", "hello \\\\", "hello \\\uFFFD"], ["'hello", "'hello'"], - ["\"hello", "\"hello\""], + ['"hello', '"hello"'], ["'hello\\", "'hello\\\\'", "'hello'"], - ["\"hello\\", "\"hello\\\\\"", "\"hello\""], + ['"hello\\', '"hello\\\\"', '"hello"'], ["/*hello", "/*hello*/"], ["/*hello*", "/*hello*/"], ["/*hello\\", "/*hello\\*/"], ["url(hello", "url(hello)"], ["url('hello", "url('hello')"], - ["url(\"hello", "url(\"hello\")"], + ['url("hello', 'url("hello")'], ["url(hello\\", "url(hello\\\\)", "url(hello\\\uFFFD)"], ["url('hello\\", "url('hello\\\\')", "url('hello')"], - ["url(\"hello\\", "url(\"hello\\\\\")", "url(\"hello\")"], + ['url("hello\\', 'url("hello\\\\")', 'url("hello")'], ]; function run_test() { diff --git a/devtools/shared/tests/unit/test_debugger_client.js b/devtools/shared/tests/unit/test_debugger_client.js index 392d8ea2491b..f49c76fbde4b 100644 --- a/devtools/shared/tests/unit/test_debugger_client.js +++ b/devtools/shared/tests/unit/test_debugger_client.js @@ -30,7 +30,10 @@ async function testCloseLoops() { client.on("closed", async () => { dump(">> CLOSED\n"); if (called) { - ok(false, "Calling client.close from closed event listener introduce loops"); + ok( + false, + "Calling client.close from closed event listener introduce loops" + ); return; } called = true; diff --git a/devtools/shared/tests/unit/test_eventemitter_basic.js b/devtools/shared/tests/unit/test_eventemitter_basic.js index da2104a43ecf..c00bfb8a2b1e 100644 --- a/devtools/shared/tests/unit/test_eventemitter_basic.js +++ b/devtools/shared/tests/unit/test_eventemitter_basic.js @@ -24,12 +24,16 @@ const TESTS = { const isAnEmitter = emitter instanceof EventEmitter; ok(emitter, "We have an event emitter"); - ok(hasMethod(emitter, "on") && - hasMethod(emitter, "off") && - hasMethod(emitter, "once") && - !hasMethod(emitter, "decorate") && - !hasMethod(emitter, "count"), - `Event Emitter ${isAnEmitter ? "instance" : "mixin"} has the expected methods.`); + ok( + hasMethod(emitter, "on") && + hasMethod(emitter, "off") && + hasMethod(emitter, "once") && + !hasMethod(emitter, "decorate") && + !hasMethod(emitter, "count"), + `Event Emitter ${ + isAnEmitter ? "instance" : "mixin" + } has the expected methods.` + ); }, testEmittingEvents(done) { @@ -56,7 +60,7 @@ const TESTS = { } function onlyOnce() { - ok(!beenHere2, "\"once\" listener has been called once"); + ok(!beenHere2, '"once" listener has been called once'); beenHere2 = true; emitter.emit("onlyonce"); @@ -175,7 +179,7 @@ const TESTS = { equal(secondCallbackCalled, false, "second callback not called yet"); - return Promise.all([ check1, check2, check3 ]).then(args => { + return Promise.all([check1, check2, check3]).then(args => { equal(args[0], "rval from c1", "callback 1 done good"); equal(args[1], "rval from c2", "callback 2 done good"); equal(args[2], "rval from c3", "callback 3 done good"); @@ -203,13 +207,21 @@ const TESTS = { emitter.emit("*", "wildcard"); equal(received.length, 2, "the listener was only triggered once"); - equal(received[1].length, 1, "the listener was called with only 1 argument"); + equal( + received[1].length, + 1, + "the listener was called with only 1 argument" + ); equal(received[1][0], "wildcard", "first argument is the actual argument"); emitter.emit("other", "arg1", "arg2"); equal(received.length, 3, "the listener was triggered once"); - equal(received[2].length, 3, "the listener was called with only 1 argument"); + equal( + received[2].length, + 3, + "the listener was called with only 1 argument" + ); equal(received[2][0], "other", "first argument is the event name"); equal(received[2][1], "arg1", "additional arguments are forwarded"); equal(received[2][2], "arg2", "additional arguments are forwarded"); @@ -250,16 +262,17 @@ const TESTS = { * @param {Object} tests * The tests descriptor object, contains the tests to run. */ -const runnable = (tests) => (async function() { - for (const name of Object.keys(tests)) { - info(name); - if (tests[name].length === 1) { - await (new Promise(resolve => tests[name](resolve))); - } else { - await tests[name](); +const runnable = tests => + async function() { + for (const name of Object.keys(tests)) { + info(name); + if (tests[name].length === 1) { + await new Promise(resolve => tests[name](resolve)); + } else { + await tests[name](); + } } - } -}); + }; // We want to run the same tests for both an instance of `EventEmitter` and an object // decorate with EventEmitter; therefore we create two strategies (`createNewEmitter` and diff --git a/devtools/shared/tests/unit/test_eventemitter_static.js b/devtools/shared/tests/unit/test_eventemitter_static.js index 57152cbb2cdf..c3a6ffa1babd 100644 --- a/devtools/shared/tests/unit/test_eventemitter_static.js +++ b/devtools/shared/tests/unit/test_eventemitter_static.js @@ -6,10 +6,17 @@ const { ConsoleAPIListener, } = require("devtools/server/actors/webconsole/listeners/console-api"); -const { on, once, off, emit, count, handler } = require("devtools/shared/event-emitter"); +const { + on, + once, + off, + emit, + count, + handler, +} = require("devtools/shared/event-emitter"); -const pass = (message) => ok(true, message); -const fail = (message) => ok(false, message); +const pass = message => ok(true, message); +const fail = message => ok(false, message); /** * Each method of this object is a test; tests can be synchronous or asynchronous: @@ -21,7 +28,7 @@ const fail = (message) => ok(false, message); */ const TESTS = { testAddListener() { - const events = [ { name: "event#1" }, "event#2" ]; + const events = [{ name: "event#1" }, "event#2"]; const target = { name: "target" }; on(target, "message", function(message) { @@ -45,10 +52,10 @@ const TESTS = { on(target, "foo", listener); emit(target, "message"); - deepEqual([ 1 ], actual, "only one message listener added"); + deepEqual([1], actual, "only one message listener added"); emit(target, "foo"); - deepEqual([ 1, 1 ], actual, "same listener added for other event"); + deepEqual([1, 1], actual, "same listener added for other event"); }, testEventTypeMatters() { @@ -61,7 +68,8 @@ const TESTS = { }, testAllArgumentsArePassed() { - const foo = { name: "foo" }, bar = "bar"; + const foo = { name: "foo" }, + bar = "bar"; const target = { name: "target" }; on(target, "message", (a, b) => { @@ -84,7 +92,7 @@ const TESTS = { }, testCanRemoveNextListener() { - const target = { name: "target"}; + const target = { name: "target" }; on(target, "data", () => { pass("first listener called"); @@ -104,7 +112,7 @@ const TESTS = { on(target, "message", () => actual.push(3)); emit(target, "message"); - deepEqual([ 1, 2, 3 ], actual, "called in order they were added"); + deepEqual([1, 2, 3], actual, "called in order they were added"); }, testRemoveListener() { @@ -120,13 +128,13 @@ const TESTS = { }); emit(target, "message"); - deepEqual([ 1 ], actual, "first listener called"); + deepEqual([1], actual, "first listener called"); emit(target, "message"); - deepEqual([ 1, 1, 2 ], actual, "second listener called"); + deepEqual([1, 1, 2], actual, "second listener called"); emit(target, "message"); - deepEqual([ 1, 1, 2, 2, 2 ], actual, "first listener removed"); + deepEqual([1, 1, 2, 2, 2], actual, "first listener removed"); }, testRemoveAllListenersForType() { @@ -142,7 +150,7 @@ const TESTS = { emit(target, "message"); emit(target, "bar"); - deepEqual([ "b" ], actual, "all message listeners were removed"); + deepEqual(["b"], actual, "all message listeners were removed"); }, testRemoveAllListeners() { @@ -164,28 +172,31 @@ const TESTS = { testFalsyArgumentsAreFine() { let type, listener; - const target = { name: "target" }, actual = []; + const target = { name: "target" }, + actual = []; on(target, "bar", () => actual.push(0)); off(target, "bar", listener); emit(target, "bar"); - deepEqual([ 0 ], actual, "3rd bad arg will keep listener"); + deepEqual([0], actual, "3rd bad arg will keep listener"); off(target, type); emit(target, "bar"); - deepEqual([ 0, 0 ], actual, "2nd bad arg will keep listener"); + deepEqual([0, 0], actual, "2nd bad arg will keep listener"); off(target, type, listener); emit(target, "bar"); - deepEqual([ 0, 0, 0 ], actual, "2nd & 3rd bad args will keep listener"); + deepEqual([0, 0, 0], actual, "2nd & 3rd bad args will keep listener"); }, testUnhandledExceptions(done) { const listener = new ConsoleAPIListener(null, { onConsoleAPICall(message) { equal(message.level, "error", "Got the first exception"); - ok(message.arguments[0].startsWith("Error: Boom!"), - "unhandled exception is logged"); + ok( + message.arguments[0].startsWith("Error: Boom!"), + "unhandled exception is logged" + ); listener.destroy(); done(); @@ -249,7 +260,11 @@ const TESTS = { const target = { name: "target" }; const actual = []; const listener = function(...args) { - equal(this, target, "the contextual object is correct for function listener"); + equal( + this, + target, + "the contextual object is correct for function listener" + ); deepEqual(args, [10, 20, 30], "arguments are properly passed"); }; @@ -257,7 +272,11 @@ const TESTS = { name: "target", [handler](type, ...rest) { actual.push(type); - equal(this, object, "the contextual object is correct for object listener"); + equal( + this, + object, + "the contextual object is correct for object listener" + ); deepEqual(rest, [10, 20, 30], "arguments are properly passed"); }, }; @@ -270,7 +289,11 @@ const TESTS = { emit(target, "bar", 10, 20, 30); emit(target, "baz", 10, 20, 30); - deepEqual(actual, ["bar", "baz"], "object's listener called in the expected order"); + deepEqual( + actual, + ["bar", "baz"], + "object's listener called in the expected order" + ); }, testRemoveListenerWithHandlerMethod() { @@ -290,13 +313,13 @@ const TESTS = { on(target, "message", object); emit(target, "message"); - deepEqual([ 1 ], actual, "first listener called"); + deepEqual([1], actual, "first listener called"); emit(target, "message"); - deepEqual([ 1, 1, 2 ], actual, "second listener called"); + deepEqual([1, 1, 2], actual, "second listener called"); emit(target, "message"); - deepEqual([ 1, 1, 2, 2, 2 ], actual, "first listener removed"); + deepEqual([1, 1, 2, 2, 2], actual, "first listener removed"); }, async testOnceListenerWithHandlerMethod() { @@ -308,7 +331,11 @@ const TESTS = { ok(!called, "listener called only once"); equal(type, "foo", "event type is properly passed"); equal(value, "bar", "correct argument was passed"); - equal(this, object, "the contextual object is correct for object listener"); + equal( + this, + object, + "the contextual object is correct for object listener" + ); }, }; @@ -324,12 +351,11 @@ const TESTS = { }, testCallingOffWithMoreThan3Args() { - const target = { name: "target"}; + const target = { name: "target" }; on(target, "data", fail); off(target, "data", fail, undefined); emit(target, "data", "Listener should be removed"); }, - }; /** @@ -338,15 +364,16 @@ const TESTS = { * @param {Object} tests * The tests descriptor object, contains the tests to run. */ -const runnable = (tests) => (async function() { - for (const name of Object.keys(tests)) { - info(name); - if (tests[name].length === 1) { - await (new Promise(resolve => tests[name](resolve))); - } else { - await tests[name](); +const runnable = tests => + async function() { + for (const name of Object.keys(tests)) { + info(name); + if (tests[name].length === 1) { + await new Promise(resolve => tests[name](resolve)); + } else { + await tests[name](); + } } - } -}); + }; add_task(runnable(TESTS)); diff --git a/devtools/shared/tests/unit/test_executeSoon.js b/devtools/shared/tests/unit/test_executeSoon.js index 6dc48646a91d..507df8254476 100644 --- a/devtools/shared/tests/unit/test_executeSoon.js +++ b/devtools/shared/tests/unit/test_executeSoon.js @@ -13,12 +13,15 @@ var { executeSoon } = require("devtools/shared/DevToolsUtils"); var defer = require("devtools/shared/defer"); -var asyncStackEnabled = - Services.prefs.getBoolPref("javascript.options.asyncstack"); +var asyncStackEnabled = Services.prefs.getBoolPref( + "javascript.options.asyncstack" +); registerCleanupFunction(() => { - Services.prefs.setBoolPref("javascript.options.asyncstack", - asyncStackEnabled); + Services.prefs.setBoolPref( + "javascript.options.asyncstack", + asyncStackEnabled + ); }); add_task(async function() { diff --git a/devtools/shared/tests/unit/test_fetch-bom.js b/devtools/shared/tests/unit/test_fetch-bom.js index 861ae548cb91..9a334512edc6 100644 --- a/devtools/shared/tests/unit/test_fetch-bom.js +++ b/devtools/shared/tests/unit/test_fetch-bom.js @@ -8,8 +8,11 @@ const CC = Components.Constructor; const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); -const BinaryOutputStream = CC("@mozilla.org/binaryoutputstream;1", - "nsIBinaryOutputStream", "setOutputStream"); +const BinaryOutputStream = CC( + "@mozilla.org/binaryoutputstream;1", + "nsIBinaryOutputStream", + "setOutputStream" +); function write8(bos) { bos.write8(0xef); @@ -70,7 +73,9 @@ add_task(async function() { async function test_one(url, encoding) { // Be sure to set the encoding to something that will yield an // invalid result if BOM sniffing is not done. - await DevToolsUtils.fetch(url, { charset: "ISO-8859-1" }).then(({content}) => { - Assert.equal(content, "hı", "The content looks correct for " + encoding); - }); + await DevToolsUtils.fetch(url, { charset: "ISO-8859-1" }).then( + ({ content }) => { + Assert.equal(content, "hı", "The content looks correct for " + encoding); + } + ); } diff --git a/devtools/shared/tests/unit/test_fetch-chrome.js b/devtools/shared/tests/unit/test_fetch-chrome.js index 559704a83f08..e508213ba429 100644 --- a/devtools/shared/tests/unit/test_fetch-chrome.js +++ b/devtools/shared/tests/unit/test_fetch-chrome.js @@ -12,12 +12,15 @@ const URL_NOT_FOUND = "chrome://this/is/not/here.js"; * Test that non-existent files are handled correctly. */ add_task(async function test_missing() { - await DevToolsUtils.fetch(URL_NOT_FOUND).then(result => { - info(result); - ok(false, "fetch resolved unexpectedly for non-existent chrome:// URI"); - }, () => { - ok(true, "fetch rejected as the chrome:// URI was non-existent."); - }); + await DevToolsUtils.fetch(URL_NOT_FOUND).then( + result => { + info(result); + ok(false, "fetch resolved unexpectedly for non-existent chrome:// URI"); + }, + () => { + ok(true, "fetch rejected as the chrome:// URI was non-existent."); + } + ); }); /** @@ -25,7 +28,10 @@ add_task(async function test_missing() { */ add_task(async function test_normal() { await DevToolsUtils.fetch(URL_FOUND).then(result => { - notDeepEqual(result.content, "", - "chrome:// URI seems to be read correctly."); + notDeepEqual( + result.content, + "", + "chrome:// URI seems to be read correctly." + ); }); }); diff --git a/devtools/shared/tests/unit/test_fetch-file.js b/devtools/shared/tests/unit/test_fetch-file.js index 5d0fbe7c0f20..786db9a283e1 100644 --- a/devtools/shared/tests/unit/test_fetch-file.js +++ b/devtools/shared/tests/unit/test_fetch-file.js @@ -5,7 +5,9 @@ // Tests for DevToolsUtils.fetch on file:// URI's. -const { FileUtils } = ChromeUtils.import("resource://gre/modules/FileUtils.jsm"); +const { FileUtils } = ChromeUtils.import( + "resource://gre/modules/FileUtils.jsm" +); const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm"); const TEST_CONTENT = "aéd"; @@ -26,7 +28,7 @@ add_task(async function test_arrow_urls() { const url = "resource://gre/modules/XPIProvider.jsm -> file://" + path; await OS.File.writeAtomic(path, TEST_CONTENT, { encoding: "utf-8" }); - const { content } = await DevToolsUtils.fetch(url); + const { content } = await DevToolsUtils.fetch(url); deepEqual(content, TEST_CONTENT, "The file contents were correctly read."); }); @@ -47,9 +49,12 @@ add_task(async function test_encoding_utf8() { const { path } = createTemporaryFile(); await OS.File.writeAtomic(path, UTF8_TEST_BUFFER); - const { content } = await DevToolsUtils.fetch(path); - deepEqual(content, TEST_CONTENT, - "The UTF-8 encoded file was correctly read."); + const { content } = await DevToolsUtils.fetch(path); + deepEqual( + content, + TEST_CONTENT, + "The UTF-8 encoded file was correctly read." + ); }); /** @@ -59,21 +64,27 @@ add_task(async function test_encoding_iso_8859_1() { const { path } = createTemporaryFile(); await OS.File.writeAtomic(path, ISO_8859_1_BUFFER); - const { content } = await DevToolsUtils.fetch(path); - deepEqual(content, TEST_CONTENT, - "The ISO 8859-1 encoded file was correctly read."); + const { content } = await DevToolsUtils.fetch(path); + deepEqual( + content, + TEST_CONTENT, + "The ISO 8859-1 encoded file was correctly read." + ); }); /** * Test that non-existent files are handled correctly. */ add_task(async function test_missing() { - await DevToolsUtils.fetch("file:///file/not/found.right").then(result => { - info(result); - ok(false, "Fetch resolved unexpectedly when the file was not found."); - }, () => { - ok(true, "Fetch rejected as expected because the file was not found."); - }); + await DevToolsUtils.fetch("file:///file/not/found.right").then( + result => { + info(result); + ok(false, "Fetch resolved unexpectedly when the file was not found."); + }, + () => { + ok(true, "Fetch rejected as expected because the file was not found."); + } + ); }); /** diff --git a/devtools/shared/tests/unit/test_fetch-http.js b/devtools/shared/tests/unit/test_fetch-http.js index 40bef10e33e9..f89d60d3cc81 100644 --- a/devtools/shared/tests/unit/test_fetch-http.js +++ b/devtools/shared/tests/unit/test_fetch-http.js @@ -32,9 +32,11 @@ registerCleanupFunction(() => { }); add_task(async function test_normal() { - await DevToolsUtils.fetch(NORMAL_URL).then(({content}) => { - ok(content.includes("The content looks correct."), - "The content looks correct."); + await DevToolsUtils.fetch(NORMAL_URL).then(({ content }) => { + ok( + content.includes("The content looks correct."), + "The content looks correct." + ); }); }); @@ -42,20 +44,23 @@ add_task(async function test_caching() { let initialContent = null; info("Performing the first request."); - await DevToolsUtils.fetch(CACHED_URL).then(({content}) => { + await DevToolsUtils.fetch(CACHED_URL).then(({ content }) => { info("Got the first response: " + content); initialContent = content; }); info("Performing another request, expecting to get cached response."); - await DevToolsUtils.fetch(CACHED_URL).then(({content}) => { + await DevToolsUtils.fetch(CACHED_URL).then(({ content }) => { deepEqual(content, initialContent, "The content was loaded from cache."); }); info("Performing a third request with cache bypassed."); const opts = { loadFromCache: false }; - await DevToolsUtils.fetch(CACHED_URL, opts).then(({content}) => { - notDeepEqual(content, initialContent, - "The URL wasn't loaded from cache with loadFromCache: false."); + await DevToolsUtils.fetch(CACHED_URL, opts).then(({ content }) => { + notDeepEqual( + content, + initialContent, + "The URL wasn't loaded from cache with loadFromCache: false." + ); }); }); diff --git a/devtools/shared/tests/unit/test_fetch-resource.js b/devtools/shared/tests/unit/test_fetch-resource.js index dd67bbd4ebce..76a6275c98aa 100644 --- a/devtools/shared/tests/unit/test_fetch-resource.js +++ b/devtools/shared/tests/unit/test_fetch-resource.js @@ -12,12 +12,15 @@ const URL_NOT_FOUND = "resource://devtools/this/is/not/here.js"; * Test that non-existent files are handled correctly. */ add_task(async function test_missing() { - await DevToolsUtils.fetch(URL_NOT_FOUND).then(result => { - info(result); - ok(false, "fetch resolved unexpectedly for non-existent resource:// URI"); - }, () => { - ok(true, "fetch rejected as the resource:// URI was non-existent."); - }); + await DevToolsUtils.fetch(URL_NOT_FOUND).then( + result => { + info(result); + ok(false, "fetch resolved unexpectedly for non-existent resource:// URI"); + }, + () => { + ok(true, "fetch rejected as the resource:// URI was non-existent."); + } + ); }); /** @@ -25,7 +28,10 @@ add_task(async function test_missing() { */ add_task(async function test_normal() { await DevToolsUtils.fetch(URL_FOUND).then(result => { - notDeepEqual(result.content, "", - "resource:// URI seems to be read correctly."); + notDeepEqual( + result.content, + "", + "resource:// URI seems to be read correctly." + ); }); }); diff --git a/devtools/shared/tests/unit/test_flatten.js b/devtools/shared/tests/unit/test_flatten.js index 11c2ac047479..24297f11127d 100644 --- a/devtools/shared/tests/unit/test_flatten.js +++ b/devtools/shared/tests/unit/test_flatten.js @@ -9,9 +9,7 @@ function run_test() { const { flatten } = DevToolsUtils; - const flat = flatten([["a", "b", "c"], - ["d", "e", "f"], - ["g", "h", "i"]]); + const flat = flatten([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]); equal(flat.length, 9); equal(flat[0], "a"); diff --git a/devtools/shared/tests/unit/test_indentation.js b/devtools/shared/tests/unit/test_indentation.js index b3301b64ee79..8d4404c6717c 100644 --- a/devtools/shared/tests/unit/test_indentation.js +++ b/devtools/shared/tests/unit/test_indentation.js @@ -15,16 +15,25 @@ const { function test_indent_from_prefs() { Services.prefs.setBoolPref(DETECT_INDENT, true); - equal(getIndentationFromPrefs(), false, - "getIndentationFromPrefs returning false"); + equal( + getIndentationFromPrefs(), + false, + "getIndentationFromPrefs returning false" + ); Services.prefs.setIntPref(TAB_SIZE, 73); Services.prefs.setBoolPref(EXPAND_TAB, false); Services.prefs.setBoolPref(DETECT_INDENT, false); - deepEqual(getTabPrefs(), {indentUnit: 73, indentWithTabs: true}, - "getTabPrefs basic test"); - deepEqual(getIndentationFromPrefs(), {indentUnit: 73, indentWithTabs: true}, - "getIndentationFromPrefs basic test"); + deepEqual( + getTabPrefs(), + { indentUnit: 73, indentWithTabs: true }, + "getTabPrefs basic test" + ); + deepEqual( + getIndentationFromPrefs(), + { indentUnit: 73, indentWithTabs: true }, + "getIndentationFromPrefs basic test" + ); } const TESTS = [ @@ -43,7 +52,7 @@ const TESTS = [ " padding-left: 10px;", "}", ], - expected: {indentUnit: 2, indentWithTabs: false}, + expected: { indentUnit: 2, indentWithTabs: false }, }, { desc: "four spaces", @@ -71,7 +80,7 @@ const TESTS = [ " }", "}", ], - expected: {indentUnit: 4, indentWithTabs: false}, + expected: { indentUnit: 4, indentWithTabs: false }, }, { desc: "tabs", @@ -88,7 +97,7 @@ const TESTS = [ "\tpadding-left: 10px;", "}", ], - expected: {indentUnit: 2, indentWithTabs: true}, + expected: { indentUnit: 2, indentWithTabs: true }, }, { desc: "no indent", @@ -99,7 +108,7 @@ const TESTS = [ " ", "", ], - expected: {indentUnit: 2, indentWithTabs: false}, + expected: { indentUnit: 2, indentWithTabs: false }, }, ]; @@ -113,13 +122,19 @@ function test_indent_detection() { test.input.slice(start, end).forEach(callback); }; - deepEqual(getIndentationFromIteration(iterFn), test.expected, - "test getIndentationFromIteration " + test.desc); + deepEqual( + getIndentationFromIteration(iterFn), + test.expected, + "test getIndentationFromIteration " + test.desc + ); } for (const test of TESTS) { - deepEqual(getIndentationFromString(test.input.join("\n")), test.expected, - "test getIndentationFromString " + test.desc); + deepEqual( + getIndentationFromString(test.input.join("\n")), + test.expected, + "test getIndentationFromString " + test.desc + ); } } diff --git a/devtools/shared/tests/unit/test_invisible_loader.js b/devtools/shared/tests/unit/test_invisible_loader.js index aa2b2fedcdc2..2de24508d271 100644 --- a/devtools/shared/tests/unit/test_invisible_loader.js +++ b/devtools/shared/tests/unit/test_invisible_loader.js @@ -3,7 +3,9 @@ "use strict"; -const { addDebuggerToGlobal } = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm"); +const { addDebuggerToGlobal } = ChromeUtils.import( + "resource://gre/modules/jsdebugger.jsm" +); addDebuggerToGlobal(this); /** @@ -32,7 +34,8 @@ function visible_loader() { // Check that for common loader used for tabs, promise modules is Promise.jsm // Which is required to support unhandled promises rejection in mochitests - const promise = ChromeUtils.import("resource://gre/modules/Promise.jsm", {}).Promise; + const promise = ChromeUtils.import("resource://gre/modules/Promise.jsm", {}) + .Promise; Assert.equal(loader.require("promise"), promise); } @@ -55,6 +58,9 @@ function invisible_loader() { // of Promise-backend.js, that to be invisible to the debugger and not step // into it. const promise = loader.require("promise"); - const promiseModule = loader._provider.loader.modules["resource://gre/modules/Promise-backend.js"]; + const promiseModule = + loader._provider.loader.modules[ + "resource://gre/modules/Promise-backend.js" + ]; Assert.equal(promise, promiseModule.exports); } diff --git a/devtools/shared/tests/unit/test_isSet.js b/devtools/shared/tests/unit/test_isSet.js index a9e1fcafa9ab..46c8372b9557 100644 --- a/devtools/shared/tests/unit/test_isSet.js +++ b/devtools/shared/tests/unit/test_isSet.js @@ -15,8 +15,9 @@ function run_test() { equal(isSet("I swear I'm a Set"), false); equal(isSet(5), false); - const systemPrincipal = Cc["@mozilla.org/systemprincipal;1"] - .createInstance(Ci.nsIPrincipal); + const systemPrincipal = Cc["@mozilla.org/systemprincipal;1"].createInstance( + Ci.nsIPrincipal + ); const sandbox = new Cu.Sandbox(systemPrincipal); equal(isSet(Cu.evalInSandbox("new Set()", sandbox)), true); diff --git a/devtools/shared/tests/unit/test_pluralForm-english.js b/devtools/shared/tests/unit/test_pluralForm-english.js index fc11b761f55d..3e22c01d9fb4 100644 --- a/devtools/shared/tests/unit/test_pluralForm-english.js +++ b/devtools/shared/tests/unit/test_pluralForm-english.js @@ -10,7 +10,7 @@ * development), English. */ -const {PluralForm} = require("devtools/shared/plural-form"); +const { PluralForm } = require("devtools/shared/plural-form"); function run_test() { // English has 2 plural forms @@ -18,7 +18,10 @@ function run_test() { // Make sure for good inputs, things work as expected for (let num = 0; num <= 200; num++) { - Assert.equal(num == 1 ? "word" : "words", PluralForm.get(num, "word;words")); + Assert.equal( + num == 1 ? "word" : "words", + PluralForm.get(num, "word;words") + ); } // Not having enough plural forms defaults to the first form diff --git a/devtools/shared/tests/unit/test_pluralForm-makeGetter.js b/devtools/shared/tests/unit/test_pluralForm-makeGetter.js index 118b55f83914..395b3a9b2546 100644 --- a/devtools/shared/tests/unit/test_pluralForm-makeGetter.js +++ b/devtools/shared/tests/unit/test_pluralForm-makeGetter.js @@ -10,7 +10,7 @@ * development), English. */ -const {PluralForm} = require("devtools/shared/plural-form"); +const { PluralForm } = require("devtools/shared/plural-form"); function run_test() { // Irish is plural rule #11 diff --git a/devtools/shared/tests/unit/test_prettifyCSS.js b/devtools/shared/tests/unit/test_prettifyCSS.js index 16d111229571..eb1a2c08269d 100644 --- a/devtools/shared/tests/unit/test_prettifyCSS.js +++ b/devtools/shared/tests/unit/test_prettifyCSS.js @@ -5,30 +5,27 @@ "use strict"; -const {prettifyCSS} = require("devtools/shared/inspector/css-logic"); +const { prettifyCSS } = require("devtools/shared/inspector/css-logic"); const EXPAND_TAB = "devtools.editor.expandtab"; const TESTS_TAB_INDENT = [ - { name: "simple test. indent using tabs", + { + name: "simple test. indent using tabs", input: "div { font-family:'Arial Black', Arial, sans-serif; }", - expected: [ - "div {", - "\tfont-family:'Arial Black', Arial, sans-serif;", - "}", - ], + expected: ["div {", "\tfont-family:'Arial Black', Arial, sans-serif;", "}"], }, - { name: "whitespace before open brace. indent using tabs", + { + name: "whitespace before open brace. indent using tabs", input: "div{}", - expected: [ - "div {", - "}", - ], + expected: ["div {", "}"], }, - { name: "minified with trailing newline. indent using tabs", - input: "\nbody{background:white;}div{font-size:4em;color:red}span{color:green;}\n", + { + name: "minified with trailing newline. indent using tabs", + input: + "\nbody{background:white;}div{font-size:4em;color:red}span{color:green;}\n", expected: [ "body {", "\tbackground:white;", @@ -43,49 +40,36 @@ const TESTS_TAB_INDENT = [ ], }, - { name: "leading whitespace. indent using tabs", + { + name: "leading whitespace. indent using tabs", input: "\n div{color: red;}", - expected: [ - "div {", - "\tcolor: red;", - "}", - ], + expected: ["div {", "\tcolor: red;", "}"], }, - { name: "CSS with extra closing brace. indent using tabs", + { + name: "CSS with extra closing brace. indent using tabs", input: "body{margin:0}} div{color:red}", - expected: [ - "body {", - "\tmargin:0", - "}", - "}", - "div {", - "\tcolor:red", - "}", - ], + expected: ["body {", "\tmargin:0", "}", "}", "div {", "\tcolor:red", "}"], }, ]; const TESTS_SPACE_INDENT = [ - { name: "simple test. indent using spaces", + { + name: "simple test. indent using spaces", input: "div { font-family:'Arial Black', Arial, sans-serif; }", - expected: [ - "div {", - " font-family:'Arial Black', Arial, sans-serif;", - "}", - ], + expected: ["div {", " font-family:'Arial Black', Arial, sans-serif;", "}"], }, - { name: "whitespace before open brace. indent using spaces", + { + name: "whitespace before open brace. indent using spaces", input: "div{}", - expected: [ - "div {", - "}", - ], + expected: ["div {", "}"], }, - { name: "minified with trailing newline. indent using spaces", - input: "\nbody{background:white;}div{font-size:4em;color:red}span{color:green;}\n", + { + name: "minified with trailing newline. indent using spaces", + input: + "\nbody{background:white;}div{font-size:4em;color:red}span{color:green;}\n", expected: [ "body {", " background:white;", @@ -100,49 +84,35 @@ const TESTS_SPACE_INDENT = [ ], }, - { name: "leading whitespace. indent using spaces", + { + name: "leading whitespace. indent using spaces", input: "\n div{color: red;}", - expected: [ - "div {", - " color: red;", - "}", - ], + expected: ["div {", " color: red;", "}"], }, - { name: "CSS with extra closing brace. indent using spaces", + { + name: "CSS with extra closing brace. indent using spaces", input: "body{margin:0}} div{color:red}", - expected: [ - "body {", - " margin:0", - "}", - "}", - "div {", - " color:red", - "}", - ], + expected: ["body {", " margin:0", "}", "}", "div {", " color:red", "}"], }, - { name: "HTML comments with some whitespace padding", + { + name: "HTML comments with some whitespace padding", input: " \n\n\t \t\n", - expected: [ - "body {", - " color:red", - "}", - ], + expected: ["body {", " color:red", "}"], }, - { name: "HTML comments without whitespace padding", + { + name: "HTML comments without whitespace padding", input: "", - expected: [ - "body {", - " color:red", - "}", - ], + expected: ["body {", " color:red", "}"], }, - { name: "Breaking after commas in selectors", - input: "@media screen, print {div, span, input {color: red;}}" + - "div, div, input, pre, table {color: blue;}", + { + name: "Breaking after commas in selectors", + input: + "@media screen, print {div, span, input {color: red;}}" + + "div, div, input, pre, table {color: blue;}", expected: [ "@media screen, print {", " div,", @@ -161,16 +131,10 @@ const TESTS_SPACE_INDENT = [ ], }, - { name: "Multiline comment in CSS", + { + name: "Multiline comment in CSS", input: "/*\n * comment\n */\n#example{display:grid;}", - expected: [ - "/*", - " * comment", - " */", - "#example {", - " display:grid;", - "}", - ], + expected: ["/*", " * comment", " */", "#example {", " display:grid;", "}"], }, ]; @@ -185,8 +149,9 @@ function run_test() { const input = test.input.split("\n").join(prettifyCSS.LINE_SEPARATOR); const { result: output } = prettifyCSS(input); - const expected = test.expected.join(prettifyCSS.LINE_SEPARATOR) + - prettifyCSS.LINE_SEPARATOR; + const expected = + test.expected.join(prettifyCSS.LINE_SEPARATOR) + + prettifyCSS.LINE_SEPARATOR; equal(output, expected, test.name); } @@ -196,8 +161,9 @@ function run_test() { const input = test.input.split("\n").join(prettifyCSS.LINE_SEPARATOR); const { result: output } = prettifyCSS(input); - const expected = test.expected.join(prettifyCSS.LINE_SEPARATOR) + - prettifyCSS.LINE_SEPARATOR; + const expected = + test.expected.join(prettifyCSS.LINE_SEPARATOR) + + prettifyCSS.LINE_SEPARATOR; equal(output, expected, test.name); } Services.prefs.clearUserPref(EXPAND_TAB); diff --git a/devtools/shared/tests/unit/test_require.js b/devtools/shared/tests/unit/test_require.js index 5b1b0e48003a..28d0195ff824 100644 --- a/devtools/shared/tests/unit/test_require.js +++ b/devtools/shared/tests/unit/test_require.js @@ -28,8 +28,10 @@ function testInvalidModule() { Assert.ok(false, "require should throw"); } catch (error) { Assert.equal(error.message, "Module `foo` is not found at foo.js"); - Assert.ok(error.stack.includes("testInvalidModule"), - "Exception's stack includes the test function"); + Assert.ok( + error.stack.includes("testInvalidModule"), + "Exception's stack includes the test function" + ); } try { @@ -38,9 +40,14 @@ function testInvalidModule() { require("devtools/foo"); Assert.ok(false, "require should throw"); } catch (error) { - Assert.equal(error.message, "Module `devtools/foo` is not found at resource://devtools/foo.js"); - Assert.ok(error.stack.includes("testInvalidModule"), - "Exception's stack includes the test function"); + Assert.equal( + error.message, + "Module `devtools/foo` is not found at resource://devtools/foo.js" + ); + Assert.ok( + error.stack.includes("testInvalidModule"), + "Exception's stack includes the test function" + ); } } @@ -54,23 +61,33 @@ function testThrowingModule() { Assert.ok(false, "require should throw"); } catch (error) { Assert.equal(error.message, "my-exception"); - Assert.ok(error.stack.includes("testThrowingModule"), - "Exception's stack includes the test function"); - Assert.ok(error.stack.includes("throwingMethod"), - "Exception's stack also includes the module function that throws"); + Assert.ok( + error.stack.includes("testThrowingModule"), + "Exception's stack includes the test function" + ); + Assert.ok( + error.stack.includes("throwingMethod"), + "Exception's stack also includes the module function that throws" + ); } try { // Require a test module that is throwing a string require("xpcshell-test/throwing-module-2.js"); Assert.ok(false, "require should throw"); } catch (error) { - Assert.equal(error.message, + Assert.equal( + error.message, "Error while loading module `xpcshell-test/throwing-module-2.js` at " + - "resource://test/throwing-module-2.js:\nmy-exception"); - Assert.ok(error.stack.includes("testThrowingModule"), - "Exception's stack includes the test function"); - Assert.ok(!error.stack.includes("throwingMethod"), - "Exception's stack also includes the module function that throws"); + "resource://test/throwing-module-2.js:\nmy-exception" + ); + Assert.ok( + error.stack.includes("testThrowingModule"), + "Exception's stack includes the test function" + ); + Assert.ok( + !error.stack.includes("throwingMethod"), + "Exception's stack also includes the module function that throws" + ); } } diff --git a/devtools/shared/tests/unit/test_require_lazy.js b/devtools/shared/tests/unit/test_require_lazy.js index 50ea8a2311f7..7299dacec9e1 100644 --- a/devtools/shared/tests/unit/test_require_lazy.js +++ b/devtools/shared/tests/unit/test_require_lazy.js @@ -3,7 +3,9 @@ "use strict"; -const { devtools } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); +const { devtools } = ChromeUtils.import( + "resource://devtools/shared/Loader.jsm" +); // Test devtools.lazyRequireGetter function run_test() { diff --git a/devtools/shared/tests/unit/test_require_raw.js b/devtools/shared/tests/unit/test_require_raw.js index cd60e4441cf6..75031ec33d9c 100644 --- a/devtools/shared/tests/unit/test_require_raw.js +++ b/devtools/shared/tests/unit/test_require_raw.js @@ -13,9 +13,14 @@ function run_test() { ok(variableFileContents.length > 0, "raw browserRequire worked"); const propertiesFileContents = require("raw!devtools/client/locales/shared.properties"); - ok(propertiesFileContents.length > 0, "unprefixed properties raw require worked"); + ok( + propertiesFileContents.length > 0, + "unprefixed properties raw require worked" + ); - const chromePropertiesFileContents = - require("raw!chrome://devtools/locale/shared.properties"); - ok(chromePropertiesFileContents.length > 0, "prefixed properties raw require worked"); + const chromePropertiesFileContents = require("raw!chrome://devtools/locale/shared.properties"); + ok( + chromePropertiesFileContents.length > 0, + "prefixed properties raw require worked" + ); } diff --git a/devtools/shared/tests/unit/test_sprintfjs.js b/devtools/shared/tests/unit/test_sprintfjs.js index e21693807662..917da920c3df 100644 --- a/devtools/shared/tests/unit/test_sprintfjs.js +++ b/devtools/shared/tests/unit/test_sprintfjs.js @@ -10,7 +10,7 @@ * Initially copied from unit tests at https://github.com/alexei/sprintf.js */ -const {sprintf} = require("devtools/shared/sprintfjs/sprintf"); +const { sprintf } = require("devtools/shared/sprintfjs/sprintf"); const PI = 3.141592653589793; function run_test() { @@ -22,8 +22,8 @@ function run_test() { equal("2", sprintf("%i", 2)); equal("2", sprintf("%d", "2")); equal("2", sprintf("%i", "2")); - equal("{\"foo\":\"bar\"}", sprintf("%j", {foo: "bar"})); - equal("[\"foo\",\"bar\"]", sprintf("%j", ["foo", "bar"])); + equal('{"foo":"bar"}', sprintf("%j", { foo: "bar" })); + equal('["foo","bar"]', sprintf("%j", ["foo", "bar"])); equal("2e+0", sprintf("%e", 2)); equal("2", sprintf("%u", 2)); equal("4294967294", sprintf("%u", -2)); @@ -33,9 +33,11 @@ function run_test() { equal("%s", sprintf("%s", "%s")); equal("ff", sprintf("%x", 255)); equal("FF", sprintf("%X", 255)); - equal("Polly wants a cracker", - sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants")); - equal("Hello world!", sprintf("Hello %(who)s!", {who: "world"})); + equal( + "Polly wants a cracker", + sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") + ); + equal("Hello world!", sprintf("Hello %(who)s!", { who: "world" })); equal("true", sprintf("%t", true)); equal("t", sprintf("%.1t", true)); equal("true", sprintf("%t", "true")); @@ -52,7 +54,7 @@ function run_test() { equal("string", sprintf("%T", "This is a string")); equal("function", sprintf("%T", Math.log)); equal("array", sprintf("%T", [1, 2, 3])); - equal("object", sprintf("%T", {foo: "bar"})); + equal("object", sprintf("%T", { foo: "bar" })); equal("regexp", sprintf("%T", /<("[^"]*"|"[^"]*"|[^"">])*>/)); @@ -60,9 +62,11 @@ function run_test() { equal("42", sprintf("%v", 42)); equal("This is a string", sprintf("%v", "This is a string")); equal("1,2,3", sprintf("%v", [1, 2, 3])); - equal("[object Object]", sprintf("%v", {foo: "bar"})); - equal("/<(\"[^\"]*\"|'[^']*'|[^'\">])*>/", - sprintf("%v", /<("[^"]*"|'[^']*'|[^'">])*>/)); + equal("[object Object]", sprintf("%v", { foo: "bar" })); + equal( + "/<(\"[^\"]*\"|'[^']*'|[^'\">])*>/", + sprintf("%v", /<("[^"]*"|'[^']*'|[^'">])*>/) + ); // sign equal("2", sprintf("%d", 2)); @@ -99,15 +103,18 @@ function run_test() { equal("1234", sprintf("%02u", 1234)); equal(" -10.235", sprintf("%8.3f", -10.23456)); equal("-12.34 xxx", sprintf("%f %s", -12.34, "xxx")); - equal("{\n \"foo\": \"bar\"\n}", sprintf("%2j", {foo: "bar"})); - equal("[\n \"foo\",\n \"bar\"\n]", sprintf("%2j", ["foo", "bar"])); + equal('{\n "foo": "bar"\n}', sprintf("%2j", { foo: "bar" })); + equal('[\n "foo",\n "bar"\n]', sprintf("%2j", ["foo", "bar"])); // precision equal("2.3", sprintf("%.1f", 2.345)); equal("xxxxx", sprintf("%5.5s", "xxxxxx")); equal(" x", sprintf("%5.1s", "xxxxxx")); - equal("foobar", sprintf("%s", function() { - return "foobar"; - })); + equal( + "foobar", + sprintf("%s", function() { + return "foobar"; + }) + ); } diff --git a/devtools/shared/tests/unit/test_stack.js b/devtools/shared/tests/unit/test_stack.js index 60891cd9f7d8..741ddface0c0 100644 --- a/devtools/shared/tests/unit/test_stack.js +++ b/devtools/shared/tests/unit/test_stack.js @@ -9,7 +9,7 @@ function run_test() { const loader = new DevToolsLoader(); const require = loader.require; - const {StackFrameCache} = require("devtools/server/actors/utils/stack"); + const { StackFrameCache } = require("devtools/server/actors/utils/stack"); const cache = new StackFrameCache(); cache.initFrames(); diff --git a/devtools/shared/transport/child-transport.js b/devtools/shared/transport/child-transport.js index 383a1ef36762..08a78e8429c2 100644 --- a/devtools/shared/transport/child-transport.js +++ b/devtools/shared/transport/child-transport.js @@ -62,7 +62,7 @@ ChildDebuggerTransport.prototype = { this.hooks.onClosed(); }, - receiveMessage: function({data}) { + receiveMessage: function({ data }) { this.hooks.onPacket(data); }, @@ -97,7 +97,8 @@ ChildDebuggerTransport.prototype = { send: function(packet) { if (flags.testing && !this._canBeSerialized(packet)) { const attributes = this.pathToUnserializable(packet); - let msg = "Following packet can't be serialized: " + JSON.stringify(packet); + let msg = + "Following packet can't be serialized: " + JSON.stringify(packet); msg += "\nBecause of attributes: " + attributes.join(", ") + "\n"; msg += "Did you pass a function or an XPCOM object in it?"; throw new Error(msg); diff --git a/devtools/shared/transport/local-transport.js b/devtools/shared/transport/local-transport.js index 382b83e0b82d..5d29313af8c7 100644 --- a/devtools/shared/transport/local-transport.js +++ b/devtools/shared/transport/local-transport.js @@ -55,15 +55,22 @@ LocalDebuggerTransport.prototype = { this._deepFreeze(packet); const other = this.other; if (other) { - DevToolsUtils.executeSoon(DevToolsUtils.makeInfallible(() => { - // Avoid the cost of JSON.stringify() when logging is disabled. - if (flags.wantLogging) { - dumpn("Received packet " + serial + ": " + JSON.stringify(packet, null, 2)); - } - if (other.hooks) { - other.hooks.onPacket(packet); - } - }, "LocalDebuggerTransport instance's this.other.hooks.onPacket")); + DevToolsUtils.executeSoon( + DevToolsUtils.makeInfallible(() => { + // Avoid the cost of JSON.stringify() when logging is disabled. + if (flags.wantLogging) { + dumpn( + "Received packet " + + serial + + ": " + + JSON.stringify(packet, null, 2) + ); + } + if (other.hooks) { + other.hooks.onPacket(packet); + } + }, "LocalDebuggerTransport instance's this.other.hooks.onPacket") + ); } }, @@ -76,7 +83,7 @@ LocalDebuggerTransport.prototype = { * others temporarily. Instead, we can just make a single use pipe and be * done with it. */ - startBulkSend: function({actor, type, length}) { + startBulkSend: function({ actor, type, length }) { const serial = this._serial.count++; dumpn("Sent bulk packet " + serial + " for actor " + actor); @@ -87,53 +94,63 @@ LocalDebuggerTransport.prototype = { const pipe = new Pipe(true, true, 0, 0, null); - DevToolsUtils.executeSoon(DevToolsUtils.makeInfallible(() => { - dumpn("Received bulk packet " + serial); - if (!this.other.hooks) { - return; - } + DevToolsUtils.executeSoon( + DevToolsUtils.makeInfallible(() => { + dumpn("Received bulk packet " + serial); + if (!this.other.hooks) { + return; + } - // Receiver - new Promise((receiverResolve) => { - const packet = { - actor: actor, - type: type, - length: length, - copyTo: (output) => { - const copying = - StreamUtils.copyStream(pipe.inputStream, output, length); - receiverResolve(copying); - return copying; - }, - stream: pipe.inputStream, - done: receiverResolve, - }; + // Receiver + new Promise(receiverResolve => { + const packet = { + actor: actor, + type: type, + length: length, + copyTo: output => { + const copying = StreamUtils.copyStream( + pipe.inputStream, + output, + length + ); + receiverResolve(copying); + return copying; + }, + stream: pipe.inputStream, + done: receiverResolve, + }; - this.other.hooks.onBulkPacket(packet); - }) - // Await the result of reading from the stream - .then(() => pipe.inputStream.close(), this.close); - }, "LocalDebuggerTransport instance's this.other.hooks.onBulkPacket")); + this.other.hooks.onBulkPacket(packet); + }) + // Await the result of reading from the stream + .then(() => pipe.inputStream.close(), this.close); + }, "LocalDebuggerTransport instance's this.other.hooks.onBulkPacket") + ); // Sender - return new Promise((senderResolve) => { + return new Promise(senderResolve => { // The remote transport is not capable of resolving immediately here, so we // shouldn't be able to either. DevToolsUtils.executeSoon(() => { - return new Promise((copyResolve) => { - senderResolve({ - copyFrom: (input) => { - const copying = - StreamUtils.copyStream(input, pipe.outputStream, length); - copyResolve(copying); - return copying; - }, - stream: pipe.outputStream, - done: copyResolve, - }); - }) - // Await the result of writing to the stream - .then(() => pipe.outputStream.close(), this.close); + return ( + new Promise(copyResolve => { + senderResolve({ + copyFrom: input => { + const copying = StreamUtils.copyStream( + input, + pipe.outputStream, + length + ); + copyResolve(copying); + return copying; + }, + stream: pipe.outputStream, + done: copyResolve, + }); + }) + // Await the result of writing to the stream + .then(() => pipe.outputStream.close(), this.close) + ); }); }); }, @@ -174,8 +191,11 @@ LocalDebuggerTransport.prototype = { // already frozen. Note that this might leave an unfrozen reference // somewhere in the object if there is an already frozen object containing // an unfrozen object. - if (object.hasOwnProperty(prop) && typeof object === "object" && - !Object.isFrozen(object)) { + if ( + object.hasOwnProperty(prop) && + typeof object === "object" && + !Object.isFrozen(object) + ) { this._deepFreeze(object[prop]); } } diff --git a/devtools/shared/transport/packets.js b/devtools/shared/transport/packets.js index f1e8f56c8ed4..1b14e60e06bf 100644 --- a/devtools/shared/transport/packets.js +++ b/devtools/shared/transport/packets.js @@ -32,8 +32,9 @@ const StreamUtils = require("devtools/shared/transport/stream-utils"); DevToolsUtils.defineLazyGetter(this, "unicodeConverter", () => { // eslint-disable-next-line no-shadow - const unicodeConverter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Ci.nsIScriptableUnicodeConverter); + const unicodeConverter = Cc[ + "@mozilla.org/intl/scriptableunicodeconverter" + ].createInstance(Ci.nsIScriptableUnicodeConverter); unicodeConverter.charset = "UTF-8"; return unicodeConverter; }); @@ -63,20 +64,25 @@ function Packet(transport) { * The parsed packet of the matching type, or null if no types matched. */ Packet.fromHeader = function(header, transport) { - return JSONPacket.fromHeader(header, transport) || - BulkPacket.fromHeader(header, transport); + return ( + JSONPacket.fromHeader(header, transport) || + BulkPacket.fromHeader(header, transport) + ); }; Packet.prototype = { - get length() { return this._length; }, set length(length) { if (length > PACKET_LENGTH_MAX) { - throw Error("Packet length " + length + " exceeds the max length of " + - PACKET_LENGTH_MAX); + throw Error( + "Packet length " + + length + + " exceeds the max length of " + + PACKET_LENGTH_MAX + ); } this._length = length; }, @@ -84,7 +90,6 @@ Packet.prototype = { destroy: function() { this._transport = null; }, - }; exports.Packet = Packet; @@ -166,8 +171,14 @@ JSONPacket.prototype.read = function(stream, scriptableStream) { json = unicodeConverter.ConvertToUnicode(json); this._object = JSON.parse(json); } catch (e) { - const msg = "Error parsing incoming packet: " + json + " (" + e + - " - " + e.stack + ")"; + const msg = + "Error parsing incoming packet: " + + json + + " (" + + e + + " - " + + e.stack + + ")"; console.error(msg); dumpn(msg); return; @@ -178,11 +189,19 @@ JSONPacket.prototype.read = function(stream, scriptableStream) { JSONPacket.prototype._readData = function(stream, scriptableStream) { if (flags.wantVerbose) { - dumpv("Reading JSON data: _l: " + this.length + " dL: " + - this._data.length + " sA: " + stream.available()); + dumpv( + "Reading JSON data: _l: " + + this.length + + " dL: " + + this._data.length + + " sA: " + + stream.available() + ); } - const bytesToRead = Math.min(this.length - this._data.length, - stream.available()); + const bytesToRead = Math.min( + this.length - this._data.length, + stream.available() + ); this._data += scriptableStream.readBytes(bytesToRead); this._done = this._data.length === this.length; }; @@ -231,7 +250,7 @@ function BulkPacket(transport) { Packet.call(this, transport); this._done = false; let _resolve; - this._readyForWriting = new Promise((resolve) => { + this._readyForWriting = new Promise(resolve => { _resolve = resolve; }); this._readyForWriting.resolve = _resolve; @@ -274,12 +293,12 @@ BulkPacket.prototype.read = function(stream) { // Temporarily pause monitoring of the input stream this._transport.pauseIncoming(); - new Promise((resolve) => { + new Promise(resolve => { this._transport._onBulkReadReady({ actor: this.actor, type: this.type, length: this.length, - copyTo: (output) => { + copyTo: output => { dumpv("CT length: " + this.length); const copying = StreamUtils.copyStream(stream, output, this.length); resolve(copying); @@ -289,8 +308,7 @@ BulkPacket.prototype.read = function(stream) { done: resolve, }); // Await the result of reading from the stream - }) - .then(() => { + }).then(() => { dumpv("onReadDone called, ending bulk mode"); this._done = true; this._transport.resumeIncoming(); @@ -308,15 +326,17 @@ BulkPacket.prototype.write = function(stream) { if (this._outgoingHeader === undefined) { dumpv("Serializing bulk packet header"); // Format the serialized packet header to a buffer - this._outgoingHeader = "bulk " + this.actor + " " + this.type + " " + - this.length + ":"; + this._outgoingHeader = + "bulk " + this.actor + " " + this.type + " " + this.length + ":"; } // Write the header, or whatever's left of it to write. if (this._outgoingHeader.length) { dumpv("Writing bulk packet header"); - const written = stream.write(this._outgoingHeader, - this._outgoingHeader.length); + const written = stream.write( + this._outgoingHeader, + this._outgoingHeader.length + ); this._outgoingHeader = this._outgoingHeader.slice(written); return; } @@ -326,9 +346,9 @@ BulkPacket.prototype.write = function(stream) { // Temporarily pause the monitoring of the output stream this._transport.pauseOutgoing(); - new Promise((resolve) => { + new Promise(resolve => { this._readyForWriting.resolve({ - copyFrom: (input) => { + copyFrom: input => { dumpv("CF length: " + this.length); const copying = StreamUtils.copyStream(input, stream, this.length); resolve(copying); @@ -338,8 +358,7 @@ BulkPacket.prototype.write = function(stream) { done: resolve, }); // Await the result of writing to the stream - }) - .then(() => { + }).then(() => { dumpv("onWriteDone called, ending bulk mode"); this._done = true; this._transport.resumeOutgoing(); diff --git a/devtools/shared/transport/stream-utils.js b/devtools/shared/transport/stream-utils.js index 8169b99b7938..dfda16c3cfdf 100644 --- a/devtools/shared/transport/stream-utils.js +++ b/devtools/shared/transport/stream-utils.js @@ -15,8 +15,11 @@ DevToolsUtils.defineLazyGetter(this, "IOUtil", () => { }); DevToolsUtils.defineLazyGetter(this, "ScriptableInputStream", () => { - return CC("@mozilla.org/scriptableinputstream;1", - "nsIScriptableInputStream", "init"); + return CC( + "@mozilla.org/scriptableinputstream;1", + "nsIScriptableInputStream", + "init" + ); }); const BUFFER_SIZE = 0x8000; @@ -68,8 +71,9 @@ function StreamCopier(input, output, length) { if (IOUtil.outputStreamIsBuffered(output)) { this.output = output; } else { - this.output = Cc["@mozilla.org/network/buffered-output-stream;1"] - .createInstance(Ci.nsIBufferedOutputStream); + this.output = Cc[ + "@mozilla.org/network/buffered-output-stream;1" + ].createInstance(Ci.nsIBufferedOutputStream); this.output.init(output, BUFFER_SIZE); } this._length = length; @@ -101,7 +105,6 @@ function StreamCopier(input, output, length) { StreamCopier._nextId = 0; StreamCopier.prototype = { - copy: function() { // Dispatch to the next tick so that it's possible to attach a progress // event listener, even for extremely fast copies (like when testing). @@ -134,8 +137,7 @@ StreamCopier.prototype = { } this._amountLeft -= bytesCopied; - this._debug("Copied: " + bytesCopied + - ", Left: " + this._amountLeft); + this._debug("Copied: " + bytesCopied + ", Left: " + this._amountLeft); this._emitProgress(); if (this._amountLeft === 0) { @@ -159,8 +161,10 @@ StreamCopier.prototype = { try { this.output.flush(); } catch (e) { - if (e.result == Cr.NS_BASE_STREAM_WOULD_BLOCK || - e.result == Cr.NS_ERROR_FAILURE) { + if ( + e.result == Cr.NS_BASE_STREAM_WOULD_BLOCK || + e.result == Cr.NS_ERROR_FAILURE + ) { this._debug("Flush would block, will retry"); this._streamReadyCallback = this._flush; this._debug("Waiting for output stream"); @@ -195,7 +199,6 @@ StreamCopier.prototype = { // understand when several copiers are running simultaneously dumpv("Copier: " + this._id + " " + msg); }, - }; /** @@ -217,8 +220,9 @@ StreamCopier.prototype = { * end with it. */ function delimitedRead(stream, delimiter, count) { - dumpv("Starting delimited read for " + delimiter + " up to " + - count + " bytes"); + dumpv( + "Starting delimited read for " + delimiter + " up to " + count + " bytes" + ); let scriptableStream; if (stream instanceof Ci.nsIScriptableInputStream) { diff --git a/devtools/shared/transport/tests/unit/head_dbg.js b/devtools/shared/transport/tests/unit/head_dbg.js index b21842c86b85..38343e6048a0 100644 --- a/devtools/shared/transport/tests/unit/head_dbg.js +++ b/devtools/shared/transport/tests/unit/head_dbg.js @@ -9,8 +9,7 @@ var CC = Components.Constructor; -const { require } = - ChromeUtils.import("resource://devtools/shared/Loader.jsm"); +const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); const { NetUtil } = require("resource://gre/modules/NetUtil.jsm"); const defer = require("devtools/shared/defer"); @@ -25,7 +24,9 @@ const Services = require("Services"); // Enable remote debugging for the relevant tests. Services.prefs.setBoolPref("devtools.debugger.remote-enabled", true); -const { ActorRegistry } = require("devtools/server/actors/utils/actor-registry"); +const { + ActorRegistry, +} = require("devtools/server/actors/utils/actor-registry"); const { DebuggerServer } = require("devtools/server/main"); const { DebuggerClient } = require("devtools/shared/client/debugger-client"); const { SocketListener } = require("devtools/shared/security/socket"); @@ -60,9 +61,16 @@ var listener = { // If we've been given an nsIScriptError, then we can print out // something nicely formatted, for tools like Emacs to pick up. message.QueryInterface(Ci.nsIScriptError); - dump(message.sourceName + ":" + message.lineNumber + ": " + - scriptErrorFlagsToKind(message.flags) + ": " + - message.errorMessage + "\n"); + dump( + message.sourceName + + ":" + + message.lineNumber + + ": " + + scriptErrorFlagsToKind(message.flags) + + ": " + + message.errorMessage + + "\n" + ); string = message.errorMessage; } catch (x) { // Be a little paranoid with message, as the whole goal here is to lose @@ -116,8 +124,9 @@ function getTestTempFile(fileName, allowMissing) { function writeTestTempFile(fileName, content) { const file = getTestTempFile(fileName, true); - const stream = Cc["@mozilla.org/network/file-output-stream;1"] - .createInstance(Ci.nsIFileOutputStream); + const stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance( + Ci.nsIFileOutputStream + ); stream.init(file, -1, -1, 0); try { do { diff --git a/devtools/shared/transport/tests/unit/test_bulk_error.js b/devtools/shared/transport/tests/unit/test_bulk_error.js index d7b55d6b7167..e86eb540c9bc 100644 --- a/devtools/shared/transport/tests/unit/test_bulk_error.js +++ b/devtools/shared/transport/tests/unit/test_bulk_error.js @@ -21,28 +21,29 @@ function run_test() { function TestBulkActor() {} TestBulkActor.prototype = { - actorPrefix: "testBulk", - jsonReply: function({length, reader, reply, done}) { + jsonReply: function({ length, reader, reply, done }) { Assert.equal(length, really_long().length); return { allDone: true, }; }, - }; TestBulkActor.prototype.requestTypes = { - "jsonReply": TestBulkActor.prototype.jsonReply, + jsonReply: TestBulkActor.prototype.jsonReply, }; function add_test_bulk_actor() { - ActorRegistry.addGlobalActor({ - constructorName: "TestBulkActor", - constructorFun: TestBulkActor, - }, "testBulk"); + ActorRegistry.addGlobalActor( + { + constructorName: "TestBulkActor", + constructorFun: TestBulkActor, + }, + "testBulk" + ); } /** * Tests ***/ @@ -51,15 +52,19 @@ var test_string_error = async function(transportFactory, onReady) { const transport = await transportFactory(); const client = new DebuggerClient(transport); - return client.connect().then(([app, traits]) => { - Assert.equal(traits.bulk, true); - return client.mainRoot.rootForm; - }).then(response => { - return onReady(client, response); - }).then(() => { - client.close(); - transport.close(); - }); + return client + .connect() + .then(([app, traits]) => { + Assert.equal(traits.bulk, true); + return client.mainRoot.rootForm; + }) + .then(response => { + return onReady(client, response); + }) + .then(() => { + client.close(); + transport.close(); + }); }; /** * Reply Types ***/ @@ -74,10 +79,11 @@ function json_reply(client, response) { }); // Send bulk data to server - return new Promise((resolve) => { - request.on("bulk-send-ready", ({writer, done}) => { - const input = Cc["@mozilla.org/io/string-input-stream;1"] - .createInstance(Ci.nsIStringInputStream); + return new Promise(resolve => { + request.on("bulk-send-ready", ({ writer, done }) => { + const input = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); input.setData(reallyLong, reallyLong.length); try { writer.copyFrom(input, () => { diff --git a/devtools/shared/transport/tests/unit/test_client_server_bulk.js b/devtools/shared/transport/tests/unit/test_client_server_bulk.js index 0dfcf4552d29..f77fb84d026e 100644 --- a/devtools/shared/transport/tests/unit/test_client_server_bulk.js +++ b/devtools/shared/transport/tests/unit/test_client_server_bulk.js @@ -30,45 +30,51 @@ function TestBulkActor(conn) { } TestBulkActor.prototype = { - actorPrefix: "testBulk", - bulkEcho: function({actor, type, length, copyTo}) { + bulkEcho: function({ actor, type, length, copyTo }) { Assert.equal(length, really_long().length); - this.conn.startBulkSend({ - actor: actor, - type: type, - length: length, - }).then(({copyFrom}) => { - // We'll just echo back the same thing - const pipe = new Pipe(true, true, 0, 0, null); - copyTo(pipe.outputStream).then(() => { - pipe.outputStream.close(); - }); - copyFrom(pipe.inputStream).then(() => { - pipe.inputStream.close(); - }); - }); - }, - - bulkReply: function({to, type}) { - this.conn.startBulkSend({ - actor: to, - type: type, - length: really_long().length, - }).then(({copyFrom}) => { - NetUtil.asyncFetch({ - uri: NetUtil.newURI(getTestTempFile("bulk-input")), - loadUsingSystemPrincipal: true, - }, input => { - copyFrom(input).then(() => { - input.close(); + this.conn + .startBulkSend({ + actor: actor, + type: type, + length: length, + }) + .then(({ copyFrom }) => { + // We'll just echo back the same thing + const pipe = new Pipe(true, true, 0, 0, null); + copyTo(pipe.outputStream).then(() => { + pipe.outputStream.close(); + }); + copyFrom(pipe.inputStream).then(() => { + pipe.inputStream.close(); }); }); - }); }, - jsonReply: function({length, copyTo}) { + bulkReply: function({ to, type }) { + this.conn + .startBulkSend({ + actor: to, + type: type, + length: really_long().length, + }) + .then(({ copyFrom }) => { + NetUtil.asyncFetch( + { + uri: NetUtil.newURI(getTestTempFile("bulk-input")), + loadUsingSystemPrincipal: true, + }, + input => { + copyFrom(input).then(() => { + input.close(); + }); + } + ); + }); + }, + + jsonReply: function({ length, copyTo }) { Assert.equal(length, really_long().length); const outputFile = getTestTempFile("bulk-output", true); @@ -76,37 +82,40 @@ TestBulkActor.prototype = { const output = FileUtils.openSafeFileOutputStream(outputFile); - return copyTo(output).then(() => { - FileUtils.closeSafeFileOutputStream(output); - return verify_files(); - }).then(() => { - return { allDone: true }; - }, do_throw); + return copyTo(output) + .then(() => { + FileUtils.closeSafeFileOutputStream(output); + return verify_files(); + }) + .then(() => { + return { allDone: true }; + }, do_throw); }, - }; TestBulkActor.prototype.requestTypes = { - "bulkEcho": TestBulkActor.prototype.bulkEcho, - "bulkReply": TestBulkActor.prototype.bulkReply, - "jsonReply": TestBulkActor.prototype.jsonReply, + bulkEcho: TestBulkActor.prototype.bulkEcho, + bulkReply: TestBulkActor.prototype.bulkReply, + jsonReply: TestBulkActor.prototype.jsonReply, }; function add_test_bulk_actor() { - ActorRegistry.addGlobalActor({ - constructorName: "TestBulkActor", - constructorFun: TestBulkActor, - }, "testBulk"); + ActorRegistry.addGlobalActor( + { + constructorName: "TestBulkActor", + constructorFun: TestBulkActor, + }, + "testBulk" + ); } /** * Reply Handlers ***/ var replyHandlers = { - json: function(request) { // Receive JSON reply from server - return new Promise((resolve) => { - request.on("json-reply", (reply) => { + return new Promise(resolve => { + request.on("json-reply", reply => { Assert.ok(reply.allDone); resolve(); }); @@ -115,8 +124,8 @@ var replyHandlers = { bulk: function(request) { // Receive bulk data reply from server - return new Promise((resolve) => { - request.on("bulk-reply", ({length, copyTo}) => { + return new Promise(resolve => { + request.on("bulk-reply", ({ length, copyTo }) => { Assert.equal(length, really_long().length); const outputFile = getTestTempFile("bulk-output", true); @@ -131,28 +140,31 @@ var replyHandlers = { }); }); }, - }; /** * Tests ***/ -var test_bulk_request_cs = async function(transportFactory, actorType, replyType) { +var test_bulk_request_cs = async function( + transportFactory, + actorType, + replyType +) { // Ensure test files are not present from a failed run cleanup_files(); writeTestTempFile("bulk-input", really_long()); let clientResolve; - const clientDeferred = new Promise((resolve) => { + const clientDeferred = new Promise(resolve => { clientResolve = resolve; }); let serverResolve; - const serverDeferred = new Promise((resolve) => { + const serverDeferred = new Promise(resolve => { serverResolve = resolve; }); let bulkCopyResolve; - const bulkCopyDeferred = new Promise((resolve) => { + const bulkCopyDeferred = new Promise(resolve => { bulkCopyResolve = resolve; }); @@ -164,34 +176,39 @@ var test_bulk_request_cs = async function(transportFactory, actorType, replyType client.mainRoot.rootForm.then(clientResolve); }); - function bulkSendReadyCallback({copyFrom}) { - NetUtil.asyncFetch({ - uri: NetUtil.newURI(getTestTempFile("bulk-input")), - loadUsingSystemPrincipal: true, - }, input => { - copyFrom(input).then(() => { - input.close(); - bulkCopyResolve(); - }); - }); + function bulkSendReadyCallback({ copyFrom }) { + NetUtil.asyncFetch( + { + uri: NetUtil.newURI(getTestTempFile("bulk-input")), + loadUsingSystemPrincipal: true, + }, + input => { + copyFrom(input).then(() => { + input.close(); + bulkCopyResolve(); + }); + } + ); } - clientDeferred.then(response => { - const request = client.startBulkRequest({ - actor: response.testBulk, - type: actorType, - length: really_long().length, - }); + clientDeferred + .then(response => { + const request = client.startBulkRequest({ + actor: response.testBulk, + type: actorType, + length: really_long().length, + }); - // Send bulk data to server - request.on("bulk-send-ready", bulkSendReadyCallback); + // Send bulk data to server + request.on("bulk-send-ready", bulkSendReadyCallback); - // Set up reply handling for this type - replyHandlers[replyType](request).then(() => { - client.close(); - transport.close(); - }); - }).catch(do_throw); + // Set up reply handling for this type + replyHandlers[replyType](request).then(() => { + client.close(); + transport.close(); + }); + }) + .catch(do_throw); DebuggerServer.on("connectionchange", type => { if (type === "closed") { @@ -199,25 +216,25 @@ var test_bulk_request_cs = async function(transportFactory, actorType, replyType } }); - return Promise.all([ - clientDeferred, - bulkCopyDeferred, - serverDeferred, - ]); + return Promise.all([clientDeferred, bulkCopyDeferred, serverDeferred]); }; -var test_json_request_cs = async function(transportFactory, actorType, replyType) { +var test_json_request_cs = async function( + transportFactory, + actorType, + replyType +) { // Ensure test files are not present from a failed run cleanup_files(); writeTestTempFile("bulk-input", really_long()); let clientResolve; - const clientDeferred = new Promise((resolve) => { + const clientDeferred = new Promise(resolve => { clientResolve = resolve; }); let serverResolve; - const serverDeferred = new Promise((resolve) => { + const serverDeferred = new Promise(resolve => { serverResolve = resolve; }); @@ -229,18 +246,20 @@ var test_json_request_cs = async function(transportFactory, actorType, replyType client.mainRoot.rootForm.then(clientResolve); }); - clientDeferred.then(response => { - const request = client.request({ - to: response.testBulk, - type: actorType, - }); + clientDeferred + .then(response => { + const request = client.request({ + to: response.testBulk, + type: actorType, + }); - // Set up reply handling for this type - replyHandlers[replyType](request).then(() => { - client.close(); - transport.close(); - }); - }).catch(do_throw); + // Set up reply handling for this type + replyHandlers[replyType](request).then(() => { + client.close(); + transport.close(); + }); + }) + .catch(do_throw); DebuggerServer.on("connectionchange", type => { if (type === "closed") { @@ -248,10 +267,7 @@ var test_json_request_cs = async function(transportFactory, actorType, replyType } }); - return Promise.all([ - clientDeferred, - serverDeferred, - ]); + return Promise.all([clientDeferred, serverDeferred]); }; /** * Test Utils ***/ @@ -266,17 +282,23 @@ function verify_files() { Assert.equal(outputFile.fileSize, reallyLong.length); // Ensure output file contents actually match - return new Promise((resolve) => { - NetUtil.asyncFetch({ - uri: NetUtil.newURI(getTestTempFile("bulk-output")), - loadUsingSystemPrincipal: true, - }, input => { - const outputData = NetUtil.readInputStreamToString(input, reallyLong.length); + return new Promise(resolve => { + NetUtil.asyncFetch( + { + uri: NetUtil.newURI(getTestTempFile("bulk-output")), + loadUsingSystemPrincipal: true, + }, + input => { + const outputData = NetUtil.readInputStreamToString( + input, + reallyLong.length + ); // Avoid do_check_eq here so we don't log the contents - Assert.ok(outputData === reallyLong); - input.close(); - resolve(); - }); + Assert.ok(outputData === reallyLong); + input.close(); + resolve(); + } + ); }).then(cleanup_files); } diff --git a/devtools/shared/transport/tests/unit/test_dbgsocket.js b/devtools/shared/transport/tests/unit/test_dbgsocket.js index 0dd629496dd9..a21a134bd761 100644 --- a/devtools/shared/transport/tests/unit/test_dbgsocket.js +++ b/devtools/shared/transport/tests/unit/test_dbgsocket.js @@ -53,19 +53,21 @@ async function test_socket_conn() { Assert.equal(settings.port, gPort); const onDebuggerConnectionClosed = DebuggerServer.once("connectionchange"); - await new Promise((resolve) => { + await new Promise(resolve => { transport.hooks = { onPacket: function(packet) { - this.onPacket = function({unicode}) { + this.onPacket = function({ unicode }) { Assert.equal(unicode, unicodeString); transport.close(); }; // Verify that things work correctly when bigger than the output // transport buffers and when transporting unicode... - transport.send({to: "root", - type: "echo", - reallylong: really_long(), - unicode: unicodeString}); + transport.send({ + to: "root", + type: "echo", + reallylong: really_long(), + unicode: unicodeString, + }); Assert.equal(packet.from, "root"); }, onClosed: function(status) { @@ -96,8 +98,10 @@ async function test_socket_shutdown() { port: gPort, }); } catch (e) { - if (e.result == Cr.NS_ERROR_CONNECTION_REFUSED || - e.result == Cr.NS_ERROR_NET_TIMEOUT) { + if ( + e.result == Cr.NS_ERROR_CONNECTION_REFUSED || + e.result == Cr.NS_ERROR_NET_TIMEOUT + ) { // The connection should be refused here, but on slow or overloaded // machines it may just time out. Assert.ok(true); diff --git a/devtools/shared/transport/tests/unit/test_dbgsocket_connection_drop.js b/devtools/shared/transport/tests/unit/test_dbgsocket_connection_drop.js index 9621240741a3..fd9be141468a 100644 --- a/devtools/shared/transport/tests/unit/test_dbgsocket_connection_drop.js +++ b/devtools/shared/transport/tests/unit/test_dbgsocket_connection_drop.js @@ -62,7 +62,7 @@ var test_helper = async function(payload) { host: "127.0.0.1", port: listener.port, }); - return new Promise((resolve) => { + return new Promise(resolve => { transport.hooks = { onPacket: function(packet) { this.onPacket = function() { diff --git a/devtools/shared/transport/tests/unit/test_delimited_read.js b/devtools/shared/transport/tests/unit/test_delimited_read.js index 8679247838b5..42a97d8fa15e 100644 --- a/devtools/shared/transport/tests/unit/test_delimited_read.js +++ b/devtools/shared/transport/tests/unit/test_delimited_read.js @@ -4,8 +4,11 @@ const StreamUtils = require("devtools/shared/transport/stream-utils"); -const StringInputStream = CC("@mozilla.org/io/string-input-stream;1", - "nsIStringInputStream", "setData"); +const StringInputStream = CC( + "@mozilla.org/io/string-input-stream;1", + "nsIStringInputStream", + "setData" +); function run_test() { add_task(async function() { diff --git a/devtools/shared/transport/tests/unit/test_packet.js b/devtools/shared/transport/tests/unit/test_packet.js index fd3627891c9e..5cb6710d1204 100644 --- a/devtools/shared/transport/tests/unit/test_packet.js +++ b/devtools/shared/transport/tests/unit/test_packet.js @@ -2,8 +2,7 @@ http://creativecommons.org/publicdomain/zero/1.0/ */ "use strict"; -const { JSONPacket, BulkPacket } = - require("devtools/shared/transport/packets"); +const { JSONPacket, BulkPacket } = require("devtools/shared/transport/packets"); function run_test() { add_test(test_packet_done); diff --git a/devtools/shared/transport/tests/unit/test_queue.js b/devtools/shared/transport/tests/unit/test_queue.js index c0a22a5a7aa6..ba91fccef93c 100644 --- a/devtools/shared/transport/tests/unit/test_queue.js +++ b/devtools/shared/transport/tests/unit/test_queue.js @@ -26,12 +26,12 @@ function run_test() { var test_transport = async function(transportFactory) { let clientResolve; - const clientDeferred = new Promise((resolve) => { + const clientDeferred = new Promise(resolve => { clientResolve = resolve; }); let serverResolve; - const serverDeferred = new Promise((resolve) => { + const serverDeferred = new Promise(resolve => { serverResolve = resolve; }); @@ -45,19 +45,22 @@ var test_transport = async function(transportFactory) { const transport = await transportFactory(); // Sending from client to server - function write_data({copyFrom}) { - NetUtil.asyncFetch({ - uri: NetUtil.newURI(getTestTempFile("bulk-input")), - loadUsingSystemPrincipal: true, - }, function(input, status) { - copyFrom(input).then(() => { - input.close(); - }); - }); + function write_data({ copyFrom }) { + NetUtil.asyncFetch( + { + uri: NetUtil.newURI(getTestTempFile("bulk-input")), + loadUsingSystemPrincipal: true, + }, + function(input, status) { + copyFrom(input).then(() => { + input.close(); + }); + } + ); } // Receiving on server from client - function on_bulk_packet({actor, type, length, copyTo}) { + function on_bulk_packet({ actor, type, length, copyTo }) { Assert.equal(actor, "root"); Assert.equal(type, "file-stream"); Assert.equal(length, reallyLong.length); @@ -67,16 +70,18 @@ var test_transport = async function(transportFactory) { const output = FileUtils.openSafeFileOutputStream(outputFile); - copyTo(output).then(() => { - FileUtils.closeSafeFileOutputStream(output); - return verify(); - }).then(() => { - // It's now safe to close - transport.hooks.onClosed = () => { - clientResolve(); - }; - transport.close(); - }); + copyTo(output) + .then(() => { + FileUtils.closeSafeFileOutputStream(output); + return verify(); + }) + .then(() => { + // It's now safe to close + transport.hooks.onClosed = () => { + clientResolve(); + }; + transport.close(); + }); } // Client @@ -89,11 +94,13 @@ var test_transport = async function(transportFactory) { type: "explode", }); - transport.startBulkSend({ - actor: "root", - type: "file-stream", - length: reallyLong.length, - }).then(write_data); + transport + .startBulkSend({ + actor: "root", + type: "file-stream", + length: reallyLong.length, + }) + .then(write_data); } transport.hooks = { @@ -156,19 +163,24 @@ function verify() { Assert.equal(outputFile.fileSize, reallyLong.length); // Ensure output file contents actually match - return new Promise((resolve) => { - NetUtil.asyncFetch({ - uri: NetUtil.newURI(getTestTempFile("bulk-output")), - loadUsingSystemPrincipal: true, - }, input => { - const outputData = NetUtil.readInputStreamToString(input, reallyLong.length); - // Avoid do_check_eq here so we don't log the contents - Assert.ok(outputData === reallyLong); - input.close(); - resolve(); - }); - }) - .then(cleanup_files); + return new Promise(resolve => { + NetUtil.asyncFetch( + { + uri: NetUtil.newURI(getTestTempFile("bulk-output")), + loadUsingSystemPrincipal: true, + }, + input => { + const outputData = NetUtil.readInputStreamToString( + input, + reallyLong.length + ); + // Avoid do_check_eq here so we don't log the contents + Assert.ok(outputData === reallyLong); + input.close(); + resolve(); + } + ); + }).then(cleanup_files); } function cleanup_files() { diff --git a/devtools/shared/transport/tests/unit/test_transport_bulk.js b/devtools/shared/transport/tests/unit/test_transport_bulk.js index c2277a1ce328..ed8ada0a2431 100644 --- a/devtools/shared/transport/tests/unit/test_transport_bulk.js +++ b/devtools/shared/transport/tests/unit/test_transport_bulk.js @@ -26,12 +26,12 @@ var test_bulk_transfer_transport = async function(transportFactory) { info("Starting bulk transfer test at " + new Date().toTimeString()); let clientResolve; - const clientDeferred = new Promise((resolve) => { + const clientDeferred = new Promise(resolve => { clientResolve = resolve; }); let serverResolve; - const serverDeferred = new Promise((resolve) => { + const serverDeferred = new Promise(resolve => { serverResolve = resolve; }); @@ -45,19 +45,22 @@ var test_bulk_transfer_transport = async function(transportFactory) { const transport = await transportFactory(); // Sending from client to server - function write_data({copyFrom}) { - NetUtil.asyncFetch({ - uri: NetUtil.newURI(getTestTempFile("bulk-input")), - loadUsingSystemPrincipal: true, - }, function(input, status) { - copyFrom(input).then(() => { - input.close(); - }); - }); + function write_data({ copyFrom }) { + NetUtil.asyncFetch( + { + uri: NetUtil.newURI(getTestTempFile("bulk-input")), + loadUsingSystemPrincipal: true, + }, + function(input, status) { + copyFrom(input).then(() => { + input.close(); + }); + } + ); } // Receiving on server from client - function on_bulk_packet({actor, type, length, copyTo}) { + function on_bulk_packet({ actor, type, length, copyTo }) { Assert.equal(actor, "root"); Assert.equal(type, "file-stream"); Assert.equal(length, reallyLong.length); @@ -67,16 +70,18 @@ var test_bulk_transfer_transport = async function(transportFactory) { const output = FileUtils.openSafeFileOutputStream(outputFile); - copyTo(output).then(() => { - FileUtils.closeSafeFileOutputStream(output); - return verify(); - }).then(() => { - // It's now safe to close - transport.hooks.onClosed = () => { - clientResolve(); - }; - transport.close(); - }); + copyTo(output) + .then(() => { + FileUtils.closeSafeFileOutputStream(output); + return verify(); + }) + .then(() => { + // It's now safe to close + transport.hooks.onClosed = () => { + clientResolve(); + }; + transport.close(); + }); } // Client @@ -98,11 +103,13 @@ var test_bulk_transfer_transport = async function(transportFactory) { } }); - transport.startBulkSend({ - actor: "root", - type: "file-stream", - length: reallyLong.length, - }).then(write_data); + transport + .startBulkSend({ + actor: "root", + type: "file-stream", + length: reallyLong.length, + }) + .then(write_data); }, onClosed: function() { @@ -127,19 +134,24 @@ function verify() { Assert.equal(outputFile.fileSize, reallyLong.length); // Ensure output file contents actually match - return new Promise((resolve) => { - NetUtil.asyncFetch({ - uri: NetUtil.newURI(getTestTempFile("bulk-output")), - loadUsingSystemPrincipal: true, - }, input => { - const outputData = NetUtil.readInputStreamToString(input, reallyLong.length); + return new Promise(resolve => { + NetUtil.asyncFetch( + { + uri: NetUtil.newURI(getTestTempFile("bulk-output")), + loadUsingSystemPrincipal: true, + }, + input => { + const outputData = NetUtil.readInputStreamToString( + input, + reallyLong.length + ); // Avoid do_check_eq here so we don't log the contents - Assert.ok(outputData === reallyLong); - input.close(); - resolve(); - }); - }) - .then(cleanup_files); + Assert.ok(outputData === reallyLong); + input.close(); + resolve(); + } + ); + }).then(cleanup_files); } function cleanup_files() { diff --git a/devtools/shared/transport/tests/unit/testactors-no-bulk.js b/devtools/shared/transport/tests/unit/testactors-no-bulk.js index 6a9966ec9124..ad56ace67e50 100644 --- a/devtools/shared/transport/tests/unit/testactors-no-bulk.js +++ b/devtools/shared/transport/tests/unit/testactors-no-bulk.js @@ -3,7 +3,9 @@ "use strict"; const { RootActor } = require("devtools/server/actors/root"); -const { ActorRegistry } = require("devtools/server/actors/utils/actor-registry"); +const { + ActorRegistry, +} = require("devtools/server/actors/utils/actor-registry"); /** * Root actor that doesn't have the bulk trait. diff --git a/devtools/shared/transport/tests/unit/testactors.js b/devtools/shared/transport/tests/unit/testactors.js index dc36b0a7d3ec..6752bd206672 100644 --- a/devtools/shared/transport/tests/unit/testactors.js +++ b/devtools/shared/transport/tests/unit/testactors.js @@ -2,11 +2,16 @@ http://creativecommons.org/publicdomain/zero/1.0/ */ "use strict"; -const { LazyPool, createExtraActors } = require("devtools/shared/protocol/lazy-pool"); +const { + LazyPool, + createExtraActors, +} = require("devtools/shared/protocol/lazy-pool"); const { RootActor } = require("devtools/server/actors/root"); const { ThreadActor } = require("devtools/server/actors/thread"); const { DebuggerServer } = require("devtools/server/main"); -const { ActorRegistry } = require("devtools/server/actors/utils/actor-registry"); +const { + ActorRegistry, +} = require("devtools/server/actors/utils/actor-registry"); var gTestGlobals = []; DebuggerServer.addTestGlobal = function(global) { @@ -104,13 +109,13 @@ TestTargetActor.prototype = { onDetach: function(request) { if (!this._attached) { - return { "error": "wrongState" }; + return { error: "wrongState" }; } return { type: "detached" }; }, }; TestTargetActor.prototype.requestTypes = { - "attach": TestTargetActor.prototype.onAttach, - "detach": TestTargetActor.prototype.onDetach, + attach: TestTargetActor.prototype.onAttach, + detach: TestTargetActor.prototype.onDetach, }; diff --git a/devtools/shared/transport/transport.js b/devtools/shared/transport/transport.js index 5b0ec9555884..50972d214a69 100644 --- a/devtools/shared/transport/transport.js +++ b/devtools/shared/transport/transport.js @@ -11,12 +11,18 @@ const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const { dumpn, dumpv } = DevToolsUtils; const flags = require("devtools/shared/flags"); const StreamUtils = require("devtools/shared/transport/stream-utils"); -const { Packet, JSONPacket, BulkPacket } = - require("devtools/shared/transport/packets"); +const { + Packet, + JSONPacket, + BulkPacket, +} = require("devtools/shared/transport/packets"); loader.lazyGetter(this, "ScriptableInputStream", () => { - return CC("@mozilla.org/scriptableinputstream;1", - "nsIScriptableInputStream", "init"); + return CC( + "@mozilla.org/scriptableinputstream;1", + "nsIScriptableInputStream", + "init" + ); }); const PACKET_HEADER_MAX = 200; @@ -322,9 +328,12 @@ DebuggerTransport.prototype = { */ onInputStreamReady: DevToolsUtils.makeInfallible(function(stream) { try { - while (stream.available() && this._incomingEnabled && - this._processIncoming(stream, stream.available())) { - // Loop until there is nothing more to process + while ( + stream.available() && + this._incomingEnabled && + this._processIncoming(stream, stream.available()) + ) { + // Loop until there is nothing more to process } this._waitForIncoming(); } catch (e) { @@ -367,8 +376,9 @@ DebuggerTransport.prototype = { // header pattern. this._incoming = Packet.fromHeader(this._incomingHeader, this); if (!this._incoming) { - throw new Error("No packet types for header: " + - this._incomingHeader); + throw new Error( + "No packet types for header: " + this._incomingHeader + ); } } @@ -378,7 +388,8 @@ DebuggerTransport.prototype = { this._incoming.read(stream, this._scriptableInput); } } catch (e) { - const msg = "Error reading incoming packet: (" + e + " - " + e.stack + ")"; + const msg = + "Error reading incoming packet: (" + e + " - " + e.stack + ")"; dumpn(msg); // Now in an invalid state, shut down the transport. @@ -406,8 +417,11 @@ DebuggerTransport.prototype = { */ _readHeader: function() { const amountToRead = PACKET_HEADER_MAX - this._incomingHeader.length; - this._incomingHeader += - StreamUtils.delimitedRead(this._scriptableInput, ":", amountToRead); + this._incomingHeader += StreamUtils.delimitedRead( + this._scriptableInput, + ":", + amountToRead + ); if (flags.wantVerbose) { dumpv("Header read: " + this._incomingHeader); } @@ -445,12 +459,14 @@ DebuggerTransport.prototype = { * Delivers the packet to this.hooks.onPacket. */ _onJSONObjectReady: function(object) { - DevToolsUtils.executeSoon(DevToolsUtils.makeInfallible(() => { - // Ensure the transport is still alive by the time this runs. - if (this.active) { - this.hooks.onPacket(object); - } - }, "DebuggerTransport instance's this.hooks.onPacket")); + DevToolsUtils.executeSoon( + DevToolsUtils.makeInfallible(() => { + // Ensure the transport is still alive by the time this runs. + if (this.active) { + this.hooks.onPacket(object); + } + }, "DebuggerTransport instance's this.hooks.onPacket") + ); }, /** @@ -460,12 +476,14 @@ DebuggerTransport.prototype = { * transport at the top of this file for more details. */ _onBulkReadReady: function(...args) { - DevToolsUtils.executeSoon(DevToolsUtils.makeInfallible(() => { - // Ensure the transport is still alive by the time this runs. - if (this.active) { - this.hooks.onBulkPacket(...args); - } - }, "DebuggerTransport instance's this.hooks.onBulkPacket")); + DevToolsUtils.executeSoon( + DevToolsUtils.makeInfallible(() => { + // Ensure the transport is still alive by the time this runs. + if (this.active) { + this.hooks.onBulkPacket(...args); + } + }, "DebuggerTransport instance's this.hooks.onBulkPacket") + ); }, /** @@ -479,7 +497,6 @@ DebuggerTransport.prototype = { this._incomingHeader = ""; this._incoming = null; }, - }; exports.DebuggerTransport = DebuggerTransport; diff --git a/devtools/shared/transport/websocket-transport.js b/devtools/shared/transport/websocket-transport.js index 66e49912c203..176f43df5ec8 100644 --- a/devtools/shared/transport/websocket-transport.js +++ b/devtools/shared/transport/websocket-transport.js @@ -65,7 +65,9 @@ WebSocketDebuggerTransport.prototype = { onMessage({ data }) { if (typeof data !== "string") { - throw new Error("Binary messages are not supported by WebSocket transport"); + throw new Error( + "Binary messages are not supported by WebSocket transport" + ); } const object = JSON.parse(data); diff --git a/devtools/shared/transport/worker-transport.js b/devtools/shared/transport/worker-transport.js index 891778665e9a..9a5ef3745b02 100644 --- a/devtools/shared/transport/worker-transport.js +++ b/devtools/shared/transport/worker-transport.js @@ -34,11 +34,13 @@ MainThreadWorkerDebuggerTransport.prototype = { }, send: function(packet) { - this._dbg.postMessage(JSON.stringify({ - type: "message", - id: this._id, - message: packet, - })); + this._dbg.postMessage( + JSON.stringify({ + type: "message", + id: this._id, + message: packet, + }) + ); }, startBulkSend: function() { @@ -84,11 +86,13 @@ WorkerThreadWorkerDebuggerTransport.prototype = { }, send: function(packet) { - this._scope.postMessage(JSON.stringify({ - type: "message", - id: this._id, - message: packet, - })); + this._scope.postMessage( + JSON.stringify({ + type: "message", + id: this._id, + message: packet, + }) + ); }, startBulkSend: function() { diff --git a/devtools/shared/wasm-source-map.js b/devtools/shared/wasm-source-map.js index b4d360888d73..42f12955a841 100644 --- a/devtools/shared/wasm-source-map.js +++ b/devtools/shared/wasm-source-map.js @@ -30,7 +30,8 @@ class WasmRemap { /** * @param url string */ - set sourceRoot(url) { // important, since sources are using this. + set sourceRoot(url) { + // important, since sources are using this. this._map.sourceRoot = url; } @@ -77,7 +78,7 @@ class WasmRemap { allGeneratedPositionsFor(originalPosition) { const positions = this._map.allGeneratedPositionsFor(originalPosition); - return positions.map((position) => { + return positions.map(position => { return this._remapGeneratedPosition(position); }); } @@ -91,23 +92,27 @@ class WasmRemap { } eachMapping(callback, context, order) { - this._map.eachMapping((entry) => { - const { - source, - generatedColumn, - originalLine, - originalColumn, - name, - } = entry; - callback({ - source, - generatedLine: generatedColumn, - generatedColumn: 0, - originalLine, - originalColumn, - name, - }); - }, context, order); + this._map.eachMapping( + entry => { + const { + source, + generatedColumn, + originalLine, + originalColumn, + name, + } = entry; + callback({ + source, + generatedLine: generatedColumn, + generatedColumn: 0, + originalLine, + originalColumn, + name, + }); + }, + context, + order + ); } } diff --git a/devtools/shared/webconsole/js-property-provider.js b/devtools/shared/webconsole/js-property-provider.js index 01ebb1c7f6e2..1d3c35d9fe48 100644 --- a/devtools/shared/webconsole/js-property-provider.js +++ b/devtools/shared/webconsole/js-property-provider.js @@ -11,14 +11,19 @@ const DevToolsUtils = require("devtools/shared/DevToolsUtils"); if (!isWorker) { loader.lazyImporter(this, "Parser", "resource://devtools/shared/Parser.jsm"); } -loader.lazyRequireGetter(this, "Reflect", "resource://gre/modules/reflect.jsm", true); +loader.lazyRequireGetter( + this, + "Reflect", + "resource://gre/modules/reflect.jsm", + true +); // Provide an easy way to bail out of even attempting an autocompletion // if an object has way too many properties. Protects against large objects // with numeric values that wouldn't be tallied towards MAX_AUTOCOMPLETIONS. -const MAX_AUTOCOMPLETE_ATTEMPTS = exports.MAX_AUTOCOMPLETE_ATTEMPTS = 100000; +const MAX_AUTOCOMPLETE_ATTEMPTS = (exports.MAX_AUTOCOMPLETE_ATTEMPTS = 100000); // Prevent iterating over too many properties during autocomplete suggestions. -const MAX_AUTOCOMPLETIONS = exports.MAX_AUTOCOMPLETIONS = 1500; +const MAX_AUTOCOMPLETIONS = (exports.MAX_AUTOCOMPLETIONS = 1500); const STATE_NORMAL = Symbol("STATE_NORMAL"); const STATE_QUOTE = Symbol("STATE_QUOTE"); @@ -131,15 +136,17 @@ function analyzeInputString(str) { // one either, and the current computed statement is not a // variable/function/class declaration, update the start position. if ( - previousNonSpaceChar !== "." && nextNonSpaceChar !== "." && - previousNonSpaceChar !== "[" && nextNonSpaceChar !== "[" && + previousNonSpaceChar !== "." && + nextNonSpaceChar !== "." && + previousNonSpaceChar !== "[" && + nextNonSpaceChar !== "[" && !NO_AUTOCOMPLETE_PREFIXES.includes(currentLastStatement) ) { - start = i + ( - nextNonSpaceCharIndex >= 0 + start = + i + + (nextNonSpaceCharIndex >= 0 ? nextNonSpaceCharIndex - : (after.length + 1) - ); + : after.length + 1); } // There's only spaces after that, so we can return. @@ -280,12 +287,9 @@ function JSPropertyProvider({ // Analyse the inputValue and find the beginning of the last part that // should be completed. - const { - err, - state, - lastStatement, - isElementAccess, - } = analyzeInputString(inputValue); + const { err, state, lastStatement, isElementAccess } = analyzeInputString( + inputValue + ); // There was an error analysing the string. if (err) { @@ -304,15 +308,24 @@ function JSPropertyProvider({ return null; } - if (NO_AUTOCOMPLETE_PREFIXES.some(prefix => lastStatement.startsWith(prefix + " "))) { + if ( + NO_AUTOCOMPLETE_PREFIXES.some(prefix => + lastStatement.startsWith(prefix + " ") + ) + ) { return null; } const env = environment || dbgObject.asEnvironment(); const completionPart = lastStatement; const lastDotIndex = completionPart.lastIndexOf("."); - const lastOpeningBracketIndex = isElementAccess ? completionPart.lastIndexOf("[") : -1; - const lastCompletionCharIndex = Math.max(lastDotIndex, lastOpeningBracketIndex); + const lastOpeningBracketIndex = isElementAccess + ? completionPart.lastIndexOf("[") + : -1; + const lastCompletionCharIndex = Math.max( + lastDotIndex, + lastOpeningBracketIndex + ); const startQuoteRegex = /^('|"|`)/; // AST representation of the expression before the last access char (`.` or `[`). @@ -329,7 +342,8 @@ function JSPropertyProvider({ const parsedExpression = completionPart.slice(0, lastCompletionCharIndex); const syntaxTree = parser.get(parsedExpression); const lastTree = syntaxTree.getLastSyntaxTree(); - const lastBody = lastTree && lastTree.AST.body[lastTree.AST.body.length - 1]; + const lastBody = + lastTree && lastTree.AST.body[lastTree.AST.body.length - 1]; // Finding the last expression since we've sliced up until the dot. // If there were parse errors this won't exist. @@ -403,7 +417,10 @@ function JSPropertyProvider({ const lastPart = properties[properties.length - 1]; const openBracketIndex = lastPart.lastIndexOf("["); matchProp = lastPart.substr(openBracketIndex + 1); - properties[properties.length - 1] = lastPart.substring(0, openBracketIndex); + properties[properties.length - 1] = lastPart.substring( + 0, + openBracketIndex + ); } else { matchProp = properties.pop().trimLeft(); } @@ -468,7 +485,8 @@ function JSPropertyProvider({ const propPath = [firstProp].concat(properties.slice(0, index + 1)); const authorized = authorizedEvaluations.some( - x => JSON.stringify(x) === JSON.stringify(propPath)); + x => JSON.stringify(x) === JSON.stringify(propPath) + ); if (!authorized && DevToolsUtils.isUnsafeGetter(obj, prop)) { // If we try to access an unsafe getter, return its name so we can consume that @@ -513,7 +531,7 @@ function JSPropertyProvider({ } } - return {isElementAccess, matchProp, matches}; + return { isElementAccess, matchProp, matches }; }; // If the final property is a primitive @@ -558,7 +576,7 @@ function getPropertiesFromAstExpression(ast) { if (!ast) { return result; } - const {type, property, object, name} = ast; + const { type, property, object, name } = ast; if (type === "ThisExpression") { result.unshift("this"); } else if (type === "Identifier" && name) { @@ -581,32 +599,34 @@ function getPropertiesFromAstExpression(ast) { } function wrapMatchesInQuotes(matches, quote = `"`) { - return new Set([...matches].map(p => { - // Escape as a double-quoted string literal - p = JSON.stringify(p); + return new Set( + [...matches].map(p => { + // Escape as a double-quoted string literal + p = JSON.stringify(p); - // We don't have to do anything more when using double quotes - if (quote == `"`) { - return p; - } + // We don't have to do anything more when using double quotes + if (quote == `"`) { + return p; + } - // Remove surrounding double quotes - p = p.slice(1, -1); + // Remove surrounding double quotes + p = p.slice(1, -1); - // Unescape inner double quotes (all must be escaped, so no need to count backslashes) - p = p.replace(/\\(?=")/g, ""); + // Unescape inner double quotes (all must be escaped, so no need to count backslashes) + p = p.replace(/\\(?=")/g, ""); - // Escape the specified quote (assuming ' or `, which are treated literally in regex) - p = p.replace(new RegExp(quote, "g"), "\\$&"); + // Escape the specified quote (assuming ' or `, which are treated literally in regex) + p = p.replace(new RegExp(quote, "g"), "\\$&"); - // Template literals treat ${ specially, escape it - if (quote == "`") { - p = p.replace(/\${/g, "\\$&"); - } + // Template literals treat ${ specially, escape it + if (quote == "`") { + p = p.replace(/\${/g, "\\$&"); + } - // Surround the result with quotes - return `${quote}${p}${quote}`; - })); + // Surround the result with quotes + return `${quote}${p}${quote}`; + }) + ); } /** @@ -642,7 +662,10 @@ function getArrayMemberProperty(obj, env, prop) { const arrayIndicesRegex = /\[[^\]]*\]/g; while ((result = arrayIndicesRegex.exec(prop)) !== null) { const indexWithBrackets = result[0]; - const indexAsText = indexWithBrackets.substr(1, indexWithBrackets.length - 2); + const indexAsText = indexWithBrackets.substr( + 1, + indexWithBrackets.length - 2 + ); const index = parseInt(indexAsText, 10); if (isNaN(index)) { @@ -721,7 +744,7 @@ function getMatchedProps(obj, match) { * Filter for properties that match this string. * @returns {Set} List of matched properties. */ -function getMatchedPropsImpl(obj, match, {chainIterator, getProperties}) { +function getMatchedPropsImpl(obj, match, { chainIterator, getProperties }) { const matches = new Set(); let numProps = 0; @@ -744,8 +767,10 @@ function getMatchedPropsImpl(obj, match, {chainIterator, getProperties}) { // If there are too many properties to event attempt autocompletion, // or if we have already added the max number, then stop looping // and return the partial set that has already been discovered. - if (numProps >= MAX_AUTOCOMPLETE_ATTEMPTS || - matches.size >= MAX_AUTOCOMPLETIONS) { + if ( + numProps >= MAX_AUTOCOMPLETE_ATTEMPTS || + matches.size >= MAX_AUTOCOMPLETIONS + ) { break; } @@ -784,7 +809,7 @@ function getMatchedPropsImpl(obj, match, {chainIterator, getProperties}) { * A Debugger.Object if the property exists in the object's prototype * chain, undefined otherwise. */ -function getExactMatchImpl(obj, name, {chainIterator, getProperty}) { +function getExactMatchImpl(obj, name, { chainIterator, getProperty }) { // We need to go up the prototype chain. const iter = chainIterator(obj); for (obj of iter) { @@ -797,7 +822,7 @@ function getExactMatchImpl(obj, name, {chainIterator, getProperty}) { } var JSObjectSupport = { - chainIterator: function* (obj) { + chainIterator: function*(obj) { while (obj) { yield obj; try { @@ -825,7 +850,7 @@ var JSObjectSupport = { }; var DebuggerObjectSupport = { - chainIterator: function* (obj) { + chainIterator: function*(obj) { while (obj) { yield obj; try { @@ -853,7 +878,7 @@ var DebuggerObjectSupport = { }; var DebuggerEnvironmentSupport = { - chainIterator: function* (obj) { + chainIterator: function*(obj) { while (obj) { yield obj; obj = obj.parent; @@ -886,8 +911,11 @@ var DebuggerEnvironmentSupport = { } // FIXME: Need actual UI, bug 941287. - if (result === undefined || result.optimizedOut || - result.missingArguments) { + if ( + result === undefined || + result.optimizedOut || + result.missingArguments + ) { return null; } return { value: result }; diff --git a/devtools/shared/webconsole/network-helper.js b/devtools/shared/webconsole/network-helper.js index b9dbc9aca033..bfbff5298d6d 100644 --- a/devtools/shared/webconsole/network-helper.js +++ b/devtools/shared/webconsole/network-helper.js @@ -59,7 +59,7 @@ "use strict"; -const {components, Cc, Ci} = require("chrome"); +const { components, Cc, Ci } = require("chrome"); loader.lazyImporter(this, "NetUtil", "resource://gre/modules/NetUtil.jsm"); const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const Services = require("Services"); @@ -93,8 +93,9 @@ var NetworkHelper = { * Converted text. */ convertToUnicode: function(text, charset) { - const conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Ci.nsIScriptableUnicodeConverter); + const conv = Cc[ + "@mozilla.org/intl/scriptableunicodeconverter" + ].createInstance(Ci.nsIScriptableUnicodeConverter); try { conv.charset = charset || "UTF-8"; return conv.ConvertToUnicode(text); @@ -121,7 +122,7 @@ var NetworkHelper = { } }, - /** + /** * Reads the posted text from request. * * @param nsIHttpChannel request @@ -188,8 +189,11 @@ var NetworkHelper = { if (webNav instanceof Ci.nsIWebPageDescriptor) { const descriptor = webNav.currentDescriptor; - if (descriptor instanceof Ci.nsISHEntry && descriptor.postData && - descriptor instanceof Ci.nsISeekableStream) { + if ( + descriptor instanceof Ci.nsISHEntry && + descriptor.postData && + descriptor instanceof Ci.nsISeekableStream + ) { descriptor.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0); return this.readAndConvertFromStream(descriptor, charset); @@ -246,8 +250,9 @@ var NetworkHelper = { } try { - return request.loadGroup.notificationCallbacks - .getInterface(Ci.nsILoadContext); + return request.loadGroup.notificationCallbacks.getInterface( + Ci.nsILoadContext + ); } catch (ex) { // Ignore. } @@ -265,7 +270,7 @@ var NetworkHelper = { if (request instanceof Ci.nsIChannel) { const loadInfo = request.loadInfo; if (loadInfo && loadInfo.isTopLevelLoad) { - return (request.loadFlags & Ci.nsIChannel.LOAD_DOCUMENT_URI); + return request.loadFlags & Ci.nsIChannel.LOAD_DOCUMENT_URI; } } @@ -285,30 +290,31 @@ var NetworkHelper = { * or null if something failed while getting the cached content. */ loadFromCache: function(url, charset, callback) { - const channel = NetUtil.newChannel({uri: url, - loadUsingSystemPrincipal: true}); + const channel = NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }); // Ensure that we only read from the cache and not the server. - channel.loadFlags = Ci.nsIRequest.LOAD_FROM_CACHE | + channel.loadFlags = + Ci.nsIRequest.LOAD_FROM_CACHE | Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | Ci.nsICachingChannel.LOAD_BYPASS_LOCAL_CACHE_IF_BUSY; - NetUtil.asyncFetch( - channel, - (inputStream, statusCode, request) => { - if (!components.isSuccessCode(statusCode)) { - callback(null); - return; - } + NetUtil.asyncFetch(channel, (inputStream, statusCode, request) => { + if (!components.isSuccessCode(statusCode)) { + callback(null); + return; + } - // Try to get the encoding from the channel. If there is none, then use - // the passed assumed charset. - const requestChannel = request.QueryInterface(Ci.nsIChannel); - const contentCharset = requestChannel.contentCharset || charset; + // Try to get the encoding from the channel. If there is none, then use + // the passed assumed charset. + const requestChannel = request.QueryInterface(Ci.nsIChannel); + const contentCharset = requestChannel.contentCharset || charset; - // Read the content of the stream using contentCharset as encoding. - callback(this.readAndConvertFromStream(inputStream, contentCharset)); - }); + // Read the content of the stream using contentCharset as encoding. + callback(this.readAndConvertFromStream(inputStream, contentCharset)); + }); }, /** @@ -328,8 +334,10 @@ var NetworkHelper = { const equal = cookie.indexOf("="); const name = cookie.substr(0, equal); const value = cookie.substr(equal + 1); - result.push({name: unescape(name.trim()), - value: unescape(value.trim())}); + result.push({ + name: unescape(name.trim()), + value: unescape(value.trim()), + }); }); return result; @@ -366,7 +374,7 @@ var NetworkHelper = { const parts = cookie.substr(equal + 1).split(";"); const value = unescape(parts.shift().trim()); - cookie = {name: name, value: value}; + cookie = { name: name, value: value }; parts.forEach(function(part) { part = part.trim(); @@ -586,8 +594,9 @@ var NetworkHelper = { securityInfo.QueryInterface(Ci.nsITransportSecurityInfo); const wpl = Ci.nsIWebProgressListener; - const NSSErrorsService = Cc["@mozilla.org/nss_errors_service;1"] - .getService(Ci.nsINSSErrorsService); + const NSSErrorsService = Cc["@mozilla.org/nss_errors_service;1"].getService( + Ci.nsINSSErrorsService + ); if (!NSSErrorsService.isNSSErrorCode(securityInfo.errorCode)) { const state = securityInfo.securityState; @@ -614,8 +623,10 @@ var NetworkHelper = { // validation. Return info as info.state = insecure. return info; } else { - DevToolsUtils.reportException("NetworkHelper.parseSecurityInfo", - "Security state " + state + " has no known STATE_IS_* flags."); + DevToolsUtils.reportException( + "NetworkHelper.parseSecurityInfo", + "Security state " + state + " has no known STATE_IS_* flags." + ); return info; } @@ -629,8 +640,9 @@ var NetworkHelper = { info.signatureSchemeName = securityInfo.signatureSchemeName; // Protocol version. - info.protocolVersion = - this.formatSecurityProtocol(securityInfo.protocolVersion); + info.protocolVersion = this.formatSecurityProtocol( + securityInfo.protocolVersion + ); // Certificate. info.cert = this.parseCertificateInfo(securityInfo.serverCert); @@ -640,14 +652,16 @@ var NetworkHelper = { // HSTS and HPKP if available. if (httpActivity.hostname) { - const sss = Cc["@mozilla.org/ssservice;1"] - .getService(Ci.nsISiteSecurityService); + const sss = Cc["@mozilla.org/ssservice;1"].getService( + Ci.nsISiteSecurityService + ); // SiteSecurityService uses different storage if the channel is // private. Thus we must give isSecureURI correct flags or we // might get incorrect results. - const flags = (httpActivity.private) ? - Ci.nsISocketProvider.NO_PERMANENT_STORAGE : 0; + const flags = httpActivity.private + ? Ci.nsISocketProvider.NO_PERMANENT_STORAGE + : 0; if (!uri) { // isSecureURI only cares about the host, not the scheme. @@ -658,8 +672,10 @@ var NetworkHelper = { info.hsts = sss.isSecureURI(sss.HEADER_HSTS, uri, flags); info.hpkp = sss.isSecureURI(sss.HEADER_HPKP, uri, flags); } else { - DevToolsUtils.reportException("NetworkHelper.parseSecurityInfo", - "Could not get HSTS/HPKP status as hostname is not available."); + DevToolsUtils.reportException( + "NetworkHelper.parseSecurityInfo", + "Could not get HSTS/HPKP status as hostname is not available." + ); info.hsts = false; info.hpkp = false; } @@ -711,8 +727,10 @@ var NetworkHelper = { sha256: cert.sha256Fingerprint, }; } else { - DevToolsUtils.reportException("NetworkHelper.parseCertificateInfo", - "Secure connection established without certificate."); + DevToolsUtils.reportException( + "NetworkHelper.parseCertificateInfo", + "Secure connection established without certificate." + ); } return info; @@ -739,8 +757,10 @@ var NetworkHelper = { case Ci.nsITransportSecurityInfo.TLS_VERSION_1_3: return "TLSv1.3"; default: - DevToolsUtils.reportException("NetworkHelper.formatSecurityProtocol", - "protocolVersion " + version + " is unknown."); + DevToolsUtils.reportException( + "NetworkHelper.formatSecurityProtocol", + "protocolVersion " + version + " is unknown." + ); return "Unknown"; } }, @@ -772,8 +792,10 @@ var NetworkHelper = { } if (!isCipher) { - DevToolsUtils.reportException("NetworkHelper.getReasonsForWeakness", - "STATE_IS_BROKEN without a known reason. Full state was: " + state); + DevToolsUtils.reportException( + "NetworkHelper.getReasonsForWeakness", + "STATE_IS_BROKEN without a known reason. Full state was: " + state + ); } } @@ -797,15 +819,20 @@ var NetworkHelper = { } // Turn the params string into an array containing { name: value } tuples. - const paramsArray = queryString.replace(/^[?&]/, "").split("&").map(e => { - const param = e.split("="); - return { - name: param[0] ? - NetworkHelper.convertToUnicode(unescape(param[0])) : "", - value: param[1] ? - NetworkHelper.convertToUnicode(unescape(param[1])) : "", - }; - }); + const paramsArray = queryString + .replace(/^[?&]/, "") + .split("&") + .map(e => { + const param = e.split("="); + return { + name: param[0] + ? NetworkHelper.convertToUnicode(unescape(param[0])) + : "", + value: param[1] + ? NetworkHelper.convertToUnicode(unescape(param[1])) + : "", + }; + }); return paramsArray; }, diff --git a/devtools/shared/webconsole/test/browser/browser_commands_registration.js b/devtools/shared/webconsole/test/browser/browser_commands_registration.js index 6102c9ddc316..8a227deff10c 100644 --- a/devtools/shared/webconsole/test/browser/browser_commands_registration.js +++ b/devtools/shared/webconsole/test/browser/browser_commands_registration.js @@ -14,8 +14,12 @@ add_task(async function() { // Fetch WebConsoleCommands so that it is available for next Content Tasks await ContentTask.spawn(gBrowser.selectedBrowser, null, async function() { - const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); - const { WebConsoleCommands } = require("devtools/server/actors/webconsole/utils"); + const { require } = ChromeUtils.import( + "resource://devtools/shared/Loader.jsm" + ); + const { + WebConsoleCommands, + } = require("devtools/server/actors/webconsole/utils"); // Bind the symbol on this in order to make it available for next tasks this.WebConsoleCommands = WebConsoleCommands; @@ -40,8 +44,10 @@ async function registerNewCommand(consoleClient) { return "ok"; }); - ok(this.WebConsoleCommands.hasCommand("setFoo"), - "The command should be registered"); + ok( + this.WebConsoleCommands.hasCommand("setFoo"), + "The command should be registered" + ); }); const command = "setFoo('bar')"; @@ -69,8 +75,11 @@ async function wrapCommand(consoleClient) { }; this.WebConsoleCommands.register("keys", newKeys); - is(this.WebConsoleCommands.getCommand("keys"), newKeys, - "the keys() command should have been replaced"); + is( + this.WebConsoleCommands.getCommand("keys"), + newKeys, + "the keys() command should have been replaced" + ); this.origKeys = origKeys; }); @@ -92,8 +101,11 @@ async function wrapCommand(consoleClient) { await ContentTask.spawn(gBrowser.selectedBrowser, null, async function() { this.WebConsoleCommands.register("keys", this.origKeys); - is(this.WebConsoleCommands.getCommand("keys"), this.origKeys, - "the keys() command should be restored"); + is( + this.WebConsoleCommands.getCommand("keys"), + this.origKeys, + "the keys() command should be restored" + ); delete this.origKeys; }); } @@ -131,10 +143,16 @@ async function registerAccessor(consoleClient) { }); await ContentTask.spawn(gBrowser.selectedBrowser, null, async function() { - is(content.document.getElementById("quack").textContent, ">o_/", - "#foo textContent should equal to \">o_/\""); + is( + content.document.getElementById("quack").textContent, + ">o_/", + '#foo textContent should equal to ">o_/"' + ); this.WebConsoleCommands.unregister("$foo"); - ok(!this.WebConsoleCommands.hasCommand("$foo"), "$foo should be unregistered"); + ok( + !this.WebConsoleCommands.hasCommand("$foo"), + "$foo should be unregistered" + ); }); } @@ -170,12 +188,14 @@ async function unregisterAfterOverridingTwice(consoleClient) { this.WebConsoleCommands.unregister("keys"); }); - info("checking the value after unregistration (should restore " + - "the original command)"); + info( + "checking the value after unregistration (should restore " + + "the original command)" + ); await evaluateJSAndCheckResult(consoleClient, "keys({});", { result: { class: "Array", - preview: {items: []}, + preview: { items: [] }, }, }); } diff --git a/devtools/shared/webconsole/test/browser/browser_network_longstring.js b/devtools/shared/webconsole/test/browser/browser_network_longstring.js index 3cd73be5b037..2b7d181b6951 100644 --- a/devtools/shared/webconsole/test/browser/browser_network_longstring.js +++ b/devtools/shared/webconsole/test/browser/browser_network_longstring.js @@ -37,12 +37,14 @@ add_task(async function() { const updates = []; let netActor = null; const onAllNetworkEventUpdateReceived = new Promise(resolve => { - const onNetworkEventUpdate = (packet) => { + const onNetworkEventUpdate = packet => { updates.push(packet.updateType); assertNetworkEventUpdate(netActor, packet); - if (updates.includes("responseContent") && - updates.includes("eventTimings")) { + if ( + updates.includes("responseContent") && + updates.includes("eventTimings") + ) { client.off("networkEventUpdate", onNetworkEventUpdate); resolve(); } @@ -151,8 +153,7 @@ function assertNetworkEventUpdate(netActor, packet) { }; break; default: - ok(false, "unknown network event update type: " + - packet.updateType); + ok(false, "unknown network event update type: " + packet.updateType); return; } @@ -201,8 +202,11 @@ function assertRequestPostData(response) { postDataDiscarded: false, }); - is(response.postData.text.initial.length, - LONG_STRING_INITIAL_LENGTH, "postData text initial length"); + is( + response.postData.text.initial.length, + LONG_STRING_INITIAL_LENGTH, + "postData text initial length" + ); } function assertResponseHeaders(response) { @@ -216,10 +220,10 @@ function assertResponseHeaders(response) { "content-length": /^\d+$/, "x-very-short": "hello world", "x-very-long": { - "type": "longString", - "length": 521, - "initial": /^Lorem ipsum.+\. Donec vitae d$/, - "actor": /[a-z]/, + type: "longString", + length: 521, + initial: /^Lorem ipsum.+\. Donec vitae d$/, + actor: /[a-z]/, }, }); } @@ -245,8 +249,11 @@ function assertResponseContent(response) { contentDiscarded: false, }); - is(response.content.text.initial.length, - LONG_STRING_INITIAL_LENGTH, "content initial length"); + is( + response.content.text.initial.length, + LONG_STRING_INITIAL_LENGTH, + "content initial length" + ); } function assertEventTimings(response) { diff --git a/devtools/shared/webconsole/test/browser/head.js b/devtools/shared/webconsole/test/browser/head.js index e50fc4c351b4..2ce4d0199843 100644 --- a/devtools/shared/webconsole/test/browser/head.js +++ b/devtools/shared/webconsole/test/browser/head.js @@ -8,7 +8,8 @@ Services.scriptloader.loadSubScript( "chrome://mochitests/content/browser/devtools/client/shared/test/shared-head.js", - this); + this +); async function getTargetForTab(tab) { const target = await TargetFactory.forTab(tab); @@ -32,8 +33,11 @@ function checkValue(name, value, expected) { ok(false, "'" + name + "' is null"); } else if (value === undefined) { ok(false, "'" + name + "' is undefined"); - } else if (typeof expected == "string" || typeof expected == "number" || - typeof expected == "boolean") { + } else if ( + typeof expected == "string" || + typeof expected == "number" || + typeof expected == "boolean" + ) { is(value, expected, "property '" + name + "'"); } else if (expected instanceof RegExp) { ok(expected.test(value), name + ": " + expected + " matched " + value); diff --git a/devtools/shared/webconsole/test/common.js b/devtools/shared/webconsole/test/common.js index a700f86bf515..3dcef9932b5b 100644 --- a/devtools/shared/webconsole/test/common.js +++ b/devtools/shared/webconsole/test/common.js @@ -10,9 +10,9 @@ closeDebugger, checkConsoleAPICalls, checkRawHeaders, runTests, nextTest, Ci, Cc, withActiveServiceWorker, Services, consoleAPICall */ -const {require} = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); -const {DebuggerServer} = require("devtools/server/main"); -const {DebuggerClient} = require("devtools/shared/client/debugger-client"); +const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); +const { DebuggerServer } = require("devtools/server/main"); +const { DebuggerClient } = require("devtools/shared/client/debugger-client"); const ObjectClient = require("devtools/shared/client/object-client"); const Services = require("Services"); @@ -50,9 +50,7 @@ async function attachConsoleToWorker(listeners, callback) { callback(state, response); } -var _attachConsole = async function( - listeners, attachToTab, attachToWorker -) { +var _attachConsole = async function(listeners, attachToTab, attachToWorker) { try { const client = await connectToDebugger(); @@ -79,7 +77,9 @@ var _attachConsole = async function( const { workers } = await target.listWorkers(); target = workers.filter(w => w.url == workerName)[0]; if (!target) { - console.error("listWorkers failed. Unable to find the worker actor\n"); + console.error( + "listWorkers failed. Unable to find the worker actor\n" + ); return null; } } @@ -104,8 +104,9 @@ var _attachConsole = async function( response, }; } catch (error) { - console.error(`attachConsole failed: ${error.error} ${error.message} - ` + - error.stack); + console.error( + `attachConsole failed: ${error.error} ${error.message} - ` + error.stack + ); } return null; }; @@ -123,8 +124,11 @@ function closeDebugger(state, callback) { } function checkConsoleAPICalls(consoleCalls, expectedConsoleCalls) { - is(consoleCalls.length, expectedConsoleCalls.length, - "received correct number of console calls"); + is( + consoleCalls.length, + expectedConsoleCalls.length, + "received correct number of console calls" + ); expectedConsoleCalls.forEach(function(message, index) { info("checking received console call #" + index); checkConsoleAPICall(consoleCalls[index], expectedConsoleCalls[index]); @@ -133,8 +137,7 @@ function checkConsoleAPICalls(consoleCalls, expectedConsoleCalls) { function checkConsoleAPICall(call, expected) { if (expected.level != "trace" && expected.arguments) { - is(call.arguments.length, expected.arguments.length, - "number of arguments"); + is(call.arguments.length, expected.arguments.length, "number of arguments"); } checkObject(call, expected); @@ -155,8 +158,11 @@ function checkValue(name, value, expected) { ok(false, "'" + name + "' is undefined"); } else if (value === null) { ok(false, "'" + name + "' is null"); - } else if (typeof expected == "string" || typeof expected == "number" || - typeof expected == "boolean") { + } else if ( + typeof expected == "string" || + typeof expected == "number" || + typeof expected == "boolean" + ) { is(value, expected, "property '" + name + "'"); } else if (expected instanceof RegExp) { ok(expected.test(value), name + ": " + expected + " matched " + value); diff --git a/devtools/shared/webconsole/test/console-test-worker.js b/devtools/shared/webconsole/test/console-test-worker.js index 04d9f0e5724a..b3091faf8f0a 100644 --- a/devtools/shared/webconsole/test/console-test-worker.js +++ b/devtools/shared/webconsole/test/console-test-worker.js @@ -6,7 +6,7 @@ function f() { const a = 1; const b = 2; const c = 3; - return {a, b, c}; + return { a, b, c }; } self.onmessage = function(event) { diff --git a/devtools/shared/webconsole/test/unit/test_js_property_provider.js b/devtools/shared/webconsole/test/unit/test_js_property_provider.js index 702570e9d8cc..1bfa69e26bc5 100644 --- a/devtools/shared/webconsole/test/unit/test_js_property_provider.js +++ b/devtools/shared/webconsole/test/unit/test_js_property_provider.js @@ -4,10 +4,13 @@ "use strict"; const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); -const { FallibleJSPropertyProvider: JSPropertyProvider } = - require("devtools/shared/webconsole/js-property-provider"); +const { + FallibleJSPropertyProvider: JSPropertyProvider, +} = require("devtools/shared/webconsole/js-property-provider"); -const {addDebuggerToGlobal} = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm"); +const { addDebuggerToGlobal } = ChromeUtils.import( + "resource://gre/modules/jsdebugger.jsm" +); addDebuggerToGlobal(this); function run_test() { @@ -67,12 +70,15 @@ function run_test() { const dbg = new Debugger(); const dbgObject = dbg.addDebuggee(sandbox); const dbgEnv = dbgObject.asEnvironment(); - Cu.evalInSandbox(` + Cu.evalInSandbox( + ` const hello = Object.create(null, Object.getOwnPropertyDescriptors({world: 1})); String.prototype.hello = hello; Number.prototype.hello = hello; Array.prototype.hello = hello; - `, sandbox); + `, + sandbox + ); Cu.evalInSandbox(testArray, sandbox); Cu.evalInSandbox(testObject, sandbox); Cu.evalInSandbox(testHyphenated, sandbox); @@ -88,12 +94,13 @@ function run_test() { } function runChecks(dbgObject, environment, sandbox) { - const propertyProvider = (inputValue, options) => JSPropertyProvider({ - dbgObject, - environment, - inputValue, - ...options, - }); + const propertyProvider = (inputValue, options) => + JSPropertyProvider({ + dbgObject, + environment, + inputValue, + ...options, + }); info("Test that suggestions are given for 'this'"); let results = propertyProvider("t"); @@ -174,9 +181,9 @@ function runChecks(dbgObject, environment, sandbox) { test_has_result(results, "charAt"); results = propertyProvider("`foo doc`."); test_has_result(results, "charAt"); - results = propertyProvider("`foo \" doc`."); + results = propertyProvider('`foo " doc`.'); test_has_result(results, "charAt"); - results = propertyProvider("`foo \' doc`."); + results = propertyProvider("`foo ' doc`."); test_has_result(results, "charAt"); results = propertyProvider("'[1,2,3]'."); test_has_result(results, "charAt"); @@ -232,7 +239,9 @@ function runChecks(dbgObject, environment, sandbox) { results = propertyProvider("testArray[1].propC[0]."); test_has_result(results, "trim"); - info("Test that suggestions are displayed when variable is wrapped in parens"); + info( + "Test that suggestions are displayed when variable is wrapped in parens" + ); results = propertyProvider("(testObject)['propA'][0]."); test_has_result(results, "propB"); @@ -264,77 +273,127 @@ function runChecks(dbgObject, environment, sandbox) { const gen2NextResult = Cu.evalInSandbox("gen2.next().value", sandbox); Assert.equal(gen2Result + 1, gen2NextResult); - info("Test that getters are not executed if authorizedEvaluations is undefined"); + info( + "Test that getters are not executed if authorizedEvaluations is undefined" + ); results = propertyProvider("testGetters.x."); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "x"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); results = propertyProvider("testGetters.x["); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "x"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); results = propertyProvider("testGetters.x.hell"); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "x"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); results = propertyProvider("testGetters.x['hell"); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "x"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); - info("Test that getters are not executed if authorizedEvaluations does not match"); - results = propertyProvider("testGetters.x.", {authorizedEvaluations: []}); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "x"]}); + info( + "Test that getters are not executed if authorizedEvaluations does not match" + ); + results = propertyProvider("testGetters.x.", { authorizedEvaluations: [] }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); results = propertyProvider("testGetters.x.", { authorizedEvaluations: [["testGetters"]], }); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "x"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); results = propertyProvider("testGetters.x.", { authorizedEvaluations: [["testGtrs", "x"]], }); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "x"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); results = propertyProvider("testGetters.x.", { authorizedEvaluations: [["x"]], }); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "x"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); info("Test that deep getter property access returns intermediate getters"); results = propertyProvider("testGetters.y.y."); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "y"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); results = propertyProvider("testGetters['y'].y."); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "y"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); results = propertyProvider("testGetters['y']['y']."); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "y"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); results = propertyProvider("testGetters.y['y']."); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "y"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); info("Test that deep getter property access invoke intermediate getters"); results = propertyProvider("testGetters.y.y.", { authorizedEvaluations: [["testGetters", "y"]], }); - Assert.deepEqual(results, - {isUnsafeGetter: true, getterPath: ["testGetters", "y", "y"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); results = propertyProvider("testGetters['y'].y.", { authorizedEvaluations: [["testGetters", "y"]], }); - Assert.deepEqual(results, - {isUnsafeGetter: true, getterPath: ["testGetters", "y", "y"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); results = propertyProvider("testGetters['y']['y'].", { authorizedEvaluations: [["testGetters", "y"]], }); - Assert.deepEqual(results, - {isUnsafeGetter: true, getterPath: ["testGetters", "y", "y"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); results = propertyProvider("testGetters.y['y'].", { authorizedEvaluations: [["testGetters", "y"]], }); - Assert.deepEqual( - results, {isUnsafeGetter: true, getterPath: ["testGetters", "y", "y"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); - info("Test that getters are executed if matching an authorizedEvaluation element"); + info( + "Test that getters are executed if matching an authorizedEvaluation element" + ); results = propertyProvider("testGetters.x.", { authorizedEvaluations: [["testGetters", "x"]], }); @@ -360,13 +419,20 @@ function runChecks(dbgObject, environment, sandbox) { }); test_has_exact_results(results, ["'hello'"]); - info("Test children getters are not executed if not included in authorizedEvaluation"); + info( + "Test children getters are not executed if not included in authorizedEvaluation" + ); results = propertyProvider("testGetters.y.y.", { authorizedEvaluations: [["testGetters", "y", "y"]], }); - Assert.deepEqual(results, {isUnsafeGetter: true, getterPath: ["testGetters", "y"]}); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); - info("Test children getters are executed if matching an authorizedEvaluation element"); + info( + "Test children getters are executed if matching an authorizedEvaluation element" + ); results = propertyProvider("testGetters.y.y.", { authorizedEvaluations: [["testGetters", "y"], ["testGetters", "y", "y"]], }); @@ -438,8 +504,10 @@ function runChecks(dbgObject, environment, sandbox) { info("Test access on dot-notation invalid property name"); results = propertyProvider("testHyphenated.prop"); - Assert.ok(!results.matches.has("prop-A"), - "Does not return invalid property name on dot access"); + Assert.ok( + !results.matches.has("prop-A"), + "Does not return invalid property name on dot access" + ); results = propertyProvider("testHyphenated['prop"); test_has_result(results, `'prop-A'`); diff --git a/devtools/shared/webconsole/test/unit/test_network_helper.js b/devtools/shared/webconsole/test/unit/test_network_helper.js index 600a6581fd94..bad2c319be9f 100644 --- a/devtools/shared/webconsole/test/unit/test_network_helper.js +++ b/devtools/shared/webconsole/test/unit/test_network_helper.js @@ -27,25 +27,41 @@ function test_isTextMimeType() { Assert.equal(NetworkHelper.isTextMimeType("application/xml"), true); // Test custom JSON subtype - Assert.equal(NetworkHelper - .isTextMimeType("application/vnd.tent.posts-feed.v0+json"), true); - Assert.equal(NetworkHelper - .isTextMimeType("application/vnd.tent.posts-feed.v0-json"), true); + Assert.equal( + NetworkHelper.isTextMimeType("application/vnd.tent.posts-feed.v0+json"), + true + ); + Assert.equal( + NetworkHelper.isTextMimeType("application/vnd.tent.posts-feed.v0-json"), + true + ); // Test custom XML subtype - Assert.equal(NetworkHelper - .isTextMimeType("application/vnd.tent.posts-feed.v0+xml"), true); - Assert.equal(NetworkHelper - .isTextMimeType("application/vnd.tent.posts-feed.v0-xml"), false); + Assert.equal( + NetworkHelper.isTextMimeType("application/vnd.tent.posts-feed.v0+xml"), + true + ); + Assert.equal( + NetworkHelper.isTextMimeType("application/vnd.tent.posts-feed.v0-xml"), + false + ); // Test case-insensitive - Assert.equal(NetworkHelper.isTextMimeType("application/vnd.BIG-CORP+json"), true); + Assert.equal( + NetworkHelper.isTextMimeType("application/vnd.BIG-CORP+json"), + true + ); // Test non-text type Assert.equal(NetworkHelper.isTextMimeType("image/png"), false); // Test invalid types Assert.equal(NetworkHelper.isTextMimeType("application/foo-+json"), false); Assert.equal(NetworkHelper.isTextMimeType("application/-foo+json"), false); - Assert.equal(NetworkHelper.isTextMimeType("application/foo--bar+json"), false); + Assert.equal( + NetworkHelper.isTextMimeType("application/foo--bar+json"), + false + ); // Test we do not cause internal errors with unoptimized regex. Bug 961097 - Assert.equal(NetworkHelper - .isTextMimeType("application/vnd.google.safebrowsing-chunk"), false); + Assert.equal( + NetworkHelper.isTextMimeType("application/vnd.google.safebrowsing-chunk"), + false + ); } diff --git a/devtools/shared/webconsole/test/unit/test_security-info-certificate.js b/devtools/shared/webconsole/test/unit/test_security-info-certificate.js index d096b81aeaec..8bd36cb4ed1f 100644 --- a/devtools/shared/webconsole/test/unit/test_security-info-certificate.js +++ b/devtools/shared/webconsole/test/unit/test_security-info-certificate.js @@ -38,30 +38,60 @@ function run_test() { const result = NetworkHelper.parseCertificateInfo(DUMMY_CERT); // Subject - equal(result.subject.commonName, DUMMY_CERT.commonName, - "Common name is correct."); - equal(result.subject.organization, DUMMY_CERT.organization, - "Organization is correct."); - equal(result.subject.organizationUnit, DUMMY_CERT.organizationUnit, - "Organizational unit is correct."); + equal( + result.subject.commonName, + DUMMY_CERT.commonName, + "Common name is correct." + ); + equal( + result.subject.organization, + DUMMY_CERT.organization, + "Organization is correct." + ); + equal( + result.subject.organizationUnit, + DUMMY_CERT.organizationUnit, + "Organizational unit is correct." + ); // Issuer - equal(result.issuer.commonName, DUMMY_CERT.issuerCommonName, - "Common name of the issuer is correct."); - equal(result.issuer.organization, DUMMY_CERT.issuerOrganization, - "Organization of the issuer is correct."); - equal(result.issuer.organizationUnit, DUMMY_CERT.issuerOrganizationUnit, - "Organizational unit of the issuer is correct."); + equal( + result.issuer.commonName, + DUMMY_CERT.issuerCommonName, + "Common name of the issuer is correct." + ); + equal( + result.issuer.organization, + DUMMY_CERT.issuerOrganization, + "Organization of the issuer is correct." + ); + equal( + result.issuer.organizationUnit, + DUMMY_CERT.issuerOrganizationUnit, + "Organizational unit of the issuer is correct." + ); // Validity - equal(result.validity.start, DUMMY_CERT.validity.notBeforeLocalDay, - "Start of the validity period is correct."); - equal(result.validity.end, DUMMY_CERT.validity.notAfterLocalDay, - "End of the validity period is correct."); + equal( + result.validity.start, + DUMMY_CERT.validity.notBeforeLocalDay, + "Start of the validity period is correct." + ); + equal( + result.validity.end, + DUMMY_CERT.validity.notAfterLocalDay, + "End of the validity period is correct." + ); // Fingerprints - equal(result.fingerprint.sha1, DUMMY_CERT.sha1Fingerprint, - "Certificate SHA1 fingerprint is correct."); - equal(result.fingerprint.sha256, DUMMY_CERT.sha256Fingerprint, - "Certificate SHA256 fingerprint is correct."); + equal( + result.fingerprint.sha1, + DUMMY_CERT.sha1Fingerprint, + "Certificate SHA1 fingerprint is correct." + ); + equal( + result.fingerprint.sha256, + DUMMY_CERT.sha256Fingerprint, + "Certificate SHA256 fingerprint is correct." + ); } diff --git a/devtools/shared/webconsole/test/unit/test_security-info-parser.js b/devtools/shared/webconsole/test/unit/test_security-info-parser.js index dfcda3a50355..692b342efba6 100644 --- a/devtools/shared/webconsole/test/unit/test_security-info-parser.js +++ b/devtools/shared/webconsole/test/unit/test_security-info-parser.js @@ -47,13 +47,19 @@ function run_test() { equal(result.state, "secure", "State is correct."); - equal(result.cipherSuite, MockSecurityInfo.cipherName, - "Cipher suite is correct."); + equal( + result.cipherSuite, + MockSecurityInfo.cipherName, + "Cipher suite is correct." + ); equal(result.protocolVersion, "TLSv1.2", "Protocol version is correct."); - deepEqual(result.cert, NetworkHelper.parseCertificateInfo(MockCertificate), - "Certificate information is correct."); + deepEqual( + result.cert, + NetworkHelper.parseCertificateInfo(MockCertificate), + "Certificate information is correct." + ); equal(result.hpkp, false, "HPKP is false when URI is not available."); equal(result.hsts, false, "HSTS is false when URI is not available."); diff --git a/devtools/shared/webconsole/test/unit/test_security-info-protocol-version.js b/devtools/shared/webconsole/test/unit/test_security-info-protocol-version.js index a2acd6c3134b..9006d12a2818 100644 --- a/devtools/shared/webconsole/test/unit/test_security-info-protocol-version.js +++ b/devtools/shared/webconsole/test/unit/test_security-info-protocol-version.js @@ -22,19 +22,23 @@ const TEST_CASES = [ description: "TLS_VERSION_1", input: 1, expected: "TLSv1", - }, { + }, + { description: "TLS_VERSION_1.1", input: 2, expected: "TLSv1.1", - }, { + }, + { description: "TLS_VERSION_1.2", input: 3, expected: "TLSv1.2", - }, { + }, + { description: "TLS_VERSION_1.3", input: 4, expected: "TLSv1.3", - }, { + }, + { description: "invalid version", input: -1, expected: "Unknown", @@ -44,10 +48,13 @@ const TEST_CASES = [ function run_test() { info("Testing NetworkHelper.formatSecurityProtocol."); - for (const {description, input, expected} of TEST_CASES) { + for (const { description, input, expected } of TEST_CASES) { info("Testing " + description); - equal(NetworkHelper.formatSecurityProtocol(input), expected, - "Got the expected protocol string."); + equal( + NetworkHelper.formatSecurityProtocol(input), + expected, + "Got the expected protocol string." + ); } } diff --git a/devtools/shared/webconsole/test/unit/test_security-info-state.js b/devtools/shared/webconsole/test/unit/test_security-info-state.js index a103321a3bd7..8e9212eb768a 100644 --- a/devtools/shared/webconsole/test/unit/test_security-info-state.js +++ b/devtools/shared/webconsole/test/unit/test_security-info-state.js @@ -40,8 +40,11 @@ function run_test() { */ function test_nullSecurityInfo() { const result = NetworkHelper.parseSecurityInfo(null, {}); - equal(result.state, "insecure", - "state == 'insecure' when securityInfo was undefined"); + equal( + result.state, + "insecure", + "state == 'insecure' when securityInfo was undefined" + ); } /** @@ -54,9 +57,12 @@ function test_insecureSecurityInfoWithNSSError() { MockSecurityInfo.errorCode = -8180; const result = NetworkHelper.parseSecurityInfo(MockSecurityInfo, {}); - equal(result.state, "broken", + equal( + result.state, + "broken", "state == 'broken' if securityState contains STATE_IS_INSECURE flag AND " + - "errorCode is NSS error."); + "errorCode is NSS error." + ); MockSecurityInfo.errorCode = 0; } @@ -68,9 +74,12 @@ function test_insecureSecurityInfoWithoutNSSError() { MockSecurityInfo.securityState = wpl.STATE_IS_INSECURE; const result = NetworkHelper.parseSecurityInfo(MockSecurityInfo, {}); - equal(result.state, "insecure", + equal( + result.state, + "insecure", "state == 'insecure' if securityState contains STATE_IS_INSECURE flag BUT " + - "errorCode is not NSS error."); + "errorCode is not NSS error." + ); } /** @@ -80,8 +89,11 @@ function test_secureSecurityInfo() { MockSecurityInfo.securityState = wpl.STATE_IS_SECURE; const result = NetworkHelper.parseSecurityInfo(MockSecurityInfo, {}); - equal(result.state, "secure", - "state == 'secure' if securityState contains STATE_IS_SECURE flag"); + equal( + result.state, + "secure", + "state == 'secure' if securityState contains STATE_IS_SECURE flag" + ); } /** @@ -91,6 +103,9 @@ function test_brokenSecurityInfo() { MockSecurityInfo.securityState = wpl.STATE_IS_BROKEN; const result = NetworkHelper.parseSecurityInfo(MockSecurityInfo, {}); - equal(result.state, "weak", - "state == 'weak' if securityState contains STATE_IS_BROKEN flag"); + equal( + result.state, + "weak", + "state == 'weak' if securityState contains STATE_IS_BROKEN flag" + ); } diff --git a/devtools/shared/webconsole/test/unit/test_security-info-static-hpkp.js b/devtools/shared/webconsole/test/unit/test_security-info-static-hpkp.js index 1650079ff33d..d1e4415beb74 100644 --- a/devtools/shared/webconsole/test/unit/test_security-info-static-hpkp.js +++ b/devtools/shared/webconsole/test/unit/test_security-info-static-hpkp.js @@ -38,6 +38,9 @@ const MockHttpInfo = { function run_test() { Services.prefs.setIntPref("security.cert_pinning.enforcement_level", 1); - const result = NetworkHelper.parseSecurityInfo(MockSecurityInfo, MockHttpInfo); + const result = NetworkHelper.parseSecurityInfo( + MockSecurityInfo, + MockHttpInfo + ); equal(result.hpkp, true, "Static HPKP detected."); } diff --git a/devtools/shared/webconsole/test/unit/test_security-info-weakness-reasons.js b/devtools/shared/webconsole/test/unit/test_security-info-weakness-reasons.js index 799e6268c362..6f60a7298289 100644 --- a/devtools/shared/webconsole/test/unit/test_security-info-weakness-reasons.js +++ b/devtools/shared/webconsole/test/unit/test_security-info-weakness-reasons.js @@ -23,11 +23,13 @@ const TEST_CASES = [ description: "weak cipher", input: wpl.STATE_IS_BROKEN | wpl.STATE_USES_WEAK_CRYPTO, expected: ["cipher"], - }, { + }, + { description: "only STATE_IS_BROKEN flag", input: wpl.STATE_IS_BROKEN, expected: [], - }, { + }, + { description: "only STATE_IS_SECURE flag", input: wpl.STATE_IS_SECURE, expected: [], @@ -37,10 +39,13 @@ const TEST_CASES = [ function run_test() { info("Testing NetworkHelper.getReasonsForWeakness."); - for (const {description, input, expected} of TEST_CASES) { + for (const { description, input, expected } of TEST_CASES) { info("Testing " + description); - deepEqual(NetworkHelper.getReasonsForWeakness(input), expected, - "Got the expected reasons for weakness."); + deepEqual( + NetworkHelper.getReasonsForWeakness(input), + expected, + "Got the expected reasons for weakness." + ); } } diff --git a/devtools/shared/webconsole/test/unit/test_throttle.js b/devtools/shared/webconsole/test/unit/test_throttle.js index e1d05236c958..870126ea9737 100644 --- a/devtools/shared/webconsole/test/unit/test_throttle.js +++ b/devtools/shared/webconsole/test/unit/test_throttle.js @@ -7,8 +7,9 @@ const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); const defer = require("devtools/shared/defer"); -const { NetworkThrottleManager } = - require("devtools/shared/webconsole/throttle"); +const { + NetworkThrottleManager, +} = require("devtools/shared/webconsole/throttle"); const nsIScriptableInputStream = Ci.nsIScriptableInputStream; function TestStreamListener() { @@ -24,8 +25,9 @@ TestStreamListener.prototype = { }, onDataAvailable: function(request, inputStream, offset, count) { - const sin = Cc["@mozilla.org/scriptableinputstream;1"] - .createInstance(nsIScriptableInputStream); + const sin = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + nsIScriptableInputStream + ); sin.init(inputStream); this.data = sin.read(count); this.setState("data"); @@ -85,15 +87,21 @@ add_task(async function() { const uploadChannel = new TestChannel(); throttler.manageUpload(uploadChannel); - equal(uploadChannel.state, "throttled", - "NetworkThrottleManager set throttleQueue"); + equal( + uploadChannel.state, + "throttled", + "NetworkThrottleManager set throttleQueue" + ); const downloadChannel = new TestChannel(); const testListener = downloadChannel.testListener; const listener = throttler.manage(downloadChannel); - equal(downloadChannel.state, "listener", - "NetworkThrottleManager called setNewListener"); + equal( + downloadChannel.state, + "listener", + "NetworkThrottleManager called setNewListener" + ); equal(testListener.state, "initial", "test listener in initial state"); @@ -103,32 +111,40 @@ add_task(async function() { const TEST_INPUT = "hi bob"; - const testStream = Cc["@mozilla.org/storagestream;1"] - .createInstance(Ci.nsIStorageStream); + const testStream = Cc["@mozilla.org/storagestream;1"].createInstance( + Ci.nsIStorageStream + ); testStream.init(512, 512); const out = testStream.getOutputStream(0); out.write(TEST_INPUT, TEST_INPUT.length); out.close(); const testInputStream = testStream.newInputStream(0); - const activityDistributor = - Cc["@mozilla.org/network/http-activity-distributor;1"] - .getService(Ci.nsIHttpActivityDistributor); + const activityDistributor = Cc[ + "@mozilla.org/network/http-activity-distributor;1" + ].getService(Ci.nsIHttpActivityDistributor); let activitySeen = false; listener.addActivityCallback( () => { activitySeen = true; }, - null, null, null, + null, + null, + null, activityDistributor.ACTIVITY_SUBTYPE_RESPONSE_COMPLETE, - null, TEST_INPUT.length, null + null, + TEST_INPUT.length, + null ); // onDataAvailable is required to immediately read the data. listener.onDataAvailable(null, testInputStream, 0, 6); equal(testInputStream.available(), 0, "no more data should be available"); - equal(testListener.state, "start", - "test listener should not have received data"); + equal( + testListener.state, + "start", + "test listener should not have received data" + ); equal(activitySeen, false, "activity not distributed yet"); let newState = await testListener.onStateChanged(); diff --git a/devtools/shared/webconsole/throttle.js b/devtools/shared/webconsole/throttle.js index 473ef52296b2..6ade992e70f9 100644 --- a/devtools/shared/webconsole/throttle.js +++ b/devtools/shared/webconsole/throttle.js @@ -6,19 +6,27 @@ "use strict"; -const {CC, Ci, Cc} = require("chrome"); +const { CC, Ci, Cc } = require("chrome"); -const ArrayBufferInputStream = CC("@mozilla.org/io/arraybuffer-input-stream;1", - "nsIArrayBufferInputStream"); -const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", "setInputStream"); +const ArrayBufferInputStream = CC( + "@mozilla.org/io/arraybuffer-input-stream;1", + "nsIArrayBufferInputStream" +); +const BinaryInputStream = CC( + "@mozilla.org/binaryinputstream;1", + "nsIBinaryInputStream", + "setInputStream" +); -loader.lazyServiceGetter(this, "gActivityDistributor", - "@mozilla.org/network/http-activity-distributor;1", - "nsIHttpActivityDistributor"); +loader.lazyServiceGetter( + this, + "gActivityDistributor", + "@mozilla.org/network/http-activity-distributor;1", + "nsIHttpActivityDistributor" +); const ChromeUtils = require("ChromeUtils"); -const {setTimeout} = require("resource://gre/modules/Timer.jsm"); +const { setTimeout } = require("resource://gre/modules/Timer.jsm"); /** * Construct a new nsIStreamListener that buffers data and provides a @@ -41,8 +49,10 @@ function NetworkThrottleListener(queue) { } NetworkThrottleListener.prototype = { - QueryInterface: - ChromeUtils.generateQI([Ci.nsIStreamListener, Ci.nsIInterfaceRequestor]), + QueryInterface: ChromeUtils.generateQI([ + Ci.nsIStreamListener, + Ci.nsIInterfaceRequestor, + ]), /** * Set the original listener for this object. The original listener @@ -68,7 +78,7 @@ NetworkThrottleListener.prototype = { * @see nsIStreamListener.onStopRequest. */ onStopRequest: function(request, statusCode) { - this.pendingData.push({request, statusCode}); + this.pendingData.push({ request, statusCode }); this.queue.dataAvailable(this); }, @@ -87,7 +97,7 @@ NetworkThrottleListener.prototype = { const stream = new ArrayBufferInputStream(); stream.setData(bytes, 0, count); - this.pendingData.push({request, stream, count}); + this.pendingData.push({ request, stream, count }); this.queue.dataAvailable(this); }, @@ -107,15 +117,15 @@ NetworkThrottleListener.prototype = { sendSomeData: function(bytesPermitted) { if (this.pendingData.length === 0) { // Shouldn't happen. - return {length: 0, done: true}; + return { length: 0, done: true }; } - const {request, stream, count, statusCode} = this.pendingData[0]; + const { request, stream, count, statusCode } = this.pendingData[0]; if (statusCode !== undefined) { this.pendingData.shift(); this.originalListener.onStopRequest(request, statusCode); - return {length: 0, done: true}; + return { length: 0, done: true }; } if (bytesPermitted > count) { @@ -123,8 +133,12 @@ NetworkThrottleListener.prototype = { } try { - this.originalListener.onDataAvailable(request, stream, - this.offset, bytesPermitted); + this.originalListener.onDataAvailable( + request, + stream, + this.offset, + bytesPermitted + ); } catch (e) { this.pendingException = e; } @@ -141,7 +155,7 @@ NetworkThrottleListener.prototype = { // Maybe our state has changed enough to emit an event. this.maybeEmitEvents(); - return {length: bytesPermitted, done}; + return { length: bytesPermitted, done }; }, /** @@ -156,16 +170,31 @@ NetworkThrottleListener.prototype = { * This is called when an http activity event is delivered. This * object delays the event until the appropriate moment. */ - addActivityCallback: function(callback, httpActivity, channel, activityType, - activitySubtype, timestamp, extraSizeData, - extraStringData) { - const datum = {callback, httpActivity, channel, activityType, - activitySubtype, extraSizeData, - extraStringData}; + addActivityCallback: function( + callback, + httpActivity, + channel, + activityType, + activitySubtype, + timestamp, + extraSizeData, + extraStringData + ) { + const datum = { + callback, + httpActivity, + channel, + activityType, + activitySubtype, + extraSizeData, + extraStringData, + }; this.activities[activitySubtype] = datum; - if (activitySubtype === - gActivityDistributor.ACTIVITY_SUBTYPE_RESPONSE_COMPLETE) { + if ( + activitySubtype === + gActivityDistributor.ACTIVITY_SUBTYPE_RESPONSE_COMPLETE + ) { this.totalSize = extraSizeData; } @@ -207,12 +236,25 @@ NetworkThrottleListener.prototype = { */ maybeEmit: function(code) { if (this.activities[code] !== undefined) { - const {callback, httpActivity, channel, activityType, - activitySubtype, extraSizeData, - extraStringData} = this.activities[code]; + const { + callback, + httpActivity, + channel, + activityType, + activitySubtype, + extraSizeData, + extraStringData, + } = this.activities[code]; const now = Date.now() * 1000; - callback(httpActivity, channel, activityType, activitySubtype, - now, extraSizeData, extraStringData); + callback( + httpActivity, + channel, + activityType, + activitySubtype, + now, + extraSizeData, + extraStringData + ); this.activities[code] = undefined; } }, @@ -312,8 +354,10 @@ NetworkThrottleQueue.prototype = { const now = Date.now(); const oneSecondAgo = now - 1000; - while (this.previousReads.length && - this.previousReads[0].when < oneSecondAgo) { + while ( + this.previousReads.length && + this.previousReads[0].when < oneSecondAgo + ) { this.previousReads.shift(); } @@ -326,14 +370,16 @@ NetworkThrottleQueue.prototype = { thisSliceBytes -= totalBytes; let readThisTime = 0; while (thisSliceBytes > 0 && this.downloadQueue.length) { - const {length, done} = this.downloadQueue[0].sendSomeData(thisSliceBytes); + const { length, done } = this.downloadQueue[0].sendSomeData( + thisSliceBytes + ); thisSliceBytes -= length; readThisTime += length; if (done) { this.downloadQueue.shift(); } } - this.previousReads.push({when: now, numBytes: readThisTime}); + this.previousReads.push({ when: now, numBytes: readThisTime }); } // If there is more data to download, then schedule ourselves for @@ -363,21 +409,30 @@ NetworkThrottleQueue.prototype = { * downloadBPSMax are <= 0. Upload throttling will not be done if * uploadBPSMean and uploadBPSMax are <= 0. */ -function NetworkThrottleManager({latencyMean, latencyMax, - downloadBPSMean, downloadBPSMax, - uploadBPSMean, uploadBPSMax}) { +function NetworkThrottleManager({ + latencyMean, + latencyMax, + downloadBPSMean, + downloadBPSMax, + uploadBPSMean, + uploadBPSMax, +}) { if (downloadBPSMax <= 0 && downloadBPSMean <= 0) { this.downloadQueue = null; } else { - this.downloadQueue = - new NetworkThrottleQueue(downloadBPSMean, downloadBPSMax, - latencyMean, latencyMax); + this.downloadQueue = new NetworkThrottleQueue( + downloadBPSMean, + downloadBPSMax, + latencyMean, + latencyMax + ); } if (uploadBPSMax <= 0 && uploadBPSMean <= 0) { this.uploadQueue = null; } else { - this.uploadQueue = Cc["@mozilla.org/network/throttlequeue;1"] - .createInstance(Ci.nsIInputChannelThrottleQueue); + this.uploadQueue = Cc[ + "@mozilla.org/network/throttlequeue;1" + ].createInstance(Ci.nsIInputChannelThrottleQueue); this.uploadQueue.init(uploadBPSMean, uploadBPSMax); } } diff --git a/devtools/shared/worker/helper.js b/devtools/shared/worker/helper.js index 84bf358dd24d..a7a9e6a1527a 100644 --- a/devtools/shared/worker/helper.js +++ b/devtools/shared/worker/helper.js @@ -14,7 +14,7 @@ } else { root.workerHelper = factory(); } -}(this, function() { +})(this, function() { /** * This file is to only be included by ChromeWorkers. This exposes * a `createTask` function to workers to register tasks for communication @@ -90,7 +90,10 @@ function handleResponse(response) { // If a promise if (response && typeof response.then === "function") { - response.then(val => self.postMessage({ id, response: val }), handleError); + response.then( + val => self.postMessage({ id, response: val }), + handleError + ); } else if (response instanceof Error) { // If an error object handleError(response); @@ -130,4 +133,4 @@ } return { createTask: createTask }; -})); +}); diff --git a/devtools/shared/worker/loader.js b/devtools/shared/worker/loader.js index ce66b2b5c0f4..f28aae957254 100644 --- a/devtools/shared/worker/loader.js +++ b/devtools/shared/worker/loader.js @@ -172,7 +172,7 @@ function lazyRequire(obj, moduleId, ...args) { for (let props of args) { if (typeof props !== "object") { - props = {[props]: props}; + props = { [props]: props }; } for (const [fromName, toName] of Object.entries(props)) { @@ -273,8 +273,9 @@ function WorkerDebuggerLoader(options) { loadSubScript(url, sandbox); } catch (error) { if (/^Error opening input stream/.test(String(error))) { - throw new Error("Can't load module '" + module.id + "' with url '" + - url + "'!"); + throw new Error( + "Can't load module '" + module.id + "' with url '" + url + "'!" + ); } throw error; } @@ -313,8 +314,12 @@ function WorkerDebuggerLoader(options) { // If the id is relative, convert it to an absolute id. if (id.startsWith(".")) { if (requirer === undefined) { - throw new Error("Can't require top-level module with relative id " + - "'" + id + "'!"); + throw new Error( + "Can't require top-level module with relative id " + + "'" + + id + + "'!" + ); } id = resolve(id, requirer.id); } @@ -379,8 +384,8 @@ function WorkerDebuggerLoader(options) { // longest path is always the first to be found. let paths = options.paths || Object.create(null); paths = Object.keys(paths) - .sort((a, b) => b.length - a.length) - .map(path => [path, paths[path]]); + .sort((a, b) => b.length - a.length) + .map(path => [path, paths[path]]); const resolve = options.resolve || resolveId; @@ -424,8 +429,10 @@ var loader = { }, lazyRequireGetter: function(obj, property, module, destructure) { Object.defineProperty(obj, property, { - get: () => destructure ? worker.require(module)[property] - : worker.require(module || property), + get: () => + destructure + ? worker.require(module)[property] + : worker.require(module || property), }); }, }; @@ -446,7 +453,7 @@ var { reportError, setImmediate, xpcInspector, -} = (function() { +} = function() { // Main thread if (typeof Components === "object") { const { Constructor: CC } = Components; @@ -458,7 +465,7 @@ var { const sandbox = Cu.Sandbox(principal, {}); Cu.evalInSandbox( "Components.utils.import('resource://gre/modules/jsdebugger.jsm');" + - "addDebuggerToGlobal(this);", + "addDebuggerToGlobal(this);", sandbox ); const Debugger = sandbox.Debugger; @@ -476,8 +483,9 @@ var { const rpc = undefined; // eslint-disable-next-line mozilla/use-services - const subScriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"] - .getService(Ci.mozIJSSubScriptLoader); + const subScriptLoader = Cc[ + "@mozilla.org/moz/jssubscript-loader;1" + ].getService(Ci.mozIJSSubScriptLoader); const loadSubScript = function(url, sandbox) { subScriptLoader.loadSubScript(url, sandbox); @@ -491,8 +499,9 @@ var { Timer.setTimeout(callback, 0); }; - const xpcInspector = Cc["@mozilla.org/jsinspector;1"] - .getService(Ci.nsIJSInspector); + const xpcInspector = Cc["@mozilla.org/jsinspector;1"].getService( + Ci.nsIJSInspector + ); return { Debugger, @@ -544,7 +553,7 @@ var { setImmediate: this.setImmediate, xpcInspector: xpcInspector, }; -}).call(this); +}.call(this); /* eslint-enable no-shadow */ // Create the default instance of the worker loader, using the APIs we defined @@ -553,36 +562,36 @@ var { this.worker = new WorkerDebuggerLoader({ createSandbox: createSandbox, globals: { - "isWorker": true, - "isReplaying": false, - "dump": dump, - "loader": loader, - "reportError": reportError, - "rpc": rpc, - "URL": URL, - "setImmediate": setImmediate, - "lazyRequire": lazyRequire, - "lazyRequireModule": lazyRequireModule, - "retrieveConsoleEvents": this.retrieveConsoleEvents, - "setConsoleEventHandler": this.setConsoleEventHandler, - "console": console, - "btoa": this.btoa, - "atob": this.atob, + isWorker: true, + isReplaying: false, + dump: dump, + loader: loader, + reportError: reportError, + rpc: rpc, + URL: URL, + setImmediate: setImmediate, + lazyRequire: lazyRequire, + lazyRequireModule: lazyRequireModule, + retrieveConsoleEvents: this.retrieveConsoleEvents, + setConsoleEventHandler: this.setConsoleEventHandler, + console: console, + btoa: this.btoa, + atob: this.atob, }, loadSubScript: loadSubScript, modules: { - "Debugger": Debugger, - "Services": Object.create(null), - "chrome": chrome, - "xpcInspector": xpcInspector, - "ChromeUtils": ChromeUtils, - "DebuggerNotificationObserver": DebuggerNotificationObserver, + Debugger: Debugger, + Services: Object.create(null), + chrome: chrome, + xpcInspector: xpcInspector, + ChromeUtils: ChromeUtils, + DebuggerNotificationObserver: DebuggerNotificationObserver, }, paths: { // ⚠ DISCUSSION ON DEV-DEVELOPER-TOOLS REQUIRED BEFORE MODIFYING ⚠ - "devtools": "resource://devtools", + devtools: "resource://devtools", // ⚠ DISCUSSION ON DEV-DEVELOPER-TOOLS REQUIRED BEFORE MODIFYING ⚠ - "promise": "resource://gre/modules/Promise-backend.js", + promise: "resource://gre/modules/Promise-backend.js", // ⚠ DISCUSSION ON DEV-DEVELOPER-TOOLS REQUIRED BEFORE MODIFYING ⚠ "xpcshell-test": "resource://test", // ⚠ DISCUSSION ON DEV-DEVELOPER-TOOLS REQUIRED BEFORE MODIFYING ⚠ diff --git a/devtools/shared/worker/tests/browser/browser_worker-01.js b/devtools/shared/worker/tests/browser/browser_worker-01.js index 1b20ec423a4d..e3c0fbd0aeb9 100644 --- a/devtools/shared/worker/tests/browser/browser_worker-01.js +++ b/devtools/shared/worker/tests/browser/browser_worker-01.js @@ -6,8 +6,7 @@ // Tests that the devtools/shared/worker communicates properly // as both CommonJS module and as a JSM. -const WORKER_URL = - "resource://devtools/client/shared/widgets/GraphsWorker.js"; +const WORKER_URL = "resource://devtools/client/shared/widgets/GraphsWorker.js"; const BUFFER_SIZE = 8; const count = 100000; @@ -24,7 +23,9 @@ const DURATION = 1000; add_task(async function() { // Test both CJS and JSM versions - await testWorker("JSM", () => ChromeUtils.import("resource://devtools/shared/worker/worker.js", null)); + await testWorker("JSM", () => + ChromeUtils.import("resource://devtools/shared/worker/worker.js", null) + ); await testWorker("CommonJS", () => require("devtools/shared/worker/worker")); await testTransfer(); }); @@ -38,28 +39,36 @@ async function testWorker(context, workerFactory) { duration: DURATION, }); - ok(results.plottedData.length, - `worker should have returned an object with array properties in ${context}`); + ok( + results.plottedData.length, + `worker should have returned an object with array properties in ${context}` + ); const fn = workerify(x => x * x); - is((await fn(5)), 25, `workerify works in ${context}`); + is(await fn(5), 25, `workerify works in ${context}`); fn.destroy(); worker.destroy(); } async function testTransfer() { - const { workerify } = - ChromeUtils.import("resource://devtools/shared/worker/worker.js", null); + const { workerify } = ChromeUtils.import( + "resource://devtools/shared/worker/worker.js", + null + ); const workerFn = workerify(({ buf }) => buf.byteLength); const buf = new ArrayBuffer(BUFFER_SIZE); - is(buf.byteLength, BUFFER_SIZE, "Size of the buffer before transfer is correct."); + is( + buf.byteLength, + BUFFER_SIZE, + "Size of the buffer before transfer is correct." + ); - is((await workerFn({ buf })), 8, "Sent array buffer to worker"); + is(await workerFn({ buf }), 8, "Sent array buffer to worker"); is(buf.byteLength, 8, "Array buffer was copied, not transferred."); - is((await workerFn({ buf }, [ buf ])), 8, "Sent array buffer to worker"); + is(await workerFn({ buf }, [buf]), 8, "Sent array buffer to worker"); is(buf.byteLength, 0, "Array buffer was transferred, not copied."); workerFn.destroy(); diff --git a/devtools/shared/worker/tests/browser/browser_worker-02.js b/devtools/shared/worker/tests/browser/browser_worker-02.js index f21325f0a465..6cf2e2d9ad50 100644 --- a/devtools/shared/worker/tests/browser/browser_worker-02.js +++ b/devtools/shared/worker/tests/browser/browser_worker-02.js @@ -6,8 +6,7 @@ // Tests errors are handled properly by the DevToolsWorker. const { DevToolsWorker } = require("devtools/shared/worker/worker"); -const WORKER_URL = - "resource://devtools/client/shared/widgets/GraphsWorker.js"; +const WORKER_URL = "resource://devtools/client/shared/widgets/GraphsWorker.js"; add_task(async function() { try { @@ -22,18 +21,28 @@ add_task(async function() { // plotTimestampsGraph requires timestamp, interval an duration props on the object // passed in so there should be an error thrown in the worker await worker.performTask("plotTimestampsGraph", {}); - ok(false, - "DevToolsWorker returns a rejected promise when an error occurs in the worker"); + ok( + false, + "DevToolsWorker returns a rejected promise when an error occurs in the worker" + ); } catch (e) { - ok(true, - "DevToolsWorker returns a rejected promise when an error occurs in the worker"); + ok( + true, + "DevToolsWorker returns a rejected promise when an error occurs in the worker" + ); } try { await worker.performTask("not a real task"); - ok(false, "DevToolsWorker returns a rejected promise when task does not exist"); + ok( + false, + "DevToolsWorker returns a rejected promise when task does not exist" + ); } catch (e) { - ok(true, "DevToolsWorker returns a rejected promise when task does not exist"); + ok( + true, + "DevToolsWorker returns a rejected promise when task does not exist" + ); } worker.destroy(); @@ -43,8 +52,14 @@ add_task(async function() { interval: 1, duration: 1, }); - ok(false, "DevToolsWorker rejects when performing a task on a destroyed worker"); + ok( + false, + "DevToolsWorker rejects when performing a task on a destroyed worker" + ); } catch (e) { - ok(true, "DevToolsWorker rejects when performing a task on a destroyed worker"); + ok( + true, + "DevToolsWorker rejects when performing a task on a destroyed worker" + ); } }); diff --git a/devtools/shared/worker/tests/browser/browser_worker-03.js b/devtools/shared/worker/tests/browser/browser_worker-03.js index c45f6f1f4305..ec8c74353e4e 100644 --- a/devtools/shared/worker/tests/browser/browser_worker-03.js +++ b/devtools/shared/worker/tests/browser/browser_worker-03.js @@ -14,7 +14,7 @@ function square(x) { } function squarePromise(x) { - return new Promise((resolve) => resolve(x * x)); + return new Promise(resolve => resolve(x * x)); } function squareError(x) { @@ -27,11 +27,11 @@ function squarePromiseReject(x) { add_task(async function() { let fn = workerify(square); - is((await fn(5)), 25, "return primitives successful"); + is(await fn(5), 25, "return primitives successful"); fn.destroy(); fn = workerify(squarePromise); - is((await fn(5)), 25, "promise primitives successful"); + is(await fn(5), 25, "promise primitives successful"); fn.destroy(); fn = workerify(squareError); diff --git a/devtools/shared/worker/worker.js b/devtools/shared/worker/worker.js index 08966881c1fc..fb17ff234dc6 100644 --- a/devtools/shared/worker/worker.js +++ b/devtools/shared/worker/worker.js @@ -11,20 +11,42 @@ // require const { Cc, Ci, Cu, ChromeWorker } = require("chrome"); const dumpn = require("devtools/shared/DevToolsUtils").dumpn; - factory.call(this, require, exports, module, { Cc, Ci, Cu }, ChromeWorker, dumpn); + factory.call( + this, + require, + exports, + module, + { Cc, Ci, Cu }, + ChromeWorker, + dumpn + ); } else { // Cu.import - const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); + const { require } = ChromeUtils.import( + "resource://devtools/shared/Loader.jsm" + ); this.isWorker = false; this.Promise = require("resource://gre/modules/Promise.jsm").Promise; this.console = console; factory.call( - this, require, this, { exports: this }, - { Cc, Ci, Cu }, ChromeWorker, null + this, + require, + this, + { exports: this }, + { Cc, Ci, Cu }, + ChromeWorker, + null ); this.EXPORTED_SYMBOLS = ["DevToolsWorker"]; } -}).call(this, function(require, exports, module, { Ci, Cc }, ChromeWorker, dumpn) { +}.call(this, function( + require, + exports, + module, + { Ci, Cc }, + ChromeWorker, + dumpn +) { let MESSAGE_COUNTER = 0; /** @@ -66,27 +88,33 @@ */ DevToolsWorker.prototype.performTask = function(task, data, transfer) { if (this._destroyed) { - return Promise.reject("Cannot call performTask on a destroyed DevToolsWorker"); + return Promise.reject( + "Cannot call performTask on a destroyed DevToolsWorker" + ); } const worker = this._worker; const id = ++MESSAGE_COUNTER; const payload = { task, id, data }; if (this._verbose && dumpn) { - dumpn("Sending message to worker" + - (this._name ? (" (" + this._name + ")") : "") + - ": " + - JSON.stringify(payload, null, 2)); + dumpn( + "Sending message to worker" + + (this._name ? " (" + this._name + ")" : "") + + ": " + + JSON.stringify(payload, null, 2) + ); } worker.postMessage(payload, transfer); return new Promise((resolve, reject) => { const listener = ({ data: result }) => { if (this._verbose && dumpn) { - dumpn("Received message from worker" + - (this._name ? (" (" + this._name + ")") : "") + - ": " + - JSON.stringify(result, null, 2)); + dumpn( + "Received message from worker" + + (this._name ? " (" + this._name + ")" : "") + + ": " + + JSON.stringify(result, null, 2) + ); } if (result.id !== id) { @@ -137,9 +165,11 @@ * @return {function} */ function workerify(fn) { - console.warn("`workerify` should only be used in tests or measuring performance. " + - "This creates an object URL on the browser window, and should not be " + - "used in production."); + console.warn( + "`workerify` should only be used in tests or measuring performance. " + + "This creates an object URL on the browser window, and should not be " + + "used in production." + ); // Fetch modules here as we don't want to include it normally. const Services = require("Services"); const { URL, Blob } = Services.wm.getMostRecentWindow("navigator:browser"); @@ -169,4 +199,4 @@ const { createTask } = require("resource://devtools/shared/worker/helper.js"); createTask(self, "workerifiedTask", ${fn.toString()});`; } -}); +})); diff --git a/devtools/startup/AboutDebuggingRegistration.jsm b/devtools/startup/AboutDebuggingRegistration.jsm index 6a50e34bee57..c52d1cb9c95b 100644 --- a/devtools/startup/AboutDebuggingRegistration.jsm +++ b/devtools/startup/AboutDebuggingRegistration.jsm @@ -22,9 +22,11 @@ AboutDebugging.prototype = { QueryInterface: ChromeUtils.generateQI([nsIAboutModule]), newChannel: function(_, loadInfo) { - const uri = Services.prefs.getBoolPref("devtools.aboutdebugging.new-enabled") - ? "chrome://devtools/content/aboutdebugging-new/index.html" - : "chrome://devtools/content/aboutdebugging/aboutdebugging.xhtml"; + const uri = Services.prefs.getBoolPref( + "devtools.aboutdebugging.new-enabled" + ) + ? "chrome://devtools/content/aboutdebugging-new/index.html" + : "chrome://devtools/content/aboutdebugging/aboutdebugging.xhtml"; const chan = Services.io.newChannelFromURIWithLoadInfo( Services.io.newURI(uri), diff --git a/devtools/startup/AboutDevToolsToolboxRegistration.jsm b/devtools/startup/AboutDevToolsToolboxRegistration.jsm index 4f6df05f02b5..af7efcd4430e 100644 --- a/devtools/startup/AboutDevToolsToolboxRegistration.jsm +++ b/devtools/startup/AboutDevToolsToolboxRegistration.jsm @@ -28,9 +28,11 @@ AboutDevtoolsToolbox.prototype = { }, getURIFlags: function(uri) { - return nsIAboutModule.ALLOW_SCRIPT | - nsIAboutModule.ENABLE_INDEXED_DB | - nsIAboutModule.HIDE_FROM_ABOUTABOUT; + return ( + nsIAboutModule.ALLOW_SCRIPT | + nsIAboutModule.ENABLE_INDEXED_DB | + nsIAboutModule.HIDE_FROM_ABOUTABOUT + ); }, }; diff --git a/devtools/startup/DevToolsShim.jsm b/devtools/startup/DevToolsShim.jsm index e1445c26e730..fbbd253a8857 100644 --- a/devtools/startup/DevToolsShim.jsm +++ b/devtools/startup/DevToolsShim.jsm @@ -6,17 +6,21 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); XPCOMUtils.defineLazyGetter(this, "DevtoolsStartup", () => { - return Cc["@mozilla.org/devtools/startup-clh;1"] - .getService(Ci.nsICommandLineHandler) - .wrappedJSObject; + return Cc["@mozilla.org/devtools/startup-clh;1"].getService( + Ci.nsICommandLineHandler + ).wrappedJSObject; }); // We don't want to spend time initializing the full loader here so we create // our own lazy require. XPCOMUtils.defineLazyGetter(this, "Telemetry", function() { - const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); + const { require } = ChromeUtils.import( + "resource://devtools/shared/Loader.jsm" + ); // eslint-disable-next-line no-shadow const Telemetry = require("devtools/client/shared/telemetry"); @@ -26,9 +30,7 @@ XPCOMUtils.defineLazyGetter(this, "Telemetry", function() { const DEVTOOLS_ENABLED_PREF = "devtools.enabled"; const DEVTOOLS_POLICY_DISABLED_PREF = "devtools.policy.disabled"; -this.EXPORTED_SYMBOLS = [ - "DevToolsShim", -]; +this.EXPORTED_SYMBOLS = ["DevToolsShim"]; function removeItem(array, callback) { const index = array.findIndex(callback); @@ -163,9 +165,9 @@ this.DevToolsShim = { return; } - const {scratchpads, browserConsole, browserToolbox} = session; - const hasDevToolsData = browserConsole || browserToolbox || - (scratchpads && scratchpads.length); + const { scratchpads, browserConsole, browserToolbox } = session; + const hasDevToolsData = + browserConsole || browserToolbox || (scratchpads && scratchpads.length); if (!hasDevToolsData) { // Do not initialize DevTools unless there is DevTools specific data in the session. return; @@ -266,10 +268,20 @@ this.DevToolsShim = { const window = Services.wm.getMostRecentWindow("navigator:browser"); this.telemetry.addEventProperty( - window, "open", "tools", null, "shortcut", "" + window, + "open", + "tools", + null, + "shortcut", + "" ); this.telemetry.addEventProperty( - window, "open", "tools", null, "entrypoint", reason + window, + "open", + "tools", + null, + "entrypoint", + reason ); } @@ -297,8 +309,11 @@ const webExtensionsMethods = [ for (const method of webExtensionsMethods) { this.DevToolsShim[method] = function() { if (!this.isEnabled()) { - throw new Error("Could not call a DevToolsShim webextension method ('" + method + - "'): DevTools are not initialized."); + throw new Error( + "Could not call a DevToolsShim webextension method ('" + + method + + "'): DevTools are not initialized." + ); } this.initDevTools(); diff --git a/devtools/startup/DevToolsStartup.jsm b/devtools/startup/DevToolsStartup.jsm index 6a120839dedf..d0d0ea3359d6 100644 --- a/devtools/startup/DevToolsStartup.jsm +++ b/devtools/startup/DevToolsStartup.jsm @@ -32,25 +32,47 @@ const DEVTOOLS_ENABLED_PREF = "devtools.enabled"; const DEVTOOLS_POLICY_DISABLED_PREF = "devtools.policy.disabled"; const PROFILER_POPUP_ENABLED_PREF = "devtools.performance.popup.enabled"; -const { XPCOMUtils } = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -ChromeUtils.defineModuleGetter(this, "Services", - "resource://gre/modules/Services.jsm"); -ChromeUtils.defineModuleGetter(this, "AppConstants", - "resource://gre/modules/AppConstants.jsm"); -ChromeUtils.defineModuleGetter(this, "CustomizableUI", - "resource:///modules/CustomizableUI.jsm"); -ChromeUtils.defineModuleGetter(this, "CustomizableWidgets", - "resource:///modules/CustomizableWidgets.jsm"); -ChromeUtils.defineModuleGetter(this, "PrivateBrowsingUtils", - "resource://gre/modules/PrivateBrowsingUtils.jsm"); -ChromeUtils.defineModuleGetter(this, "ProfilerMenuButton", - "resource://devtools/client/performance-new/popup/menu-button.jsm"); +ChromeUtils.defineModuleGetter( + this, + "Services", + "resource://gre/modules/Services.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "AppConstants", + "resource://gre/modules/AppConstants.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "CustomizableUI", + "resource:///modules/CustomizableUI.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "CustomizableWidgets", + "resource:///modules/CustomizableWidgets.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "ProfilerMenuButton", + "resource://devtools/client/performance-new/popup/menu-button.jsm" +); // We don't want to spend time initializing the full loader here so we create // our own lazy require. XPCOMUtils.defineLazyGetter(this, "Telemetry", function() { - const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); + const { require } = ChromeUtils.import( + "resource://devtools/shared/Loader.jsm" + ); // eslint-disable-next-line no-shadow const Telemetry = require("devtools/client/shared/telemetry"); @@ -83,13 +105,17 @@ XPCOMUtils.defineLazyGetter(this, "KeyShortcuts", function() { // or the default one. { id: "toggleToolbox", - shortcut: KeyShortcutsBundle.GetStringFromName("toggleToolbox.commandkey"), + shortcut: KeyShortcutsBundle.GetStringFromName( + "toggleToolbox.commandkey" + ), modifiers, }, // All locales are using F12 { id: "toggleToolboxF12", - shortcut: KeyShortcutsBundle.GetStringFromName("toggleToolboxF12.commandkey"), + shortcut: KeyShortcutsBundle.GetStringFromName( + "toggleToolboxF12.commandkey" + ), modifiers: "", // F12 is the only one without modifiers }, // Open WebIDE window @@ -101,19 +127,25 @@ XPCOMUtils.defineLazyGetter(this, "KeyShortcuts", function() { // Open the Browser Toolbox { id: "browserToolbox", - shortcut: KeyShortcutsBundle.GetStringFromName("browserToolbox.commandkey"), + shortcut: KeyShortcutsBundle.GetStringFromName( + "browserToolbox.commandkey" + ), modifiers: "accel,alt,shift", }, // Open the Browser Console { id: "browserConsole", - shortcut: KeyShortcutsBundle.GetStringFromName("browserConsole.commandkey"), + shortcut: KeyShortcutsBundle.GetStringFromName( + "browserConsole.commandkey" + ), modifiers: "accel,shift", }, // Toggle the Responsive Design Mode { id: "responsiveDesignMode", - shortcut: KeyShortcutsBundle.GetStringFromName("responsiveDesignMode.commandkey"), + shortcut: KeyShortcutsBundle.GetStringFromName( + "responsiveDesignMode.commandkey" + ), modifiers, }, // Open ScratchPad window @@ -171,7 +203,9 @@ XPCOMUtils.defineLazyGetter(this, "KeyShortcuts", function() { // Key for opening the Accessibility Panel { toolId: "accessibility", - shortcut: KeyShortcutsBundle.GetStringFromName("accessibilityF12.commandkey"), + shortcut: KeyShortcutsBundle.GetStringFromName( + "accessibilityF12.commandkey" + ), modifiers: "shift", }, ]; @@ -198,13 +232,17 @@ function getProfilerKeyShortcuts() { // Start/stop the profiler { id: "profilerStartStop", - shortcut: KeyShortcutsBundle.GetStringFromName("profilerStartStop.commandkey"), + shortcut: KeyShortcutsBundle.GetStringFromName( + "profilerStartStop.commandkey" + ), modifiers: "control,shift", }, // Capture a profile { id: "profilerCapture", - shortcut: KeyShortcutsBundle.GetStringFromName("profilerCapture.commandkey"), + shortcut: KeyShortcutsBundle.GetStringFromName( + "profilerCapture.commandkey" + ), modifiers: "control,shift", }, ]; @@ -220,7 +258,8 @@ function isProfilerButtonEnabled() { XPCOMUtils.defineLazyGetter(this, "ProfilerPopupBackground", function() { return ChromeUtils.import( - "resource://devtools/client/performance-new/popup/background.jsm"); + "resource://devtools/client/performance-new/popup/background.jsm" + ); }); function DevToolsStartup() { @@ -270,7 +309,8 @@ DevToolsStartup.prototype = { const flags = this.readCommandLineFlags(cmdLine); // handle() can be called after browser startup (e.g. opening links from other apps). - const isInitialLaunch = cmdLine.state == Ci.nsICommandLine.STATE_INITIAL_LAUNCH; + const isInitialLaunch = + cmdLine.state == Ci.nsICommandLine.STATE_INITIAL_LAUNCH; if (isInitialLaunch) { // Execute only on first launch of this browser instance. const hasDevToolsFlag = flags.console || flags.devtools || flags.debugger; @@ -279,7 +319,10 @@ DevToolsStartup.prototype = { // Store devtoolsFlag to check it later in onWindowReady. this.devtoolsFlag = flags.devtools; // Only top level Firefox Windows fire a browser-delayed-startup-finished event - Services.obs.addObserver(this.onWindowReady, "browser-delayed-startup-finished"); + Services.obs.addObserver( + this.onWindowReady, + "browser-delayed-startup-finished" + ); if (!this.isDisabledByPolicy()) { if (AppConstants.MOZ_DEV_EDITION) { @@ -292,7 +335,10 @@ DevToolsStartup.prototype = { } // Update menu items when devtools.enabled changes. - Services.prefs.addObserver(DEVTOOLS_ENABLED_PREF, this.onEnabledPrefChanged); + Services.prefs.addObserver( + DEVTOOLS_ENABLED_PREF, + this.onEnabledPrefChanged + ); } if (flags.console) { @@ -312,7 +358,12 @@ DevToolsStartup.prototype = { readCommandLineFlags(cmdLine) { // All command line flags are disabled if DevTools are disabled by policy. if (this.isDisabledByPolicy()) { - return { console: false, debugger: false, devtools: false, debuggerServer: false }; + return { + console: false, + debugger: false, + devtools: false, + debuggerServer: false, + }; } const console = cmdLine.handleFlag("jsconsole", false); @@ -321,8 +372,10 @@ DevToolsStartup.prototype = { let debuggerServer; try { - debuggerServer = - cmdLine.handleFlagWithParam("start-debugger-server", false); + debuggerServer = cmdLine.handleFlagWithParam( + "start-debugger-server", + false + ); } catch (e) { // We get an error if the option is given but not followed by a value. // By catching and trying again, the value is effectively optional. @@ -356,10 +409,13 @@ DevToolsStartup.prototype = { removeDevToolsMenus(window) { // This will hide the "Tools > Web Developer" menu. - window.document.getElementById("webDeveloperMenu").setAttribute("hidden", "true"); + window.document + .getElementById("webDeveloperMenu") + .setAttribute("hidden", "true"); // This will hide the "Web Developer" item in the hamburger menu. - window.document.getElementById("appMenu-developer-button").setAttribute("hidden", - "true"); + window.document + .getElementById("appMenu-developer-button") + .setAttribute("hidden", "true"); }, onFirstWindowReady(window) { @@ -453,7 +509,7 @@ DevToolsStartup.prototype = { viewId: "PanelUI-developer", shortcutId: "key_toggleToolbox", tooltiptext: "developer-button.tooltiptext2", - onViewShowing: (event) => { + onViewShowing: event => { if (Services.prefs.getBoolPref(DEVTOOLS_ENABLED_PREF)) { // If DevTools are enabled, initialize DevTools to create all menuitems in the // system menu before trying to copy them. @@ -469,7 +525,10 @@ DevToolsStartup.prototype = { const itemsToDisplay = [...menu.children]; // Hardcode the addition of the "work offline" menuitem at the bottom: - itemsToDisplay.push({localName: "menuseparator", getAttribute: () => {}}); + itemsToDisplay.push({ + localName: "menuseparator", + getAttribute: () => {}, + }); itemsToDisplay.push(doc.getElementById("goOfflineMenuitem")); const developerItems = doc.getElementById("PanelUI-developerItems"); @@ -481,7 +540,7 @@ DevToolsStartup.prototype = { // it right away. this.onBeforeCreated(anchor.ownerDocument); }, - onBeforeCreated: (doc) => { + onBeforeCreated: doc => { // The developer toggle needs the "key_toggleToolbox" element. // In DEV EDITION, the toggle is added before 1st paint and hookKeyShortcuts() is // not called yet when CustomizableUI creates the widget. @@ -543,14 +602,19 @@ DevToolsStartup.prototype = { * System Menu. */ createDevToolsEnableMenuItem(window) { - const {document} = window; + const { document } = window; // Create the menu item. const item = document.createXULElement("menuitem"); item.id = "enableDeveloperTools"; - item.setAttribute("label", StartupBundle.GetStringFromName("enableDevTools.label")); - item.setAttribute("accesskey", - StartupBundle.GetStringFromName("enableDevTools.accesskey")); + item.setAttribute( + "label", + StartupBundle.GetStringFromName("enableDevTools.label") + ); + item.setAttribute( + "accesskey", + StartupBundle.GetStringFromName("enableDevTools.accesskey") + ); // The menu item should open the install page for DevTools. item.addEventListener("command", () => { @@ -602,7 +666,9 @@ DevToolsStartup.prototype = { */ setupEnabledPref(hasDevToolsFlag) { // Read the current experiment state. - const experimentState = Services.prefs.getCharPref("devtools.onboarding.experiment"); + const experimentState = Services.prefs.getCharPref( + "devtools.onboarding.experiment" + ); const isRegularExperiment = experimentState == "on"; const isForcedExperiment = experimentState == "force"; const isInExperiment = isRegularExperiment || isForcedExperiment; @@ -616,7 +682,10 @@ DevToolsStartup.prototype = { // Force devtools.enabled to false once for each experiment user. if (!Services.prefs.getBoolPref("devtools.onboarding.experiment.flipped")) { Services.prefs.setBoolPref(DEVTOOLS_ENABLED_PREF, false); - Services.prefs.setBoolPref("devtools.onboarding.experiment.flipped", true); + Services.prefs.setBoolPref( + "devtools.onboarding.experiment.flipped", + true + ); } if (Services.prefs.getBoolPref(DEVTOOLS_ENABLED_PREF)) { @@ -655,8 +724,10 @@ DevToolsStartup.prototype = { // Watch for the profiler to enable or disable the profiler popup, then toggle // the keyboard shortcuts on and off. - Services.prefs.addObserver(PROFILER_POPUP_ENABLED_PREF, - this.toggleProfilerKeyShortcuts); + Services.prefs.addObserver( + PROFILER_POPUP_ENABLED_PREF, + this.toggleProfilerKeyShortcuts + ); }, /** @@ -738,7 +809,9 @@ DevToolsStartup.prototype = { // i.e. especially take `initDevTools` into account. const startTime = Cu.now(); const require = this.initDevTools("KeyShortcut", key); - const { gDevToolsBrowser } = require("devtools/client/framework/devtools-browser"); + const { + gDevToolsBrowser, + } = require("devtools/client/framework/devtools-browser"); await gDevToolsBrowser.onKeyShortcut(window, key, startTime); } } catch (e) { @@ -792,7 +865,9 @@ DevToolsStartup.prototype = { } this.initialized = true; - const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); + const { require } = ChromeUtils.import( + "resource://devtools/shared/Loader.jsm" + ); // Ensure loading main devtools module that hooks up into browser UI // and initialize all devtools machinery. require("devtools/client/framework/devtools-browser"); @@ -823,8 +898,10 @@ DevToolsStartup.prototype = { const browser = tab.linkedBrowser; // browser.documentURI might be undefined if the browser tab is still loading. const location = browser.documentURI ? browser.documentURI.spec : ""; - if (location.startsWith("about:devtools") && - !location.startsWith("about:devtools-toolbox")) { + if ( + location.startsWith("about:devtools") && + !location.startsWith("about:devtools-toolbox") + ) { // Focus the existing about:devtools tab and bail out. gBrowser.selectedTab = tab; return; @@ -852,7 +929,9 @@ DevToolsStartup.prototype = { } // Set relatedToCurrent: true to open the tab next to the current one. - gBrowser.selectedTab = gBrowser.addTrustedTab(url, {relatedToCurrent: true}); + gBrowser.selectedTab = gBrowser.addTrustedTab(url, { + relatedToCurrent: true, + }); }, handleConsoleFlag: function(cmdLine) { @@ -874,8 +953,8 @@ DevToolsStartup.prototype = { // Open the toolbox on the selected tab once the browser starts up. handleDevToolsFlag: async function(window) { const require = this.initDevTools("CommandLine"); - const {gDevTools} = require("devtools/client/framework/devtools"); - const {TargetFactory} = require("devtools/client/framework/target"); + const { gDevTools } = require("devtools/client/framework/devtools"); + const { TargetFactory } = require("devtools/client/framework/target"); const target = await TargetFactory.forTab(window.gBrowser.selectedTab); gDevTools.showToolbox(target); }, @@ -891,8 +970,10 @@ DevToolsStartup.prototype = { return false; } if (!remoteDebuggingEnabled) { - const errorMsg = "Could not run chrome debugger! You need the following " + - "prefs to be set to true: " + kDebuggerPrefs.join(", "); + const errorMsg = + "Could not run chrome debugger! You need the following " + + "prefs to be set to true: " + + kDebuggerPrefs.join(", "); console.error(new Error(errorMsg)); // Dump as well, as we're doing this from a commandline, make sure people // don't miss it: @@ -916,7 +997,9 @@ DevToolsStartup.prototype = { Services.obs.addObserver(observe, "devtools-thread-resumed"); } - const { BrowserToolboxProcess } = ChromeUtils.import("resource://devtools/client/framework/ToolboxProcess.jsm"); + const { BrowserToolboxProcess } = ChromeUtils.import( + "resource://devtools/client/framework/ToolboxProcess.jsm" + ); BrowserToolboxProcess.init(); if (pauseOnStartup) { @@ -957,10 +1040,14 @@ DevToolsStartup.prototype = { } let webSocket = false; - const defaultPort = Services.prefs.getIntPref("devtools.debugger.remote-port"); + const defaultPort = Services.prefs.getIntPref( + "devtools.debugger.remote-port" + ); if (portOrPath === true) { // Default to pref values if no values given on command line - webSocket = Services.prefs.getBoolPref("devtools.debugger.remote-websocket"); + webSocket = Services.prefs.getBoolPref( + "devtools.debugger.remote-websocket" + ); portOrPath = defaultPort; } else if (portOrPath.startsWith("ws:")) { webSocket = true; @@ -968,8 +1055,9 @@ DevToolsStartup.prototype = { portOrPath = Number(port) ? port : defaultPort; } - const { DevToolsLoader } = - ChromeUtils.import("resource://devtools/shared/Loader.jsm"); + const { DevToolsLoader } = ChromeUtils.import( + "resource://devtools/shared/Loader.jsm" + ); try { // Create a separate loader instance, so that we can be sure to receive @@ -980,9 +1068,12 @@ DevToolsStartup.prototype = { // settings). const serverLoader = new DevToolsLoader(); serverLoader.invisibleToDebugger = true; - const { DebuggerServer: debuggerServer } = - serverLoader.require("devtools/server/main"); - const { SocketListener } = serverLoader.require("devtools/shared/security/socket"); + const { DebuggerServer: debuggerServer } = serverLoader.require( + "devtools/server/main" + ); + const { SocketListener } = serverLoader.require( + "devtools/shared/security/socket" + ); debuggerServer.init(); debuggerServer.registerAllActors(); debuggerServer.allowChromeProcess = true; @@ -1033,8 +1124,22 @@ DevToolsStartup.prototype = { const window = Services.wm.getMostRecentWindow("navigator:browser"); - this.telemetry.addEventProperty(window, "open", "tools", null, "shortcut", keys); - this.telemetry.addEventProperty(window, "open", "tools", null, "entrypoint", reason); + this.telemetry.addEventProperty( + window, + "open", + "tools", + null, + "shortcut", + keys + ); + this.telemetry.addEventProperty( + window, + "open", + "tools", + null, + "entrypoint", + reason + ); if (this.recorded) { return; @@ -1061,15 +1166,16 @@ DevToolsStartup.prototype = { }, /* eslint-disable max-len */ - helpInfo: " --jsconsole Open the Browser Console.\n" + - " --jsdebugger Open the Browser Toolbox.\n" + - " --wait-for-jsdebugger Spin event loop until JS debugger connects.\n" + - " Enables debugging (some) application startup code paths.\n" + - " Only has an effect when `--jsdebugger` is also supplied.\n" + - " --devtools Open DevTools on initial load.\n" + - " --start-debugger-server [ws:][ | ] Start the debugger server on\n" + - " a TCP port or Unix domain socket path. Defaults to TCP port\n" + - " 6000. Use WebSocket protocol if ws: prefix is specified.\n", + helpInfo: + " --jsconsole Open the Browser Console.\n" + + " --jsdebugger Open the Browser Toolbox.\n" + + " --wait-for-jsdebugger Spin event loop until JS debugger connects.\n" + + " Enables debugging (some) application startup code paths.\n" + + " Only has an effect when `--jsdebugger` is also supplied.\n" + + " --devtools Open DevTools on initial load.\n" + + " --start-debugger-server [ws:][ | ] Start the debugger server on\n" + + " a TCP port or Unix domain socket path. Defaults to TCP port\n" + + " 6000. Use WebSocket protocol if ws: prefix is specified.\n", /* eslint-disable max-len */ classID: Components.ID("{9e9a9283-0ce9-4e4a-8f1c-ba129a032c32}"), @@ -1096,13 +1202,13 @@ const JsonView = { // of the JSON data. Services.ppmm.loadProcessScript( "resource://devtools/client/jsonview/converter-observer.js", - true); + true + ); // Register for messages coming from the child process. // This is never removed as there is no particular need to unregister // it during shutdown. - Services.ppmm.addMessageListener( - "devtools:jsonview:save", this.onSave); + Services.ppmm.addMessageListener("devtools:jsonview:save", this.onSave); }, // Message handlers for events from child processes @@ -1118,7 +1224,10 @@ const JsonView = { // Save original contents chrome.saveBrowser(browser); } else { - if (!message.data.startsWith("blob:null") || !browser.contentPrincipal.isNullPrincipal) { + if ( + !message.data.startsWith("blob:null") || + !browser.contentPrincipal.isNullPrincipal + ) { Cu.reportError("Got invalid request to save JSON data"); return; } @@ -1134,16 +1243,24 @@ const JsonView = { onDocumentReady(doc) { const uri = chrome.makeURI(doc.documentURI, doc.characterSet); const filename = chrome.getDefaultFileName(undefined, uri, doc, null); - chrome.internalSave(message.data, null, filename, null, doc.contentType, + chrome.internalSave( + message.data, + null, + filename, + null, + doc.contentType, false /* bypass cache */, - null, /* filepicker title key */ - null, /* file chosen */ - null, /* referrer */ - null, /* initiating document */ - false, /* don't skip prompt for a location */ - null, /* cache key */ - PrivateBrowsingUtils.isBrowserPrivate(browser), /* private browsing ? */ - Services.scriptSecurityManager.getSystemPrincipal()); + null /* filepicker title key */, + null /* file chosen */, + null /* referrer */, + null /* initiating document */, + false /* don't skip prompt for a location */, + null /* cache key */, + PrivateBrowsingUtils.isBrowserPrivate( + browser + ) /* private browsing ? */, + Services.scriptSecurityManager.getSystemPrincipal() + ); }, onError(status) { throw new Error("JSON Viewer's onSave failed in startPersistence"); diff --git a/devtools/startup/aboutdevtools/AboutDevToolsRegistration.jsm b/devtools/startup/aboutdevtools/AboutDevToolsRegistration.jsm index 37f7e4e9ab6b..dbdbe1c7459b 100644 --- a/devtools/startup/aboutdevtools/AboutDevToolsRegistration.jsm +++ b/devtools/startup/aboutdevtools/AboutDevToolsRegistration.jsm @@ -13,7 +13,9 @@ const { nsIAboutModule } = Ci; function AboutDevtools() {} AboutDevtools.prototype = { - uri: Services.io.newURI("chrome://devtools-startup/content/aboutdevtools/aboutdevtools.xhtml"), + uri: Services.io.newURI( + "chrome://devtools-startup/content/aboutdevtools/aboutdevtools.xhtml" + ), classDescription: "about:devtools", classID: Components.ID("3a16d383-92bd-4c24-ac10-0e2bd66883ab"), contractID: "@mozilla.org/network/protocol/about;1?what=devtools", @@ -21,10 +23,7 @@ AboutDevtools.prototype = { QueryInterface: ChromeUtils.generateQI([nsIAboutModule]), newChannel: function(uri, loadInfo) { - const chan = Services.io.newChannelFromURIWithLoadInfo( - this.uri, - loadInfo - ); + const chan = Services.io.newChannelFromURIWithLoadInfo(this.uri, loadInfo); chan.owner = Services.scriptSecurityManager.getSystemPrincipal(); return chan; }, diff --git a/devtools/startup/aboutdevtools/aboutdevtools.js b/devtools/startup/aboutdevtools/aboutdevtools.js index 688a2c92de8e..84846762b2a9 100644 --- a/devtools/startup/aboutdevtools/aboutdevtools.js +++ b/devtools/startup/aboutdevtools/aboutdevtools.js @@ -31,7 +31,8 @@ const GA_PARAMETERS = [ ["utm_medium", "onboarding"], ]; -const KEY_SHORTCUTS_STRINGS = "chrome://devtools-startup/locale/key-shortcuts.properties"; +const KEY_SHORTCUTS_STRINGS = + "chrome://devtools-startup/locale/key-shortcuts.properties"; const keyShortcutsBundle = Services.strings.createBundle(KEY_SHORTCUTS_STRINGS); // URL constructor doesn't support about: scheme, @@ -46,7 +47,9 @@ let isEnabledOnLoad; function getToolboxShortcut() { const modifier = Services.appinfo.OS == "Darwin" ? "Cmd+Opt+" : "Ctrl+Shift+"; - return modifier + keyShortcutsBundle.GetStringFromName("toggleToolbox.commandkey"); + return ( + modifier + keyShortcutsBundle.GetStringFromName("toggleToolbox.commandkey") + ); } function onInstallButtonClick() { @@ -86,47 +89,64 @@ function updatePage() { */ const features = [ { - icon: "chrome://devtools-startup/content/aboutdevtools/images/feature-inspector.svg", + icon: + "chrome://devtools-startup/content/aboutdevtools/images/feature-inspector.svg", title: "features-inspector-title", desc: "features-inspector-desc", link: "https://developer.mozilla.org/docs/Tools/Page_Inspector", - }, { - icon: "chrome://devtools-startup/content/aboutdevtools/images/feature-console.svg", + }, + { + icon: + "chrome://devtools-startup/content/aboutdevtools/images/feature-console.svg", title: "features-console-title", desc: "features-console-desc", link: "https://developer.mozilla.org/docs/Tools/Web_Console", - }, { - icon: "chrome://devtools-startup/content/aboutdevtools/images/feature-debugger.svg", + }, + { + icon: + "chrome://devtools-startup/content/aboutdevtools/images/feature-debugger.svg", title: "features-debugger-title", desc: "features-debugger-desc", link: "https://developer.mozilla.org/docs/Tools/Debugger", - }, { - icon: "chrome://devtools-startup/content/aboutdevtools/images/feature-network.svg", + }, + { + icon: + "chrome://devtools-startup/content/aboutdevtools/images/feature-network.svg", title: "features-network-title", desc: "features-network-desc", link: "https://developer.mozilla.org/docs/Tools/Network_Monitor", - }, { - icon: "chrome://devtools-startup/content/aboutdevtools/images/feature-storage.svg", + }, + { + icon: + "chrome://devtools-startup/content/aboutdevtools/images/feature-storage.svg", title: "features-storage-title", desc: "features-storage-desc", link: "https://developer.mozilla.org/docs/Tools/Storage_Inspector", - }, { - icon: "chrome://devtools-startup/content/aboutdevtools/images/feature-responsive.svg", + }, + { + icon: + "chrome://devtools-startup/content/aboutdevtools/images/feature-responsive.svg", title: "features-responsive-title", desc: "features-responsive-desc", link: "https://developer.mozilla.org/docs/Tools/Responsive_Design_Mode", - }, { - icon: "chrome://devtools-startup/content/aboutdevtools/images/feature-visualediting.svg", + }, + { + icon: + "chrome://devtools-startup/content/aboutdevtools/images/feature-visualediting.svg", title: "features-visual-editing-title", desc: "features-visual-editing-desc", link: "https://developer.mozilla.org/docs/Tools/Style_Editor", - }, { - icon: "chrome://devtools-startup/content/aboutdevtools/images/feature-performance.svg", + }, + { + icon: + "chrome://devtools-startup/content/aboutdevtools/images/feature-performance.svg", title: "features-performance-title", desc: "features-performance-desc", link: "https://developer.mozilla.org/docs/Tools/Performance", - }, { - icon: "chrome://devtools-startup/content/aboutdevtools/images/feature-memory.svg", + }, + { + icon: + "chrome://devtools-startup/content/aboutdevtools/images/feature-memory.svg", title: "features-memory-title", desc: "features-memory-desc", link: "https://developer.mozilla.org/docs/Tools/Memory", @@ -140,10 +160,9 @@ function createFeatureEl(feature) { const li = document.createElement("li"); li.classList.add("feature"); - const {icon, link, title, desc} = feature; + const { icon, link, title, desc } = feature; // eslint-disable-next-line no-unsanitized/property - li.innerHTML = - ` + li.innerHTML = `

@@ -155,95 +174,118 @@ function createFeatureEl(feature) { return li; } -window.addEventListener("load", function() { - const inspectorShortcut = getToolboxShortcut(); - const welcomeMessage = document.getElementById("welcome-message"); +window.addEventListener( + "load", + function() { + const inspectorShortcut = getToolboxShortcut(); + const welcomeMessage = document.getElementById("welcome-message"); - // Set the welcome message content with the correct keyboard shortcut for the current - // platform. - document.l10n.setAttributes(welcomeMessage, "welcome-message", - { shortcut: inspectorShortcut }); + // Set the welcome message content with the correct keyboard shortcut for the current + // platform. + document.l10n.setAttributes(welcomeMessage, "welcome-message", { + shortcut: inspectorShortcut, + }); - // Set the appropriate title message. - if (reason == "ContextMenu") { - document.getElementById("inspect-title").removeAttribute("hidden"); - } else { - document.getElementById("common-title").removeAttribute("hidden"); - } - - // Display the message specific to the reason - const id = MESSAGES[reason]; - if (id) { - const message = document.getElementById(id); - message.removeAttribute("hidden"); - } - - // Attach event listeners - document.getElementById("install").addEventListener("click", onInstallButtonClick); - document.getElementById("close").addEventListener("click", onCloseButtonClick); - Services.prefs.addObserver(DEVTOOLS_ENABLED_PREF, updatePage); - - const featuresContainer = document.querySelector(".features-list"); - for (const feature of features) { - featuresContainer.appendChild(createFeatureEl(feature)); - } - - // Add Google Analytics parameters to all the external links. - const externalLinks = [...document.querySelectorAll("a.external")]; - for (const link of externalLinks) { - const linkUrl = new URL(link.getAttribute("href")); - GA_PARAMETERS.forEach(([key, value]) => linkUrl.searchParams.set(key, value)); - link.setAttribute("href", linkUrl.href); - } - - // Update the current page based on the current value of DEVTOOLS_ENABLED_PREF. - updatePage(); - - try { - if (reason) { - telemetry.getHistogramById(TELEMETRY_OPENED_REASON).add(reason); + // Set the appropriate title message. + if (reason == "ContextMenu") { + document.getElementById("inspect-title").removeAttribute("hidden"); + } else { + document.getElementById("common-title").removeAttribute("hidden"); } - if (keyid) { - telemetry.getHistogramById(TELEMETRY_OPENED_KEY).add(keyid); + // Display the message specific to the reason + const id = MESSAGES[reason]; + if (id) { + const message = document.getElementById(id); + message.removeAttribute("hidden"); } - telemetry.scalarAdd(TELEMETRY_OPENED, 1); - } catch (e) { - dump("about:devtools onload telemetry failed: " + e + "\n"); - } -}, { once: true }); + // Attach event listeners + document + .getElementById("install") + .addEventListener("click", onInstallButtonClick); + document + .getElementById("close") + .addEventListener("click", onCloseButtonClick); + Services.prefs.addObserver(DEVTOOLS_ENABLED_PREF, updatePage); -window.addEventListener("beforeunload", function() { - // Focus the tab that triggered the DevTools onboarding. - if (document.visibilityState != "visible") { - // Only try to focus the correct tab if the current tab is the about:devtools page. - return; - } + const featuresContainer = document.querySelector(".features-list"); + for (const feature of features) { + featuresContainer.appendChild(createFeatureEl(feature)); + } - // Retrieve the original tab if it is still available. - const browserWindow = Services.wm.getMostRecentWindow("navigator:browser"); - const { gBrowser } = browserWindow; - const originalBrowser = gBrowser.getBrowserForOuterWindowID(tabid); - const originalTab = gBrowser.getTabForBrowser(originalBrowser); + // Add Google Analytics parameters to all the external links. + const externalLinks = [...document.querySelectorAll("a.external")]; + for (const link of externalLinks) { + const linkUrl = new URL(link.getAttribute("href")); + GA_PARAMETERS.forEach(([key, value]) => + linkUrl.searchParams.set(key, value) + ); + link.setAttribute("href", linkUrl.href); + } - if (originalTab) { - // If the original tab was found, select it. - gBrowser.selectedTab = originalTab; - } -}, {once: true}); + // Update the current page based on the current value of DEVTOOLS_ENABLED_PREF. + updatePage(); -window.addEventListener("unload", function() { - document.getElementById("install").removeEventListener("click", onInstallButtonClick); - document.getElementById("close").removeEventListener("click", onCloseButtonClick); - Services.prefs.removeObserver(DEVTOOLS_ENABLED_PREF, updatePage); - - const isEnabled = Services.prefs.getBoolPref("devtools.enabled"); - if (!isEnabledOnLoad && !isEnabled) { try { - telemetry.scalarAdd(TELEMETRY_NOINSTALL_EXITS, 1); + if (reason) { + telemetry.getHistogramById(TELEMETRY_OPENED_REASON).add(reason); + } + + if (keyid) { + telemetry.getHistogramById(TELEMETRY_OPENED_KEY).add(keyid); + } + + telemetry.scalarAdd(TELEMETRY_OPENED, 1); } catch (e) { - dump("about:devtools onunload telemetry failed: " + e + "\n"); + dump("about:devtools onload telemetry failed: " + e + "\n"); } - } -}, {once: true}); + }, + { once: true } +); + +window.addEventListener( + "beforeunload", + function() { + // Focus the tab that triggered the DevTools onboarding. + if (document.visibilityState != "visible") { + // Only try to focus the correct tab if the current tab is the about:devtools page. + return; + } + + // Retrieve the original tab if it is still available. + const browserWindow = Services.wm.getMostRecentWindow("navigator:browser"); + const { gBrowser } = browserWindow; + const originalBrowser = gBrowser.getBrowserForOuterWindowID(tabid); + const originalTab = gBrowser.getTabForBrowser(originalBrowser); + + if (originalTab) { + // If the original tab was found, select it. + gBrowser.selectedTab = originalTab; + } + }, + { once: true } +); + +window.addEventListener( + "unload", + function() { + document + .getElementById("install") + .removeEventListener("click", onInstallButtonClick); + document + .getElementById("close") + .removeEventListener("click", onCloseButtonClick); + Services.prefs.removeObserver(DEVTOOLS_ENABLED_PREF, updatePage); + + const isEnabled = Services.prefs.getBoolPref("devtools.enabled"); + if (!isEnabledOnLoad && !isEnabled) { + try { + telemetry.scalarAdd(TELEMETRY_NOINSTALL_EXITS, 1); + } catch (e) { + dump("about:devtools onunload telemetry failed: " + e + "\n"); + } + } + }, + { once: true } +); diff --git a/devtools/startup/aboutdevtools/subscribe.js b/devtools/startup/aboutdevtools/subscribe.js index 532fcb25005f..7e18b5a578f6 100644 --- a/devtools/startup/aboutdevtools/subscribe.js +++ b/devtools/startup/aboutdevtools/subscribe.js @@ -9,136 +9,150 @@ * It is largely inspired from https://mozilla.github.io/basket-example/ */ -window.addEventListener("load", function() { - // Timeout for the subscribe XHR. - const REQUEST_TIMEOUT = 5000; +window.addEventListener( + "load", + function() { + // Timeout for the subscribe XHR. + const REQUEST_TIMEOUT = 5000; - const emailInput = document.getElementById("email"); - const newsletterErrors = document.getElementById("newsletter-errors"); - const newsletterForm = document.getElementById("newsletter-form"); - const newsletterPrivacySection = document.getElementById("newsletter-privacy"); - const newsletterThanks = document.getElementById("newsletter-thanks"); + const emailInput = document.getElementById("email"); + const newsletterErrors = document.getElementById("newsletter-errors"); + const newsletterForm = document.getElementById("newsletter-form"); + const newsletterPrivacySection = document.getElementById( + "newsletter-privacy" + ); + const newsletterThanks = document.getElementById("newsletter-thanks"); - /** - * Update the error panel to display the provided errors. If the argument is null or - * empty, a default error message will be displayed. - * - * @param {Array} errors - * Array of strings, each item being an error message to display. - */ - async function updateErrorPanel(errors) { - clearErrorPanel(); + /** + * Update the error panel to display the provided errors. If the argument is null or + * empty, a default error message will be displayed. + * + * @param {Array} errors + * Array of strings, each item being an error message to display. + */ + async function updateErrorPanel(errors) { + clearErrorPanel(); - if (!errors || errors.length == 0) { - errors = [await document.l10n.formatValues([{id: "newsletter-error-unknown"}])]; + if (!errors || errors.length == 0) { + errors = [ + await document.l10n.formatValues([ + { id: "newsletter-error-unknown" }, + ]), + ]; + } + + // Create errors markup. + const fragment = document.createDocumentFragment(); + for (const error of errors) { + const item = document.createElement("p"); + item.classList.add("error"); + item.appendChild(document.createTextNode(error)); + fragment.appendChild(item); + } + + newsletterErrors.appendChild(fragment); + newsletterErrors.classList.add("show"); } - // Create errors markup. - const fragment = document.createDocumentFragment(); - for (const error of errors) { - const item = document.createElement("p"); - item.classList.add("error"); - item.appendChild(document.createTextNode(error)); - fragment.appendChild(item); + /** + * Hide the error panel and remove all errors. + */ + function clearErrorPanel() { + newsletterErrors.classList.remove("show"); + newsletterErrors.innerHTML = ""; } - newsletterErrors.appendChild(fragment); - newsletterErrors.classList.add("show"); - } + // Show the additional form fields on focus of the email input. + function onEmailInputFocus() { + // Create a hidden measuring container, append it to the parent of the privacy section + const container = document.createElement("div"); + container.style.cssText = + "visibility: hidden; overflow: hidden; position: absolute"; + newsletterPrivacySection.parentNode.appendChild(container); - /** - * Hide the error panel and remove all errors. - */ - function clearErrorPanel() { - newsletterErrors.classList.remove("show"); - newsletterErrors.innerHTML = ""; - } + // Clone the privacy section, append the clone to the measuring container. + const clone = newsletterPrivacySection.cloneNode(true); + container.appendChild(clone); - // Show the additional form fields on focus of the email input. - function onEmailInputFocus() { - // Create a hidden measuring container, append it to the parent of the privacy section - const container = document.createElement("div"); - container.style.cssText = "visibility: hidden; overflow: hidden; position: absolute"; - newsletterPrivacySection.parentNode.appendChild(container); + // Measure the target height of the privacy section. + clone.style.height = "auto"; + const height = clone.offsetHeight; - // Clone the privacy section, append the clone to the measuring container. - const clone = newsletterPrivacySection.cloneNode(true); - container.appendChild(clone); + // Cleanup the measuring container. + container.remove(); - // Measure the target height of the privacy section. - clone.style.height = "auto"; - const height = clone.offsetHeight; + // Set the animate class and set the height to the measured height. + newsletterPrivacySection.classList.add("animate"); + newsletterPrivacySection.style.cssText = `height: ${height}px; margin-bottom: 0;`; + } - // Cleanup the measuring container. - container.remove(); + // XHR subscribe; handle errors; display thanks message on success. + function onFormSubmit(evt) { + evt.preventDefault(); + evt.stopPropagation(); - // Set the animate class and set the height to the measured height. - newsletterPrivacySection.classList.add("animate"); - newsletterPrivacySection.style.cssText = `height: ${height}px; margin-bottom: 0;`; - } + // New submission, clear old errors + clearErrorPanel(); - // XHR subscribe; handle errors; display thanks message on success. - function onFormSubmit(evt) { - evt.preventDefault(); - evt.stopPropagation(); + const xhr = new XMLHttpRequest(); - // New submission, clear old errors - clearErrorPanel(); + xhr.onload = async function(r) { + if (r.target.status >= 200 && r.target.status < 300) { + const { response } = r.target; - const xhr = new XMLHttpRequest(); - - xhr.onload = async function(r) { - if (r.target.status >= 200 && r.target.status < 300) { - const {response} = r.target; - - if (response.success === true) { - // Hide form and show success message. - newsletterForm.style.display = "none"; - newsletterThanks.classList.add("show"); + if (response.success === true) { + // Hide form and show success message. + newsletterForm.style.display = "none"; + newsletterThanks.classList.add("show"); + } else { + // We trust the error messages from the service to be meaningful for the user. + updateErrorPanel(response.errors); + } } else { - // We trust the error messages from the service to be meaningful for the user. - updateErrorPanel(response.errors); + const { status, statusText } = r.target; + const statusInfo = `${status} - ${statusText}`; + const error = await document.l10n.formatValues([ + { + id: "newsletter-error-common", + args: { errorDescription: statusInfo }, + }, + ]); + updateErrorPanel([error]); } - } else { - const {status, statusText} = r.target; - const statusInfo = `${status} - ${statusText}`; + }; + + xhr.onerror = () => { + updateErrorPanel(); + }; + + xhr.ontimeout = async () => { const error = await document.l10n.formatValues([ - { id: "newsletter-error-common", args: { errorDescription: statusInfo } }, + { id: "newsletter-error-timeout" }, ]); updateErrorPanel([error]); - } - }; + }; - xhr.onerror = () => { - updateErrorPanel(); - }; + const url = newsletterForm.getAttribute("action"); - xhr.ontimeout = async () => { - const error = await document.l10n.formatValues([ - { id: "newsletter-error-timeout" }, - ]); - updateErrorPanel([error]); - }; + xhr.open("POST", url, true); + xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); + xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); + xhr.timeout = REQUEST_TIMEOUT; + xhr.responseType = "json"; - const url = newsletterForm.getAttribute("action"); + // Create form data. + const formData = new FormData(newsletterForm); + formData.append("source_url", document.location.href); - xhr.open("POST", url, true); - xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); - xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); - xhr.timeout = REQUEST_TIMEOUT; - xhr.responseType = "json"; + const params = new URLSearchParams(formData); - // Create form data. - const formData = new FormData(newsletterForm); - formData.append("source_url", document.location.href); + // Send the request. + xhr.send(params.toString()); + } - const params = new URLSearchParams(formData); - - // Send the request. - xhr.send(params.toString()); - } - - // Attach event listeners. - newsletterForm.addEventListener("submit", onFormSubmit); - emailInput.addEventListener("focus", onEmailInputFocus); -}, { once: true }); + // Attach event listeners. + newsletterForm.addEventListener("submit", onFormSubmit); + emailInput.addEventListener("focus", onEmailInputFocus); + }, + { once: true } +); diff --git a/devtools/startup/aboutdevtools/test/browser_aboutdevtools_closes_page.js b/devtools/startup/aboutdevtools/test/browser_aboutdevtools_closes_page.js index e193665f0dc8..9b5160df9580 100644 --- a/devtools/startup/aboutdevtools/test/browser_aboutdevtools_closes_page.js +++ b/devtools/startup/aboutdevtools/test/browser_aboutdevtools_closes_page.js @@ -9,14 +9,15 @@ add_task(async function() { pushPref("devtools.enabled", false); - const {doc, win} = await openAboutDevTools(); + const { doc, win } = await openAboutDevTools(); info("Check that the close button is available on the page"); const closeButton = doc.getElementById("close"); ok(closeButton, "close button is displayed"); - const onWindowUnload = - new Promise(r => win.addEventListener("unload", r, {once: true})); + const onWindowUnload = new Promise(r => + win.addEventListener("unload", r, { once: true }) + ); info("Click on the install button to enable DevTools."); EventUtils.synthesizeMouseAtCenter(closeButton, {}, win); diff --git a/devtools/startup/aboutdevtools/test/browser_aboutdevtools_enables_devtools.js b/devtools/startup/aboutdevtools/test/browser_aboutdevtools_enables_devtools.js index d70e978ba2b5..383e64bc7c70 100644 --- a/devtools/startup/aboutdevtools/test/browser_aboutdevtools_enables_devtools.js +++ b/devtools/startup/aboutdevtools/test/browser_aboutdevtools_enables_devtools.js @@ -9,12 +9,14 @@ add_task(async function() { pushPref("devtools.enabled", false); - const {tab, doc, win} = await openAboutDevTools(); + const { tab, doc, win } = await openAboutDevTools(); const installPage = doc.getElementById("install-page"); const welcomePage = doc.getElementById("welcome-page"); - info("Check that about:devtools is in the correct state with devtools.enabled=false"); + info( + "Check that about:devtools is in the correct state with devtools.enabled=false" + ); ok(!installPage.hasAttribute("hidden"), "install screen is visible"); ok(welcomePage.hasAttribute("hidden"), "welcome screen is hidden"); @@ -25,8 +27,10 @@ add_task(async function() { info("Wait until the UI updates"); await waitUntil(() => installPage.hasAttribute("hidden") === true); ok(!welcomePage.hasAttribute("hidden"), "welcome screen is visible"); - ok(Services.prefs.getBoolPref("devtools.enabled"), - "The preference devtools.enabled has been flipped to true."); + ok( + Services.prefs.getBoolPref("devtools.enabled"), + "The preference devtools.enabled has been flipped to true." + ); // Flip the devtools.enabled preference back to false, otherwise the pushPref cleanup // times out. diff --git a/devtools/startup/aboutdevtools/test/browser_aboutdevtools_focus_owner_tab.js b/devtools/startup/aboutdevtools/test/browser_aboutdevtools_focus_owner_tab.js index 5e255dc5bcd8..28df7f1d07f6 100644 --- a/devtools/startup/aboutdevtools/test/browser_aboutdevtools_focus_owner_tab.js +++ b/devtools/startup/aboutdevtools/test/browser_aboutdevtools_focus_owner_tab.js @@ -16,7 +16,10 @@ add_task(async function() { info("Add an about:blank tab"); const tab1 = await addTab("data:text/html;charset=utf-8,tab1"); const tab2 = await addTab("data:text/html;charset=utf-8,tab2"); - ok(tab1 === gBrowser.tabs[1], "tab1 is the second tab in the current browser window"); + ok( + tab1 === gBrowser.tabs[1], + "tab1 is the second tab in the current browser window" + ); info("Select the first tab"); gBrowser.selectedTab = tab1; @@ -28,8 +31,10 @@ add_task(async function() { info("about:devtools was opened as expected."); const aboutDevtoolsTab = gBrowser.selectedTab; - ok(aboutDevtoolsTab === gBrowser.tabs[2], - "about:devtools was opened next to its owner tab"); + ok( + aboutDevtoolsTab === gBrowser.tabs[2], + "about:devtools was opened next to its owner tab" + ); info("Move the owner tab to the end of the tabs array."); gBrowser.moveTabTo(tab1, gBrowser.tabs.length - 1); @@ -52,7 +57,10 @@ add_task(async function() { info("Add an about:blank tab"); const tab1 = await addTab("data:text/html;charset=utf-8,tab1"); const tab2 = await addTab("data:text/html;charset=utf-8,tab2"); - ok(tab1 === gBrowser.tabs[1], "tab1 is the second tab in the current browser window"); + ok( + tab1 === gBrowser.tabs[1], + "tab1 is the second tab in the current browser window" + ); info("Select the first tab"); gBrowser.selectedTab = tab1; @@ -64,8 +72,10 @@ add_task(async function() { info("about:devtools was opened as expected."); const aboutDevtoolsTab = gBrowser.selectedTab; - ok(aboutDevtoolsTab === gBrowser.tabs[2], - "about:devtools was opened next to its owner tab"); + ok( + aboutDevtoolsTab === gBrowser.tabs[2], + "about:devtools was opened next to its owner tab" + ); info("Select the second tab"); gBrowser.selectedTab = tab2; @@ -75,8 +85,7 @@ add_task(async function() { await removeTab(aboutDevtoolsTab); - ok(tab2 == gBrowser.selectedTab, - "Tab 2 should still be selected."); + ok(tab2 == gBrowser.selectedTab, "Tab 2 should still be selected."); await removeTab(tab1); await removeTab(tab2); diff --git a/devtools/startup/aboutdevtools/test/browser_aboutdevtools_reuse_existing.js b/devtools/startup/aboutdevtools/test/browser_aboutdevtools_reuse_existing.js index 8058d284b3b5..f403f5832561 100644 --- a/devtools/startup/aboutdevtools/test/browser_aboutdevtools_reuse_existing.js +++ b/devtools/startup/aboutdevtools/test/browser_aboutdevtools_reuse_existing.js @@ -33,9 +33,14 @@ add_task(async function() { // filter is not available on gBrowser.tabs. const aboutDevtoolsTabs = [...gBrowser.tabs].filter(isAboutDevtoolsTab); - ok(aboutDevtoolsTabs.length === 1, "Only one tab of about:devtools was opened."); - ok(aboutDevtoolsTabs[0] === aboutDevtoolsTab, - "The existing about:devtools tab was reused."); + ok( + aboutDevtoolsTabs.length === 1, + "Only one tab of about:devtools was opened." + ); + ok( + aboutDevtoolsTabs[0] === aboutDevtoolsTab, + "The existing about:devtools tab was reused." + ); await removeTab(aboutDevtoolsTab); await removeTab(tab); diff --git a/devtools/startup/aboutdevtools/test/head.js b/devtools/startup/aboutdevtools/test/head.js index f17a5b38c806..fc69a5c39785 100644 --- a/devtools/startup/aboutdevtools/test/head.js +++ b/devtools/startup/aboutdevtools/test/head.js @@ -56,7 +56,7 @@ const removeTab = async function(tab) { const { gBrowser } = tab.ownerGlobal; await new Promise(resolve => { - gBrowser.tabContainer.addEventListener("TabClose", resolve, {once: true}); + gBrowser.tabContainer.addEventListener("TabClose", resolve, { once: true }); gBrowser.removeTab(tab); }); @@ -74,7 +74,7 @@ const openAboutDevTools = async function() { const doc = browser.contentDocument; const win = browser.contentWindow; - return {tab, doc, win}; + return { tab, doc, win }; }; /** @@ -83,7 +83,7 @@ const openAboutDevTools = async function() { */ const pushPref = function(preferenceName, value) { return new Promise(resolve => { - const options = {"set": [[preferenceName, value]]}; + const options = { set: [[preferenceName, value]] }; SpecialPowers.pushPrefEnv(options, resolve); }); }; diff --git a/devtools/startup/tests/browser/browser_shim_disable_devtools.js b/devtools/startup/tests/browser/browser_shim_disable_devtools.js index feb1f45ecb9a..90c41eb6310d 100644 --- a/devtools/startup/tests/browser/browser_shim_disable_devtools.js +++ b/devtools/startup/tests/browser/browser_shim_disable_devtools.js @@ -7,7 +7,9 @@ /* eslint-env browser */ const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); -const { CustomizableUI } = ChromeUtils.import("resource:///modules/CustomizableUI.jsm"); +const { CustomizableUI } = ChromeUtils.import( + "resource:///modules/CustomizableUI.jsm" +); const { AppConstants } = require("resource://gre/modules/AppConstants.jsm"); const { gDevTools } = require("devtools/client/framework/devtools"); @@ -15,9 +17,11 @@ const { gDevTools } = require("devtools/client/framework/devtools"); * Test that the preference devtools.policy.disabled disables entry points for devtools. */ add_task(async function() { - info("Disable DevTools entry points (does not apply to the already created window"); + info( + "Disable DevTools entry points (does not apply to the already created window" + ); await new Promise(resolve => { - const options = {"set": [["devtools.policy.disabled", true]]}; + const options = { set: [["devtools.policy.disabled", true]] }; SpecialPowers.pushPrefEnv(options, resolve); }); @@ -29,16 +33,24 @@ add_task(async function() { CustomizableUI.removeWidgetFromArea("developer-button"); } - info("Open a new window, all window-specific hooks for DevTools will be disabled."); - const win = OpenBrowserWindow({private: false}); + info( + "Open a new window, all window-specific hooks for DevTools will be disabled." + ); + const win = OpenBrowserWindow({ private: false }); await waitForDelayedStartupFinished(win); - info("Open a new tab on the new window to ensure the focus is on the new window"); - const tab = BrowserTestUtils.addTab(win.gBrowser, - "data:text/html;charset=utf-8,foo"); + info( + "Open a new tab on the new window to ensure the focus is on the new window" + ); + const tab = BrowserTestUtils.addTab( + win.gBrowser, + "data:text/html;charset=utf-8,foo" + ); await BrowserTestUtils.browserLoaded(win.gBrowser.getBrowserForTab(tab)); - info("Synthesize a DevTools shortcut, the toolbox should not open on this new window."); + info( + "Synthesize a DevTools shortcut, the toolbox should not open on this new window." + ); synthesizeToggleToolboxKey(win); // There is no event to wait for here as this shortcut should have no effect. @@ -49,27 +61,45 @@ add_task(async function() { const browser = gBrowser.selectedTab.linkedBrowser; const location = browser.documentURI.spec; - ok(!location.startsWith("about:devtools"), "The current tab is not about:devtools"); + ok( + !location.startsWith("about:devtools"), + "The current tab is not about:devtools" + ); info("Open the context menu for the content page."); const contextMenu = win.document.getElementById("contentAreaContextMenu"); - const popupShownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown"); - EventUtils.synthesizeMouseAtCenter(win.document.documentElement, - { type: "contextmenu", button: 2 }, win); + const popupShownPromise = BrowserTestUtils.waitForEvent( + contextMenu, + "popupshown" + ); + EventUtils.synthesizeMouseAtCenter( + win.document.documentElement, + { type: "contextmenu", button: 2 }, + win + ); await popupShownPromise; const inspectElementItem = contextMenu.querySelector(`#context-inspect`); - ok(inspectElementItem.hidden, "The inspect element item is hidden in the context menu"); + ok( + inspectElementItem.hidden, + "The inspect element item is hidden in the context menu" + ); info("Close the context menu"); - const onContextMenuHidden = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden"); + const onContextMenuHidden = BrowserTestUtils.waitForEvent( + contextMenu, + "popuphidden" + ); contextMenu.hidePopup(); await onContextMenuHidden; const toolsMenu = win.document.getElementById("webDeveloperMenu"); ok(toolsMenu.hidden, "The Web Developer item of the tools menu is hidden"); const hamburgerMenu = win.document.getElementById("appMenu-developer-button"); - ok(hamburgerMenu.hidden, "The Web Developer item of the hamburger menu is hidden"); + ok( + hamburgerMenu.hidden, + "The Web Developer item of the hamburger menu is hidden" + ); win.gBrowser.removeTab(tab); diff --git a/devtools/startup/tests/unit/test_devtools_shim.js b/devtools/startup/tests/unit/test_devtools_shim.js index 9abea8d6cc7b..63a50eda1161 100644 --- a/devtools/startup/tests/unit/test_devtools_shim.js +++ b/devtools/startup/tests/unit/test_devtools_shim.js @@ -4,8 +4,9 @@ "use strict"; -const { DevToolsShim } = - ChromeUtils.import("chrome://devtools-startup/content/DevToolsShim.jsm"); +const { DevToolsShim } = ChromeUtils.import( + "chrome://devtools-startup/content/DevToolsShim.jsm" +); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); // Test the DevToolsShim @@ -43,8 +44,10 @@ function createMockDevTools() { * arguments provided to the last call, if appropriate. */ function checkCalls(mock, method, length, lastArgs) { - ok(mock.callLog[method].length === length, - "Devtools.on was called the expected number of times"); + ok( + mock.callLog[method].length === length, + "Devtools.on was called the expected number of times" + ); // If we don't want to check the last call or if the method was never called, bail out. if (!lastArgs || length === 0) { @@ -53,8 +56,10 @@ function checkCalls(mock, method, length, lastArgs) { for (let i = 0; i < lastArgs.length; i++) { const expectedArg = lastArgs[i]; - ok(mock.callLog[method][length - 1][i] === expectedArg, - `Devtools.${method} was called with the expected argument (index ${i})`); + ok( + mock.callLog[method][length - 1][i] === expectedArg, + `Devtools.${method} was called with the expected argument (index ${i})` + ); } }