Import Cobalt 19.master.0.188393 Includes the following patches: https://cobalt-review.googlesource.com/c/cobalt/+/4970 by milko.leporis@mips.com https://cobalt-review.googlesource.com/c/cobalt/+/4990 by z102.zhang@samsung.com Change-Id: I9ac637c775da20fe2ddf4a1337b70c896cee4e27
diff --git a/src/README.md b/src/README.md index 29c40c8..ced1010 100644 --- a/src/README.md +++ b/src/README.md
@@ -223,11 +223,16 @@ out/linux-x64x11_debug/cobalt [--url=<url>] - * If you want to use `http` instead of `https`, you must pass the - `--allow_http` flag to the Cobalt command-line. * If you want to connect to an `https` host that doesn't have a certificate validatable by our set of root CAs, you must pass the `--ignore_certificate_errors` flag to the Cobalt command-line. + * Cobalt requires that the HTML5 content be fetched over HTTPS and + enforces CSP when compiled in the "gold" configuration. However, if + CSP is served in other builds, Cobalt still respects it. Currently + Cobalt is at CSP level 2. + * When the HTML5 content is served with a special "h5vcc-location-src" + CSP directive, a navigation jail is enabled in Cobalt that cannot be + disabled via Cobalt options. * See [`cobalt/browser/switches.cc`](cobalt/browser/switches.cc) for more command-line options.
diff --git a/src/base/test/test_suite.cc b/src/base/test/test_suite.cc index 57de666..ff17a7a 100644 --- a/src/base/test/test_suite.cc +++ b/src/base/test/test_suite.cc
@@ -301,4 +301,5 @@ } void TestSuite::Shutdown() { + logging::CloseLogFile(); }
diff --git a/src/base/threading/post_task_and_reply_impl.cc b/src/base/threading/post_task_and_reply_impl.cc index 192198b..855364f 100644 --- a/src/base/threading/post_task_and_reply_impl.cc +++ b/src/base/threading/post_task_and_reply_impl.cc
@@ -5,6 +5,7 @@ #include "base/threading/post_task_and_reply_impl.h" #include "base/bind.h" +#include "base/debug/leak_annotations.h" #include "base/location.h" #include "base/message_loop_proxy.h" @@ -74,6 +75,11 @@ const tracked_objects::Location& from_here, const Closure& task, const Closure& reply) { + // As mentioned in a comment above, this code is prepared to leak in the case + // that the original calling message loop goes away while the task is being + // processed. Therefore, explicitly recognize this possibility by allowing + // memory leaks here. + ANNOTATE_SCOPED_MEMORY_LEAK; PostTaskAndReplyRelay* relay = new PostTaskAndReplyRelay(from_here, task, reply); if (!PostTask(from_here, Bind(&PostTaskAndReplyRelay::Run,
diff --git a/src/cobalt/CHANGELOG.md b/src/cobalt/CHANGELOG.md index 464062d..433e565 100644 --- a/src/cobalt/CHANGELOG.md +++ b/src/cobalt/CHANGELOG.md
@@ -2,6 +2,11 @@ This document records all notable changes made to Cobalt since the last release. +## Version 20 + - **Improvements and Bug Fixes** + - Fix bug where Cobalt would not refresh the layout when the textContent + property of a DOM TextNode is modified. + ## Version 19 - **Add support for V8 JavaScript Engine**
diff --git a/src/cobalt/base/console_commands.cc b/src/cobalt/base/console_commands.cc index 293958c..4db73b5 100644 --- a/src/cobalt/base/console_commands.cc +++ b/src/cobalt/base/console_commands.cc
@@ -26,10 +26,10 @@ #if defined(ENABLE_DEBUG_CONSOLE) ConsoleCommandManager::CommandHandler::CommandHandler( - const std::string& channel, + const std::string& command, const ConsoleCommandManager::CommandCallback& callback, const std::string& short_help, const std::string& long_help) - : channel_(channel), + : command_(command), callback_(callback), short_help_(short_help), long_help_(long_help) { @@ -44,84 +44,69 @@ manager->UnregisterCommandHandler(this); } -void ConsoleCommandManager::HandleCommand(const std::string& channel, +void ConsoleCommandManager::HandleCommand(const std::string& command, const std::string& message) const { - DCHECK_GT(channel.length(), size_t(0)); + DCHECK_GT(command.length(), size_t(0)); base::AutoLock auto_lock(lock_); - CommandHandlerMap::const_iterator iter = - command_channel_map_.lower_bound(channel); - bool handler_found = false; - while (iter != command_channel_map_.end() && iter->first == channel) { - handler_found = true; + CommandHandlerMap::const_iterator iter = command_command_map_.find(command); + if (iter != command_command_map_.end()) { iter->second->callback().Run(message); - ++iter; - } - if (!handler_found) { - DLOG(WARNING) << "No command handler registered for channel: " << channel; + } else { + DLOG(WARNING) << "No handler registered for command: " << command; } } -std::set<std::string> ConsoleCommandManager::GetRegisteredChannels() const { +std::set<std::string> ConsoleCommandManager::GetRegisteredCommands() const { std::set<std::string> result; base::AutoLock auto_lock(lock_); - for (CommandHandlerMap::const_iterator iter = command_channel_map_.begin(); - iter != command_channel_map_.end(); ++iter) { + for (CommandHandlerMap::const_iterator iter = command_command_map_.begin(); + iter != command_command_map_.end(); ++iter) { result.insert(iter->first); } return result; } std::string ConsoleCommandManager::GetShortHelp( - const std::string& channel) const { + const std::string& command) const { base::AutoLock auto_lock(lock_); - for (CommandHandlerMap::const_iterator iter = - command_channel_map_.lower_bound(channel); - iter != command_channel_map_.end() && iter->first == channel; ++iter) { + CommandHandlerMap::const_iterator iter = command_command_map_.find(command); + if (iter != command_command_map_.end()) { return iter->second->short_help(); } - return "No help available for unregistered channel: " + channel; + return "No help available for unregistered command: " + command; } std::string ConsoleCommandManager::GetLongHelp( - const std::string& channel) const { + const std::string& command) const { base::AutoLock auto_lock(lock_); - for (CommandHandlerMap::const_iterator iter = - command_channel_map_.lower_bound(channel); - iter != command_channel_map_.end() && iter->first == channel; ++iter) { + CommandHandlerMap::const_iterator iter = command_command_map_.find(command); + if (iter != command_command_map_.end()) { return iter->second->long_help(); } - return "No help available for unregistered channel: " + channel; + return "No help available for unregistered command: " + command; } void ConsoleCommandManager::RegisterCommandHandler( const CommandHandler* handler) { - DCHECK_GT(handler->channel().length(), size_t(0)); + DCHECK_GT(handler->command().length(), size_t(0)); base::AutoLock auto_lock(lock_); - command_channel_map_.insert(std::make_pair(handler->channel(), handler)); + command_command_map_[handler->command()] = handler; } void ConsoleCommandManager::UnregisterCommandHandler( const CommandHandler* handler) { - const std::string& channel = handler->channel(); - DCHECK_GT(channel.length(), size_t(0)); + DCHECK_GT(handler->command().length(), size_t(0)); base::AutoLock auto_lock(lock_); - for (CommandHandlerMap::iterator iter = - command_channel_map_.lower_bound(channel); - iter != command_channel_map_.end() && iter->first == channel; ++iter) { - if (iter->second == handler) { - command_channel_map_.erase(iter); - break; - } - } + command_command_map_.erase(handler->command()); } #else // ENABLE_DEBUG_CONSOLE ConsoleCommandManager::CommandHandler::CommandHandler( - const std::string& channel, + const std::string& command, const ConsoleCommandManager::CommandCallback& callback, const std::string& short_help, const std::string& long_help) { - UNREFERENCED_PARAMETER(channel); + UNREFERENCED_PARAMETER(command); UNREFERENCED_PARAMETER(callback); UNREFERENCED_PARAMETER(short_help); UNREFERENCED_PARAMETER(long_help); @@ -129,25 +114,25 @@ ConsoleCommandManager::CommandHandler::~CommandHandler() {} -void ConsoleCommandManager::HandleCommand(const std::string& channel, +void ConsoleCommandManager::HandleCommand(const std::string& command, const std::string& message) const { - UNREFERENCED_PARAMETER(channel); + UNREFERENCED_PARAMETER(command); UNREFERENCED_PARAMETER(message); } -std::set<std::string> ConsoleCommandManager::GetRegisteredChannels() const { +std::set<std::string> ConsoleCommandManager::GetRegisteredCommands() const { return std::set<std::string>(); } std::string ConsoleCommandManager::GetShortHelp( - const std::string& channel) const { - UNREFERENCED_PARAMETER(channel); + const std::string& command) const { + UNREFERENCED_PARAMETER(command); return ""; } std::string ConsoleCommandManager::GetLongHelp( - const std::string& channel) const { - UNREFERENCED_PARAMETER(channel); + const std::string& command) const { + UNREFERENCED_PARAMETER(command); return ""; } #endif // ENABLE_DEBUG_CONSOLE
diff --git a/src/cobalt/base/console_commands.h b/src/cobalt/base/console_commands.h index 55fa7f6..1dc465f 100644 --- a/src/cobalt/base/console_commands.h +++ b/src/cobalt/base/console_commands.h
@@ -29,15 +29,14 @@ // triggered by the debug console. // // Any component can create a handler object of the CommandHandler class to -// listen for commands on a particular channel. A CommandHandler object -// automatically registers itself with the ConsoleCommandManager singleton on -// construction and unregisters itself on destruction. +// listen for commands. A CommandHandler object automatically registers itself +// with the ConsoleCommandManager singleton on construction and unregisters +// itself on destruction. // -// Each CommandHandler object specifies a callback and a help string. When the -// ConsoleCommandManager receives a command broadcast on a particular channel, -// it runs the callback of the CommandHandler object registered to that -// channel. The help string is used within the debug console to document the -// channels that have been registered to listen for commands. +// Each CommandHandler object specifies a callback and a help string. The +// ConsoleCommandManager handles a particular command by running the callback of +// the CommandHandler object registered for that command. The help string is +// used within the debug console to document the registered commands. class ConsoleCommandManager { public: @@ -47,17 +46,17 @@ // Command handler that registers itself with this object. class CommandHandler { public: - CommandHandler(const std::string& channel, const CommandCallback& callback, + CommandHandler(const std::string& command, const CommandCallback& callback, const std::string& short_help, const std::string& long_help); ~CommandHandler(); - const std::string& channel() const { return channel_; } + const std::string& command() const { return command_; } const CommandCallback& callback() const { return callback_; } const std::string& short_help() const { return short_help_; } const std::string& long_help() const { return long_help_; } private: - std::string channel_; + std::string command_; CommandCallback callback_; std::string short_help_; std::string long_help_; @@ -69,16 +68,16 @@ static ConsoleCommandManager* GetInstance(); // Handles a command by posting the message to the handler registered for - // the specified channel, if any. - void HandleCommand(const std::string& channel, + // the specified command, if any. + void HandleCommand(const std::string& command, const std::string& message) const; - // Returns a set of all the currently registered channels. - std::set<std::string> GetRegisteredChannels() const; + // Returns a set of all the currently registered commands. + std::set<std::string> GetRegisteredCommands() const; - // Returns the help strings for a channel. - std::string GetShortHelp(const std::string& channel) const; - std::string GetLongHelp(const std::string& channel) const; + // Returns the help strings for a command. + std::string GetShortHelp(const std::string& command) const; + std::string GetLongHelp(const std::string& command) const; private: // Class can only be instanced via the singleton @@ -87,7 +86,7 @@ #if defined(ENABLE_DEBUG_CONSOLE) // Command handler map type. - typedef std::multimap<std::string, const CommandHandler*> CommandHandlerMap; + typedef std::map<std::string, const CommandHandler*> CommandHandlerMap; // Methods to register/unregister command handlers. // These are intended only to be called from the command handler objects. @@ -97,8 +96,8 @@ mutable base::Lock lock_; - // Map of command handlers, one for each channel. - CommandHandlerMap command_channel_map_; + // Map of command handlers, one for each command. + CommandHandlerMap command_command_map_; #endif // ENABLE_DEBUG_CONSOLE };
diff --git a/src/cobalt/base/copy_i18n_data.gypi b/src/cobalt/base/copy_i18n_data.gypi index 07b467a..6edde23 100644 --- a/src/cobalt/base/copy_i18n_data.gypi +++ b/src/cobalt/base/copy_i18n_data.gypi
@@ -33,7 +33,7 @@ 'all_dependent_settings': { 'variables': { - 'content_deploy_subdirs': [ 'icu' ] + 'content_deploy_subdirs': [ 'i18n' ] } }, }
diff --git a/src/cobalt/base/token.cc b/src/cobalt/base/token.cc index c6b5443..ba5b852 100644 --- a/src/cobalt/base/token.cc +++ b/src/cobalt/base/token.cc
@@ -19,6 +19,7 @@ #include "base/logging.h" #include "base/memory/singleton.h" +#include "base/string_piece.h" #include "base/synchronization/lock.h" namespace base { @@ -54,12 +55,14 @@ #if defined(BASE_HASH_USE_HASH_STRUCT) uint32 hash(const char* str) { - return BASE_HASH_NAMESPACE::hash<const char*>()(str); + return BASE_HASH_NAMESPACE::hash<base::StringPiece>()(str); } #else -uint32 hash(const char* str) { return BASE_HASH_NAMESPACE::hash_value(str); } +uint32 hash(const char* str) { + return BASE_HASH_NAMESPACE::hash_value(base::StringPiece(str)); +} #endif // COMPILER
diff --git a/src/cobalt/black_box_tests/black_box_tests.py b/src/cobalt/black_box_tests/black_box_tests.py index e15fce0..faa1693 100644 --- a/src/cobalt/black_box_tests/black_box_tests.py +++ b/src/cobalt/black_box_tests/black_box_tests.py
@@ -26,8 +26,7 @@ ] # These tests only need app launchers with webdriver. _TESTS_NO_SIGNAL = [ - # TODO: Re-enable cookie test after its flakiness is resovled. - # 'persistent_cookie', + 'persistent_cookie', 'allow_eval', 'disable_eval_with_csp', ] @@ -64,13 +63,13 @@ return new_runner -def LoadTests(platform, config): +def LoadTests(platform, config, device_id): launcher = abstract_launcher.LauncherFactory( platform, 'cobalt', config, - device_id=None, + device_id=device_id, target_params=None, output_file=None, out_directory=None) @@ -101,7 +100,7 @@ suite = unittest.TestLoader().loadTestsFromModule( importlib.import_module(_TEST_DIR_PATH + self.test_name)) else: - suite = LoadTests(_device_params.platform, _device_params.config) + suite = LoadTests(_device_params.platform, _device_params.config, _device_params.device_id) return_code = not unittest.TextTestRunner( verbosity=0, stream=sys.stdout).run(suite).wasSuccessful() return return_code @@ -123,4 +122,4 @@ # make module-owned variables like device_param accessible to the tests. main_module = importlib.import_module( 'cobalt.black_box_tests.black_box_tests') - main_module.main() + sys.exit(main_module.main())
diff --git a/src/cobalt/black_box_tests/testdata/persistent_cookie.html b/src/cobalt/black_box_tests/testdata/persistent_cookie.html index dd4c75f..d7e838f 100644 --- a/src/cobalt/black_box_tests/testdata/persistent_cookie.html +++ b/src/cobalt/black_box_tests/testdata/persistent_cookie.html
@@ -67,8 +67,6 @@ } else if (event.keyCode === 99) { thirdRun(); } - // Flush local storage to ensure cookie is written before closing. - h5vcc.storage.flush(); onEndTest(); } setupFinished();
diff --git a/src/cobalt/black_box_tests/threaded_web_server.py b/src/cobalt/black_box_tests/threaded_web_server.py index b1cb297..8291375 100644 --- a/src/cobalt/black_box_tests/threaded_web_server.py +++ b/src/cobalt/black_box_tests/threaded_web_server.py
@@ -62,27 +62,34 @@ def __init__(self, handler=MakeRequestHandlerClass(os.path.dirname(__file__))): _ThreadedTCPServer.allow_reuse_address = True - # Get the socket address for the ANY interface. Doing it this way - # has it so that it will work for IPv4, and IPv6 only networks. - # Note that putting '::' as the hostname does not work at this time - # (see https://bugs.python.org/issue20215). Instead, the following code - # was inspired by https://docs.python.org/2/library/socket.html. - for result in socket.getaddrinfo(None, 0, socket.AF_UNSPEC, - socket.SOCK_STREAM, 0, socket.AI_PASSIVE): - # This is (0.0.0.0, 0) or equivalent in IPv6 (could be more than 2 - # elements). - socket_address = result[4] - break - self._server = _ThreadedTCPServer(socket_address, handler) + try: + self._server = _ThreadedTCPServer(('0.0.0.0', 8000), handler) + except socket.error: + # Get the socket address for the ANY interface. Doing it this way + # has it so that it will work for IPv4. IPv6 is not supported yet because + # SocketServer.TCPServer can not take '::' as the hostname at this time. + # (see https://bugs.python.org/issue20215). Instead, the following code + # was inspired by https://docs.python.org/2/library/socket.html. + for result in socket.getaddrinfo(None, 0, socket.AF_UNSPEC, + socket.SOCK_STREAM, 0, socket.AI_PASSIVE + ): + if len(result[4]) == 2: + # This is (0.0.0.0, 0). + socket_address = result[4] + break + self._server = _ThreadedTCPServer(socket_address, handler) + self._server_thread = None self._bound_port = self._server.server_address[1] address_pack_list = socket.getaddrinfo(socket.gethostname(), self._bound_port) - first_address_pack = address_pack_list[0] - self._bound_ip, _ = first_address_pack[4] - self._bound_host, _ = first_address_pack[4] + for address_pack in address_pack_list: + if len(address_pack[4]) == 2: + self._bound_ip, _ = address_pack[4] + self._bound_host, _ = address_pack[4] + break def GetURL(self, file_name): """Given a |file_name|, return a HTTP URI that can be fetched.
diff --git a/src/cobalt/browser/application.cc b/src/cobalt/browser/application.cc index 7fee6c2..35b2953 100644 --- a/src/cobalt/browser/application.cc +++ b/src/cobalt/browser/application.cc
@@ -868,6 +868,7 @@ const network::NetworkEvent* network_event = base::polymorphic_downcast<const network::NetworkEvent*>(event); if (network_event->type() == network::NetworkEvent::kDisconnection) { + LOG(INFO) << "Detected a network disconnection."; network_status_ = kDisconnectedNetworkStatus; ++network_disconnect_count_; browser_module_->Navigate(GURL("h5vcc://network-failure"));
diff --git a/src/cobalt/browser/browser_bindings_gen.gyp b/src/cobalt/browser/browser_bindings_gen.gyp index 2c708e9..cf277ee 100644 --- a/src/cobalt/browser/browser_bindings_gen.gyp +++ b/src/cobalt/browser/browser_bindings_gen.gyp
@@ -226,6 +226,7 @@ 'generated_header_idl_files': [ '../audio/audio_node_channel_count_mode.idl', '../audio/audio_node_channel_interpretation.idl', + '../debug/console_command.idl', '../dom/blob_property_bag.idl', '../dom/captions/caption_character_edge_style.idl', '../dom/captions/caption_color.idl',
diff --git a/src/cobalt/browser/browser_module.cc b/src/cobalt/browser/browser_module.cc index 3e6bffb..5daa9c4 100644 --- a/src/cobalt/browser/browser_module.cc +++ b/src/cobalt/browser/browser_module.cc
@@ -337,6 +337,15 @@ options_.web_module_options.injected_window_attributes["h5vcc"] = base::Bind(&CreateH5VCC, h5vcc_settings); + if (command_line->HasSwitch(switches::kDisableTimerResolutionLimit)) { + options_.web_module_options.limit_performance_timer_resolution = false; + } + +#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) + options_.web_module_options.enable_partial_layout = + !command_line->HasSwitch(switches::kDisablePartialLayout); +#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) + base::optional<std::string> extension_object_name = GetWebAPIExtensionObjectPropertyName(); if (extension_object_name) { @@ -1036,6 +1045,14 @@ } #if defined(ENABLE_DEBUG_CONSOLE) + // If the debug console is fully visible, it gets the next chance to handle + // pointer events. + if (debug_console_->GetMode() >= debug::DebugHub::kDebugConsoleOn) { + if (!debug_console_->FilterPointerEvent(type, event)) { + return; + } + } + trace_manager_.OnInputEventProduced(); #endif // defined(ENABLE_DEBUG_CONSOLE) @@ -1054,6 +1071,14 @@ } #if defined(ENABLE_DEBUG_CONSOLE) + // If the debug console is fully visible, it gets the next chance to handle + // wheel events. + if (debug_console_->GetMode() >= debug::DebugHub::kDebugConsoleOn) { + if (!debug_console_->FilterWheelEvent(type, event)) { + return; + } + } + trace_manager_.OnInputEventProduced(); #endif // defined(ENABLE_DEBUG_CONSOLE) @@ -1116,6 +1141,8 @@ on_error_triggered_count_++; #endif + LOG(INFO) << "Network error: " << error; + // Set |pending_navigate_url_| to the url where the error occurred. This will // cause the OnError callback to Navigate() to this URL if it receives a // positive response; otherwise, if Cobalt is currently preloaded or
diff --git a/src/cobalt/browser/cobalt.gyp b/src/cobalt/browser/cobalt.gyp index 3d5fd8b..b06913c 100644 --- a/src/cobalt/browser/cobalt.gyp +++ b/src/cobalt/browser/cobalt.gyp
@@ -24,6 +24,11 @@ '<(DEPTH)/cobalt/browser/browser.gyp:browser', ], 'conditions': [ + ['clang and target_os not in ["tvos", "android", "orbis"]', { + 'dependencies': [ + '<(DEPTH)/third_party/musl/musl.gyp:c' + ], + }], ['cobalt_enable_lib == 1', { 'sources': [ 'lib/cobalt.def',
diff --git a/src/cobalt/browser/debug_console.cc b/src/cobalt/browser/debug_console.cc index bf5143e..a71be63 100644 --- a/src/cobalt/browser/debug_console.cc +++ b/src/cobalt/browser/debug_console.cc
@@ -211,6 +211,22 @@ return false; } +bool DebugConsole::FilterWheelEvent(base::Token type, + const dom::WheelEventInit& event) { + // Assume here the full debug console is visible - pass all events to its + // web module, and return false to indicate the event has been consumed. + web_module_->InjectWheelEvent(type, event); + return false; +} + +bool DebugConsole::FilterPointerEvent(base::Token type, + const dom::PointerEventInit& event) { + // Assume here the full debug console is visible - pass all events to its + // web module, and return false to indicate the event has been consumed. + web_module_->InjectPointerEvent(type, event); + return false; +} + #if SB_HAS(ON_SCREEN_KEYBOARD) bool DebugConsole::InjectOnScreenKeyboardInputEvent( base::Token type, const dom::InputEventInit& event) {
diff --git a/src/cobalt/browser/debug_console.h b/src/cobalt/browser/debug_console.h index 20f7049..dcf7d41 100644 --- a/src/cobalt/browser/debug_console.h +++ b/src/cobalt/browser/debug_console.h
@@ -27,6 +27,8 @@ #include "cobalt/debug/debug_hub.h" #include "cobalt/dom/input_event_init.h" #include "cobalt/dom/keyboard_event_init.h" +#include "cobalt/dom/pointer_event_init.h" +#include "cobalt/dom/wheel_event_init.h" #include "cobalt/dom/window.h" #include "googleurl/src/gurl.h" @@ -53,6 +55,16 @@ // false if it was consumed within this function. bool FilterKeyEvent(base::Token type, const dom::KeyboardEventInit& event); + // Filters a pointer event. + // Returns true if the event should be passed on to other handlers, + // false if it was consumed within this function. + bool FilterPointerEvent(base::Token type, const dom::PointerEventInit& event); + + // Filters a wheel event. + // Returns true if the event should be passed on to other handlers, + // false if it was consumed within this function. + bool FilterWheelEvent(base::Token type, const dom::WheelEventInit& event); + #if SB_HAS(ON_SCREEN_KEYBOARD) // Inject an on screen keyboard input event. // Returns true if the event should be passed on to other handlers,
diff --git a/src/cobalt/browser/debug_console/debug_commands.js b/src/cobalt/browser/debug_console/debug_commands.js index 755a4be..a6dbbc7 100644 --- a/src/cobalt/browser/debug_console/debug_commands.js +++ b/src/cobalt/browser/debug_console/debug_commands.js
@@ -103,7 +103,7 @@ 'Get the debugger client. The debugger client can be used to issue ' + 'JavaScript debugging commands to the main web module.'; - addUserCommands(); + addConsoleCommands(); } function help(command) { @@ -148,21 +148,18 @@ executeMain(js); } -function addUserCommands() { - var channelString = window.debugHub.getCommandChannels(); - var channels = channelString.split(' '); - for (var i = 0; i < channels.length; i++) { - addSingleUserCommand(channels[i]) +function addConsoleCommands() { + var consoleCommands = window.debugHub.debugger.consoleCommands; + for (var i = 0; i < consoleCommands.length; i++) { + var c = consoleCommands[i]; + addOneConsoleCommand(c.command, c.shortHelp, c.longHelp); } } -function addSingleUserCommand(channel) { - var channelHelp = window.debugHub.getCommandChannelShortHelp(channel); - debug[channel] = function(message) { - window.debugHub.sendCommand(channel, message); +function addOneConsoleCommand(command, shortHelp, longHelp) { + debug[command] = function(message) { + window.debugHub.debugger.sendConsoleCommand(command, message); } - debug[channel].shortHelp = - window.debugHub.getCommandChannelShortHelp(channel); - debug[channel].longHelp = - window.debugHub.getCommandChannelLongHelp(channel); + debug[command].shortHelp = shortHelp; + debug[command].longHelp = longHelp; }
diff --git a/src/cobalt/browser/debug_console/debug_console.js b/src/cobalt/browser/debug_console/debug_console.js index 5878b5c..ba503ff 100644 --- a/src/cobalt/browser/debug_console/debug_console.js +++ b/src/cobalt/browser/debug_console/debug_console.js
@@ -229,6 +229,14 @@ executeCommand(command); } +function onWheel(event) { + if (event.deltaY > 0) { + messageLog.scrollDown(event.deltaY); + } else if (event.deltaY < 0) { + messageLog.scrollUp(-event.deltaY); + } +} + function onKeydown(event) { var key = event.key; if (key == 'Unidentified') { @@ -313,6 +321,7 @@ createConsoleValues(); initDebugCommands(); addLogMessageCallback(); + document.addEventListener('wheel', onWheel); document.addEventListener('keypress', onKeypress); document.addEventListener('keydown', onKeydown); document.addEventListener('keyup', onKeyup);
diff --git a/src/cobalt/browser/debug_console/message_log.js b/src/cobalt/browser/debug_console/message_log.js index d51a915..4f378f5 100644 --- a/src/cobalt/browser/debug_console/message_log.js +++ b/src/cobalt/browser/debug_console/message_log.js
@@ -189,8 +189,8 @@ } } -MessageLog.prototype.pageUp = function() { - this.displayPos += this.SCROLL_SIZE; +MessageLog.prototype.scrollUp = function(size) { + this.displayPos += size; var max = this.buffer.size - this.DISPLAY_AT_HEAD; if (this.displayPos > max) { this.displayPos = max; @@ -198,14 +198,22 @@ this.displayMessages(); } -MessageLog.prototype.pageDown = function() { - this.displayPos -= this.SCROLL_SIZE; +MessageLog.prototype.scrollDown = function(size) { + this.displayPos -= size; if (this.displayPos < 0) { this.displayPos = 0; } this.displayMessages(); } +MessageLog.prototype.pageUp = function() { + this.scrollUp(this.SCROLL_SIZE); +} + +MessageLog.prototype.pageDown = function() { + this.scrollDown(this.SCROLL_SIZE); +} + MessageLog.prototype.toHead = function() { this.displayPos = this.buffer.size - this.DISPLAY_AT_HEAD; this.displayMessages();
diff --git a/src/cobalt/browser/memory_tracker/tool/leak_finder_tool.cc b/src/cobalt/browser/memory_tracker/tool/leak_finder_tool.cc index 69dfa9b..3f0f188 100644 --- a/src/cobalt/browser/memory_tracker/tool/leak_finder_tool.cc +++ b/src/cobalt/browser/memory_tracker/tool/leak_finder_tool.cc
@@ -31,6 +31,9 @@ namespace browser { namespace memory_tracker { +// Number of output values to display in the csv. +const size_t kNumberOfOutputColumns = 40; + LeakFinderTool::LeakFinderTool(StackTraceMode mode) : string_pool_(128), frame_map_(128), @@ -202,14 +205,13 @@ std::vector<AllocationProfile> alloc_profiles; GenerateTopLeakingAllocationProfiles(time_values, map_allocations, &alloc_profiles); - if (alloc_profiles.empty()) { params->logger()->Output( "MemoryTrackerLeakFinder: alloc_profiles was " "empty and nothing is written."); } else { - if (alloc_profiles.size() > 20) { - alloc_profiles.resize(20); + if (alloc_profiles.size() > kNumberOfOutputColumns) { + alloc_profiles.resize(kNumberOfOutputColumns); } std::string csv_str = GenerateCSV(time_values, alloc_profiles); @@ -319,8 +321,12 @@ ss << kNewLine << kNewLine; // HEADER - ss << "// Allocation in megabytes." << kNewLine; - ss << kQuote << "Time(min)" << kQuote << kDelimiter; + ss << "// Allocation in megabytes. Keep in mind that only" << kNewLine + << "// the N top allocations will be displayed, sorted" << kNewLine + << "// by slope steepness. Negative slopping allocations" << kNewLine + << "// and allocations that have few blocks may be filtered" << kNewLine + << "// out." << kNewLine + << kQuote << "Time(min)" << kQuote << kDelimiter; for (size_t i = 0; i < data.size(); ++i) { const AllocationProfile& alloc_profile = data[i]; const std::string& name = *alloc_profile.name_;
diff --git a/src/cobalt/browser/screen_shot_writer.cc b/src/cobalt/browser/screen_shot_writer.cc index 925b96f..3f25781 100644 --- a/src/cobalt/browser/screen_shot_writer.cc +++ b/src/cobalt/browser/screen_shot_writer.cc
@@ -28,9 +28,7 @@ : pipeline_(pipeline), screenshot_thread_("Screenshot IO thread") { DCHECK(pipeline); - base::Thread::Options options; - options.message_loop_type = MessageLoop::TYPE_IO; - screenshot_thread_.StartWithOptions(options); + screenshot_thread_.Start(); } void ScreenShotWriter::RequestScreenshotToFile(
diff --git a/src/cobalt/browser/switches.cc b/src/cobalt/browser/switches.cc index 98fbd7a..65b0cfa 100644 --- a/src/cobalt/browser/switches.cc +++ b/src/cobalt/browser/switches.cc
@@ -108,8 +108,10 @@ "sessions and no data being persisted to future sessions. It effectively " "makes the app run as if it has no local storage."; -const char kPartialLayout[] = "partial_layout"; -const char kPartialLayoutHelp[] = "Switches partial layout: on | off"; +const char kDisablePartialLayout[] = "disable_partial_layout"; +const char kDisablePartialLayoutHelp[] = + "Causes layout to re-compute the boxes for the entire DOM rather than " + "re-using boxes for elements that have not been invalidated."; const char kProd[] = "prod"; const char kProdHelp[] = @@ -191,6 +193,13 @@ const char kDisableJavaScriptJitHelp[] = "Specifies that javascript jit should be disabled."; +const char kDisableTimerResolutionLimit[] = "disable_timer_resolution_limit"; +const char kDisableTimerResolutionLimitHelp[] = + "By default, window.performance.now() will return values at a clamped " + "minimum resolution of 20us. By specifying this flag, the limit will be " + "removed and the resolution will be 1us (or larger depending on the " + "platform."; + const char kEnableMapToMeshRectanglar[] = "enable_map_to_mesh_rectangular"; const char kEnableMapToMeshRectanglarHelp[] = "If toggled and map-to-mesh is supported on this platform, this allows it " @@ -364,7 +373,7 @@ {kMinLogLevel, kMinLogLevelHelp}, {kNullAudioStreamer, kNullAudioStreamerHelp}, {kNullSavegame, kNullSavegameHelp}, - {kPartialLayout, kPartialLayoutHelp}, {kProd, kProdHelp}, + {kDisablePartialLayout, kDisablePartialLayoutHelp}, {kProd, kProdHelp}, {kProxy, kProxyHelp}, {kRemoteDebuggingPort, kRemoteDebuggingPortHelp}, {kRequireCSP, kRequireCSPHelp}, {kRequireHTTPSLocation, kRequireHTTPSLocationHelp}, @@ -379,6 +388,7 @@ #endif // ENABLE_DEBUG_COMMAND_LINE_SWITCHES {kDisableJavaScriptJit, kDisableJavaScriptJitHelp}, + {kDisableTimerResolutionLimit, kDisableTimerResolutionLimitHelp}, {kEnableMapToMeshRectanglar, kEnableMapToMeshRectanglarHelp}, {kForceMigrationForStoragePartitioning, kForceMigrationForStoragePartitioningHelp},
diff --git a/src/cobalt/browser/switches.h b/src/cobalt/browser/switches.h index 9c9e4fc..ed76f19 100644 --- a/src/cobalt/browser/switches.h +++ b/src/cobalt/browser/switches.h
@@ -56,8 +56,8 @@ extern const char kNullAudioStreamerHelp[]; extern const char kNullSavegame[]; extern const char kNullSavegameHelp[]; -extern const char kPartialLayout[]; -extern const char kPartialLayoutHelp[]; +extern const char kDisablePartialLayout[]; +extern const char kDisablePartialLayoutHelp[]; extern const char kProd[]; extern const char kProdHelp[]; extern const char kProxy[]; @@ -90,6 +90,8 @@ extern const char kDisableJavaScriptJit[]; extern const char kDisableJavaScriptJitHelp[]; +extern const char kDisableTimerResolutionLimit[]; +extern const char kDisableTimerResolutionLimitHelp[]; extern const char kEnableMapToMeshRectanglar[]; extern const char kForceMigrationForStoragePartitioning[]; extern const char kFPSPrint[];
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-85.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-85.mp4 deleted file mode 100644 index 831859e..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-85.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-86.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-86.mp4 deleted file mode 100644 index fe5f3ca..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-86.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-8b.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-8b.mp4 deleted file mode 100644 index 703415a..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-8b.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-8c.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-8c.mp4 deleted file mode 100644 index 381ffa9..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-8c.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-8d.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-8d.mp4 deleted file mode 100644 index 3e9abdd..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-20120827-8d.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-audio-1MB-trunc.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-audio-1MB-trunc.mp4 deleted file mode 100644 index 5a8e3aa..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car-audio-1MB-trunc.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_20130125_18.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_20130125_18.mp4 deleted file mode 100644 index cb88666..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_20130125_18.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-85.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-85.mp4 deleted file mode 100644 index 2abd243..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-85.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-8b.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-8b.mp4 deleted file mode 100644 index 4f89212..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-8b.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-8c.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-8c.mp4 deleted file mode 100644 index 899fa90..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-8c.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-8d.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-8d.mp4 deleted file mode 100644 index 60237b0..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/car_cenc-20120827-8d.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/nq-frames23-tfdt24.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/nq-frames23-tfdt24.mp4 deleted file mode 100644 index ebf0935..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/nq-frames23-tfdt24.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/nq-frames24-tfdt23.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/nq-frames24-tfdt23.mp4 deleted file mode 100644 index 75b6afb..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/nq-frames24-tfdt23.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/oops_cenc-20121114-145-143.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/oops_cenc-20121114-145-143.mp4 deleted file mode 100644 index 6007fd8..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/oops_cenc-20121114-145-143.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/sintel-trunc.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/sintel-trunc.mp4 deleted file mode 100644 index e9692fa..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/sintel-trunc.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/test-video-1MB.mp4 b/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/test-video-1MB.mp4 deleted file mode 100644 index 217a71a..0000000 --- a/src/cobalt/browser/testdata/mse-eme-conformance-tests/media/test-video-1MB.mp4 +++ /dev/null Binary files differ
diff --git a/src/cobalt/browser/trace_manager.cc b/src/cobalt/browser/trace_manager.cc index 77e059c..059e207 100644 --- a/src/cobalt/browser/trace_manager.cc +++ b/src/cobalt/browser/trace_manager.cc
@@ -23,10 +23,10 @@ namespace browser { namespace { -// Name of the channel to listen for trace commands from the debug console. -const char kTraceCommandChannel[] = "trace"; +// Name of the trace command from the debug console. +const char kTraceCommand[] = "trace"; -// Help strings for the trace command channel. +// Help strings for the trace command. const char kTraceCommandShortHelp[] = "Starts/stops execution tracing."; const char kTraceCommandLongHelp[] = "If a trace is currently running, stops it and saves the result; " @@ -51,7 +51,7 @@ TraceManager::TraceManager() : self_message_loop_(MessageLoop::current()), ALLOW_THIS_IN_INITIALIZER_LIST(trace_command_handler_( - kTraceCommandChannel, + kTraceCommand, base::Bind(&TraceManager::OnTraceMessage, base::Unretained(this)), kTraceCommandShortHelp, kTraceCommandLongHelp)), ALLOW_THIS_IN_INITIALIZER_LIST(input_trace_command_handler_(
diff --git a/src/cobalt/browser/web_module.cc b/src/cobalt/browser/web_module.cc index cb9a1ae..cf84a18 100644 --- a/src/cobalt/browser/web_module.cc +++ b/src/cobalt/browser/web_module.cc
@@ -34,8 +34,8 @@ #include "cobalt/base/type_id.h" #include "cobalt/browser/splash_screen_cache.h" #include "cobalt/browser/stack_size_constants.h" -#include "cobalt/browser/switches.h" #include "cobalt/browser/web_module_stat_tracker.h" +#include "cobalt/browser/switches.h" #include "cobalt/css_parser/parser.h" #include "cobalt/debug/debug_server_module.h" #include "cobalt/dom/blob.h" @@ -77,27 +77,6 @@ // deeper than this could be discarded, and will not be rendered. const int kDOMMaxElementDepth = 32; -#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) -// Help string for the 'partial_layout' command. -const char kPartialLayoutCommandShortHelp[] = - "Controls partial layout: on | off | wipe | wipe,off"; -const char kPartialLayoutCommandLongHelp[] = - "Controls partial layout.\n" - "\n" - "Syntax:\n" - " debug.partial_layout('CMD [, CMD ...]')\n" - "\n" - "Where CMD can be:\n" - " on : turn partial layout on.\n" - " off : turn partial layout off.\n" - " wipe : wipe the box tree.\n" - "\n" - "Example:\n" - " debug.partial_layout('off,wipe')\n" - "\n" - "To wipe the box tree and turn partial layout off."; -#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - bool CacheUrlContent(SplashScreenCache* splash_screen_cache, const GURL& url, const std::string& content) { base::optional<std::string> key = SplashScreenCache::GetKeyForStartUrl(url); @@ -198,10 +177,6 @@ // so that the message loop can easily exit void ClearAllIntervalsAndTimeouts(); -#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - void OnPartialLayoutConsoleCommandReceived(const std::string& message); -#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - #if defined(ENABLE_WEBDRIVER) // Creates a new webdriver::WindowDriver that interacts with the Window that // is owned by this WebModule instance. @@ -428,12 +403,6 @@ // DocumentObserver that observes the loading document. scoped_ptr<DocumentLoadedObserver> document_load_observer_; -#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - // Handles the 'partial_layout' command. - scoped_ptr<base::ConsoleCommandManager::CommandHandler> - partial_layout_command_handler_; -#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - scoped_ptr<media_session::MediaSessionClient> media_session_client_; scoped_ptr<layout::TopmostEventTarget> topmost_event_target_; @@ -611,6 +580,11 @@ global_environment_->AddRoot(&mutation_observer_task_manager_); global_environment_->AddRoot(media_source_registry_.get()); + bool log_tts = false; +#if defined(ENABLE_DEBUG_COMMAND_LINE_SWITCHES) + log_tts = CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseTTS); +#endif + window_ = new dom::Window( data.window_dimensions.width(), data.window_dimensions.height(), data.video_pixel_ratio, data.initial_application_state, css_parser_.get(), @@ -646,11 +620,13 @@ #if defined(ENABLE_TEST_RUNNER) data.options.layout_trigger == layout::LayoutManager::kTestRunnerMode ? dom::Window::kClockTypeTestRunner - : dom::Window::kClockTypeSystemTime, + : (data.options.limit_performance_timer_resolution + ? dom::Window::kClockTypeResolutionLimitedSystemTime + : dom::Window::kClockTypeSystemTime), #else dom::Window::kClockTypeSystemTime, #endif - splash_screen_cache_callback, system_caption_settings_); + splash_screen_cache_callback, system_caption_settings_, log_tts); DCHECK(window_); window_weak_ = base::AsWeakPtr(window_.get()); @@ -714,6 +690,10 @@ window_->document()->AddObserver(document_load_observer_.get()); } +#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) + window_->document()->SetPartialLayout(data.options.enable_partial_layout); +#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) + is_running_ = true; } @@ -942,17 +922,6 @@ synchronous_loader_interrupt_.Signal(); } -#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) -void WebModule::Impl::OnPartialLayoutConsoleCommandReceived( - const std::string& message) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(is_running_); - DCHECK(window_); - DCHECK(window_->document()); - window_->document()->SetPartialLayout(message); -} -#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - void WebModule::Impl::OnCspPolicyChanged() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(is_running_); @@ -1329,30 +1298,11 @@ message_loop()->PostBlockingTask( FROM_HERE, base::Bind(&WebModule::Initialize, base::Unretained(this), construction_data)); - -#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - CommandLine* command_line = CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(browser::switches::kPartialLayout)) { - const std::string partial_layout_string = - command_line->GetSwitchValueASCII(browser::switches::kPartialLayout); - OnPartialLayoutConsoleCommandReceived(partial_layout_string); - } - partial_layout_command_handler_.reset( - new base::ConsoleCommandManager::CommandHandler( - browser::switches::kPartialLayout, - base::Bind(&WebModule::OnPartialLayoutConsoleCommandReceived, - base::Unretained(this)), - kPartialLayoutCommandShortHelp, kPartialLayoutCommandLongHelp)); -#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) } WebModule::~WebModule() { DCHECK(message_loop()); -#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - partial_layout_command_handler_.reset(); -#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - // Create a destruction observer to shut down the WebModule once all pending // tasks have been executed and the message loop is about to be destroyed. // This allows us to safely stop the thread, drain the task queue, then @@ -1524,19 +1474,6 @@ } } -#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) -void WebModule::OnPartialLayoutConsoleCommandReceived( - const std::string& message) { - DCHECK(message_loop()); - DCHECK(impl_); - - message_loop()->PostTask( - FROM_HERE, - base::Bind(&WebModule::Impl::OnPartialLayoutConsoleCommandReceived, - base::Unretained(impl_.get()), message)); -} -#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - #if defined(ENABLE_WEBDRIVER) scoped_ptr<webdriver::WindowDriver> WebModule::CreateWindowDriver( const webdriver::protocol::WindowId& window_id) {
diff --git a/src/cobalt/browser/web_module.h b/src/cobalt/browser/web_module.h index 06163fb..4b7a43a 100644 --- a/src/cobalt/browser/web_module.h +++ b/src/cobalt/browser/web_module.h
@@ -232,6 +232,16 @@ // color of transparent will replace existing pixel values, effectively // clearing the screen. bool clear_window_with_background_color; + + // As a preventative measure against Spectre attacks, we explicitly limit + // the resolution of the performance timer by default. Setting this option + // can allow the limit to be disabled. + bool limit_performance_timer_resolution = true; + +#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) + // Whether layout is optimized to re-use boxes for still-valid elements. + bool enable_partial_layout = true; +#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) }; typedef layout::LayoutManager::LayoutResults LayoutResults; @@ -416,10 +426,6 @@ void CancelSynchronousLoads(); -#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - void OnPartialLayoutConsoleCommandReceived(const std::string& message); -#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - // The message loop this object is running on. MessageLoop* message_loop() const { return thread_.message_loop(); } @@ -430,12 +436,6 @@ // All sub-objects of this object are created on this thread, and all public // member functions are re-posted to this thread if necessary. base::Thread thread_; - -#if defined(ENABLE_PARTIAL_LAYOUT_CONTROL) - // Handles the 'partial_layout' command. - scoped_ptr<base::ConsoleCommandManager::CommandHandler> - partial_layout_command_handler_; -#endif // defined(ENABLE_PARTIAL_LAYOUT_CONTROL) }; } // namespace browser
diff --git a/src/cobalt/build/build.id b/src/cobalt/build/build.id index a23811b..6ec0091 100644 --- a/src/cobalt/build/build.id +++ b/src/cobalt/build/build.id
@@ -1 +1 @@ -186250 \ No newline at end of file +188393 \ No newline at end of file
diff --git a/src/cobalt/content/ssl/certs/2c11d503.0 b/src/cobalt/content/ssl/certs/2c11d503.0 deleted file mode 100644 index acedb11..0000000 --- a/src/cobalt/content/ssl/certs/2c11d503.0 +++ /dev/null
@@ -1,12 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICITCCAaagAwIBAgISESDm+Ez8JLC+BUCs2oMbNGA/MAoGCCqGSM49BAMDMEAxCzAJBgNVBAYT -AkZSMRIwEAYDVQQKDAlPcGVuVHJ1c3QxHTAbBgNVBAMMFE9wZW5UcnVzdCBSb290IENBIEczMB4X -DTE0MDUyNjAwMDAwMFoXDTM4MDExNTAwMDAwMFowQDELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCU9w -ZW5UcnVzdDEdMBsGA1UEAwwUT3BlblRydXN0IFJvb3QgQ0EgRzMwdjAQBgcqhkjOPQIBBgUrgQQA -IgNiAARK7liuTcpm3gY6oxH84Bjwbhy6LTAMidnW7ptzg6kjFYwvWYpa3RTqnVkrQ7cG7DK2uu5B -ta1doYXM6h0UZqNnfkbilPPntlahFVmhTzeXuSIevRHr9LIfXsMUmuXZl5mjYzBhMA4GA1UdDwEB -/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRHd8MUi2I5DMlv4VBN0BBY3JWIbTAf -BgNVHSMEGDAWgBRHd8MUi2I5DMlv4VBN0BBY3JWIbTAKBggqhkjOPQQDAwNpADBmAjEAj6jcnboM -BBf6Fek9LykBl7+BFjNAk2z8+e2AcG+qj9uEwov1NcoG3GRvaBbhj5G5AjEA2Euly8LQCGzpGPta -3U1fJAuwACEl74+nBCZx4nxp5V2a+EEfOzmTk51V6s2N8fvB ------END CERTIFICATE-----
diff --git a/src/cobalt/content/ssl/certs/451b5485.0 b/src/cobalt/content/ssl/certs/451b5485.0 deleted file mode 100644 index bf864ae..0000000 --- a/src/cobalt/content/ssl/certs/451b5485.0 +++ /dev/null
@@ -1,12 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICHDCCAaKgAwIBAgISESDZkc6uo+jF5//pAq/Pc7xVMAoGCCqGSM49BAMDMD4xCzAJBgNVBAYT -AkZSMREwDwYDVQQKDAhDZXJ0cGx1czEcMBoGA1UEAwwTQ2VydHBsdXMgUm9vdCBDQSBHMjAeFw0x -NDA1MjYwMDAwMDBaFw0zODAxMTUwMDAwMDBaMD4xCzAJBgNVBAYTAkZSMREwDwYDVQQKDAhDZXJ0 -cGx1czEcMBoGA1UEAwwTQ2VydHBsdXMgUm9vdCBDQSBHMjB2MBAGByqGSM49AgEGBSuBBAAiA2IA -BM0PW1aC3/BFGtat93nwHcmsltaeTpwftEIRyoa/bfuFo8XlGVzX7qY/aWfYeOKmycTbLXku54uN -Am8xIk0G42ByRZ0OQneezs/lf4WbGOT8zC5y0xaTTsqZY1yhBSpsBqNjMGEwDgYDVR0PAQH/BAQD -AgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNqDYwJ5jtpMxjwjFNiPwyCrKGBZMB8GA1Ud -IwQYMBaAFNqDYwJ5jtpMxjwjFNiPwyCrKGBZMAoGCCqGSM49BAMDA2gAMGUCMHD+sAvZ94OX7PNV -HdTcswYO/jOYnYs5kGuUIe22113WTNchp+e/IQ8rzfcq3IUHnQIxAIYUFuXcsGXCwI4Un78kFmjl -vPl5adytRSv3tjFzzAalU5ORGpOucGpnutee5WEaXw== ------END CERTIFICATE-----
diff --git a/src/cobalt/content/ssl/certs/608a55ad.0 b/src/cobalt/content/ssl/certs/608a55ad.0 deleted file mode 100644 index eb2e84f..0000000 --- a/src/cobalt/content/ssl/certs/608a55ad.0 +++ /dev/null
@@ -1,27 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIFbzCCA1egAwIBAgISESChaRu/vbm9UpaPI+hIvyYRMA0GCSqGSIb3DQEBDQUAMEAxCzAJBgNV -BAYTAkZSMRIwEAYDVQQKDAlPcGVuVHJ1c3QxHTAbBgNVBAMMFE9wZW5UcnVzdCBSb290IENBIEcy -MB4XDTE0MDUyNjAwMDAwMFoXDTM4MDExNTAwMDAwMFowQDELMAkGA1UEBhMCRlIxEjAQBgNVBAoM -CU9wZW5UcnVzdDEdMBsGA1UEAwwUT3BlblRydXN0IFJvb3QgQ0EgRzIwggIiMA0GCSqGSIb3DQEB -AQUAA4ICDwAwggIKAoICAQDMtlelM5QQgTJT32F+D3Y5z1zCU3UdSXqWON2ic2rxb95eolq5cSG+ -Ntmh/LzubKh8NBpxGuga2F8ORAbtp+Dz0mEL4DKiltE48MLaARf85KxP6O6JHnSrT78eCbY2albz -4e6WiWYkBuTNQjpK3eCasMSCRbP+yatcfD7J6xcvDH1urqWPyKwlCm/61UWY0jUJ9gNDlP7ZvyCV -eYCYitmJNbtRG6Q3ffyZO6v/v6wNj0OxmXsWEH4db0fEFY8ElggGQgT4hNYdvJGmQr5J1WqIP7wt -UdGejeBSzFfdNTVY27SPJIjki9/ca1TSgSuyzpJLHB9G+h3Ykst2Z7UJmQnlrBcUVXDGPKBWCgOz -3GIZ38i1MH/1PCZ1Eb3XG7OHngevZXHloM8apwkQHZOJZlvoPGIytbU6bumFAYueQ4xncyhZW+vj -3CzMpSZyYhK05pyDRPZRpOLAeiRXyg6lPzq1O4vldu5w5pLeFlwoW5cZJ5L+epJUzpM5ChaHvGOz -9bGTXOBut9Dq+WIyiET7vycotjCVXRIouZW+j1MY5aIYFuJWpLIsEPUdN6b4t/bQWVyJ98LVtZR0 -0dX+G7bw5tYee9I8y6jj9RjzIR9u701oBnstXW5DiabA+aC/gh7PU3+06yzbXfZqfUAkBXKJOAGT -y3HCOV0GEfZvePg3DTmEJwIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB -/zAdBgNVHQ4EFgQUajn6QiL35okATV59M4PLuG53hq8wHwYDVR0jBBgwFoAUajn6QiL35okATV59 -M4PLuG53hq8wDQYJKoZIhvcNAQENBQADggIBAJjLq0A85TMCl38th6aP1F5Kr7ge57tx+4BkJamz -Gj5oXScmp7oq4fBXgwpkTx4idBvpkF/wrM//T2h6OKQQbA2xx6R3gBi2oihEdqc0nXGEL8pZ0keI -mUEiyTCYYW49qKgFbdEfwFFEVn8nNQLdXpgKQuswv42hm1GqO+qTRmTFAHneIWv2V6CG1wZy7HBG -S4tz3aAhdT7cHcCP009zHIXZ/n9iyJVvttN7jLpTwm+bREx50B1ws9efAvSyB7DH5fitIw6mVskp -EndI2S9G/Tvw/HRwkqWOOAgfZDC2t0v7NqwQjqBSM2OdAzVWxWm9xiNaJ5T2pBL4LTM8oValX9YZ -6e18CL13zSdkzJTaTkZQh+D5wVOAHrut+0dSixv9ovneDiK3PTNZbNTe9ZUGMg1RGUFcPk8G97kr -gCf2o6p6fAbhQ8MTOWIaNr3gKC6UAuQpLmBVrkA9sHSSXvAgZJY/X0VdiLWK2gKgW0VU3jg9CcCo -SmVGFvyqv1ROTVu+OEO3KMqLM6oaJbolXCkvW0pujOotnCr2BXbgd5eAiN1nE28daCSLT7d0geX0 -YJ96Vdc+N9oWaz53rK4YcJUIeSkDiv7BO7M/Gg+kO14fWKGVyasvc0rQLW6aWQ9VGHgtPFGml4vm -u7JwqkwR3v98KzfUetF3NI/n+UL3PIEMS1IK ------END CERTIFICATE-----
diff --git a/src/cobalt/content/ssl/certs/773e07ad.0 b/src/cobalt/content/ssl/certs/773e07ad.0 new file mode 100644 index 0000000..4e0d8e9 --- /dev/null +++ b/src/cobalt/content/ssl/certs/773e07ad.0
@@ -0,0 +1,13 @@ +-----BEGIN CERTIFICATE----- +MIICaTCCAe+gAwIBAgIQISpWDK7aDKtARb8roi066jAKBggqhkjOPQQDAzBtMQswCQYDVQQGEwJD +SDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNlZDEo +MCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwgUm9vdCBHQyBDQTAeFw0xNzA1MDkwOTQ4MzRa +Fw00MjA1MDkwOTU4MzNaMG0xCzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQL +ExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh +bCBSb290IEdDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAETOlQwMYPchi82PG6s4nieUqjFqdr +VCTbUf/q9Akkwwsin8tqJ4KBDdLArzHkdIJuyiXZjHWd8dvQmqJLIX4Wp2OQ0jnUsYd4XxiWD1Ab +NTcPasbc2RNNpI6QN+a9WzGRo1QwUjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAd +BgNVHQ4EFgQUSIcUrOPDnpBgOtfKie7TrYy0UGYwEAYJKwYBBAGCNxUBBAMCAQAwCgYIKoZIzj0E +AwMDaAAwZQIwJsdpW9zV57LnyAyMjMPdeYwbY9XJUpROTYJKcx6ygISpJcBMWm1JKWB4E+J+SOtk +AjEA2zQgMgj/mkkCtojeFK9dbJlxjRo/i9fgojaGHAeCOnZT/cKi7e97sIBPWA9LUzm9 +-----END CERTIFICATE-----
diff --git a/src/cobalt/content/ssl/certs/87229d21.0 b/src/cobalt/content/ssl/certs/87229d21.0 deleted file mode 100644 index 90c8eb7..0000000 --- a/src/cobalt/content/ssl/certs/87229d21.0 +++ /dev/null
@@ -1,27 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIFbzCCA1egAwIBAgISESCzkFU5fX82bWTCp59rY45nMA0GCSqGSIb3DQEBCwUAMEAxCzAJBgNV -BAYTAkZSMRIwEAYDVQQKDAlPcGVuVHJ1c3QxHTAbBgNVBAMMFE9wZW5UcnVzdCBSb290IENBIEcx -MB4XDTE0MDUyNjA4NDU1MFoXDTM4MDExNTAwMDAwMFowQDELMAkGA1UEBhMCRlIxEjAQBgNVBAoM -CU9wZW5UcnVzdDEdMBsGA1UEAwwUT3BlblRydXN0IFJvb3QgQ0EgRzEwggIiMA0GCSqGSIb3DQEB -AQUAA4ICDwAwggIKAoICAQD4eUbalsUwXopxAy1wpLuwxQjczeY1wICkES3d5oeuXT2R0odsN7fa -Yp6bwiTXj/HbpqbfRm9RpnHLPhsxZ2L3EVs0J9V5ToybWL0iEA1cJwzdMOWo010hOHQX/uMftk87 -ay3bfWAfjH1MBcLrARYVmBSO0ZB3Ij/swjm4eTrwSSTilZHcYTSSjFR077F9jAHiOH3BX2pfJLKO -YheteSCtqx234LSWSE9mQxAGFiQD4eCcjsZGT44ameGPuY4zbGneWK2gDqdkVBFpRGZPTBKnjix9 -xNRbxQA0MMHZmf4yzgeEtE7NCv82TWLxp2NX5Ntqp66/K7nJ5rInieV+mhxNaMbBGN4zK1FGSxyO -9z0M+Yo0FMT7MzUj8czxKselu7Cizv5Ta01BG2Yospb6p64KTrk5M0ScdMGTHPjgniQlQ/GbI4Kq -3ywgsNw2TgOzfALU5nsaqocTvz6hdLubDuHAk5/XpGbKuxs74zD0M1mKB3IDVedzagMxbm+WG+Oi -n6+Sx+31QrclTDsTBM8clq8cIqPQqwWyTBIjUtz9GVsnnB47ev1CI9sjgBPwvFEVVJSmdz7QdFG9 -URQIOTfLHzSpMJ1ShC5VkLG631UAC9hWLbFJSXKAqWLXwPYYEQRVzXR7z2FwefR7LFxckvzluFqr -TJOVoSfupb7PcSNCupt2LQIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB -/zAdBgNVHQ4EFgQUl0YhVyE12jZVx/PxN3DlCPaTKbYwHwYDVR0jBBgwFoAUl0YhVyE12jZVx/Px -N3DlCPaTKbYwDQYJKoZIhvcNAQELBQADggIBAB3dAmB84DWn5ph76kTOZ0BP8pNuZtQ5iSas000E -PLuHIT839HEl2ku6q5aCgZG27dmxpGWX4m9kWaSW7mDKHyP7Rbr/jyTwyqkxf3kfgLMtMrpkZ2Cv -uVnN35pJ06iCsfmYlIrM4LvgBBuZYLFGZdwIorJGnkSI6pN+VxbSFXJfLkur1J1juONI5f6ELlgK -n0Md/rcYkoZDSw6cMoYsYPXpSOqV7XAp8dUv/TW0V8/bhUiZucJvbI/NeJWsZCj9VrDDb8O+WVLh -X4SPgPL0DTatdrOjteFkdjpY3H1PXlZs5VVZV6Xf8YpmMIzUUmI4d7S+KNfKNsSbBfD4Fdvb8e80 -nR14SohWZ25g/4/Ii+GOvUKpMwpZQhISKvqxnUOOBZuZ2mKtVzazHbYNeS2WuOvyDEsMpZTGMKcm -GS3tTAZQMPH9WD25SxdfGbRqhFS0OE85og2WaMMolP3tLR9Ka0OWLpABEPs4poEL0L9109S5zvE/ -bw4cHjdx5RiHdRk/ULlepEU0rbDK5uUTdg8xFKmOLZTW1YVNcxVPS/KyPu1svf0OnWZzsD2097+o -4BGkxK51CUpjAEggpsadCwmKtODmzj7HPiY46SvepghJAwSQiumPv+i2tCqjI40cHLI5kqiPAlxA -OXXUc0ECd97N4EOH1uS6SsNsEn/+KuYj1oxx ------END CERTIFICATE-----
diff --git a/src/cobalt/content/ssl/certs/9168f543.0 b/src/cobalt/content/ssl/certs/9168f543.0 deleted file mode 100644 index c037748..0000000 --- a/src/cobalt/content/ssl/certs/9168f543.0 +++ /dev/null
@@ -1,27 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIFazCCA1OgAwIBAgISESBVg+QtPlRWhS2DN7cs3EYRMA0GCSqGSIb3DQEBDQUAMD4xCzAJBgNV -BAYTAkZSMREwDwYDVQQKDAhDZXJ0cGx1czEcMBoGA1UEAwwTQ2VydHBsdXMgUm9vdCBDQSBHMTAe -Fw0xNDA1MjYwMDAwMDBaFw0zODAxMTUwMDAwMDBaMD4xCzAJBgNVBAYTAkZSMREwDwYDVQQKDAhD -ZXJ0cGx1czEcMBoGA1UEAwwTQ2VydHBsdXMgUm9vdCBDQSBHMTCCAiIwDQYJKoZIhvcNAQEBBQAD -ggIPADCCAgoCggIBANpQh7bauKk+nWT6VjOaVj0W5QOVsjQcmm1iBdTYj+eJZJ+622SLZOZ5KmHN -r49aiZFluVj8tANfkT8tEBXgfs+8/H9DZ6itXjYj2JizTfNDnjl8KvzsiNWI7nC9hRYt6kuJPKNx -Qv4c/dMcLRC4hlTqQ7jbxofaqK6AJc96Jh2qkbBIb6613p7Y1/oA/caP0FG7Yn2ksYyy/yARujVj -BYZHYEMzkPZHogNPlk2dT8Hq6pyi/jQu3rfKG3akt62f6ajUeD94/vI4CTYd0hYCyOwqaK/1jpTv -LRN6HkJKHRUxrgwEV/xhc/MxVoYxgKDEEW4wduOU8F8ExKyHcomYxZ3MVwia9Az8fXoFOvpHgDm2 -z4QTd28n6v+WZxcIbekN1iNQMLAVdBM+5S//Ds3EC0pd8NgAM0lm66EYfFkuPSi5YXHLtaW6uOrc -4nBvCGrch2c0798wct3zyT8j/zXhviEpIDCB5BmlIOklynMxdCm+4kLV87ImZsdo/Rmz5yCTmehd -4F6H50boJZwKKSTUzViGUkAksnsPmBIgJPaQbEfIDbsYIC7Z/fyL8inqh3SV4EJQeIQEQWGw9CEj -jy3LKCHyamz0GqbFFLQ3ZU+V/YDI+HLlJWvEYLF7bY5KinPOWftwenMGE9nTdDckQQoRb5fc5+R+ -ob0V8rqHDz1oihYHAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0G -A1UdDgQWBBSowcCbkahDFXxdBie0KlHYlwuBsTAfBgNVHSMEGDAWgBSowcCbkahDFXxdBie0KlHY -lwuBsTANBgkqhkiG9w0BAQ0FAAOCAgEAnFZvAX7RvUz1isbwJh/k4DgYzDLDKTudQSk0YcbX8ACh -66Ryj5QXvBMsdbRX7gp8CXrc1cqh0DQT+Hern+X+2B50ioUHj3/MeXrKls3N/U/7/SMNkPX0XtPG -YX2eEeAC7gkE2Qfdpoq3DIMku4NQkv5gdRE+2J2winq14J2by5BSS7CTKtQ+FjPlnsZlFT5kOwQ/ -2wyPX1wdaR+v8+khjPPvl/aatxm2hHSco1S1cE5j2FddUyGbQJJD+tZ3VTNPZNX70Cxqjm0lpu+F -6ALEUz65noe8zDUa3qHpimOHZR4RKttjd5cUvpoUmRGywO6wT/gUITJDT5+rosuoD6o7BlXGEilX -CNQ314cnrUlZp5GrRHpejXDbl85IULFzk/bwg2D5zfHhMf1bfHEhYxQUqq/F3pN+aLHsIqKqkHWe -tUNy6mSjhEv9DKgma3GX7lZjZuhCVPnHHd/Qj1vfyDBviP4NxDMcU6ij/UgQ8uQKTuEVV/xuZDDC -VRHc6qnNSlSsKWNEz0pAoNZoWRsz+e86i9sgktxChL8Bq4fA1SCC28a5g4VCXA9DO2pJNdWY9BW/ -+mGBDAkgGNLQFwzLSABQ6XaCjGTXOqAHVcweMcDvOrRl++O/QmueD6i9a5jc2NvLi6Td11n0bt3+ -qsOR0C5CB8AMTVPNJLFMWx5R9N/pkvo= ------END CERTIFICATE-----
diff --git a/src/cobalt/content/ssl/certs/dc4d6a89.0 b/src/cobalt/content/ssl/certs/dc4d6a89.0 new file mode 100644 index 0000000..097abc0 --- /dev/null +++ b/src/cobalt/content/ssl/certs/dc4d6a89.0
@@ -0,0 +1,27 @@ +-----BEGIN CERTIFICATE----- +MIIFgzCCA2ugAwIBAgIORea7A4Mzw4VlSOb/RVEwDQYJKoZIhvcNAQEMBQAwTDEgMB4GA1UECxMX +R2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkds +b2JhbFNpZ24wHhcNMTQxMjEwMDAwMDAwWhcNMzQxMjEwMDAwMDAwWjBMMSAwHgYDVQQLExdHbG9i +YWxTaWduIFJvb3QgQ0EgLSBSNjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFs +U2lnbjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJUH6HPKZvnsFMp7PPcNCPG0RQss +grRIxutbPK6DuEGSMxSkb3/pKszGsIhrxbaJ0cay/xTOURQh7ErdG1rG1ofuTToVBu1kZguSgMpE +3nOUTvOniX9PeGMIyBJQbUJmL025eShNUhqKGoC3GYEOfsSKvGRMIRxDaNc9PIrFsmbVkJq3MQbF +vuJtMgamHvm566qjuL++gmNQ0PAYid/kD3n16qIfKtJwLnvnvJO7bVPiSHyMEAc4/2ayd2F+4OqM +PKq0pPbzlUoSB239jLKJz9CgYXfIWHSw1CM69106yqLbnQneXUQtkPGBzVeS+n68UARjNN9rkxi+ +azayOeSsJDa38O+2HBNXk7besvjihbdzorg1qkXy4J02oW9UivFyVm4uiMVRQkQVlO6jxTiWm05O +WgtH8wY2SXcwvHE35absIQh1/OZhFj931dmRl4QKbNQCTXTAFO39OfuD8l4UoQSwC+n+7o/hbguy +CLNhZglqsQY6ZZZZwPA1/cnaKI0aEYdwgQqomnUdnjqGBQCe24DWJfncBZ4nWUx2OVvq+aWh2IMP +0f/fMBH5hc8zSPXKbWQULHpYT9NLCEnFlWQaYw55PfWzjMpYrZxCRXluDocZXFSxZba/jJvcE+kN +b7gu3GduyYsRtYQUigAZcIN5kZeR1BonvzceMgfYFGM8KEyvAgMBAAGjYzBhMA4GA1UdDwEB/wQE +AwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSubAWjkxPioufi1xzWx/B/yGdToDAfBgNV +HSMEGDAWgBSubAWjkxPioufi1xzWx/B/yGdToDANBgkqhkiG9w0BAQwFAAOCAgEAgyXt6NH9lVLN +nsAEoJFp5lzQhN7craJP6Ed41mWYqVuoPId8AorRbrcWc+ZfwFSY1XS+wc3iEZGtIxg93eFyRJa0 +lV7Ae46ZeBZDE1ZXs6KzO7V33EByrKPrmzU+sQghoefEQzd5Mr6155wsTLxDKZmOMNOsIeDjHfrY +BzN2VAAiKrlNIC5waNrlU/yDXNOd8v9EDERm8tLjvUYAGm0CuiVdjaExUd1URhxN25mW7xocBFym +Fe944Hn+Xds+qkxV/ZoVqW/hpvvfcDDpw+5CRu3CkwWJ+n1jez/QcYF8AOiYrg54NMMl+68KnyBr +3TsTjxKM4kEaSHpzoHdpx7Zcf4LIHv5YGygrqGytXm3ABdJ7t+uA/iU3/gKbaKxCXcPu9czc8FB1 +0jZpnOZ7BN9uBmm23goJSFmH63sUYHpkqmlD75HHTOwY3WzvUy2MmeFe8nI+z1TIvWfspA9MRf/T +uTAjB0yPEL+GltmZWrSZVxykzLsViVO6LAUP5MSeGbEYNNVMnbrt9x+vJJUEeKgDu+6B5dpffItK +oZB0JaezPkvILFa9x8jvOOJckvB595yEunQtYQEgfn7R8k8HWV+LLUNS60YMlOH1Zkd5d9VUWx+t +JDfLRVpOoERIyNiwmcUVhAn21klJwGW45hpxbqCo8YLoRT5s1gLXCmeDBVrJpBA= +-----END CERTIFICATE-----
diff --git a/src/cobalt/css_parser/scanner.cc b/src/cobalt/css_parser/scanner.cc index ce0bc8c..872fe85 100644 --- a/src/cobalt/css_parser/scanner.cc +++ b/src/cobalt/css_parser/scanner.cc
@@ -666,8 +666,6 @@ number.begin = input_iterator_; // Negative numbers are handled in the grammar. - // Scientific notation is required by the standard but is not supported - // neither by WebKit nor Blink. bool dot_seen(false); while (true) { if (!IsAsciiDigit(input_iterator_[0])) { @@ -681,7 +679,6 @@ } ++input_iterator_; } - number.end = input_iterator_; if (UNLIKELY(parsing_mode_ == kNthChildMode) && !dot_seen && IsAsciiAlphaCaselessEqual(*input_iterator_, 'n')) { @@ -696,16 +693,38 @@ return kNthToken; } + // Handle numbers in scientific notation. + bool is_scientific(false); + if (IsAsciiAlphaCaselessEqual(*input_iterator_, 'e')) { + // Only one exponent symbol is allowed for a number, + // and it must be followed by a sign and digits, or just digits. + int exponent_prefix = 0; + if ((input_iterator_[1] == '-' || input_iterator_[1] == '+') && + IsAsciiDigit(input_iterator_[2])) { + exponent_prefix = 3; + } + if (IsAsciiDigit(input_iterator_[1])) { + exponent_prefix = 2; + } + if (exponent_prefix > 0) { + is_scientific = true; + input_iterator_ = input_iterator_ + exponent_prefix; + } + while (IsAsciiDigit(input_iterator_[0])) { + ++input_iterator_; + } + } + + number.end = input_iterator_; char* number_end(const_cast<char*>(number.end)); // We parse into |double| for two reasons: // - C++03 doesn't have std::strtof() function; // - |float|'s significand is not large enough to represent |int| precisely. // |number_end| is used by std::strtod() as a pure output parameter - it's // input value is not used. std::strtod() may parse more of the number than - // we expect, e.g. in the case of scientific notation or hexadecimal format. - // In these cases (number_end != number.end), return an invalid number token. + // we expect, e.g. in the case of hexadecimal format. In these cases + // (number_end != number.end), return an invalid number token. double real_as_double(std::strtod(number.begin, &number_end)); - if (number_end != number.end || real_as_double != real_as_double || // n != n if and only if it's NaN. real_as_double == std::numeric_limits<float>::infinity() || @@ -740,7 +759,8 @@ return kPercentageToken; } - if (!dot_seen && real_as_double <= std::numeric_limits<int>::max()) { + if (!dot_seen && !is_scientific && + real_as_double <= std::numeric_limits<int>::max()) { token_value->integer = static_cast<int>(real_as_double); return kIntegerToken; }
diff --git a/src/cobalt/css_parser/scanner_test.cc b/src/cobalt/css_parser/scanner_test.cc index 0327be8..5089c71 100644 --- a/src/cobalt/css_parser/scanner_test.cc +++ b/src/cobalt/css_parser/scanner_test.cc
@@ -381,17 +381,29 @@ ASSERT_EQ(kEndOfFileToken, yylex(&token_value_, &token_location_, &scanner)); } -TEST_F(ScannerTest, ScansScientificNotationNumber) { - // Scientific notation is required by the standard but is not supported - // by WebKit or Blink. So we don't support it either. +TEST_F(ScannerTest, ScansScientificNotationNumberWithNegativeExponent) { Scanner scanner("1e-14", &string_pool_); - ASSERT_EQ(kInvalidNumberToken, - yylex(&token_value_, &token_location_, &scanner)); - ASSERT_EQ("1", token_value_.string); + ASSERT_EQ(kRealToken, yylex(&token_value_, &token_location_, &scanner)); + ASSERT_FLOAT_EQ(0.00000000000001f, token_value_.real); - ASSERT_EQ(kIdentifierToken, yylex(&token_value_, &token_location_, &scanner)); - ASSERT_EQ("e-14", token_value_.string); + ASSERT_EQ(kEndOfFileToken, yylex(&token_value_, &token_location_, &scanner)); +} + +TEST_F(ScannerTest, ScansScientificNotationNumberWithPositiveExponent) { + Scanner scanner("2.5e+6", &string_pool_); + + ASSERT_EQ(kRealToken, yylex(&token_value_, &token_location_, &scanner)); + ASSERT_EQ(2500000, token_value_.real); + + ASSERT_EQ(kEndOfFileToken, yylex(&token_value_, &token_location_, &scanner)); +} + +TEST_F(ScannerTest, ScansScientificNotationNumberWithUnsignedExponent) { + Scanner scanner("3e5", &string_pool_); + + ASSERT_EQ(kRealToken, yylex(&token_value_, &token_location_, &scanner)); + ASSERT_EQ(300000, token_value_.real); ASSERT_EQ(kEndOfFileToken, yylex(&token_value_, &token_location_, &scanner)); }
diff --git a/src/cobalt/debug/component_connector.cc b/src/cobalt/debug/component_connector.cc index be921bc..b249ad8 100644 --- a/src/cobalt/debug/component_connector.cc +++ b/src/cobalt/debug/component_connector.cc
@@ -95,6 +95,27 @@ } } +void ComponentConnector::SendScriptEvent(const std::string& method, + const std::string& command, + const JSONObject& params) { + if (!server_) { + DLOG(WARNING) << "Not attached to debug server. Not sending " << method; + return; + } + + script::ScriptDebugger::ScopedPauseOnExceptionsState no_pause( + script_debugger_, script::ScriptDebugger::kNone); + JSONObject command_result = server_->RunScriptCommand(command, params); + base::DictionaryValue* event; + if (command_result->GetDictionary(DebugServer::kResult, &event)) { + server_->OnEvent(method, JSONObject(event->DeepCopy())); + } else { + std::string error; + command_result->GetString(DebugServer::kErrorMessage, &error); + DLOG(ERROR) << "Script event failed (" << method << "): " << error; + } +} + void ComponentConnector::SendEvent(const std::string& method, const JSONObject& params) { if (server_) {
diff --git a/src/cobalt/debug/component_connector.h b/src/cobalt/debug/component_connector.h index ef2b6e0..2c3e911 100644 --- a/src/cobalt/debug/component_connector.h +++ b/src/cobalt/debug/component_connector.h
@@ -58,6 +58,12 @@ // Creates a Runtime.Remote object from an ValueHandleHolder. JSONObject CreateRemoteObject(const script::ValueHandleHolder* object); + // Runs a JavaScript function with JSON parameters, and sends the event it + // returns to the |DebugServer| referenced by this object. + void SendScriptEvent(const std::string& method, + const std::string& command, + const JSONObject& params); + // Sends an event to the |DebugServer| referenced by this object. void SendEvent(const std::string& method, const JSONObject& params);
diff --git a/src/cobalt/debug/console_command.idl b/src/cobalt/debug/console_command.idl new file mode 100644 index 0000000..972b00e --- /dev/null +++ b/src/cobalt/debug/console_command.idl
@@ -0,0 +1,23 @@ +// Copyright 2018 The Cobalt Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Custom dictionary to advertise registered app commands to the debug console. + +[ + Conditional=ENABLE_DEBUG_CONSOLE +] dictionary ConsoleCommand { + DOMString command; + DOMString shortHelp; + DOMString longHelp; +};
diff --git a/src/cobalt/debug/content/backend/runtime.js b/src/cobalt/debug/content/backend/runtime.js index 7f21dfb..5d33494 100644 --- a/src/cobalt/debug/content/backend/runtime.js +++ b/src/cobalt/debug/content/backend/runtime.js
@@ -37,6 +37,22 @@ devtoolsBackend.runtime = {}; +// Creates an executionContextCreated event. +// https://chromedevtools.github.io/devtools-protocol/1-3/Runtime#event-executionContextCreated +devtoolsBackend.runtime.executionContextCreatedEvent = function() { + var event = { + context: { + id: 1, + origin: window.location.origin, + name: "Cobalt", + auxData: { + isDefault: true + } + } + }; + return JSON.stringify(event); +} + // Calls a function on a previously accessed RemoteObject with an argument list // and returns a new RemoteObject. Used extensively by devtools for // auto-completion. The new RemoteObject uses the same |objectGroup| as the @@ -64,7 +80,7 @@ } // Evaluates a string and returns a RemoteObject. -// https://developer.chrome.com/devtools/docs/protocol/1.1/runtime#command-evaluate +// https://chromedevtools.github.io/devtools-protocol/1-3/Runtime#method-evaluate devtoolsBackend.runtime.evaluate = function(params) { var result = {}; var value = null; @@ -111,6 +127,14 @@ return JSON.stringify(result); } +// Returns all let, const and class variables from global scope. +// https://chromedevtools.github.io/devtools-protocol/1-3/Runtime#method-globalLexicalScopeNames +devtoolsBackend.runtime.globalLexicalScopeNames = function(params) { + var result = []; + // TODO: Get the globals. + return JSON.stringify(result); +} + // Returns the properties of a previously accessed object as an array of // PropertyDescriptor objects. // The parameters specifify several options:
diff --git a/src/cobalt/debug/content/devtools/Images/breakpoint.png b/src/cobalt/debug/content/devtools/Images/breakpoint.png deleted file mode 100644 index 1eaea29..0000000 --- a/src/cobalt/debug/content/devtools/Images/breakpoint.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/breakpointConditional.png b/src/cobalt/debug/content/devtools/Images/breakpointConditional.png deleted file mode 100644 index 8a22283..0000000 --- a/src/cobalt/debug/content/devtools/Images/breakpointConditional.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/breakpointConditional_2x.png b/src/cobalt/debug/content/devtools/Images/breakpointConditional_2x.png deleted file mode 100644 index 851adfc..0000000 --- a/src/cobalt/debug/content/devtools/Images/breakpointConditional_2x.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/breakpoint_2x.png b/src/cobalt/debug/content/devtools/Images/breakpoint_2x.png deleted file mode 100644 index a227bac..0000000 --- a/src/cobalt/debug/content/devtools/Images/breakpoint_2x.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/checkboxCheckmark.png b/src/cobalt/debug/content/devtools/Images/checkboxCheckmark.png deleted file mode 100644 index 3a80164..0000000 --- a/src/cobalt/debug/content/devtools/Images/checkboxCheckmark.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/checkboxCheckmark_2x.png b/src/cobalt/debug/content/devtools/Images/checkboxCheckmark_2x.png deleted file mode 100644 index 237e419..0000000 --- a/src/cobalt/debug/content/devtools/Images/checkboxCheckmark_2x.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/chevrons.png b/src/cobalt/debug/content/devtools/Images/chevrons.png deleted file mode 100644 index 460aafb..0000000 --- a/src/cobalt/debug/content/devtools/Images/chevrons.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/chevrons_2x.png b/src/cobalt/debug/content/devtools/Images/chevrons_2x.png deleted file mode 100644 index 091217f..0000000 --- a/src/cobalt/debug/content/devtools/Images/chevrons_2x.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/errorWave.png b/src/cobalt/debug/content/devtools/Images/errorWave.png deleted file mode 100644 index 32b1b68..0000000 --- a/src/cobalt/debug/content/devtools/Images/errorWave.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/errorWave_2x.png b/src/cobalt/debug/content/devtools/Images/errorWave_2x.png deleted file mode 100644 index ffecbf8..0000000 --- a/src/cobalt/debug/content/devtools/Images/errorWave_2x.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/largeIcons.png b/src/cobalt/debug/content/devtools/Images/largeIcons.png deleted file mode 100644 index 381fbdd..0000000 --- a/src/cobalt/debug/content/devtools/Images/largeIcons.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/largeIcons_2x.png b/src/cobalt/debug/content/devtools/Images/largeIcons_2x.png deleted file mode 100644 index c771c2c..0000000 --- a/src/cobalt/debug/content/devtools/Images/largeIcons_2x.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/mediumIcons.png b/src/cobalt/debug/content/devtools/Images/mediumIcons.png deleted file mode 100644 index 6dc3bb4..0000000 --- a/src/cobalt/debug/content/devtools/Images/mediumIcons.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/mediumIcons_2x.png b/src/cobalt/debug/content/devtools/Images/mediumIcons_2x.png deleted file mode 100644 index ae6e2b6..0000000 --- a/src/cobalt/debug/content/devtools/Images/mediumIcons_2x.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/securityIcons.png b/src/cobalt/debug/content/devtools/Images/securityIcons.png deleted file mode 100644 index 5271256..0000000 --- a/src/cobalt/debug/content/devtools/Images/securityIcons.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/securityIcons_2x.png b/src/cobalt/debug/content/devtools/Images/securityIcons_2x.png deleted file mode 100644 index d67c76d..0000000 --- a/src/cobalt/debug/content/devtools/Images/securityIcons_2x.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/smallIcons.png b/src/cobalt/debug/content/devtools/Images/smallIcons.png deleted file mode 100644 index 1e23959..0000000 --- a/src/cobalt/debug/content/devtools/Images/smallIcons.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/smallIcons_2x.png b/src/cobalt/debug/content/devtools/Images/smallIcons_2x.png deleted file mode 100644 index 9c50439..0000000 --- a/src/cobalt/debug/content/devtools/Images/smallIcons_2x.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/treeoutlineTriangles.png b/src/cobalt/debug/content/devtools/Images/treeoutlineTriangles.png deleted file mode 100644 index 71a09d3..0000000 --- a/src/cobalt/debug/content/devtools/Images/treeoutlineTriangles.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/treeoutlineTriangles_2x.png b/src/cobalt/debug/content/devtools/Images/treeoutlineTriangles_2x.png deleted file mode 100644 index 1d8aa0e..0000000 --- a/src/cobalt/debug/content/devtools/Images/treeoutlineTriangles_2x.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Images/whatsnew.png b/src/cobalt/debug/content/devtools/Images/whatsnew.png deleted file mode 100644 index d8ebe05..0000000 --- a/src/cobalt/debug/content/devtools/Images/whatsnew.png +++ /dev/null Binary files differ
diff --git a/src/cobalt/debug/content/devtools/Tests.js b/src/cobalt/debug/content/devtools/Tests.js deleted file mode 100644 index e6c0d06..0000000 --- a/src/cobalt/debug/content/devtools/Tests.js +++ /dev/null
@@ -1,1223 +0,0 @@ -/* - * Copyright (C) 2010 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -/* eslint-disable indent */ - -/** - * @fileoverview This file contains small testing framework along with the - * test suite for the frontend. These tests are a part of the continues build - * and are executed by the devtools_sanity_unittest.cc as a part of the - * Interactive UI Test suite. - * FIXME: change field naming style to use trailing underscore. - */ - -(function createTestSuite(window) { - - /** - * @unrestricted - */ - var TestSuite = class { - /** - * Test suite for interactive UI tests. - * @param {Object} domAutomationController DomAutomationController instance. - */ - constructor(domAutomationController) { - this.domAutomationController_ = domAutomationController; - this.controlTaken_ = false; - this.timerId_ = -1; - this._asyncInvocationId = 0; - } - - /** - * Key event with given key identifier. - */ - static createKeyEvent(key) { - return new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key: key}); - } - }; - - /** - * Reports test failure. - * @param {string} message Failure description. - */ - TestSuite.prototype.fail = function(message) { - if (this.controlTaken_) - this.reportFailure_(message); - else - throw message; - }; - - /** - * Equals assertion tests that expected === actual. - * @param {!Object|boolean} expected Expected object. - * @param {!Object|boolean} actual Actual object. - * @param {string} opt_message User message to print if the test fails. - */ - TestSuite.prototype.assertEquals = function(expected, actual, opt_message) { - if (expected !== actual) { - var message = 'Expected: \'' + expected + '\', but was \'' + actual + '\''; - if (opt_message) - message = opt_message + '(' + message + ')'; - this.fail(message); - } - }; - - /** - * True assertion tests that value == true. - * @param {!Object} value Actual object. - * @param {string} opt_message User message to print if the test fails. - */ - TestSuite.prototype.assertTrue = function(value, opt_message) { - this.assertEquals(true, !!value, opt_message); - }; - - /** - * Takes control over execution. - */ - TestSuite.prototype.takeControl = function() { - this.controlTaken_ = true; - // Set up guard timer. - var self = this; - this.timerId_ = setTimeout(function() { - self.reportFailure_('Timeout exceeded: 20 sec'); - }, 20000); - }; - - /** - * Releases control over execution. - */ - TestSuite.prototype.releaseControl = function() { - if (this.timerId_ !== -1) { - clearTimeout(this.timerId_); - this.timerId_ = -1; - } - this.controlTaken_ = false; - this.reportOk_(); - }; - - /** - * Async tests use this one to report that they are completed. - */ - TestSuite.prototype.reportOk_ = function() { - this.domAutomationController_.send('[OK]'); - }; - - /** - * Async tests use this one to report failures. - */ - TestSuite.prototype.reportFailure_ = function(error) { - if (this.timerId_ !== -1) { - clearTimeout(this.timerId_); - this.timerId_ = -1; - } - this.domAutomationController_.send('[FAILED] ' + error); - }; - - /** - * Run specified test on a fresh instance of the test suite. - * @param {Array<string>} args method name followed by its parameters. - */ - TestSuite.prototype.dispatchOnTestSuite = function(args) { - var methodName = args.shift(); - try { - this[methodName].apply(this, args); - if (!this.controlTaken_) - this.reportOk_(); - } catch (e) { - this.reportFailure_(e); - } - }; - - /** - * Wrap an async method with TestSuite.{takeControl(), releaseControl()} - * and invoke TestSuite.reportOk_ upon completion. - * @param {Array<string>} args method name followed by its parameters. - */ - TestSuite.prototype.waitForAsync = function(var_args) { - var args = Array.prototype.slice.call(arguments); - this.takeControl(); - args.push(this.releaseControl.bind(this)); - this.dispatchOnTestSuite(args); - }; - - /** - * Overrides the method with specified name until it's called first time. - * @param {!Object} receiver An object whose method to override. - * @param {string} methodName Name of the method to override. - * @param {!Function} override A function that should be called right after the - * overridden method returns. - * @param {?boolean} opt_sticky Whether restore original method after first run - * or not. - */ - TestSuite.prototype.addSniffer = function(receiver, methodName, override, opt_sticky) { - var orig = receiver[methodName]; - if (typeof orig !== 'function') - this.fail('Cannot find method to override: ' + methodName); - var test = this; - receiver[methodName] = function(var_args) { - try { - var result = orig.apply(this, arguments); - } finally { - if (!opt_sticky) - receiver[methodName] = orig; - } - // In case of exception the override won't be called. - try { - override.apply(this, arguments); - } catch (e) { - test.fail('Exception in overriden method \'' + methodName + '\': ' + e); - } - return result; - }; - }; - - /** - * Waits for current throttler invocations, if any. - * @param {!Common.Throttler} throttler - * @param {function()} callback - */ - TestSuite.prototype.waitForThrottler = function(throttler, callback) { - var test = this; - var scheduleShouldFail = true; - test.addSniffer(throttler, 'schedule', onSchedule); - - function hasSomethingScheduled() { - return throttler._isRunningProcess || throttler._process; - } - - function checkState() { - if (!hasSomethingScheduled()) { - scheduleShouldFail = false; - callback(); - return; - } - - test.addSniffer(throttler, '_processCompletedForTests', checkState); - } - - function onSchedule() { - if (scheduleShouldFail) - test.fail('Unexpected Throttler.schedule'); - } - - checkState(); - }; - - /** - * @param {string} panelName Name of the panel to show. - */ - TestSuite.prototype.showPanel = function(panelName) { - return UI.inspectorView.showPanel(panelName); - }; - - // UI Tests - - /** - * Tests that scripts tab can be open and populated with inspected scripts. - */ - TestSuite.prototype.testShowScriptsTab = function() { - var test = this; - this.showPanel('sources').then(function() { - // There should be at least main page script. - this._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() { - test.releaseControl(); - }); - }.bind(this)); - // Wait until all scripts are added to the debugger. - this.takeControl(); - }; - - /** - * Tests that scripts tab is populated with inspected scripts even if it - * hadn't been shown by the moment inspected paged refreshed. - * @see http://crbug.com/26312 - */ - TestSuite.prototype.testScriptsTabIsPopulatedOnInspectedPageRefresh = function() { - var test = this; - var debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel); - debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed); - - this.showPanel('elements').then(function() { - // Reload inspected page. It will reset the debugger agent. - test.evaluateInConsole_('window.location.reload(true);', function(resultText) {}); - }); - - function waitUntilScriptIsParsed() { - debuggerModel.removeEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed); - test.showPanel('sources').then(function() { - test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() { - test.releaseControl(); - }); - }); - } - - // Wait until all scripts are added to the debugger. - this.takeControl(); - }; - - /** - * Tests that scripts list contains content scripts. - */ - TestSuite.prototype.testContentScriptIsPresent = function() { - var test = this; - this.showPanel('sources').then(function() { - test._waitUntilScriptsAreParsed(['page_with_content_script.html', 'simple_content_script.js'], function() { - test.releaseControl(); - }); - }); - - // Wait until all scripts are added to the debugger. - this.takeControl(); - }; - - /** - * Tests that scripts are not duplicaed on Scripts tab switch. - */ - TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function() { - var test = this; - - function switchToElementsTab() { - test.showPanel('elements').then(function() { - setTimeout(switchToScriptsTab, 0); - }); - } - - function switchToScriptsTab() { - test.showPanel('sources').then(function() { - setTimeout(checkScriptsPanel, 0); - }); - } - - function checkScriptsPanel() { - test.assertTrue(test._scriptsAreParsed(['debugger_test_page.html']), 'Some scripts are missing.'); - checkNoDuplicates(); - test.releaseControl(); - } - - function checkNoDuplicates() { - var uiSourceCodes = test.nonAnonymousUISourceCodes_(); - for (var i = 0; i < uiSourceCodes.length; i++) { - for (var j = i + 1; j < uiSourceCodes.length; j++) { - test.assertTrue( - uiSourceCodes[i].url() !== uiSourceCodes[j].url(), - 'Found script duplicates: ' + test.uiSourceCodesToString_(uiSourceCodes)); - } - } - } - - this.showPanel('sources').then(function() { - test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() { - checkNoDuplicates(); - setTimeout(switchToElementsTab, 0); - }); - }); - - // Wait until all scripts are added to the debugger. - this.takeControl(); - }; - - // Tests that debugger works correctly if pause event occurs when DevTools - // frontend is being loaded. - TestSuite.prototype.testPauseWhenLoadingDevTools = function() { - var debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel); - if (debuggerModel.debuggerPausedDetails) - return; - - this.showPanel('sources').then(function() { - // Script execution can already be paused. - - this._waitForScriptPause(this.releaseControl.bind(this)); - }.bind(this)); - - this.takeControl(); - }; - - // Tests that pressing "Pause" will pause script execution if the script - // is already running. - TestSuite.prototype.testPauseWhenScriptIsRunning = function() { - this.showPanel('sources').then(function() { - this.evaluateInConsole_('setTimeout("handleClick()", 0)', didEvaluateInConsole.bind(this)); - }.bind(this)); - - function didEvaluateInConsole(resultText) { - this.assertTrue(!isNaN(resultText), 'Failed to get timer id: ' + resultText); - // Wait for some time to make sure that inspected page is running the - // infinite loop. - setTimeout(testScriptPause.bind(this), 300); - } - - function testScriptPause() { - // The script should be in infinite loop. Click "Pause" button to - // pause it and wait for the result. - UI.panels.sources._togglePause(); - - this._waitForScriptPause(this.releaseControl.bind(this)); - } - - this.takeControl(); - }; - - /** - * Tests network size. - */ - TestSuite.prototype.testNetworkSize = function() { - var test = this; - - function finishRequest(request, finishTime) { - test.assertEquals(25, request.resourceSize, 'Incorrect total data length'); - test.releaseControl(); - } - - this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest); - - // Reload inspected page to sniff network events - test.evaluateInConsole_('window.location.reload(true);', function(resultText) {}); - - this.takeControl(); - }; - - /** - * Tests network sync size. - */ - TestSuite.prototype.testNetworkSyncSize = function() { - var test = this; - - function finishRequest(request, finishTime) { - test.assertEquals(25, request.resourceSize, 'Incorrect total data length'); - test.releaseControl(); - } - - this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest); - - // Send synchronous XHR to sniff network events - test.evaluateInConsole_( - 'var xhr = new XMLHttpRequest(); xhr.open("GET", "chunked", false); xhr.send(null);', function() {}); - - this.takeControl(); - }; - - /** - * Tests network raw headers text. - */ - TestSuite.prototype.testNetworkRawHeadersText = function() { - var test = this; - - function finishRequest(request, finishTime) { - if (!request.responseHeadersText) - test.fail('Failure: resource does not have response headers text'); - var index = request.responseHeadersText.indexOf('Date:'); - test.assertEquals( - 112, request.responseHeadersText.substring(index).length, 'Incorrect response headers text length'); - test.releaseControl(); - } - - this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest); - - // Reload inspected page to sniff network events - test.evaluateInConsole_('window.location.reload(true);', function(resultText) {}); - - this.takeControl(); - }; - - /** - * Tests network timing. - */ - TestSuite.prototype.testNetworkTiming = function() { - var test = this; - - function finishRequest(request, finishTime) { - // Setting relaxed expectations to reduce flakiness. - // Server sends headers after 100ms, then sends data during another 100ms. - // We expect these times to be measured at least as 70ms. - test.assertTrue( - request.timing.receiveHeadersEnd - request.timing.connectStart >= 70, - 'Time between receiveHeadersEnd and connectStart should be >=70ms, but was ' + - 'receiveHeadersEnd=' + request.timing.receiveHeadersEnd + ', connectStart=' + - request.timing.connectStart + '.'); - test.assertTrue( - request.responseReceivedTime - request.startTime >= 0.07, - 'Time between responseReceivedTime and startTime should be >=0.07s, but was ' + - 'responseReceivedTime=' + request.responseReceivedTime + ', startTime=' + request.startTime + '.'); - test.assertTrue( - request.endTime - request.startTime >= 0.14, - 'Time between endTime and startTime should be >=0.14s, but was ' + - 'endtime=' + request.endTime + ', startTime=' + request.startTime + '.'); - - test.releaseControl(); - } - - this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest); - - // Reload inspected page to sniff network events - test.evaluateInConsole_('window.location.reload(true);', function(resultText) {}); - - this.takeControl(); - }; - - TestSuite.prototype.testPushTimes = function(url) { - var test = this; - var pendingRequestCount = 2; - - function finishRequest(request, finishTime) { - test.assertTrue( - typeof request.timing.pushStart === 'number' && request.timing.pushStart > 0, - `pushStart is invalid: ${request.timing.pushStart}`); - test.assertTrue(typeof request.timing.pushEnd === 'number', `pushEnd is invalid: ${request.timing.pushEnd}`); - test.assertTrue(request.timing.pushStart < request.startTime, 'pushStart should be before startTime'); - if (request.url().endsWith('?pushUseNullEndTime')) { - test.assertTrue(request.timing.pushEnd === 0, `pushEnd should be 0 but is ${request.timing.pushEnd}`); - } else { - test.assertTrue( - request.timing.pushStart < request.timing.pushEnd, - `pushStart should be before pushEnd (${request.timing.pushStart} >= ${request.timing.pushEnd})`); - // The below assertion is just due to the way we generate times in the moch URLRequestJob and is not generally an invariant. - test.assertTrue(request.timing.pushEnd < request.endTime, 'pushEnd should be before endTime'); - test.assertTrue(request.startTime < request.timing.pushEnd, 'pushEnd should be after startTime'); - } - if (!--pendingRequestCount) - test.releaseControl(); - } - - this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest, true); - - test.evaluateInConsole_('addImage(\'' + url + '\')', function(resultText) {}); - test.evaluateInConsole_('addImage(\'' + url + '?pushUseNullEndTime\')', function(resultText) {}); - this.takeControl(); - }; - - TestSuite.prototype.testConsoleOnNavigateBack = function() { - - function filteredMessages() { - return ConsoleModel.consoleModel.messages().filter( - a => a.source !== ConsoleModel.ConsoleMessage.MessageSource.Violation); - } - - if (filteredMessages().length === 1) { - firstConsoleMessageReceived.call(this, null); - } else { - ConsoleModel.consoleModel.addEventListener( - ConsoleModel.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this); - } - - - function firstConsoleMessageReceived(event) { - if (event && event.data.source === ConsoleModel.ConsoleMessage.MessageSource.Violation) - return; - ConsoleModel.consoleModel.removeEventListener( - ConsoleModel.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this); - this.evaluateInConsole_('clickLink();', didClickLink.bind(this)); - } - - function didClickLink() { - // Check that there are no new messages(command is not a message). - this.assertEquals(3, filteredMessages().length); - this.evaluateInConsole_('history.back();', didNavigateBack.bind(this)); - } - - function didNavigateBack() { - // Make sure navigation completed and possible console messages were pushed. - this.evaluateInConsole_('void 0;', didCompleteNavigation.bind(this)); - } - - function didCompleteNavigation() { - this.assertEquals(7, filteredMessages().length); - this.releaseControl(); - } - - this.takeControl(); - }; - - TestSuite.prototype.testSharedWorker = function() { - function didEvaluateInConsole(resultText) { - this.assertEquals('2011', resultText); - this.releaseControl(); - } - this.evaluateInConsole_('globalVar', didEvaluateInConsole.bind(this)); - this.takeControl(); - }; - - TestSuite.prototype.testPauseInSharedWorkerInitialization1 = function() { - // Make sure the worker is loaded. - this.takeControl(); - this._waitForTargets(2, callback.bind(this)); - - function callback() { - Protocol.InspectorBackend.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this)); - } - }; - - TestSuite.prototype.testPauseInSharedWorkerInitialization2 = function() { - this.takeControl(); - this._waitForTargets(2, callback.bind(this)); - - function callback() { - var debuggerModel = SDK.targetManager.models(SDK.DebuggerModel)[0]; - if (debuggerModel.isPaused()) { - this.releaseControl(); - return; - } - this._waitForScriptPause(this.releaseControl.bind(this)); - } - }; - - TestSuite.prototype.enableTouchEmulation = function() { - var deviceModeModel = new Emulation.DeviceModeModel(function() {}); - deviceModeModel._target = SDK.targetManager.mainTarget(); - deviceModeModel._applyTouch(true, true); - }; - - TestSuite.prototype.enableAutoAttachToCreatedPages = function() { - Common.settingForTest('autoAttachToCreatedPages').set(true); - }; - - TestSuite.prototype.waitForDebuggerPaused = function() { - var debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel); - if (debuggerModel.debuggerPausedDetails) - return; - - this.takeControl(); - this._waitForScriptPause(this.releaseControl.bind(this)); - }; - - TestSuite.prototype.switchToPanel = function(panelName) { - this.showPanel(panelName).then(this.releaseControl.bind(this)); - this.takeControl(); - }; - - // Regression test for crbug.com/370035. - TestSuite.prototype.testDeviceMetricsOverrides = function() { - function dumpPageMetrics() { - return JSON.stringify( - {width: window.innerWidth, height: window.innerHeight, deviceScaleFactor: window.devicePixelRatio}); - } - - var test = this; - - async function testOverrides(params, metrics, callback) { - await SDK.targetManager.mainTarget().emulationAgent().invoke_setDeviceMetricsOverride(params); - test.evaluateInConsole_('(' + dumpPageMetrics.toString() + ')()', checkMetrics); - - function checkMetrics(consoleResult) { - test.assertEquals( - '"' + JSON.stringify(metrics) + '"', consoleResult, 'Wrong metrics for params: ' + JSON.stringify(params)); - callback(); - } - } - - function step1() { - testOverrides( - {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true}, - {width: 1200, height: 1000, deviceScaleFactor: 1}, step2); - } - - function step2() { - testOverrides( - {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false}, - {width: 1200, height: 1000, deviceScaleFactor: 1}, step3); - } - - function step3() { - testOverrides( - {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true}, - {width: 1200, height: 1000, deviceScaleFactor: 3}, step4); - } - - function step4() { - testOverrides( - {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false}, - {width: 1200, height: 1000, deviceScaleFactor: 3}, finish); - } - - function finish() { - test.releaseControl(); - } - - test.takeControl(); - step1(); - }; - - TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() { - var test = this; - var receivedReady = false; - - function signalToShowAutofill() { - SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( - {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40}); - SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( - {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40}); - } - - function selectTopAutoFill() { - SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( - {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40}); - SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( - {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40}); - SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( - {type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13}); - SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( - {type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13}); - - test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput); - } - - function onResultOfInput(value) { - // Console adds "" around the response. - test.assertEquals('"Abbf"', value); - test.releaseControl(); - } - - function onConsoleMessage(event) { - var message = event.data.messageText; - if (message === 'ready' && !receivedReady) { - receivedReady = true; - signalToShowAutofill(); - } - // This log comes from the browser unittest code. - if (message === 'didShowSuggestions') - selectTopAutoFill(); - } - - this.takeControl(); - - // It is possible for the ready console messagage to be already received but not handled - // or received later. This ensures we can catch both cases. - ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); - - var messages = ConsoleModel.consoleModel.messages(); - if (messages.length) { - var text = messages[0].messageText; - this.assertEquals('ready', text); - signalToShowAutofill(); - } - }; - - TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() { - SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( - {type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'}); - SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( - {type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'}); - }; - - // Simple sanity check to make sure network throttling is wired up - // See crbug.com/747724 - TestSuite.prototype.testOfflineNetworkConditions = async function() { - var test = this; - SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions); - - function finishRequest(request) { - test.assertEquals( - 'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed'); - test.releaseControl(); - } - - this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest); - - test.takeControl(); - test.evaluateInConsole_('window.location.reload(true);', function(resultText) {}); - }; - - TestSuite.prototype.testEmulateNetworkConditions = function() { - var test = this; - - function testPreset(preset, messages, next) { - function onConsoleMessage(event) { - var index = messages.indexOf(event.data.messageText); - if (index === -1) { - test.fail('Unexpected message: ' + event.data.messageText); - return; - } - - messages.splice(index, 1); - if (!messages.length) { - ConsoleModel.consoleModel.removeEventListener( - ConsoleModel.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); - next(); - } - } - - ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); - SDK.multitargetNetworkManager.setNetworkConditions(preset); - } - - test.takeControl(); - step1(); - - function step1() { - testPreset( - MobileThrottling.networkPresets[2], - ['offline event: online = false', 'connection change event: type = none; downlinkMax = 0'], step2); - } - - function step2() { - testPreset( - MobileThrottling.networkPresets[1], - ['online event: online = true', 'connection change event: type = cellular; downlinkMax = 0.390625'], step3); - } - - function step3() { - testPreset( - MobileThrottling.networkPresets[0], - ['connection change event: type = cellular; downlinkMax = 1.4400000000000002'], - test.releaseControl.bind(test)); - } - }; - - TestSuite.prototype.testScreenshotRecording = function() { - var test = this; - - function performActionsInPage(callback) { - var count = 0; - var div = document.createElement('div'); - div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;'); - document.body.appendChild(div); - requestAnimationFrame(frame); - function frame() { - var color = [0, 0, 0]; - color[count % 3] = 255; - div.style.backgroundColor = 'rgb(' + color.join(',') + ')'; - if (++count > 10) - requestAnimationFrame(callback); - else - requestAnimationFrame(frame); - } - } - - var captureFilmStripSetting = Common.settings.createSetting('timelineCaptureFilmStrip', false); - captureFilmStripSetting.set(true); - test.evaluateInConsole_(performActionsInPage.toString(), function() {}); - test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone); - - function onTimelineDone() { - captureFilmStripSetting.set(false); - var filmStripModel = UI.panels.timeline._performanceModel.filmStripModel(); - var frames = filmStripModel.frames(); - test.assertTrue(frames.length > 4 && typeof frames.length === 'number'); - loadFrameImages(frames); - } - - function loadFrameImages(frames) { - var readyImages = []; - for (var frame of frames) - frame.imageDataPromise().then(onGotImageData); - - function onGotImageData(data) { - var image = new Image(); - test.assertTrue(!!data, 'No image data for frame'); - image.addEventListener('load', onLoad); - image.src = 'data:image/jpg;base64,' + data; - } - - function onLoad(event) { - readyImages.push(event.target); - if (readyImages.length === frames.length) - validateImagesAndCompleteTest(readyImages); - } - } - - function validateImagesAndCompleteTest(images) { - var redCount = 0; - var greenCount = 0; - var blueCount = 0; - - var canvas = document.createElement('canvas'); - var ctx = canvas.getContext('2d'); - for (var image of images) { - test.assertTrue(image.naturalWidth > 10); - test.assertTrue(image.naturalHeight > 10); - canvas.width = image.naturalWidth; - canvas.height = image.naturalHeight; - ctx.drawImage(image, 0, 0); - var data = ctx.getImageData(0, 0, 1, 1); - var color = Array.prototype.join.call(data.data, ','); - if (data.data[0] > 200) - redCount++; - else if (data.data[1] > 200) - greenCount++; - else if (data.data[2] > 200) - blueCount++; - else - test.fail('Unexpected color: ' + color); - } - test.assertTrue(redCount && greenCount && blueCount, 'Color sanity check failed'); - test.releaseControl(); - } - - test.takeControl(); - }; - - TestSuite.prototype.testSettings = function() { - var test = this; - - createSettings(); - test.takeControl(); - setTimeout(reset, 0); - - function createSettings() { - var localSetting = Common.settings.createLocalSetting('local', undefined); - localSetting.set({s: 'local', n: 1}); - var globalSetting = Common.settings.createSetting('global', undefined); - globalSetting.set({s: 'global', n: 2}); - } - - function reset() { - Runtime.experiments.clearForTest(); - InspectorFrontendHost.getPreferences(gotPreferences); - } - - function gotPreferences(prefs) { - Main.Main._instanceForTest._createSettings(prefs); - - var localSetting = Common.settings.createLocalSetting('local', undefined); - test.assertEquals('object', typeof localSetting.get()); - test.assertEquals('local', localSetting.get().s); - test.assertEquals(1, localSetting.get().n); - var globalSetting = Common.settings.createSetting('global', undefined); - test.assertEquals('object', typeof globalSetting.get()); - test.assertEquals('global', globalSetting.get().s); - test.assertEquals(2, globalSetting.get().n); - test.releaseControl(); - } - }; - - TestSuite.prototype.testWindowInitializedOnNavigateBack = function() { - var messages = ConsoleModel.consoleModel.messages(); - this.assertEquals(1, messages.length); - var text = messages[0].messageText; - if (text.indexOf('Uncaught') !== -1) - this.fail(text); - }; - - TestSuite.prototype.testConsoleContextNames = function() { - var test = this; - test.takeControl(); - this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this))); - - function onExecutionContexts() { - var consoleView = Console.ConsoleView.instance(); - var selector = consoleView._consoleContextSelector; - var values = []; - for (var item of selector._items) - values.push(selector.titleFor(item)); - test.assertEquals('top', values[0]); - test.assertEquals('Simple content script', values[1]); - test.releaseControl(); - } - }; - - TestSuite.prototype.testRawHeadersWithHSTS = function(url) { - var test = this; - test.takeControl(); - SDK.targetManager.addModelListener( - SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived); - - this.evaluateInConsole_(` - var img = document.createElement('img'); - img.src = "${url}"; - document.body.appendChild(img); - `, () => {}); - - var count = 0; - function onResponseReceived(event) { - var networkRequest = event.data; - if (!networkRequest.url().startsWith('http')) - return; - switch (++count) { - case 1: // Original redirect - test.assertEquals(301, networkRequest.statusCode); - test.assertEquals('Moved Permanently', networkRequest.statusText); - test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location'))); - break; - - case 2: // HSTS internal redirect - test.assertTrue(networkRequest.url().startsWith('http://')); - test.assertEquals(undefined, networkRequest.requestHeadersText()); - test.assertEquals(307, networkRequest.statusCode); - test.assertEquals('Internal Redirect', networkRequest.statusText); - test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason')); - test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://')); - break; - - case 3: // Final response - test.assertTrue(networkRequest.url().startsWith('https://')); - test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1')); - test.assertEquals(200, networkRequest.statusCode); - test.assertEquals('OK', networkRequest.statusText); - test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length')); - test.releaseControl(); - } - } - }; - - TestSuite.prototype.testDOMWarnings = function() { - var messages = ConsoleModel.consoleModel.messages(); - this.assertEquals(1, messages.length); - var expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:'; - this.assertTrue(messages[0].messageText.startsWith(expectedPrefix)); - }; - - TestSuite.prototype.waitForTestResultsInConsole = function() { - var messages = ConsoleModel.consoleModel.messages(); - for (var i = 0; i < messages.length; ++i) { - var text = messages[i].messageText; - if (text === 'PASS') - return; - else if (/^FAIL/.test(text)) - this.fail(text); // This will throw. - } - // Neither PASS nor FAIL, so wait for more messages. - function onConsoleMessage(event) { - var text = event.data.messageText; - if (text === 'PASS') - this.releaseControl(); - else if (/^FAIL/.test(text)) - this.fail(text); - } - - ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); - this.takeControl(); - }; - - TestSuite.prototype._overrideMethod = function(receiver, methodName, override) { - var original = receiver[methodName]; - if (typeof original !== 'function') { - this.fail(`TestSuite._overrideMethod: $[methodName] is not a function`); - return; - } - receiver[methodName] = function() { - try { - var value = original.apply(receiver, arguments); - } finally { - receiver[methodName] = original; - } - override.apply(original, arguments); - return value; - }; - }; - - TestSuite.prototype.startTimeline = function(callback) { - var test = this; - this.showPanel('timeline').then(function() { - var timeline = UI.panels.timeline; - test._overrideMethod(timeline, '_recordingStarted', callback); - timeline._toggleRecording(); - }); - }; - - TestSuite.prototype.stopTimeline = function(callback) { - var timeline = UI.panels.timeline; - this._overrideMethod(timeline, 'loadingComplete', callback); - timeline._toggleRecording(); - }; - - TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) { - var callback = arguments[arguments.length - 1]; - var doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`; - var argsString = arguments.length < 3 ? - '' : - Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ','; - this.evaluateInConsole_( - `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {}); - ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.MessageAdded, onConsoleMessage); - - function onConsoleMessage(event) { - var text = event.data.messageText; - if (text === doneMessage) { - ConsoleModel.consoleModel.removeEventListener(ConsoleModel.ConsoleModel.Events.MessageAdded, onConsoleMessage); - callback(); - } - } - }; - - TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) { - var test = this; - - this.startTimeline(onRecordingStarted); - - function onRecordingStarted() { - test.invokePageFunctionAsync(functionName, pageActionsDone); - } - - function pageActionsDone() { - test.stopTimeline(callback); - } - }; - - TestSuite.prototype.enableExperiment = function(name) { - Runtime.experiments.enableForTest(name); - }; - - TestSuite.prototype.checkInputEventsPresent = function() { - var expectedEvents = new Set(arguments); - var model = UI.panels.timeline._performanceModel.timelineModel(); - var asyncEvents = model.mainThreadAsyncEvents(); - var input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || []; - var prefix = 'InputLatency::'; - for (var e of input) { - if (!e.name.startsWith(prefix)) - continue; - if (e.steps.length < 2) - continue; - if (e.name.startsWith(prefix + 'Mouse') && - typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') - throw `Missing timeWaitingForMainThread on ${e.name}`; - expectedEvents.delete(e.name.substr(prefix.length)); - } - if (expectedEvents.size) - throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(','); - }; - - /** - * Serializes array of uiSourceCodes to string. - * @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes - * @return {string} - */ - TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) { - var names = []; - for (var i = 0; i < uiSourceCodes.length; i++) - names.push('"' + uiSourceCodes[i].url() + '"'); - return names.join(','); - }; - - /** - * Returns all loaded non anonymous uiSourceCodes. - * @return {!Array.<!Workspace.UISourceCode>} - */ - TestSuite.prototype.nonAnonymousUISourceCodes_ = function() { - /** - * @param {!Workspace.UISourceCode} uiSourceCode - */ - function filterOutService(uiSourceCode) { - return !uiSourceCode.project().isServiceProject(); - } - - var uiSourceCodes = Workspace.workspace.uiSourceCodes(); - return uiSourceCodes.filter(filterOutService); - }; - - /* - * Evaluates the code in the console as if user typed it manually and invokes - * the callback when the result message is received and added to the console. - * @param {string} code - * @param {function(string)} callback - */ - TestSuite.prototype.evaluateInConsole_ = function(code, callback) { - function innerEvaluate() { - UI.context.removeFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this); - var consoleView = Console.ConsoleView.instance(); - consoleView._prompt._appendCommand(code); - - this.addSniffer(Console.ConsoleView.prototype, '_consoleMessageAddedForTest', function(viewMessage) { - callback(viewMessage.toMessageElement().deepTextContent()); - }.bind(this)); - } - - function showConsoleAndEvaluate() { - Common.console.showPromise().then(innerEvaluate.bind(this)); - } - - if (!UI.context.flavor(SDK.ExecutionContext)) { - UI.context.addFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this); - return; - } - showConsoleAndEvaluate.call(this); - }; - - /** - * Checks that all expected scripts are present in the scripts list - * in the Scripts panel. - * @param {!Array.<string>} expected Regular expressions describing - * expected script names. - * @return {boolean} Whether all the scripts are in "scripts-files" select - * box - */ - TestSuite.prototype._scriptsAreParsed = function(expected) { - var uiSourceCodes = this.nonAnonymousUISourceCodes_(); - // Check that at least all the expected scripts are present. - var missing = expected.slice(0); - for (var i = 0; i < uiSourceCodes.length; ++i) { - for (var j = 0; j < missing.length; ++j) { - if (uiSourceCodes[i].name().search(missing[j]) !== -1) { - missing.splice(j, 1); - break; - } - } - } - return missing.length === 0; - }; - - /** - * Waits for script pause, checks expectations, and invokes the callback. - * @param {function():void} callback - */ - TestSuite.prototype._waitForScriptPause = function(callback) { - this.addSniffer(SDK.DebuggerModel.prototype, '_pausedScript', callback); - }; - - /** - * Waits until all the scripts are parsed and invokes the callback. - */ - TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) { - var test = this; - - function waitForAllScripts() { - if (test._scriptsAreParsed(expectedScripts)) - callback(); - else - test.addSniffer(UI.panels.sources.sourcesView(), '_addUISourceCode', waitForAllScripts); - } - - waitForAllScripts(); - }; - - TestSuite.prototype._waitForTargets = function(n, callback) { - checkTargets.call(this); - - function checkTargets() { - if (SDK.targetManager.targets().length >= n) - callback.call(null); - else - this.addSniffer(SDK.TargetManager.prototype, 'addTarget', checkTargets.bind(this)); - } - }; - - TestSuite.prototype._waitForExecutionContexts = function(n, callback) { - var runtimeModel = SDK.targetManager.mainTarget().model(SDK.RuntimeModel); - checkForExecutionContexts.call(this); - - function checkForExecutionContexts() { - if (runtimeModel.executionContexts().length >= n) - callback.call(null); - else - this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this)); - } - }; - - - window.uiTests = new TestSuite(window.domAutomationController); -})(window);
diff --git a/src/cobalt/debug/content/devtools/animation/animation_module.js b/src/cobalt/debug/content/devtools/animation/animation_module.js deleted file mode 100644 index 3b37406..0000000 --- a/src/cobalt/debug/content/devtools/animation/animation_module.js +++ /dev/null
@@ -1,279 +0,0 @@ -Animation.AnimationModel=class extends SDK.SDKModel{constructor(target){super(target);this._runtimeModel=(target.model(SDK.RuntimeModel));this._agent=target.animationAgent();target.registerAnimationDispatcher(new Animation.AnimationDispatcher(this));this._animationsById=new Map();this._animationGroups=new Map();this._pendingAnimations=[];this._playbackRate=1;var resourceTreeModel=(target.model(SDK.ResourceTreeModel));resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._reset,this);var screenCaptureModel=target.model(SDK.ScreenCaptureModel);if(screenCaptureModel) -this._screenshotCapture=new Animation.AnimationModel.ScreenshotCapture(this,screenCaptureModel);} -_reset(){this._animationsById.clear();this._animationGroups.clear();this._pendingAnimations=[];this.dispatchEventToListeners(Animation.AnimationModel.Events.ModelReset);} -animationCreated(id){this._pendingAnimations.push(id);} -_animationCanceled(id){this._pendingAnimations.remove(id);this._flushPendingAnimationsIfNeeded();} -animationStarted(payload){if(!payload.source||!payload.source.backendNodeId) -return;var animation=Animation.AnimationModel.Animation.parsePayload(this,payload);if(animation.type()==='WebAnimation'&&animation.source().keyframesRule().keyframes().length===0){this._pendingAnimations.remove(animation.id());}else{this._animationsById.set(animation.id(),animation);if(this._pendingAnimations.indexOf(animation.id())===-1) -this._pendingAnimations.push(animation.id());} -this._flushPendingAnimationsIfNeeded();} -_flushPendingAnimationsIfNeeded(){for(var id of this._pendingAnimations){if(!this._animationsById.get(id)) -return;} -while(this._pendingAnimations.length) -this._matchExistingGroups(this._createGroupFromPendingAnimations());} -_matchExistingGroups(incomingGroup){var matchedGroup=null;for(var group of this._animationGroups.values()){if(group._matches(incomingGroup)){matchedGroup=group;group._update(incomingGroup);break;}} -if(!matchedGroup){this._animationGroups.set(incomingGroup.id(),incomingGroup);if(this._screenshotCapture) -this._screenshotCapture.captureScreenshots(incomingGroup.finiteDuration(),incomingGroup._screenshots);} -this.dispatchEventToListeners(Animation.AnimationModel.Events.AnimationGroupStarted,matchedGroup||incomingGroup);return!!matchedGroup;} -_createGroupFromPendingAnimations(){console.assert(this._pendingAnimations.length);var groupedAnimations=[this._animationsById.get(this._pendingAnimations.shift())];var remainingAnimations=[];for(var id of this._pendingAnimations){var anim=this._animationsById.get(id);if(anim.startTime()===groupedAnimations[0].startTime()) -groupedAnimations.push(anim);else -remainingAnimations.push(id);} -this._pendingAnimations=remainingAnimations;return new Animation.AnimationModel.AnimationGroup(this,groupedAnimations[0].id(),groupedAnimations);} -setPlaybackRate(playbackRate){this._playbackRate=playbackRate;this._agent.setPlaybackRate(playbackRate);} -_releaseAnimations(animations){this._agent.releaseAnimations(animations);} -suspendModel(){this._reset();return this._agent.disable();} -resumeModel(){if(!this._enabled) -return Promise.resolve();return this._agent.enable();} -ensureEnabled(){if(this._enabled) -return;this._agent.enable();this._enabled=true;}};SDK.SDKModel.register(Animation.AnimationModel,SDK.Target.Capability.DOM,false);Animation.AnimationModel.Events={AnimationGroupStarted:Symbol('AnimationGroupStarted'),ModelReset:Symbol('ModelReset')};Animation.AnimationModel.Animation=class{constructor(animationModel,payload){this._animationModel=animationModel;this._payload=payload;this._source=new Animation.AnimationModel.AnimationEffect(animationModel,(this._payload.source));} -static parsePayload(animationModel,payload){return new Animation.AnimationModel.Animation(animationModel,payload);} -payload(){return this._payload;} -id(){return this._payload.id;} -name(){return this._payload.name;} -paused(){return this._payload.pausedState;} -playState(){return this._playState||this._payload.playState;} -setPlayState(playState){this._playState=playState;} -playbackRate(){return this._payload.playbackRate;} -startTime(){return this._payload.startTime;} -endTime(){if(!this.source().iterations) -return Infinity;return this.startTime()+this.source().delay()+this.source().duration()*this.source().iterations()+ -this.source().endDelay();} -_finiteDuration(){var iterations=Math.min(this.source().iterations(),3);return this.source().delay()+this.source().duration()*iterations;} -currentTime(){return this._payload.currentTime;} -source(){return this._source;} -type(){return(this._payload.type);} -overlaps(animation){if(!this.source().iterations()||!animation.source().iterations()) -return true;var firstAnimation=this.startTime()<animation.startTime()?this:animation;var secondAnimation=firstAnimation===this?animation:this;return firstAnimation.endTime()>=secondAnimation.startTime();} -setTiming(duration,delay){this._source.node().then(this._updateNodeStyle.bind(this,duration,delay));this._source._duration=duration;this._source._delay=delay;this._animationModel._agent.setTiming(this.id(),duration,delay);} -_updateNodeStyle(duration,delay,node){var animationPrefix;if(this.type()===Animation.AnimationModel.Animation.Type.CSSTransition) -animationPrefix='transition-';else if(this.type()===Animation.AnimationModel.Animation.Type.CSSAnimation) -animationPrefix='animation-';else -return;var cssModel=node.domModel().cssModel();cssModel.setEffectivePropertyValueForNode(node.id,animationPrefix+'duration',duration+'ms');cssModel.setEffectivePropertyValueForNode(node.id,animationPrefix+'delay',delay+'ms');} -remoteObjectPromise(){return this._animationModel._agent.resolveAnimation(this.id()).then(payload=>payload&&this._animationModel._runtimeModel.createRemoteObject(payload));} -_cssId(){return this._payload.cssId||'';}};Animation.AnimationModel.Animation.Type={CSSTransition:'CSSTransition',CSSAnimation:'CSSAnimation',WebAnimation:'WebAnimation'};Animation.AnimationModel.AnimationEffect=class{constructor(animationModel,payload){this._animationModel=animationModel;this._payload=payload;if(payload.keyframesRule) -this._keyframesRule=new Animation.AnimationModel.KeyframesRule(payload.keyframesRule);this._delay=this._payload.delay;this._duration=this._payload.duration;} -delay(){return this._delay;} -endDelay(){return this._payload.endDelay;} -iterationStart(){return this._payload.iterationStart;} -iterations(){if(!this.delay()&&!this.endDelay()&&!this.duration()) -return 0;return this._payload.iterations||Infinity;} -duration(){return this._duration;} -direction(){return this._payload.direction;} -fill(){return this._payload.fill;} -node(){if(!this._deferredNode) -this._deferredNode=new SDK.DeferredDOMNode(this._animationModel.target(),this.backendNodeId());return this._deferredNode.resolvePromise();} -deferredNode(){return new SDK.DeferredDOMNode(this._animationModel.target(),this.backendNodeId());} -backendNodeId(){return(this._payload.backendNodeId);} -keyframesRule(){return this._keyframesRule;} -easing(){return this._payload.easing;}};Animation.AnimationModel.KeyframesRule=class{constructor(payload){this._payload=payload;this._keyframes=this._payload.keyframes.map(function(keyframeStyle){return new Animation.AnimationModel.KeyframeStyle(keyframeStyle);});} -_setKeyframesPayload(payload){this._keyframes=payload.map(function(keyframeStyle){return new Animation.AnimationModel.KeyframeStyle(keyframeStyle);});} -name(){return this._payload.name;} -keyframes(){return this._keyframes;}};Animation.AnimationModel.KeyframeStyle=class{constructor(payload){this._payload=payload;this._offset=this._payload.offset;} -offset(){return this._offset;} -setOffset(offset){this._offset=offset*100+'%';} -offsetAsNumber(){return parseFloat(this._offset)/100;} -easing(){return this._payload.easing;}};Animation.AnimationModel.AnimationGroup=class{constructor(animationModel,id,animations){this._animationModel=animationModel;this._id=id;this._animations=animations;this._paused=false;this._screenshots=[];this._screenshotImages=[];} -id(){return this._id;} -animations(){return this._animations;} -release(){this._animationModel._animationGroups.remove(this.id());this._animationModel._releaseAnimations(this._animationIds());} -_animationIds(){function extractId(animation){return animation.id();} -return this._animations.map(extractId);} -startTime(){return this._animations[0].startTime();} -finiteDuration(){var maxDuration=0;for(var i=0;i<this._animations.length;++i) -maxDuration=Math.max(maxDuration,this._animations[i]._finiteDuration());return maxDuration;} -seekTo(currentTime){this._animationModel._agent.seekAnimations(this._animationIds(),currentTime);} -paused(){return this._paused;} -togglePause(paused){if(paused===this._paused) -return;this._paused=paused;this._animationModel._agent.setPaused(this._animationIds(),paused);} -currentTimePromise(){var longestAnim=null;for(var anim of this._animations){if(!longestAnim||anim.endTime()>longestAnim.endTime()) -longestAnim=anim;} -return this._animationModel._agent.getCurrentTime(longestAnim.id()).then(currentTime=>currentTime||0);} -_matches(group){function extractId(anim){if(anim.type()===Animation.AnimationModel.Animation.Type.WebAnimation) -return anim.type()+anim.id();else -return anim._cssId();} -if(this._animations.length!==group._animations.length) -return false;var left=this._animations.map(extractId).sort();var right=group._animations.map(extractId).sort();for(var i=0;i<left.length;i++){if(left[i]!==right[i]) -return false;} -return true;} -_update(group){this._animationModel._releaseAnimations(this._animationIds());this._animations=group._animations;} -screenshots(){for(var i=0;i<this._screenshots.length;++i){var image=new Image();image.src='data:image/jpeg;base64,'+this._screenshots[i];this._screenshotImages.push(image);} -this._screenshots=[];return this._screenshotImages;}};Animation.AnimationDispatcher=class{constructor(animationModel){this._animationModel=animationModel;} -animationCreated(id){this._animationModel.animationCreated(id);} -animationCanceled(id){this._animationModel._animationCanceled(id);} -animationStarted(payload){this._animationModel.animationStarted(payload);}};Animation.AnimationModel.ScreenshotCapture=class{constructor(animationModel,screenCaptureModel){this._requests=[];this._screenCaptureModel=screenCaptureModel;this._animationModel=animationModel;this._animationModel.addEventListener(Animation.AnimationModel.Events.ModelReset,this._stopScreencast,this);} -captureScreenshots(duration,screenshots){var screencastDuration=Math.min(duration/this._animationModel._playbackRate,3000);var endTime=screencastDuration+window.performance.now();this._requests.push({endTime:endTime,screenshots:screenshots});if(!this._endTime||endTime>this._endTime){clearTimeout(this._stopTimer);this._stopTimer=setTimeout(this._stopScreencast.bind(this),screencastDuration);this._endTime=endTime;} -if(this._capturing) -return;this._capturing=true;this._screenCaptureModel.startScreencast('jpeg',80,undefined,300,2,this._screencastFrame.bind(this),visible=>{});} -_screencastFrame(base64Data,metadata){function isAnimating(request){return request.endTime>=now;} -if(!this._capturing) -return;var now=window.performance.now();this._requests=this._requests.filter(isAnimating);for(var request of this._requests) -request.screenshots.push(base64Data);} -_stopScreencast(){if(!this._capturing) -return;delete this._stopTimer;delete this._endTime;this._requests=[];this._capturing=false;this._screenCaptureModel.stopScreencast();}};Animation.AnimationModel.ScreenshotCapture.Request;;Animation.AnimationGroupPreviewUI=class{constructor(model){this._model=model;this.element=createElementWithClass('div','animation-buffer-preview');this.element.createChild('div','animation-paused fill');this._removeButton=this.element.createChild('div','animation-remove-button');this._removeButton.textContent='\u2715';this._replayOverlayElement=this.element.createChild('div','animation-buffer-preview-animation');this._svg=this.element.createSVGChild('svg');this._svg.setAttribute('width','100%');this._svg.setAttribute('preserveAspectRatio','none');this._svg.setAttribute('height','100%');this._viewBoxHeight=32;this._svg.setAttribute('viewBox','0 0 100 '+this._viewBoxHeight);this._svg.setAttribute('shape-rendering','crispEdges');this._render();} -_groupDuration(){var duration=0;for(var anim of this._model.animations()){var animDuration=anim.source().delay()+anim.source().duration();if(animDuration>duration) -duration=animDuration;} -return duration;} -removeButton(){return this._removeButton;} -replay(){this._replayOverlayElement.animate([{offset:0,width:'0%',opacity:1},{offset:0.9,width:'100%',opacity:1},{offset:1,width:'100%',opacity:0}],{duration:200,easing:'cubic-bezier(0, 0, 0.2, 1)'});} -_render(){this._svg.removeChildren();var maxToShow=10;var numberOfAnimations=Math.min(this._model.animations().length,maxToShow);var timeToPixelRatio=100/Math.max(this._groupDuration(),750);for(var i=0;i<numberOfAnimations;i++){var effect=this._model.animations()[i].source();var line=this._svg.createSVGChild('line');line.setAttribute('x1',effect.delay()*timeToPixelRatio);line.setAttribute('x2',(effect.delay()+effect.duration())*timeToPixelRatio);var y=Math.floor(this._viewBoxHeight/Math.max(6,numberOfAnimations)*i+1);line.setAttribute('y1',y);line.setAttribute('y2',y);line.style.stroke=Animation.AnimationUI.Color(this._model.animations()[i]);}}};;Animation.AnimationScreenshotPopover=class extends UI.VBox{constructor(images){super(true);console.assert(images.length);this.registerRequiredCSS('animation/animationScreenshotPopover.css');this.contentElement.classList.add('animation-screenshot-popover');this._frames=images;for(var image of images){this.contentElement.appendChild(image);image.style.display='none';} -this._currentFrame=0;this._frames[0].style.display='block';this._progressBar=this.contentElement.createChild('div','animation-progress');} -wasShown(){this._rafId=this.contentElement.window().requestAnimationFrame(this._changeFrame.bind(this));} -willHide(){this.contentElement.window().cancelAnimationFrame(this._rafId);delete this._endDelay;} -_changeFrame(){this._rafId=this.contentElement.window().requestAnimationFrame(this._changeFrame.bind(this));if(this._endDelay){this._endDelay--;return;} -this._showFrame=!this._showFrame;if(!this._showFrame) -return;var numFrames=this._frames.length;this._frames[this._currentFrame%numFrames].style.display='none';this._currentFrame++;this._frames[(this._currentFrame)%numFrames].style.display='block';if(this._currentFrame%numFrames===numFrames-1) -this._endDelay=50;this._progressBar.style.width=(this._currentFrame%numFrames+1)/numFrames*100+'%';}};;Animation.AnimationTimeline=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('animation/animationTimeline.css');this.element.classList.add('animations-timeline');this._grid=this.contentElement.createSVGChild('svg','animation-timeline-grid');this._playbackRate=1;this._allPaused=false;this._createHeader();this._animationsContainer=this.contentElement.createChild('div','animation-timeline-rows');var timelineHint=this.contentElement.createChild('div','animation-timeline-rows-hint');timelineHint.textContent=Common.UIString('Select an effect above to inspect and modify.');this._defaultDuration=100;this._duration=this._defaultDuration;this._timelineControlsWidth=150;this._nodesMap=new Map();this._uiAnimations=[];this._groupBuffer=[];this._previewMap=new Map();this._symbol=Symbol('animationTimeline');this._animationsMap=new Map();SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.NodeRemoved,this._nodeRemoved,this);SDK.targetManager.observeModels(Animation.AnimationModel,this);UI.context.addFlavorChangeListener(SDK.DOMNode,this._nodeChanged,this);} -wasShown(){for(var animationModel of SDK.targetManager.models(Animation.AnimationModel)) -this._addEventListeners(animationModel);} -willHide(){for(var animationModel of SDK.targetManager.models(Animation.AnimationModel)) -this._removeEventListeners(animationModel);this._popoverHelper.hidePopover();} -modelAdded(animationModel){if(this.isShowing()) -this._addEventListeners(animationModel);} -modelRemoved(animationModel){this._removeEventListeners(animationModel);} -_addEventListeners(animationModel){animationModel.ensureEnabled();animationModel.addEventListener(Animation.AnimationModel.Events.AnimationGroupStarted,this._animationGroupStarted,this);animationModel.addEventListener(Animation.AnimationModel.Events.ModelReset,this._reset,this);} -_removeEventListeners(animationModel){animationModel.removeEventListener(Animation.AnimationModel.Events.AnimationGroupStarted,this._animationGroupStarted,this);animationModel.removeEventListener(Animation.AnimationModel.Events.ModelReset,this._reset,this);} -_nodeChanged(){for(var nodeUI of this._nodesMap.values()) -nodeUI._nodeChanged();} -_createScrubber(){this._timelineScrubber=createElementWithClass('div','animation-scrubber hidden');this._timelineScrubberLine=this._timelineScrubber.createChild('div','animation-scrubber-line');this._timelineScrubberLine.createChild('div','animation-scrubber-head');this._timelineScrubber.createChild('div','animation-time-overlay');return this._timelineScrubber;} -_createHeader(){var toolbarContainer=this.contentElement.createChild('div','animation-timeline-toolbar-container');var topToolbar=new UI.Toolbar('animation-timeline-toolbar',toolbarContainer);var clearButton=new UI.ToolbarButton(Common.UIString('Clear all'),'largeicon-clear');clearButton.addEventListener(UI.ToolbarButton.Events.Click,this._reset.bind(this));topToolbar.appendToolbarItem(clearButton);topToolbar.appendSeparator();this._pauseButton=new UI.ToolbarToggle(Common.UIString('Pause all'),'largeicon-pause','largeicon-resume');this._pauseButton.addEventListener(UI.ToolbarButton.Events.Click,this._togglePauseAll.bind(this));topToolbar.appendToolbarItem(this._pauseButton);var playbackRateControl=toolbarContainer.createChild('div','animation-playback-rate-control');this._playbackRateButtons=[];for(var playbackRate of Animation.AnimationTimeline.GlobalPlaybackRates){var button=playbackRateControl.createChild('div','animation-playback-rate-button');button.textContent=playbackRate?Common.UIString(playbackRate*100+'%'):Common.UIString('Pause');button.playbackRate=playbackRate;button.addEventListener('click',this._setPlaybackRate.bind(this,playbackRate));button.title=Common.UIString('Set speed to ')+button.textContent;this._playbackRateButtons.push(button);} -this._updatePlaybackControls();this._previewContainer=this.contentElement.createChild('div','animation-timeline-buffer');this._popoverHelper=new UI.PopoverHelper(this._previewContainer,this._getPopoverRequest.bind(this));this._popoverHelper.setDisableOnClick(true);this._popoverHelper.setTimeout(0);var emptyBufferHint=this.contentElement.createChild('div','animation-timeline-buffer-hint');emptyBufferHint.textContent=Common.UIString('Listening for animations...');var container=this.contentElement.createChild('div','animation-timeline-header');var controls=container.createChild('div','animation-controls');this._currentTime=controls.createChild('div','animation-timeline-current-time monospace');var toolbar=new UI.Toolbar('animation-controls-toolbar',controls);this._controlButton=new UI.ToolbarToggle(Common.UIString('Replay timeline'),'largeicon-replay-animation');this._controlState=Animation.AnimationTimeline._ControlState.Replay;this._controlButton.setToggled(true);this._controlButton.addEventListener(UI.ToolbarButton.Events.Click,this._controlButtonToggle.bind(this));toolbar.appendToolbarItem(this._controlButton);var gridHeader=container.createChild('div','animation-grid-header');UI.installDragHandle(gridHeader,this._repositionScrubber.bind(this),this._scrubberDragMove.bind(this),this._scrubberDragEnd.bind(this),'text');container.appendChild(this._createScrubber());UI.installDragHandle(this._timelineScrubberLine,this._scrubberDragStart.bind(this),this._scrubberDragMove.bind(this),this._scrubberDragEnd.bind(this),'col-resize');this._currentTime.textContent='';return container;} -_getPopoverRequest(event){var element=event.target;if(!element.isDescendant(this._previewContainer)) -return null;return{box:event.target.boxInWindow(),show:popover=>{var animGroup;for(var group of this._previewMap.keysArray()){if(this._previewMap.get(group).element===element.parentElement) -animGroup=group;} -console.assert(animGroup);var screenshots=animGroup.screenshots();if(!screenshots.length) -return Promise.resolve(false);var fulfill;var promise=new Promise(x=>fulfill=x);if(!screenshots[0].complete) -screenshots[0].onload=onFirstScreenshotLoaded.bind(null,screenshots);else -onFirstScreenshotLoaded(screenshots);return promise;function onFirstScreenshotLoaded(screenshots){new Animation.AnimationScreenshotPopover(screenshots).show(popover.contentElement);fulfill(true);}}};} -_togglePauseAll(){this._allPaused=!this._allPaused;this._pauseButton.setToggled(this._allPaused);this._setPlaybackRate(this._playbackRate);this._pauseButton.setTitle(this._allPaused?Common.UIString('Resume all'):Common.UIString('Pause all'));} -_setPlaybackRate(playbackRate){this._playbackRate=playbackRate;for(var animationModel of SDK.targetManager.models(Animation.AnimationModel)) -animationModel.setPlaybackRate(this._allPaused?0:this._playbackRate);Host.userMetrics.actionTaken(Host.UserMetrics.Action.AnimationsPlaybackRateChanged);if(this._scrubberPlayer) -this._scrubberPlayer.playbackRate=this._effectivePlaybackRate();this._updatePlaybackControls();} -_updatePlaybackControls(){for(var button of this._playbackRateButtons){var selected=this._playbackRate===button.playbackRate;button.classList.toggle('selected',selected);}} -_controlButtonToggle(){if(this._controlState===Animation.AnimationTimeline._ControlState.Play) -this._togglePause(false);else if(this._controlState===Animation.AnimationTimeline._ControlState.Replay) -this._replay();else -this._togglePause(true);} -_updateControlButton(){this._controlButton.setEnabled(!!this._selectedGroup);if(this._selectedGroup&&this._selectedGroup.paused()){this._controlState=Animation.AnimationTimeline._ControlState.Play;this._controlButton.setToggled(true);this._controlButton.setTitle(Common.UIString('Play timeline'));this._controlButton.setGlyph('largeicon-play-animation');}else if(!this._scrubberPlayer||this._scrubberPlayer.currentTime>=this.duration()){this._controlState=Animation.AnimationTimeline._ControlState.Replay;this._controlButton.setToggled(true);this._controlButton.setTitle(Common.UIString('Replay timeline'));this._controlButton.setGlyph('largeicon-replay-animation');}else{this._controlState=Animation.AnimationTimeline._ControlState.Pause;this._controlButton.setToggled(false);this._controlButton.setTitle(Common.UIString('Pause timeline'));this._controlButton.setGlyph('largeicon-pause-animation');}} -_effectivePlaybackRate(){return(this._allPaused||(this._selectedGroup&&this._selectedGroup.paused()))?0:this._playbackRate;} -_togglePause(pause){this._selectedGroup.togglePause(pause);if(this._scrubberPlayer) -this._scrubberPlayer.playbackRate=this._effectivePlaybackRate();this._previewMap.get(this._selectedGroup).element.classList.toggle('paused',pause);this._updateControlButton();} -_replay(){if(!this._selectedGroup) -return;this._selectedGroup.seekTo(0);this._animateTime(0);this._updateControlButton();} -duration(){return this._duration;} -setDuration(duration){this._duration=duration;this.scheduleRedraw();} -_clearTimeline(){this._uiAnimations=[];this._nodesMap.clear();this._animationsMap.clear();this._animationsContainer.removeChildren();this._duration=this._defaultDuration;this._timelineScrubber.classList.add('hidden');delete this._selectedGroup;if(this._scrubberPlayer) -this._scrubberPlayer.cancel();delete this._scrubberPlayer;this._currentTime.textContent='';this._updateControlButton();} -_reset(){this._clearTimeline();if(this._allPaused) -this._togglePauseAll();else -this._setPlaybackRate(this._playbackRate);for(var group of this._groupBuffer) -group.release();this._groupBuffer=[];this._previewMap.clear();this._previewContainer.removeChildren();this._popoverHelper.hidePopover();this._renderGrid();} -_animationGroupStarted(event){this._addAnimationGroup((event.data));} -_addAnimationGroup(group){function startTimeComparator(left,right){return left.startTime()>right.startTime();} -if(this._previewMap.get(group)){if(this._selectedGroup===group) -this._syncScrubber();else -this._previewMap.get(group).replay();return;} -this._groupBuffer.sort(startTimeComparator);var groupsToDiscard=[];var bufferSize=this.width()/50;while(this._groupBuffer.length>bufferSize){var toDiscard=this._groupBuffer.splice(this._groupBuffer[0]===this._selectedGroup?1:0,1);groupsToDiscard.push(toDiscard[0]);} -for(var g of groupsToDiscard){this._previewMap.get(g).element.remove();this._previewMap.delete(g);g.release();} -var preview=new Animation.AnimationGroupPreviewUI(group);this._groupBuffer.push(group);this._previewMap.set(group,preview);this._previewContainer.appendChild(preview.element);preview.removeButton().addEventListener('click',this._removeAnimationGroup.bind(this,group));preview.element.addEventListener('click',this._selectAnimationGroup.bind(this,group));} -_removeAnimationGroup(group,event){this._groupBuffer.remove(group);this._previewMap.get(group).element.remove();this._previewMap.delete(group);group.release();event.consume(true);if(this._selectedGroup===group){this._clearTimeline();this._renderGrid();}} -_selectAnimationGroup(group){function applySelectionClass(ui,group){ui.element.classList.toggle('selected',this._selectedGroup===group);} -if(this._selectedGroup===group){this._togglePause(false);this._replay();return;} -this._clearTimeline();this._selectedGroup=group;this._previewMap.forEach(applySelectionClass,this);this.setDuration(Math.max(500,group.finiteDuration()+100));for(var anim of group.animations()) -this._addAnimation(anim);this.scheduleRedraw();this._timelineScrubber.classList.remove('hidden');this._togglePause(false);this._replay();} -_addAnimation(animation){function nodeResolved(node){nodeUI.nodeResolved(node);uiAnimation.setNode(node);if(node) -node[this._symbol]=nodeUI;} -var nodeUI=this._nodesMap.get(animation.source().backendNodeId());if(!nodeUI){nodeUI=new Animation.AnimationTimeline.NodeUI(animation.source());this._animationsContainer.appendChild(nodeUI.element);this._nodesMap.set(animation.source().backendNodeId(),nodeUI);} -var nodeRow=nodeUI.createNewRow();var uiAnimation=new Animation.AnimationUI(animation,this,nodeRow);animation.source().deferredNode().resolve(nodeResolved.bind(this));this._uiAnimations.push(uiAnimation);this._animationsMap.set(animation.id(),animation);} -_nodeRemoved(event){var node=event.data.node;if(node[this._symbol]) -node[this._symbol].nodeRemoved();} -_renderGrid(){var gridSize=250;this._grid.setAttribute('width',this.width()+10);this._grid.setAttribute('height',this._cachedTimelineHeight+30);this._grid.setAttribute('shape-rendering','crispEdges');this._grid.removeChildren();var lastDraw=undefined;for(var time=0;time<this.duration();time+=gridSize){var line=this._grid.createSVGChild('rect','animation-timeline-grid-line');line.setAttribute('x',time*this.pixelMsRatio()+10);line.setAttribute('y',23);line.setAttribute('height','100%');line.setAttribute('width',1);} -for(var time=0;time<this.duration();time+=gridSize){var gridWidth=time*this.pixelMsRatio();if(lastDraw===undefined||gridWidth-lastDraw>50){lastDraw=gridWidth;var label=this._grid.createSVGChild('text','animation-timeline-grid-label');label.textContent=Common.UIString(Number.millisToString(time));label.setAttribute('x',gridWidth+10);label.setAttribute('y',16);}}} -scheduleRedraw(){this._renderQueue=[];for(var ui of this._uiAnimations) -this._renderQueue.push(ui);if(this._redrawing) -return;this._redrawing=true;this._renderGrid();this._animationsContainer.window().requestAnimationFrame(this._render.bind(this));} -_render(timestamp){while(this._renderQueue.length&&(!timestamp||window.performance.now()-timestamp<50)) -this._renderQueue.shift().redraw();if(this._renderQueue.length) -this._animationsContainer.window().requestAnimationFrame(this._render.bind(this));else -delete this._redrawing;} -onResize(){this._cachedTimelineWidth=Math.max(0,this._animationsContainer.offsetWidth-this._timelineControlsWidth)||0;this._cachedTimelineHeight=this._animationsContainer.offsetHeight;this.scheduleRedraw();if(this._scrubberPlayer) -this._syncScrubber();delete this._gridOffsetLeft;} -width(){return this._cachedTimelineWidth||0;} -_resizeWindow(animation){var resized=false;var duration=animation.source().duration()*Math.min(2,animation.source().iterations());var requiredDuration=animation.source().delay()+duration+animation.source().endDelay();if(requiredDuration>this._duration){resized=true;this._duration=requiredDuration+200;} -return resized;} -_syncScrubber(){if(!this._selectedGroup) -return;this._selectedGroup.currentTimePromise().then(this._animateTime.bind(this)).then(this._updateControlButton.bind(this));} -_animateTime(currentTime){if(this._scrubberPlayer) -this._scrubberPlayer.cancel();this._scrubberPlayer=this._timelineScrubber.animate([{transform:'translateX(0px)'},{transform:'translateX('+this.width()+'px)'}],{duration:this.duration(),fill:'forwards'});this._scrubberPlayer.playbackRate=this._effectivePlaybackRate();this._scrubberPlayer.onfinish=this._updateControlButton.bind(this);this._scrubberPlayer.currentTime=currentTime;this.element.window().requestAnimationFrame(this._updateScrubber.bind(this));} -pixelMsRatio(){return this.width()/this.duration()||0;} -_updateScrubber(timestamp){if(!this._scrubberPlayer) -return;this._currentTime.textContent=Common.UIString(Number.millisToString(this._scrubberPlayer.currentTime));if(this._scrubberPlayer.playState==='pending'||this._scrubberPlayer.playState==='running') -this.element.window().requestAnimationFrame(this._updateScrubber.bind(this));else if(this._scrubberPlayer.playState==='finished') -this._currentTime.textContent='';} -_repositionScrubber(event){if(!this._selectedGroup) -return false;if(!this._gridOffsetLeft) -this._gridOffsetLeft=this._grid.totalOffsetLeft()+10;var seekTime=Math.max(0,event.x-this._gridOffsetLeft)/this.pixelMsRatio();this._selectedGroup.seekTo(seekTime);this._togglePause(true);this._animateTime(seekTime);this._originalScrubberTime=seekTime;this._originalMousePosition=event.x;return true;} -_scrubberDragStart(event){if(!this._scrubberPlayer||!this._selectedGroup) -return false;this._originalScrubberTime=this._scrubberPlayer.currentTime;this._timelineScrubber.classList.remove('animation-timeline-end');this._scrubberPlayer.pause();this._originalMousePosition=event.x;this._togglePause(true);return true;} -_scrubberDragMove(event){var delta=event.x-this._originalMousePosition;var currentTime=Math.max(0,Math.min(this._originalScrubberTime+delta/this.pixelMsRatio(),this.duration()));this._scrubberPlayer.currentTime=currentTime;this._currentTime.textContent=Common.UIString(Number.millisToString(Math.round(currentTime)));this._selectedGroup.seekTo(currentTime);} -_scrubberDragEnd(event){var currentTime=Math.max(0,this._scrubberPlayer.currentTime);this._scrubberPlayer.play();this._scrubberPlayer.currentTime=currentTime;this._currentTime.window().requestAnimationFrame(this._updateScrubber.bind(this));}};Animation.AnimationTimeline.GlobalPlaybackRates=[1,0.25,0.1];Animation.AnimationTimeline._ControlState={Play:'play-outline',Replay:'replay-outline',Pause:'pause-outline'};Animation.AnimationTimeline.NodeUI=class{constructor(animationEffect){this.element=createElementWithClass('div','animation-node-row');this._description=this.element.createChild('div','animation-node-description');this._timelineElement=this.element.createChild('div','animation-node-timeline');} -nodeResolved(node){if(!node){this._description.createTextChild(Common.UIString('<node>'));return;} -this._node=node;this._nodeChanged();this._description.appendChild(Components.DOMPresentationUtils.linkifyNodeReference(node));if(!node.ownerDocument) -this.nodeRemoved();} -createNewRow(){return this._timelineElement.createChild('div','animation-timeline-row');} -nodeRemoved(){this.element.classList.add('animation-node-removed');this._node=null;} -_nodeChanged(){this.element.classList.toggle('animation-node-selected',this._node&&this._node===UI.context.flavor(SDK.DOMNode));}};Animation.AnimationTimeline.StepTimingFunction=class{constructor(steps,stepAtPosition){this.steps=steps;this.stepAtPosition=stepAtPosition;} -static parse(text){var match=text.match(/^steps\((\d+), (start|middle)\)$/);if(match) -return new Animation.AnimationTimeline.StepTimingFunction(parseInt(match[1],10),match[2]);match=text.match(/^steps\((\d+)\)$/);if(match) -return new Animation.AnimationTimeline.StepTimingFunction(parseInt(match[1],10),'end');return null;}};;Animation.AnimationUI=class{constructor(animation,timeline,parentElement){this._animation=animation;this._timeline=timeline;this._parentElement=parentElement;if(this._animation.source().keyframesRule()) -this._keyframes=this._animation.source().keyframesRule().keyframes();this._nameElement=parentElement.createChild('div','animation-name');this._nameElement.textContent=this._animation.name();this._svg=parentElement.createSVGChild('svg','animation-ui');this._svg.setAttribute('height',Animation.AnimationUI.Options.AnimationSVGHeight);this._svg.style.marginLeft='-'+Animation.AnimationUI.Options.AnimationMargin+'px';this._svg.addEventListener('contextmenu',this._onContextMenu.bind(this));this._activeIntervalGroup=this._svg.createSVGChild('g');UI.installDragHandle(this._activeIntervalGroup,this._mouseDown.bind(this,Animation.AnimationUI.MouseEvents.AnimationDrag,null),this._mouseMove.bind(this),this._mouseUp.bind(this),'-webkit-grabbing','-webkit-grab');this._cachedElements=[];this._movementInMs=0;this._color=Animation.AnimationUI.Color(this._animation);} -static Color(animation){var names=Object.keys(Animation.AnimationUI.Colors);var color=Animation.AnimationUI.Colors[names[String.hashCode(animation.name()||animation.id())%names.length]];return color.asString(Common.Color.Format.RGB);} -animation(){return this._animation;} -setNode(node){this._node=node;} -_createLine(parentElement,className){var line=parentElement.createSVGChild('line',className);line.setAttribute('x1',Animation.AnimationUI.Options.AnimationMargin);line.setAttribute('y1',Animation.AnimationUI.Options.AnimationHeight);line.setAttribute('y2',Animation.AnimationUI.Options.AnimationHeight);line.style.stroke=this._color;return line;} -_drawAnimationLine(iteration,parentElement){var cache=this._cachedElements[iteration];if(!cache.animationLine) -cache.animationLine=this._createLine(parentElement,'animation-line');cache.animationLine.setAttribute('x2',(this._duration()*this._timeline.pixelMsRatio()+Animation.AnimationUI.Options.AnimationMargin).toFixed(2));} -_drawDelayLine(parentElement){if(!this._delayLine){this._delayLine=this._createLine(parentElement,'animation-delay-line');this._endDelayLine=this._createLine(parentElement,'animation-delay-line');} -var fill=this._animation.source().fill();this._delayLine.classList.toggle('animation-fill',fill==='backwards'||fill==='both');var margin=Animation.AnimationUI.Options.AnimationMargin;this._delayLine.setAttribute('x1',margin);this._delayLine.setAttribute('x2',(this._delay()*this._timeline.pixelMsRatio()+margin).toFixed(2));var forwardsFill=fill==='forwards'||fill==='both';this._endDelayLine.classList.toggle('animation-fill',forwardsFill);var leftMargin=Math.min(this._timeline.width(),(this._delay()+this._duration()*this._animation.source().iterations())*this._timeline.pixelMsRatio());this._endDelayLine.style.transform='translateX('+leftMargin.toFixed(2)+'px)';this._endDelayLine.setAttribute('x1',margin);this._endDelayLine.setAttribute('x2',forwardsFill?(this._timeline.width()-leftMargin+margin).toFixed(2):(this._animation.source().endDelay()*this._timeline.pixelMsRatio()+margin).toFixed(2));} -_drawPoint(iteration,parentElement,x,keyframeIndex,attachEvents){if(this._cachedElements[iteration].keyframePoints[keyframeIndex]){this._cachedElements[iteration].keyframePoints[keyframeIndex].setAttribute('cx',x.toFixed(2));return;} -var circle=parentElement.createSVGChild('circle',keyframeIndex<=0?'animation-endpoint':'animation-keyframe-point');circle.setAttribute('cx',x.toFixed(2));circle.setAttribute('cy',Animation.AnimationUI.Options.AnimationHeight);circle.style.stroke=this._color;circle.setAttribute('r',Animation.AnimationUI.Options.AnimationMargin/2);if(keyframeIndex<=0) -circle.style.fill=this._color;this._cachedElements[iteration].keyframePoints[keyframeIndex]=circle;if(!attachEvents) -return;var eventType;if(keyframeIndex===0) -eventType=Animation.AnimationUI.MouseEvents.StartEndpointMove;else if(keyframeIndex===-1) -eventType=Animation.AnimationUI.MouseEvents.FinishEndpointMove;else -eventType=Animation.AnimationUI.MouseEvents.KeyframeMove;UI.installDragHandle(circle,this._mouseDown.bind(this,eventType,keyframeIndex),this._mouseMove.bind(this),this._mouseUp.bind(this),'ew-resize');} -_renderKeyframe(iteration,keyframeIndex,parentElement,leftDistance,width,easing){function createStepLine(parentElement,x,strokeColor){var line=parentElement.createSVGChild('line');line.setAttribute('x1',x);line.setAttribute('x2',x);line.setAttribute('y1',Animation.AnimationUI.Options.AnimationMargin);line.setAttribute('y2',Animation.AnimationUI.Options.AnimationHeight);line.style.stroke=strokeColor;} -var bezier=UI.Geometry.CubicBezier.parse(easing);var cache=this._cachedElements[iteration].keyframeRender;if(!cache[keyframeIndex]){cache[keyframeIndex]=bezier?parentElement.createSVGChild('path','animation-keyframe'):parentElement.createSVGChild('g','animation-keyframe-step');} -var group=cache[keyframeIndex];group.style.transform='translateX('+leftDistance.toFixed(2)+'px)';if(easing==='linear'){group.style.fill=this._color;var height=InlineEditor.BezierUI.Height;group.setAttribute('d',['M',0,height,'L',0,5,'L',width.toFixed(2),5,'L',width.toFixed(2),height,'Z'].join(' '));}else if(bezier){group.style.fill=this._color;InlineEditor.BezierUI.drawVelocityChart(bezier,group,width);}else{var stepFunction=Animation.AnimationTimeline.StepTimingFunction.parse(easing);group.removeChildren();var offsetMap={'start':0,'middle':0.5,'end':1};var offsetWeight=offsetMap[stepFunction.stepAtPosition];for(var i=0;i<stepFunction.steps;i++) -createStepLine(group,(i+offsetWeight)*width/stepFunction.steps,this._color);}} -redraw(){var maxWidth=this._timeline.width()-Animation.AnimationUI.Options.AnimationMargin;this._svg.setAttribute('width',(maxWidth+2*Animation.AnimationUI.Options.AnimationMargin).toFixed(2));this._activeIntervalGroup.style.transform='translateX('+(this._delay()*this._timeline.pixelMsRatio()).toFixed(2)+'px)';this._nameElement.style.transform='translateX('+ -(this._delay()*this._timeline.pixelMsRatio()+Animation.AnimationUI.Options.AnimationMargin).toFixed(2)+'px)';this._nameElement.style.width=(this._duration()*this._timeline.pixelMsRatio()).toFixed(2)+'px';this._drawDelayLine(this._svg);if(this._animation.type()==='CSSTransition'){this._renderTransition();return;} -this._renderIteration(this._activeIntervalGroup,0);if(!this._tailGroup) -this._tailGroup=this._activeIntervalGroup.createSVGChild('g','animation-tail-iterations');var iterationWidth=this._duration()*this._timeline.pixelMsRatio();for(var iteration=1;iteration<this._animation.source().iterations()&&iterationWidth*(iteration-1)<this._timeline.width();iteration++) -this._renderIteration(this._tailGroup,iteration);while(iteration<this._cachedElements.length) -this._cachedElements.pop().group.remove();} -_renderTransition(){if(!this._cachedElements[0]) -this._cachedElements[0]={animationLine:null,keyframePoints:{},keyframeRender:{},group:null};this._drawAnimationLine(0,this._activeIntervalGroup);this._renderKeyframe(0,0,this._activeIntervalGroup,Animation.AnimationUI.Options.AnimationMargin,this._duration()*this._timeline.pixelMsRatio(),this._animation.source().easing());this._drawPoint(0,this._activeIntervalGroup,Animation.AnimationUI.Options.AnimationMargin,0,true);this._drawPoint(0,this._activeIntervalGroup,this._duration()*this._timeline.pixelMsRatio()+Animation.AnimationUI.Options.AnimationMargin,-1,true);} -_renderIteration(parentElement,iteration){if(!this._cachedElements[iteration]){this._cachedElements[iteration]={animationLine:null,keyframePoints:{},keyframeRender:{},group:parentElement.createSVGChild('g')};} -var group=this._cachedElements[iteration].group;group.style.transform='translateX('+(iteration*this._duration()*this._timeline.pixelMsRatio()).toFixed(2)+'px)';this._drawAnimationLine(iteration,group);console.assert(this._keyframes.length>1);for(var i=0;i<this._keyframes.length-1;i++){var leftDistance=this._offset(i)*this._duration()*this._timeline.pixelMsRatio()+ -Animation.AnimationUI.Options.AnimationMargin;var width=this._duration()*(this._offset(i+1)-this._offset(i))*this._timeline.pixelMsRatio();this._renderKeyframe(iteration,i,group,leftDistance,width,this._keyframes[i].easing());if(i||(!i&&iteration===0)) -this._drawPoint(iteration,group,leftDistance,i,iteration===0);} -this._drawPoint(iteration,group,this._duration()*this._timeline.pixelMsRatio()+Animation.AnimationUI.Options.AnimationMargin,-1,iteration===0);} -_delay(){var delay=this._animation.source().delay();if(this._mouseEventType===Animation.AnimationUI.MouseEvents.AnimationDrag||this._mouseEventType===Animation.AnimationUI.MouseEvents.StartEndpointMove) -delay+=this._movementInMs;return Math.max(0,delay);} -_duration(){var duration=this._animation.source().duration();if(this._mouseEventType===Animation.AnimationUI.MouseEvents.FinishEndpointMove) -duration+=this._movementInMs;else if(this._mouseEventType===Animation.AnimationUI.MouseEvents.StartEndpointMove) -duration-=Math.max(this._movementInMs,-this._animation.source().delay());return Math.max(0,duration);} -_offset(i){var offset=this._keyframes[i].offsetAsNumber();if(this._mouseEventType===Animation.AnimationUI.MouseEvents.KeyframeMove&&i===this._keyframeMoved){console.assert(i>0&&i<this._keyframes.length-1,'First and last keyframe cannot be moved');offset+=this._movementInMs/this._animation.source().duration();offset=Math.max(offset,this._keyframes[i-1].offsetAsNumber());offset=Math.min(offset,this._keyframes[i+1].offsetAsNumber());} -return offset;} -_mouseDown(mouseEventType,keyframeIndex,event){if(event.buttons===2) -return false;if(this._svg.enclosingNodeOrSelfWithClass('animation-node-removed')) -return false;this._mouseEventType=mouseEventType;this._keyframeMoved=keyframeIndex;this._downMouseX=event.clientX;event.consume(true);if(this._node) -Common.Revealer.reveal(this._node);return true;} -_mouseMove(event){this._movementInMs=(event.clientX-this._downMouseX)/this._timeline.pixelMsRatio();if(this._delay()+this._duration()>this._timeline.duration()*0.8) -this._timeline.setDuration(this._timeline.duration()*1.2);this.redraw();} -_mouseUp(event){this._movementInMs=(event.clientX-this._downMouseX)/this._timeline.pixelMsRatio();if(this._mouseEventType===Animation.AnimationUI.MouseEvents.KeyframeMove) -this._keyframes[this._keyframeMoved].setOffset(this._offset(this._keyframeMoved));else -this._animation.setTiming(this._duration(),this._delay());this._movementInMs=0;this.redraw();delete this._mouseEventType;delete this._downMouseX;delete this._keyframeMoved;} -_onContextMenu(event){function showContextMenu(remoteObject){if(!remoteObject) -return;var contextMenu=new UI.ContextMenu(event);contextMenu.appendApplicableItems(remoteObject);contextMenu.show();} -this._animation.remoteObjectPromise().then(showContextMenu);event.consume(true);}};Animation.AnimationUI.MouseEvents={AnimationDrag:'AnimationDrag',KeyframeMove:'KeyframeMove',StartEndpointMove:'StartEndpointMove',FinishEndpointMove:'FinishEndpointMove'};Animation.AnimationUI.Options={AnimationHeight:26,AnimationSVGHeight:50,AnimationMargin:7,EndpointsClickRegionSize:10,GridCanvasHeight:40};Animation.AnimationUI.Colors={'Purple':Common.Color.parse('#9C27B0'),'Light Blue':Common.Color.parse('#03A9F4'),'Deep Orange':Common.Color.parse('#FF5722'),'Blue':Common.Color.parse('#5677FC'),'Lime':Common.Color.parse('#CDDC39'),'Blue Grey':Common.Color.parse('#607D8B'),'Pink':Common.Color.parse('#E91E63'),'Green':Common.Color.parse('#0F9D58'),'Brown':Common.Color.parse('#795548'),'Cyan':Common.Color.parse('#00BCD4')};;Runtime.cachedResources["animation/animationScreenshotPopover.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\nimg {\n max-height: 300px;\n border-radius: 2px;\n}\n\n.animation-progress {\n position: absolute;\n height: 2px;\n bottom: 0;\n left: 0;\n background: hsl(217, 89%, 61%);\n}\n\n/*# sourceURL=animation/animationScreenshotPopover.css */";Runtime.cachedResources["animation/animationTimeline.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow: hidden;\n}\n\n.animation-node-row {\n width: 100%;\n display: flex;\n border-bottom: 1px dashed hsla(0,0%,94%,1);\n}\n\n.animation-node-description {\n width: 150px;\n padding-left: 8px;\n overflow: hidden;\n position: relative;\n transform-style: preserve-3d;\n border-bottom: 1px solid hsl(0, 0%, 90%);\n margin-bottom: -1px;\n background-color: hsl(0, 0%, 98%);\n display: flex;\n align-items: center;\n flex: 0 0 150px;\n}\n\n.animation-node-description > * {\n flex: 0 0 auto;\n}\n\n.animation-timeline-row {\n height: 32px;\n position: relative;\n}\n\npath.animation-keyframe {\n fill-opacity: 0.2;\n}\n\nsvg.animation-ui g:first-child:hover path.animation-keyframe {\n fill-opacity: 0.4;\n}\n\n.animation-node-selected path.animation-keyframe {\n fill-opacity: 0.4;\n}\n\nline.animation-line {\n stroke-width: 2px;\n stroke-linecap: round;\n fill: none;\n}\n\nline.animation-delay-line {\n stroke-width: 2px;\n stroke-dasharray: 6, 4;\n}\n\nline.animation-delay-line.animation-fill {\n stroke-dasharray: none;\n}\n\ncircle.animation-endpoint, circle.animation-keyframe-point {\n stroke-width: 2px;\n transition: transform 100ms cubic-bezier(0, 0, 0.2, 1);\n transform: scale(1);\n transform-origin: 50% 50%;\n}\n\n.animation-ui circle.animation-endpoint:hover, .animation-ui circle.animation-keyframe-point:hover {\n transform: scale(1.2);\n}\n\ncircle.animation-endpoint:active, circle.animation-keyframe-point:active {\n transform: scale(1);\n}\n\ncircle.animation-keyframe-point {\n fill: white;\n}\n\n.animation-name {\n position: absolute;\n top: 8px;\n color: #333;\n text-align: center;\n margin-left: -8px;\n white-space: nowrap;\n}\n\n.animation-timeline-toolbar-container {\n display: flex;\n border-bottom: 1px solid #ccc;\n flex: 0 0;\n}\n\n.animation-timeline-toolbar {\n display: inline-block;\n}\n\n.animation-timeline-header {\n height: 28px;\n border-bottom: 1px solid #ccc;\n flex-shrink: 0;\n display: flex;\n}\n\n.animation-timeline-header:after {\n content: \"\";\n height: calc(100% - 48px - 28px);\n position: absolute;\n width: 150px;\n left: 0;\n margin-top: 28px;\n background-color: hsl(0, 0%, 98%);\n z-index: 0;\n border-right: 1px solid hsl(0, 0%, 90%);\n}\n\n.animation-controls {\n flex: 0 0 150px;\n position: relative;\n display: flex;\n justify-content: flex-end;\n padding-right: 8px;\n}\n\n.animation-timeline-current-time {flex: 0 0 auto;line-height: 28px;margin-right: 5px;}\n.animation-grid-header {\n flex: 1 0 auto;\n z-index: 1;\n cursor: text;\n}\n\n.animation-timeline-buffer, .animation-timeline-buffer-hint {\n height: 48px;\n flex: 0 0 auto;\n border-bottom: 1px solid #ccc;\n display: flex;\n padding: 0 2px;\n}\n\n.animation-timeline-buffer:empty, .animation-timeline-buffer-hint {\n display: none;\n}\n\n.animation-timeline-buffer:empty ~ .animation-timeline-buffer-hint {\n align-items: center;\n justify-content: center;\n font-size: 14px;\n z-index: 101;\n display: flex;\n}\n\n.animation-time-overlay {\n background-color: black;\n opacity: 0.05;\n position: absolute;\n height: 100%;\n width: 100%;\n z-index: -1;\n}\n\n.animation-timeline-end > .animation-time-overlay {\n visibility: hidden;\n}\n\n.animation-scrubber {\n opacity: 1;\n position: absolute;\n left: 150px;\n height: calc(100% - 103px);\n width: calc(100% - 150px);\n top: 103px;\n border-left: 1px solid hsla(4,90%,58%,1);\n z-index: 1;\n}\n\n.animation-scrubber-line {\n width: 11px;\n background: linear-gradient(to right, transparent 5px, hsla(4,90%,58%,1) 5px, hsla(4,90%,58%,1) 6px, transparent 6px);\n position: absolute;\n top: -28px;\n height: 28px;\n left: -6px;\n padding: 0 5px;\n z-index: 2;\n}\n\n.animation-scrubber-head {\n width: 7px;\n height: 7px;\n transform: rotate(45deg);\n background: red;\n position: absolute;\n left: 2px;\n top: 1px;\n}\n\nsvg.animation-timeline-grid {\n position: absolute;\n left: 140px;\n top: 76px;\n z-index: 0;\n}\n\nrect.animation-timeline-grid-line {\n fill: hsla(0,0%,93%,1);\n}\n\n.animation-timeline-row > svg.animation-ui {\n position: absolute;\n}\n\n.animation-node-timeline {\n flex-grow: 1;\n}\n\n.animation-node-description > div {\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n max-height: 100%;\n}\n\n.animation-node-removed {\n -webkit-filter: saturate(0);\n cursor: not-allowed;\n}\n\nsvg.animation-ui g:first-child {\n opacity: 1;\n}\n\n.animation-tail-iterations {\n opacity: 0.5;\n}\n\n.animation-keyframe-step line {\n stroke-width: 2;\n stroke-opacity: 0.3;\n}\n\ntext.animation-timeline-grid-label {\n font-size: 10px;\n fill: #5a5a5a;\n text-anchor: middle;\n}\n\n.animation-timeline-rows, .animation-timeline-rows-hint {\n flex-grow: 1;\n overflow-y: auto;\n z-index: 1;\n overflow-x: hidden;\n}\n\n.animation-timeline-rows-hint {\n display: none;\n}\n\n.animation-timeline-buffer:not(:empty) ~ .animation-timeline-rows:empty {\n flex-grow: 0;\n}\n\n.animation-timeline-buffer:not(:empty) ~ .animation-timeline-rows:empty ~ .animation-timeline-rows-hint {\n font-size: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n margin-left: 150px;\n padding: 10px;\n}\n\n.toolbar.animation-controls-toolbar {\n flex: 0 0 auto;\n}\n\n.animation-node-row.animation-node-selected {\n background-color: hsla(216, 71%, 53%, 0.08);\n}\n\n.animation-node-selected > .animation-node-description {\n background-color: #EFF4FD;\n}\n\n.animation-timeline-empty-message {\n padding-left: 230px;\n padding-right: 30px;\n text-align: center;\n position: absolute;\n font-size: 20px;\n line-height: 32px;\n align-items: center; justify-content: center;\n width: 100%;\n height: calc(100% - 44px);\n display: flex;\n}\n\n.animation-buffer-preview {\n height: 40px;\n margin: 4px 2px;\n background-color: #F3F3F3;\n border-radius: 2px;\n flex: 1 1;\n padding: 4px;\n max-width: 100px;\n animation: newGroupAnim 200ms;\n position: relative;\n}\n\n.animation-buffer-preview-animation {\n width: 100%;\n height: 100%;\n border-radius: 2px 0 0 2px;\n position: absolute;\n top: 0;\n left: 0;\n background: hsla(219, 100%, 66%, 0.27);\n opacity: 0;\n border-right: 1px solid #A7A7A7;\n cursor: pointer;\n}\n\n.animation-buffer-preview:not(.selected):hover {\n background-color: hsla(217,90%,92%,1);\n}\n\n.animation-buffer-preview.selected {\n background-color: hsl(217, 89%, 61%);\n}\n\n.animation-paused {\n display: flex;\n align-items: center;\n justify-content: center;\n background-color: hsla(0,0%,70%,0.5);\n display: none;\n}\n\n.animation-paused:before, .animation-paused:after {\n content: \"\";\n background: hsl(0, 100%, 100%);\n width: 7px;\n height: 20px;\n border-radius: 2px;\n margin: 2px;\n border: 1px solid #ccc;\n}\n\n.animation-buffer-preview.paused .animation-paused {\n display: flex;\n}\n\n.animation-buffer-preview.selected > svg > line {\n stroke: white !important;\n}\n\n.animation-buffer-preview > svg > line {\n stroke-width: 1px;\n}\n\n@keyframes newGroupAnim {\n from {\n -webkit-clip-path: polygon(0% 0%, 0% 100%, 0% 100%, 0% 0%);\n }\n to {\n -webkit-clip-path: polygon(0% 0%, 0% 100%, 100% 100%, 100% 0%);\n }\n}\n\n.animation-playback-rate-control {\n margin: 4px 0 4px 2px;\n display: flex;\n width: 120px;\n}\n\n.animation-playback-rate-button:first-child {\n border-radius: 4px 0 0 4px;\n}\n\n.animation-playback-rate-button:last-child {\n border-radius: 0 4px 4px 0;\n}\n\n.animation-playback-rate-button {\n border: 1px solid #ccc;\n display: inline-block;\n margin-right: -1px;\n padding: 1px 4px;\n background: white;\n flex: 1 0 auto;\n text-align: center;\n cursor: pointer;\n}\n\n.animation-playback-rate-button:not(.selected):hover {\n background: hsl(211, 100%, 95%);\n}\n\n.animation-playback-rate-button.selected {\n color: hsl(0, 100%, 100%);\n background-color: hsl(217, 89%, 61%);\n border-color: hsl(217, 89%, 61%);\n z-index: 1;\n}\n\n.animation-playback-rate-button.selected:first-child {\n color: hsl(217, 89%, 61%);\n background-color: hsl(217, 89%, 100%);\n}\n\n.animation-remove-button {\n position: absolute;\n top: -3px;\n right: -3px;\n background: #7B7B7B;\n border-radius: 12px;\n height: 16px;\n width: 16px;\n align-items: center;\n font-size: 10px;\n justify-content: center;\n box-shadow: 0 1px 4px 0 rgb(185, 185, 185);\n z-index: 100;\n display: none;\n cursor: pointer;\n font-weight: 700;\n color: white;\n}\n\n.animation-remove-button:hover {\n background: #585858;\n}\n\n.animation-buffer-preview:hover .animation-remove-button {\n display: flex;\n}\n\n/*# sourceURL=animation/animationTimeline.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/audits2/audits2_module.js b/src/cobalt/debug/content/devtools/audits2/audits2_module.js deleted file mode 100644 index 8442c06..0000000 --- a/src/cobalt/debug/content/devtools/audits2/audits2_module.js +++ /dev/null
@@ -1,221 +0,0 @@ -'use strict';const ELLIPSIS='\u2026';const NBSP='\xa0';const RATINGS={PASS:{label:'pass',minScore:75},AVERAGE:{label:'average',minScore:45},FAIL:{label:'fail'},};class Util{static calculateRating(score){let rating=RATINGS.FAIL.label;if(score>=RATINGS.PASS.minScore){rating=RATINGS.PASS.label;}else if(score>=RATINGS.AVERAGE.minScore){rating=RATINGS.AVERAGE.label;} -return rating;} -static formatNumber(number,decimalPlaces=1){return number.toLocaleString(undefined,{maximumFractionDigits:decimalPlaces});} -static formatBytesToKB(size,decimalPlaces=2){const kbs=(size/1024).toLocaleString(undefined,{maximumFractionDigits:decimalPlaces});return`${kbs}${NBSP}KB`;} -static formatMilliseconds(ms,granularity=10){const coarseTime=Math.round(ms/granularity)*granularity;return`${coarseTime.toLocaleString()}${NBSP}ms`;} -static formatDateTime(date){const options={month:'short',day:'numeric',year:'numeric',hour:'numeric',minute:'numeric',timeZoneName:'short',};let formatter=new Intl.DateTimeFormat('en-US',options);const tz=formatter.resolvedOptions().timeZone;if(!tz||tz.toLowerCase()==='etc/unknown'){options.timeZone='UTC';formatter=new Intl.DateTimeFormat('en-US',options);} -return formatter.format(new Date(date));} -static getURLDisplayName(parsedUrl,options={}){const numPathParts=options.numPathParts!==undefined?options.numPathParts:2;const preserveQuery=options.preserveQuery!==undefined?options.preserveQuery:true;const preserveHost=options.preserveHost||false;let name;if(parsedUrl.protocol==='about:'||parsedUrl.protocol==='data:'){name=parsedUrl.href;}else{name=parsedUrl.pathname;const parts=name.split('/').filter(part=>part.length);if(numPathParts&&parts.length>numPathParts){name=ELLIPSIS+parts.slice(-1*numPathParts).join('/');} -if(preserveHost){name=`${parsedUrl.host}/${name.replace(/^\//, '')}`;} -if(preserveQuery){name=`${name}${parsedUrl.search}`;}} -const MAX_LENGTH=64;name=name.replace(/([a-f0-9]{7})[a-f0-9]{13}[a-f0-9]*/g,`$1${ELLIPSIS}`);if(name.length>MAX_LENGTH&&name.includes('?')){name=name.replace(/\?([^=]*)(=)?.*/,`?$1$2${ELLIPSIS}`);if(name.length>MAX_LENGTH){name=name.replace(/\?.*/,`?${ELLIPSIS}`);}} -if(name.length>MAX_LENGTH){const dotIndex=name.lastIndexOf('.');if(dotIndex>=0){name=name.slice(0,MAX_LENGTH-1-(name.length-dotIndex))+`${ELLIPSIS}${name.slice(dotIndex)}`;}else{name=name.slice(0,MAX_LENGTH-1)+ELLIPSIS;}} -return name;} -static parseURL(url){const parsedUrl=new URL(url);return{file:Util.getURLDisplayName(parsedUrl),hostname:parsedUrl.hostname};} -static chainDuration(startTime,endTime){return Util.formatNumber((endTime-startTime)*1000);}} -if(typeof module!=='undefined'&&module.exports){module.exports=Util;}else{self.Util=Util;};'use strict';class DOM{constructor(document){this._document=document;} -createElement(name,className,attrs={}){const element=this._document.createElement(name);if(className){element.className=className;} -Object.keys(attrs).forEach(key=>{const value=attrs[key];if(typeof value!=='undefined'){element.setAttribute(key,value);}});return element;} -createChildOf(parentElem,elementName,className,attrs){const element=this.createElement(elementName,className,attrs);parentElem.appendChild(element);return element;} -cloneTemplate(selector,context){const template=(context.querySelector(selector));if(!template){throw new Error(`Template not found: template${selector}`);} -const clone=(this._document.importNode(template.content,true));if(template.hasAttribute('data-stamped')){this.findAll('style',clone).forEach(style=>style.remove());} -template.setAttribute('data-stamped',true);return clone;} -resetTemplates(){this.findAll('template[data-stamped]',this._document).forEach(t=>{t.removeAttribute('data-stamped');});} -convertMarkdownLinkSnippets(text){const element=this.createElement('span');const parts=text.split(/\[([^\]]*?)\]\((https?:\/\/.*?)\)/g);while(parts.length){const[preambleText,linkText,linkHref]=parts.splice(0,3);element.appendChild(this._document.createTextNode(preambleText));if(linkText&&linkHref){const a=(this.createElement('a'));a.rel='noopener';a.target='_blank';a.textContent=linkText;a.href=(new URL(linkHref)).href;element.appendChild(a);}} -return element;} -convertMarkdownCodeSnippets(text){const element=this.createElement('span');const parts=text.split(/`(.*?)`/g);while(parts.length){const[preambleText,codeText]=parts.splice(0,2);element.appendChild(this._document.createTextNode(preambleText));if(codeText){const pre=(this.createElement('code'));pre.textContent=codeText;element.appendChild(pre);}} -return element;} -document(){return this._document;} -find(query,context){const result=context.querySelector(query);if(result===null){throw new Error(`query ${query} not found`);} -return result;} -findAll(query,context){return Array.from(context.querySelectorAll(query));}} -if(typeof module!=='undefined'&&module.exports){module.exports=DOM;}else{self.DOM=DOM;};'use strict';class CategoryRenderer{constructor(dom,detailsRenderer){this._dom=dom;this._detailsRenderer=detailsRenderer;this._templateContext=this._dom.document();this._detailsRenderer.setTemplateContext(this._templateContext);} -_renderAuditScore(audit){const tmpl=this._dom.cloneTemplate('#tmpl-lh-audit-score',this._templateContext);const scoringMode=audit.result.scoringMode;const description=audit.result.helpText;let title=audit.result.description;if(audit.result.displayValue){title+=`: ${audit.result.displayValue}`;} -if(audit.result.optimalValue){title+=` (target: ${audit.result.optimalValue})`;} -if(audit.result.debugString){const debugStrEl=tmpl.appendChild(this._dom.createElement('div','lh-debug'));debugStrEl.textContent=audit.result.debugString;} -const header=(this._dom.find('.lh-score__header',tmpl));if(audit.result.details){header.appendChild(this._detailsRenderer.render(audit.result.details));} -const scoreEl=this._dom.find('.lh-score',tmpl);if(audit.result.informative){scoreEl.classList.add('lh-score--informative');} -if(audit.result.manual){scoreEl.classList.add('lh-score--manual');} -return this._populateScore(tmpl,audit.score,scoringMode,title,description);} -_populateScore(element,score,scoringMode,title,description){const valueEl=this._dom.find('.lh-score__value',element);valueEl.textContent=Util.formatNumber(score);valueEl.classList.add(`lh-score__value--${Util.calculateRating(score)}`,`lh-score__value--${scoringMode}`);this._dom.find('.lh-score__title',element).appendChild(this._dom.convertMarkdownCodeSnippets(title));this._dom.find('.lh-score__description',element).appendChild(this._dom.convertMarkdownLinkSnippets(description));return(element);} -_renderCategoryScore(category){const tmpl=this._dom.cloneTemplate('#tmpl-lh-category-score',this._templateContext);const score=Math.round(category.score);const gaugeContainerEl=this._dom.find('.lh-score__gauge',tmpl);const gaugeEl=this.renderScoreGauge(category);gaugeContainerEl.appendChild(gaugeEl);return this._populateScore(tmpl,score,'numeric',category.name,category.description);} -_renderAudit(audit){const element=this._dom.createElement('div','lh-audit');element.appendChild(this._renderAuditScore(audit));return element;} -_renderTimelineMetricAudit(audit,scale){const tmpl=this._dom.cloneTemplate('#tmpl-lh-timeline-metric',this._templateContext);const element=this._dom.find('.lh-timeline-metric',tmpl);element.classList.add(`lh-timeline-metric--${Util.calculateRating(audit.score)}`);const titleEl=this._dom.find('.lh-timeline-metric__title',tmpl);titleEl.textContent=audit.result.description;const valueEl=this._dom.find('.lh-timeline-metric__value',tmpl);valueEl.textContent=audit.result.displayValue;const descriptionEl=this._dom.find('.lh-timeline-metric__description',tmpl);descriptionEl.appendChild(this._dom.convertMarkdownLinkSnippets(audit.result.helpText));if(typeof audit.result.rawValue!=='number'){const debugStrEl=this._dom.createChildOf(element,'div','lh-debug');debugStrEl.textContent=audit.result.debugString||'Report error: no metric information';return element;} -const sparklineBarEl=this._dom.find('.lh-sparkline__bar',tmpl);sparklineBarEl.style.width=`${audit.result.rawValue / scale * 100}%`;return element;} -_renderPerfHintAudit(audit,scale){const extendedInfo=(audit.result.extendedInfo);const tooltipAttrs={title:audit.result.displayValue};const element=this._dom.createElement('details',['lh-perf-hint',`lh-perf-hint--${Util.calculateRating(audit.score)}`,'lh-expandable-details',].join(' '));const summary=this._dom.createChildOf(element,'summary','lh-perf-hint__summary '+'lh-expandable-details__summary');const titleEl=this._dom.createChildOf(summary,'div','lh-perf-hint__title');titleEl.textContent=audit.result.description;this._dom.createChildOf(summary,'div','lh-toggle-arrow',{title:'See resources'});if(!extendedInfo||typeof audit.result.rawValue!=='number'){const debugStrEl=this._dom.createChildOf(summary,'div','lh-debug');debugStrEl.textContent=audit.result.debugString||'Report error: no extended information';return element;} -const sparklineContainerEl=this._dom.createChildOf(summary,'div','lh-perf-hint__sparkline',tooltipAttrs);const sparklineEl=this._dom.createChildOf(sparklineContainerEl,'div','lh-sparkline');const sparklineBarEl=this._dom.createChildOf(sparklineEl,'div','lh-sparkline__bar');sparklineBarEl.style.width=audit.result.rawValue/scale*100+'%';const statsEl=this._dom.createChildOf(summary,'div','lh-perf-hint__stats',tooltipAttrs);const statsMsEl=this._dom.createChildOf(statsEl,'div','lh-perf-hint__primary-stat');statsMsEl.textContent=Util.formatMilliseconds(audit.result.rawValue);if(extendedInfo.value.wastedKb){const statsKbEl=this._dom.createChildOf(statsEl,'div','lh-perf-hint__secondary-stat');statsKbEl.textContent=Util.formatNumber(extendedInfo.value.wastedKb)+' KB';} -const descriptionEl=this._dom.createChildOf(element,'div','lh-perf-hint__description');descriptionEl.appendChild(this._dom.convertMarkdownLinkSnippets(audit.result.helpText));if(audit.result.debugString){const debugStrEl=this._dom.createChildOf(summary,'div','lh-debug');debugStrEl.textContent=audit.result.debugString;} -if(audit.result.details){element.appendChild(this._detailsRenderer.render(audit.result.details));} -return element;} -_renderAuditGroup(group,opts){const expandable=opts.expandable;const element=this._dom.createElement(expandable?'details':'div','lh-audit-group');const summmaryEl=this._dom.createChildOf(element,'summary','lh-audit-group__summary');const headerEl=this._dom.createChildOf(summmaryEl,'div','lh-audit-group__header');this._dom.createChildOf(summmaryEl,'div',`lh-toggle-arrow ${expandable ? '' : ' lh-toggle-arrow-unexpandable'}`,{title:'See audits',});if(group.description){const auditGroupDescription=this._dom.createElement('div','lh-audit-group__description');auditGroupDescription.appendChild(this._dom.convertMarkdownLinkSnippets(group.description));element.appendChild(auditGroupDescription);} -headerEl.textContent=group.title;return element;} -_renderPassedAuditsSection(elements){const passedElem=this._renderAuditGroup({title:`${elements.length} Passed Audits`,},{expandable:true});passedElem.classList.add('lh-passed-audits');elements.forEach(elem=>passedElem.appendChild(elem));return passedElem;} -_renderManualAudits(manualAudits,groupDefinitions,element){const auditsGroupedByGroup=({});manualAudits.forEach(audit=>{const group=auditsGroupedByGroup[audit.group]||[];group.push(audit);auditsGroupedByGroup[audit.group]=group;});Object.keys(auditsGroupedByGroup).forEach(groupId=>{const group=groupDefinitions[groupId];const auditGroupElem=this._renderAuditGroup(group,{expandable:true});auditGroupElem.classList.add('lh-audit-group--manual');auditsGroupedByGroup[groupId].forEach(audit=>{auditGroupElem.appendChild(this._renderAudit(audit));});element.appendChild(auditGroupElem);});} -setTemplateContext(context){this._templateContext=context;this._detailsRenderer.setTemplateContext(context);} -renderScoreGauge(category){const tmpl=this._dom.cloneTemplate('#tmpl-lh-gauge',this._templateContext);this._dom.find('.lh-gauge__wrapper',tmpl).href=`#${category.id}`;this._dom.find('.lh-gauge__label',tmpl).textContent=category.name;const score=Math.round(category.score);const fillRotation=Math.floor((score/100)*180);const gauge=this._dom.find('.lh-gauge',tmpl);gauge.setAttribute('data-progress',score);gauge.classList.add(`lh-gauge--${Util.calculateRating(score)}`);this._dom.findAll('.lh-gauge__fill',gauge).forEach(el=>{el.style.transform=`rotate(${fillRotation}deg)`;});this._dom.find('.lh-gauge__mask--full',gauge).style.transform=`rotate(${fillRotation}deg)`;this._dom.find('.lh-gauge__fill--fix',gauge).style.transform=`rotate(${fillRotation * 2}deg)`;this._dom.find('.lh-gauge__percentage',gauge).textContent=score;return tmpl;} -render(category,groups){switch(category.id){case'performance':return this._renderPerformanceCategory(category,groups);case'accessibility':return this._renderAccessibilityCategory(category,groups);default:return this._renderDefaultCategory(category,groups);}} -_renderDefaultCategory(category,groupDefinitions){const element=this._dom.createElement('div','lh-category');this._createPermalinkSpan(element,category.id);element.appendChild(this._renderCategoryScore(category));const manualAudits=category.audits.filter(audit=>audit.result.manual);const nonManualAudits=category.audits.filter(audit=>!manualAudits.includes(audit));const passedAudits=nonManualAudits.filter(audit=>audit.score===100&&!audit.result.debugString);const nonPassedAudits=nonManualAudits.filter(audit=>!passedAudits.includes(audit));const nonPassedElem=this._renderAuditGroup({title:`${nonPassedAudits.length} Failed Audits`,},{expandable:false});nonPassedElem.classList.add('lh-failed-audits');nonPassedAudits.forEach(audit=>nonPassedElem.appendChild(this._renderAudit(audit)));element.appendChild(nonPassedElem);if(passedAudits.length){const passedElem=this._renderPassedAuditsSection(passedAudits.map(audit=>this._renderAudit(audit)));element.appendChild(passedElem);} -this._renderManualAudits(manualAudits,groupDefinitions,element);return element;} -_renderPerformanceCategory(category,groups){const element=this._dom.createElement('div','lh-category');this._createPermalinkSpan(element,category.id);element.appendChild(this._renderCategoryScore(category));const metricAudits=category.audits.filter(audit=>audit.group==='perf-metric');const metricAuditsEl=this._renderAuditGroup(groups['perf-metric'],{expandable:false});const timelineContainerEl=this._dom.createChildOf(metricAuditsEl,'div','lh-timeline-container');const timelineEl=this._dom.createChildOf(timelineContainerEl,'div','lh-timeline');let perfTimelineScale=0;metricAudits.forEach(audit=>{if(typeof audit.result.rawValue==='number'&&audit.result.rawValue){perfTimelineScale=Math.max(perfTimelineScale,audit.result.rawValue);}});const thumbnailAudit=category.audits.find(audit=>audit.id==='screenshot-thumbnails');const thumbnailResult=thumbnailAudit&&thumbnailAudit.result;if(thumbnailResult&&thumbnailResult.details){const thumbnailDetails=(thumbnailResult.details);perfTimelineScale=Math.max(perfTimelineScale,thumbnailDetails.scale);const filmstripEl=this._detailsRenderer.render(thumbnailDetails);timelineEl.appendChild(filmstripEl);} -metricAudits.forEach(item=>{if(item.id==='speed-index-metric'||item.id==='estimated-input-latency'){return metricAuditsEl.appendChild(this._renderAudit(item));} -timelineEl.appendChild(this._renderTimelineMetricAudit(item,perfTimelineScale));});metricAuditsEl.open=true;element.appendChild(metricAuditsEl);const hintAudits=category.audits.filter(audit=>audit.group==='perf-hint'&&audit.score<100).sort((auditA,auditB)=>auditB.result.rawValue-auditA.result.rawValue);if(hintAudits.length){const maxWaste=Math.max(...hintAudits.map(audit=>audit.result.rawValue));const scale=Math.ceil(maxWaste/1000)*1000;const hintAuditsEl=this._renderAuditGroup(groups['perf-hint'],{expandable:false});hintAudits.forEach(item=>hintAuditsEl.appendChild(this._renderPerfHintAudit(item,scale)));hintAuditsEl.open=true;element.appendChild(hintAuditsEl);} -const infoAudits=category.audits.filter(audit=>audit.group==='perf-info'&&audit.score<100);if(infoAudits.length){const infoAuditsEl=this._renderAuditGroup(groups['perf-info'],{expandable:false});infoAudits.forEach(item=>infoAuditsEl.appendChild(this._renderAudit(item)));infoAuditsEl.open=true;element.appendChild(infoAuditsEl);} -const passedElements=category.audits.filter(audit=>(audit.group==='perf-hint'||audit.group==='perf-info')&&audit.score===100).map(audit=>this._renderAudit(audit));if(!passedElements.length)return element;const passedElem=this._renderPassedAuditsSection(passedElements);element.appendChild(passedElem);return element;} -_renderAccessibilityCategory(category,groupDefinitions){const element=this._dom.createElement('div','lh-category');this._createPermalinkSpan(element,category.id);element.appendChild(this._renderCategoryScore(category));const auditsGroupedByGroup=({});category.audits.forEach(audit=>{const groupId=audit.group;const groups=auditsGroupedByGroup[groupId]||{passed:[],failed:[]};if(audit.score===100){groups.passed.push(audit);}else{groups.failed.push(audit);} -auditsGroupedByGroup[groupId]=groups;});const passedElements=([]);Object.keys(auditsGroupedByGroup).forEach(groupId=>{const group=groupDefinitions[groupId];const groups=auditsGroupedByGroup[groupId];if(groups.failed.length){const auditGroupElem=this._renderAuditGroup(group,{expandable:false});groups.failed.forEach(item=>auditGroupElem.appendChild(this._renderAudit(item)));auditGroupElem.open=true;element.appendChild(auditGroupElem);} -if(groups.passed.length){const auditGroupElem=this._renderAuditGroup(group,{expandable:true});groups.passed.forEach(item=>auditGroupElem.appendChild(this._renderAudit(item)));passedElements.push(auditGroupElem);}});if(!passedElements.length)return element;const passedElem=this._renderPassedAuditsSection(passedElements);element.appendChild(passedElem);return element;} -_createPermalinkSpan(element,id){const permalinkEl=this._dom.createChildOf(element,'span','lh-permalink');permalinkEl.id=id;}} -if(typeof module!=='undefined'&&module.exports){module.exports=CategoryRenderer;}else{self.CategoryRenderer=CategoryRenderer;} -CategoryRenderer.PerfHintExtendedInfo;;'use strict';class DetailsRenderer{constructor(dom){this._dom=dom;this._templateContext;} -setTemplateContext(context){this._templateContext=context;} -render(details){switch(details.type){case'text':return this._renderText(details);case'url':return this._renderTextURL(details);case'link':return this._renderLink((details));case'thumbnail':return this._renderThumbnail((details));case'filmstrip':return this._renderFilmstrip((details));case'cards':return this._renderCards((details));case'table':return this._renderTable((details));case'code':return this._renderCode(details);case'node':return this.renderNode((details));case'criticalrequestchain':return CriticalRequestChainRenderer.render(this._dom,this._templateContext,(details));case'list':return this._renderList((details));default:throw new Error(`Unknown type: ${details.type}`);}} -_renderTextURL(text){const url=text.text||'';let displayedURL;let title;try{displayedURL=Util.parseURL(url).file;title=url;}catch(e){if(!(e instanceof TypeError)){throw e;} -displayedURL=url;} -const element=this._renderText({type:'url',text:displayedURL,});element.classList.add('lh-text__url');if(title){element.title=url;} -return element;} -_renderLink(details){const allowedProtocols=['https:','http:'];const url=new URL(details.url);if(!allowedProtocols.includes(url.protocol)){return this._renderText(details);} -const a=(this._dom.createElement('a'));a.rel='noopener';a.target='_blank';a.textContent=details.text;a.href=url.href;return a;} -_renderText(text){const element=this._dom.createElement('div','lh-text');element.textContent=text.text;return element;} -_renderThumbnail(value){if(/^image/.test(value.mimeType)===false){return this._dom.createElement('span');} -const element=this._dom.createElement('img','lh-thumbnail');element.src=value.url;element.alt='';element.title=value.url;return element;} -_renderList(list){if(!list.items.length)return this._dom.createElement('span');const element=this._dom.createElement('details','lh-details');element.open=true;if(list.header){const summary=this._dom.createElement('summary','lh-list__header');summary.textContent=list.header.text;element.appendChild(summary);} -const itemsElem=this._dom.createChildOf(element,'div','lh-list__items');for(const item of list.items){const itemElem=this._dom.createChildOf(itemsElem,'span','lh-list__item');itemElem.appendChild(this.render(item));} -return element;} -_renderTable(details){if(!details.items.length)return this._dom.createElement('span');const element=this._dom.createElement('details','lh-details');element.open=true;if(details.header){element.appendChild(this._dom.createElement('summary')).textContent=details.header;} -const tableElem=this._dom.createChildOf(element,'table','lh-table');const theadElem=this._dom.createChildOf(tableElem,'thead');const theadTrElem=this._dom.createChildOf(theadElem,'tr');for(const heading of details.itemHeaders){const itemType=heading.itemType||'text';const classes=`lh-table-column--${itemType}`;this._dom.createChildOf(theadTrElem,'th',classes).appendChild(this.render(heading));} -const tbodyElem=this._dom.createChildOf(tableElem,'tbody');for(const row of details.items){const rowElem=this._dom.createChildOf(tbodyElem,'tr');for(const columnItem of row){const classes=`lh-table-column--${columnItem.type}`;this._dom.createChildOf(rowElem,'td',classes).appendChild(this.render(columnItem));}} -return element;} -renderNode(item){const element=this._dom.createElement('span','lh-node');element.textContent=item.snippet;element.title=item.selector;if(item.text)element.setAttribute('data-text',item.text);if(item.path)element.setAttribute('data-path',item.path);if(item.selector)element.setAttribute('data-selector',item.selector);if(item.snippet)element.setAttribute('data-snippet',item.snippet);return element;} -_renderCards(details){const element=this._dom.createElement('details','lh-details');element.open=true;if(details.header){element.appendChild(this._dom.createElement('summary')).textContent=details.header.text;} -const cardsParent=this._dom.createElement('div','lh-scorecards');for(const item of details.items){const card=cardsParent.appendChild(this._dom.createElement('div','lh-scorecard',{title:item.snippet}));const titleEl=this._dom.createElement('div','lh-scorecard__title');const valueEl=this._dom.createElement('div','lh-scorecard__value');const targetEl=this._dom.createElement('div','lh-scorecard__target');card.appendChild(titleEl).textContent=item.title;card.appendChild(valueEl).textContent=item.value;if(item.target){card.appendChild(targetEl).textContent=`target: ${item.target}`;}} -element.appendChild(cardsParent);return element;} -_renderFilmstrip(details){const filmstripEl=this._dom.createElement('div','lh-filmstrip');for(const thumbnail of details.items){const frameEl=this._dom.createChildOf(filmstripEl,'div','lh-filmstrip__frame');let timing=Util.formatMilliseconds(thumbnail.timing,1);if(thumbnail.timing>1000){timing=Util.formatNumber(thumbnail.timing/1000)+' s';} -const timingEl=this._dom.createChildOf(frameEl,'div','lh-filmstrip__timestamp');timingEl.textContent=timing;const base64data=thumbnail.data;this._dom.createChildOf(frameEl,'img','lh-filmstrip__thumbnail',{src:`data:image/jpeg;base64,${base64data}`,alt:`Screenshot at ${timing}`,});} -return filmstripEl;} -_renderCode(details){const pre=this._dom.createElement('pre','lh-code');pre.textContent=details.text;return pre;}} -if(typeof module!=='undefined'&&module.exports){module.exports=DetailsRenderer;}else{self.DetailsRenderer=DetailsRenderer;} -DetailsRenderer.DetailsJSON;DetailsRenderer.ListDetailsJSON;DetailsRenderer.NodeDetailsJSON;DetailsRenderer.CardsDetailsJSON;DetailsRenderer.TableHeaderJSON;DetailsRenderer.NodeDetailsJSON;DetailsRenderer.TableDetailsJSON;DetailsRenderer.ThumbnailDetails;DetailsRenderer.LinkDetailsJSON;DetailsRenderer.FilmstripDetails;;'use strict';class CriticalRequestChainRenderer{static initTree(tree){let startTime=0;const rootNodes=Object.keys(tree);if(rootNodes.length>0){const node=tree[rootNodes[0]];startTime=node.request.startTime;} -return{tree,startTime,transferSize:0};} -static createSegment(parent,id,startTime,transferSize,treeMarkers,parentIsLastChild){const node=parent[id];const siblings=Object.keys(parent);const isLastChild=siblings.indexOf(id)===(siblings.length-1);const hasChildren=Object.keys(node.children).length>0;const newTreeMarkers=Array.isArray(treeMarkers)?treeMarkers.slice(0):[];if(typeof parentIsLastChild!=='undefined'){newTreeMarkers.push(!parentIsLastChild);} -return{node,isLastChild,hasChildren,startTime,transferSize:transferSize+node.request.transferSize,treeMarkers:newTreeMarkers,};} -static createChainNode(dom,tmpl,segment){const chainsEl=dom.cloneTemplate('#tmpl-lh-crc__chains',tmpl);dom.find('.crc-node',chainsEl).setAttribute('title',segment.node.request.url);const treeMarkeEl=dom.find('.crc-node__tree-marker',chainsEl);segment.treeMarkers.forEach(separator=>{if(separator){treeMarkeEl.appendChild(dom.createElement('span','tree-marker vert'));treeMarkeEl.appendChild(dom.createElement('span','tree-marker'));}else{treeMarkeEl.appendChild(dom.createElement('span','tree-marker'));treeMarkeEl.appendChild(dom.createElement('span','tree-marker'));}});if(segment.isLastChild){treeMarkeEl.appendChild(dom.createElement('span','tree-marker up-right'));treeMarkeEl.appendChild(dom.createElement('span','tree-marker right'));}else{treeMarkeEl.appendChild(dom.createElement('span','tree-marker vert-right'));treeMarkeEl.appendChild(dom.createElement('span','tree-marker right'));} -if(segment.hasChildren){treeMarkeEl.appendChild(dom.createElement('span','tree-marker horiz-down'));}else{treeMarkeEl.appendChild(dom.createElement('span','tree-marker right'));} -const{file,hostname}=Util.parseURL(segment.node.request.url);const treevalEl=dom.find('.crc-node__tree-value',chainsEl);dom.find('.crc-node__tree-file',treevalEl).textContent=`${file}`;dom.find('.crc-node__tree-hostname',treevalEl).textContent=`(${hostname})`;if(!segment.hasChildren){const span=dom.createElement('span','crc-node__chain-duration');span.textContent=' - '+Util.chainDuration(segment.node.request.startTime,segment.node.request.endTime)+'ms, ';const span2=dom.createElement('span','crc-node__chain-duration');span2.textContent=Util.formatBytesToKB(segment.node.request.transferSize);treevalEl.appendChild(span);treevalEl.appendChild(span2);} -return chainsEl;} -static buildTree(dom,tmpl,segment,detailsEl,details){detailsEl.appendChild(CriticalRequestChainRenderer.createChainNode(dom,tmpl,segment));for(const key of Object.keys(segment.node.children)){const childSegment=CriticalRequestChainRenderer.createSegment(segment.node.children,key,segment.startTime,segment.transferSize,segment.treeMarkers,segment.isLastChild);CriticalRequestChainRenderer.buildTree(dom,tmpl,childSegment,detailsEl,details);}} -static render(dom,templateContext,details){const tmpl=dom.cloneTemplate('#tmpl-lh-crc',templateContext);dom.find('.lh-crc__longest_duration',tmpl).textContent=Util.formatNumber(details.longestChain.duration)+'ms';dom.find('.lh-crc__longest_length',tmpl).textContent=details.longestChain.length;dom.find('.lh-crc__longest_transfersize',tmpl).textContent=Util.formatBytesToKB(details.longestChain.transferSize);const detailsEl=dom.find('.lh-details',tmpl);detailsEl.open=true;dom.find('.lh-details > summary',tmpl).textContent=details.header.text;const root=CriticalRequestChainRenderer.initTree(details.chains);for(const key of Object.keys(root.tree)){const segment=CriticalRequestChainRenderer.createSegment(root.tree,key,root.startTime,root.transferSize);CriticalRequestChainRenderer.buildTree(dom,tmpl,segment,detailsEl,details);} -return tmpl;}} -if(typeof module!=='undefined'&&module.exports){module.exports=CriticalRequestChainRenderer;}else{self.CriticalRequestChainRenderer=CriticalRequestChainRenderer;} -CriticalRequestChainRenderer.CRCDetailsJSON;CriticalRequestChainRenderer.CRCRequest;CriticalRequestChainRenderer.CRCNode=function(){};CriticalRequestChainRenderer.CRCNode.prototype.children;CriticalRequestChainRenderer.CRCNode.prototype.request;CriticalRequestChainRenderer.CRCSegment;;'use strict';class ReportRenderer{constructor(dom,categoryRenderer){this._dom=dom;this._categoryRenderer=categoryRenderer;this._templateContext=this._dom.document();} -renderReport(report,container){container.textContent='';const element=container.appendChild(this._renderReport(report));return(element);} -setTemplateContext(context){this._templateContext=context;this._categoryRenderer.setTemplateContext(context);} -_renderReportHeader(report){const header=this._dom.cloneTemplate('#tmpl-lh-heading',this._templateContext);this._dom.find('.lh-config__timestamp',header).textContent=Util.formatDateTime(report.generatedTime);const url=this._dom.find('.lh-metadata__url',header);url.href=report.url;url.textContent=report.url;this._dom.find('.lh-env__item__ua',header).textContent=report.userAgent;const env=this._dom.find('.lh-env__items',header);report.runtimeConfig.environment.forEach(runtime=>{const item=this._dom.cloneTemplate('#tmpl-lh-env__items',env);this._dom.find('.lh-env__name',item).textContent=runtime.name;this._dom.find('.lh-env__description',item).textContent=runtime.description;this._dom.find('.lh-env__enabled',item).textContent=runtime.enabled?'Enabled':'Disabled';env.appendChild(item);});return header;} -_renderReportFooter(report){const footer=this._dom.cloneTemplate('#tmpl-lh-footer',this._templateContext);this._dom.find('.lh-footer__version',footer).textContent=report.lighthouseVersion;this._dom.find('.lh-footer__timestamp',footer).textContent=Util.formatDateTime(report.generatedTime);return footer;} -_renderReportNav(report){const leftNav=this._dom.cloneTemplate('#tmpl-lh-leftnav',this._templateContext);this._dom.find('.leftnav__header__version',leftNav).textContent=`Version: ${report.lighthouseVersion}`;const nav=this._dom.find('.lh-leftnav',leftNav);for(const category of report.reportCategories){const itemsTmpl=this._dom.cloneTemplate('#tmpl-lh-leftnav__items',leftNav);const navItem=this._dom.find('.lh-leftnav__item',itemsTmpl);navItem.href=`#${category.id}`;this._dom.find('.leftnav-item__category',navItem).textContent=category.name;const score=this._dom.find('.leftnav-item__score',navItem);score.classList.add(`lh-score__value--${Util.calculateRating(category.score)}`);score.textContent=Math.round(category.score);nav.appendChild(navItem);} -return leftNav;} -_renderReport(report){const container=this._dom.createElement('div','lh-container');container.appendChild(this._renderReportHeader(report));container.appendChild(this._renderReportNav(report));const reportSection=container.appendChild(this._dom.createElement('div','lh-report'));let scoreHeader;const isSoloCategory=report.reportCategories.length===1;if(!isSoloCategory){scoreHeader=reportSection.appendChild(this._dom.createElement('div','lh-scores-header'));} -const categories=reportSection.appendChild(this._dom.createElement('div','lh-categories'));for(const category of report.reportCategories){if(scoreHeader){scoreHeader.appendChild(this._categoryRenderer.renderScoreGauge(category));} -categories.appendChild(this._categoryRenderer.render(category,report.reportGroups));} -reportSection.appendChild(this._renderReportFooter(report));return container;}} -if(typeof module!=='undefined'&&module.exports){module.exports=ReportRenderer;}else{self.ReportRenderer=ReportRenderer;} -ReportRenderer.AuditJSON;ReportRenderer.CategoryJSON;ReportRenderer.GroupJSON;ReportRenderer.ReportJSON;;Audits2.Audits2Panel=class extends UI.Panel{constructor(){super('audits2');this.registerRequiredCSS('audits2/lighthouse/report-styles.css');this.registerRequiredCSS('audits2/audits2Panel.css');this._protocolService=new Audits2.ProtocolService();this._protocolService.registerStatusCallback(msg=>this._updateStatus(Common.UIString(msg)));var toolbar=new UI.Toolbar('',this.element);var newButton=new UI.ToolbarButton(Common.UIString('New audit\u2026'),'largeicon-add');toolbar.appendToolbarItem(newButton);newButton.addEventListener(UI.ToolbarButton.Events.Click,this._showLauncherUI.bind(this));var downloadButton=new UI.ToolbarButton(Common.UIString('Download report'),'largeicon-download');toolbar.appendToolbarItem(downloadButton);downloadButton.addEventListener(UI.ToolbarButton.Events.Click,this._downloadSelected.bind(this));toolbar.appendSeparator();this._reportSelector=new Audits2.ReportSelector();toolbar.appendToolbarItem(this._reportSelector.comboBox());var clearButton=new UI.ToolbarButton(Common.UIString('Clear all'),'largeicon-clear');toolbar.appendToolbarItem(clearButton);clearButton.addEventListener(UI.ToolbarButton.Events.Click,this._clearAll.bind(this));this._auditResultsElement=this.contentElement.createChild('div','audits2-results-container');this._dropTarget=new UI.DropTarget(this.contentElement,[UI.DropTarget.Type.File],Common.UIString('Drop audit file here'),this._handleDrop.bind(this));for(var preset of Audits2.Audits2Panel.Presets) -preset.setting.addChangeListener(this._updateStartButtonEnabled.bind(this));this._showLandingPage();SDK.targetManager.observeModels(SDK.ServiceWorkerManager,this);SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._updateStartButtonEnabled,this);} -modelAdded(serviceWorkerManager){if(this._manager) -return;this._manager=serviceWorkerManager;this._serviceWorkerListeners=[this._manager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationUpdated,this._updateStartButtonEnabled,this),this._manager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationDeleted,this._updateStartButtonEnabled,this),];this._updateStartButtonEnabled();} -modelRemoved(serviceWorkerManager){if(!this._manager||this._manager!==serviceWorkerManager) -return;Common.EventTarget.removeEventListeners(this._serviceWorkerListeners);this._manager=null;this._serviceWorkerListeners=null;this._updateStartButtonEnabled();} -_hasActiveServiceWorker(){if(!this._manager) -return false;var mainTarget=SDK.targetManager.mainTarget();if(!mainTarget) -return false;var inspectedURL=mainTarget.inspectedURL().asParsedURL();var inspectedOrigin=inspectedURL&&inspectedURL.securityOrigin();for(var registration of this._manager.registrations().values()){if(registration.securityOrigin!==inspectedOrigin) -continue;for(var version of registration.versions.values()){if(version.controlledClients.length>1) -return true;}} -return false;} -_hasAtLeastOneCategory(){return Audits2.Audits2Panel.Presets.some(preset=>preset.setting.get());} -_unauditablePageMessage(){if(!this._manager) -return null;var mainTarget=SDK.targetManager.mainTarget();var inspectedURL=mainTarget&&mainTarget.inspectedURL();if(inspectedURL&&!/^(http|chrome-extension)/.test(inspectedURL)){return Common.UIString('Can only audit HTTP/HTTPS pages and Chrome extensions. '+'Navigate to a different page to start an audit.');} -if(!Host.isUnderTest()&&!Runtime.queryParam('can_dock')) -return Common.UIString('Can only audit tabs. Navigate to this page in a separate tab to start an audit.');return null;} -_updateStartButtonEnabled(){var hasActiveServiceWorker=this._hasActiveServiceWorker();var hasAtLeastOneCategory=this._hasAtLeastOneCategory();var unauditablePageMessage=this._unauditablePageMessage();var isDisabled=hasActiveServiceWorker||!hasAtLeastOneCategory||!!unauditablePageMessage;if(this._dialogHelpText&&hasActiveServiceWorker){this._dialogHelpText.textContent=Common.UIString('Multiple tabs are being controlled by the same service worker. '+'Close your other tabs on the same origin to audit this page.');} -if(this._dialogHelpText&&!hasAtLeastOneCategory) -this._dialogHelpText.textContent=Common.UIString('At least one category must be selected.');if(this._dialogHelpText&&unauditablePageMessage) -this._dialogHelpText.textContent=unauditablePageMessage;if(this._dialogHelpText) -this._dialogHelpText.classList.toggle('hidden',!isDisabled);if(this._startButton) -this._startButton.disabled=isDisabled;} -_clearAll(){this._reportSelector.clearAll();this._showLandingPage();} -_downloadSelected(){this._reportSelector.downloadSelected();} -_showLandingPage(){if(this._reportSelector.comboBox().size()) -return;this._auditResultsElement.removeChildren();var landingPage=this._auditResultsElement.createChild('div','vbox audits2-landing-page');var landingCenter=landingPage.createChild('div','vbox audits2-landing-center');landingCenter.createChild('div','audits2-logo');var text=landingCenter.createChild('div','audits2-landing-text');text.createChild('span','audits2-landing-bold-text').textContent=Common.UIString('Audits');text.createChild('span').textContent=Common.UIString(' help you identify and fix common problems that affect'+' your site\'s performance, accessibility, and user experience. ');var link=text.createChild('span','link');link.textContent=Common.UIString('Learn more');link.addEventListener('click',()=>InspectorFrontendHost.openInNewTab('https://developers.google.com/web/tools/lighthouse/'));var newButton=UI.createTextButton(Common.UIString('Perform an audit\u2026'),this._showLauncherUI.bind(this),'',true);landingCenter.appendChild(newButton);this.setDefaultFocusedElement(newButton);} -_showLauncherUI(){this._dialog=new UI.Dialog();this._dialog.setOutsideClickCallback(event=>event.consume(true));var root=UI.createShadowRootWithCoreStyles(this._dialog.contentElement,'audits2/audits2Dialog.css');var auditsViewElement=root.createChild('div','audits2-view');var closeButton=auditsViewElement.createChild('div','dialog-close-button','dt-close-button');closeButton.addEventListener('click',()=>this._cancelAndClose());var uiElement=auditsViewElement.createChild('div');var headerElement=uiElement.createChild('header');this._headerTitleElement=headerElement.createChild('p');this._headerTitleElement.textContent=Common.UIString('Audits to perform');uiElement.appendChild(headerElement);this._auditSelectorForm=uiElement.createChild('form','audits2-form');for(var preset of Audits2.Audits2Panel.Presets){preset.setting.setTitle(preset.title);var checkbox=new UI.ToolbarSettingCheckbox(preset.setting);var row=this._auditSelectorForm.createChild('div','vbox audits2-launcher-row');row.appendChild(checkbox.element);row.createChild('span','audits2-launcher-description dimmed').textContent=preset.description;} -this._statusView=this._createStatusView(uiElement);this._dialogHelpText=uiElement.createChild('div','audits2-dialog-help-text');var buttonsRow=uiElement.createChild('div','audits2-dialog-buttons hbox');this._startButton=UI.createTextButton(Common.UIString('Run audit'),this._start.bind(this),'',true);this._startButton.autofocus=true;this._updateStartButtonEnabled();buttonsRow.appendChild(this._startButton);this._cancelButton=UI.createTextButton(Common.UIString('Cancel'),this._cancel.bind(this));buttonsRow.appendChild(this._cancelButton);this._dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.SetExactWidthMaxHeight);this._dialog.setMaxContentSize(new UI.Size(500,400));this._dialog.show(this._auditResultsElement);auditsViewElement.tabIndex=0;auditsViewElement.focus();} -_createStatusView(launcherUIElement){var statusView=launcherUIElement.createChild('div','audits2-status vbox hidden');this._statusIcon=statusView.createChild('div','icon');this._statusElement=statusView.createChild('div');this._updateStatus(Common.UIString('Loading...'));return statusView;} -_updateInspectedURL(){var mainTarget=SDK.targetManager.mainTarget();var runtimeModel=mainTarget.model(SDK.RuntimeModel);var executionContext=runtimeModel&&runtimeModel.defaultExecutionContext();this._inspectedURL=mainTarget.inspectedURL();if(!executionContext) -return Promise.resolve();return executionContext.evaluate({expression:'window.location.href',objectGroup:'audits',includeCommandLineAPI:false,silent:false,returnByValue:true,generatePreview:false},false,false).then(result=>{if(!result.exceptionDetails&&result.object){this._inspectedURL=result.object.value;result.object.release();}});} -_start(){var emulationModel=self.singleton(Emulation.DeviceModeModel);this._emulationEnabledBefore=emulationModel.enabledSetting().get();this._emulationOutlineEnabledBefore=emulationModel.deviceOutlineSetting().get();emulationModel.enabledSetting().set(true);emulationModel.deviceOutlineSetting().set(true);emulationModel.toolbarControlsEnabledSetting().set(false);for(var device of Emulation.EmulatedDevicesList.instance().standard()){if(device.title==='Nexus 5X') -emulationModel.emulate(Emulation.DeviceModeModel.Type.Device,device,device.modes[0],1);} -this._dialog.setCloseOnEscape(false);var categoryIDs=[];for(var preset of Audits2.Audits2Panel.Presets){if(preset.setting.get()) -categoryIDs.push(preset.configID);} -Host.userMetrics.actionTaken(Host.UserMetrics.Action.Audits2Started);return Promise.resolve().then(_=>this._updateInspectedURL()).then(_=>this._protocolService.attach()).then(_=>{this._auditRunning=true;this._updateButton();this._updateStatus(Common.UIString('Loading\u2026'));}).then(_=>this._protocolService.startLighthouse(this._inspectedURL,categoryIDs)).then(lighthouseResult=>{if(lighthouseResult&&lighthouseResult.fatal){const error=new Error(lighthouseResult.message);error.stack=lighthouseResult.stack;throw error;} -return this._stopAndReattach().then(()=>this._buildReportUI(lighthouseResult));}).catch(err=>{if(err instanceof Error) -this._renderBugReport(err);});} -_hideDialog(){if(!this._dialog) -return;this._dialog.hide();delete this._dialog;delete this._statusView;delete this._statusIcon;delete this._statusElement;delete this._startButton;delete this._cancelButton;delete this._auditSelectorForm;delete this._headerTitleElement;delete this._emulationEnabledBefore;delete this._emulationOutlineEnabledBefore;} -_cancelAndClose(){this._cancel();this._hideDialog();} -_cancel(){if(this._auditRunning){this._updateStatus(Common.UIString('Cancelling\u2026'));this._stopAndReattach();}else{this._hideDialog();}} -_updateButton(){if(!this._dialog) -return;this._startButton.classList.toggle('hidden',this._auditRunning);this._startButton.disabled=this._auditRunning;this._statusView.classList.toggle('hidden',!this._auditRunning);this._auditSelectorForm.classList.toggle('hidden',this._auditRunning);if(this._auditRunning) -this._headerTitleElement.textContent=Common.UIString('Auditing your web page \u2026');else -this._headerTitleElement.textContent=Common.UIString('Audits to perform');} -_updateStatus(statusMessage){if(!this._dialog) -return;this._statusElement.textContent=statusMessage;} -async _stopAndReattach(){await this._protocolService.detach();var emulationModel=self.singleton(Emulation.DeviceModeModel);emulationModel.enabledSetting().set(this._emulationEnabledBefore);emulationModel.deviceOutlineSetting().set(this._emulationOutlineEnabledBefore);emulationModel.toolbarControlsEnabledSetting().set(true);Emulation.InspectedPagePlaceholder.instance().update(true);Host.userMetrics.actionTaken(Host.UserMetrics.Action.Audits2Finished);var resourceTreeModel=SDK.targetManager.mainTarget().model(SDK.ResourceTreeModel);await resourceTreeModel.navigate(this._inspectedURL);this._auditRunning=false;this._updateButton();} -_buildReportUI(lighthouseResult){if(lighthouseResult===null){this._updateStatus(Common.UIString('Auditing failed.'));return;} -var optionElement=new Audits2.ReportSelector.Item(lighthouseResult,this._auditResultsElement,this._showLandingPage.bind(this));this._reportSelector.prepend(optionElement);this._hideDialog();} -_renderBugReport(err){console.error(err);this._statusElement.textContent='';this._statusIcon.classList.add('error');this._statusElement.createTextChild(Common.UIString('Ah, sorry! We ran into an error: '));this._statusElement.createChild('em').createTextChild(err.message);if(Audits2.Audits2Panel.KnownBugPatterns.some(pattern=>pattern.test(err.message))){var message=Common.UIString('Try to navigate to the URL in a fresh Chrome profile without any other tabs or '+'extensions open and try again.');this._statusElement.createChild('p').createTextChild(message);}else{this._createBugReportLink(err,this._statusElement);}} -_createBugReportLink(err,parentElem){var baseURI='https://github.com/GoogleChrome/lighthouse/issues/new?';var title=encodeURI('title=DevTools Error: '+err.message.substring(0,60));var issueBody=` -**Initial URL**: ${this._inspectedURL} -**Chrome Version**: ${navigator.userAgent.match(/Chrome\/(\S+)/)[1]} -**Error Message**: ${err.message} -**Stack Trace**: -\`\`\` -${err.stack} -\`\`\` - `;var body='&body='+encodeURIComponent(issueBody.trim());var reportErrorEl=parentElem.createChild('a','audits2-link audits2-report-error');reportErrorEl.href=baseURI+title+body;reportErrorEl.textContent=Common.UIString('Report this bug');reportErrorEl.target='_blank';} -_handleDrop(dataTransfer){var items=dataTransfer.items;if(!items.length) -return;var item=items[0];if(item.kind==='file'){var entry=items[0].webkitGetAsEntry();if(!entry.isFile) -return;entry.file(file=>{var reader=new FileReader();reader.onload=()=>this._loadedFromFile((reader.result));reader.readAsText(file);});}} -_loadedFromFile(profile){var data=JSON.parse(profile);if(!data['lighthouseVersion']) -return;this._buildReportUI((data));}};Audits2.Audits2Panel.ReportRenderer=class extends ReportRenderer{_renderReportNav(){return createDocumentFragment();} -_renderReportHeader(report){return createDocumentFragment();}};class ReportUIFeatures{initFeatures(report){}} -Audits2.Audits2Panel.KnownBugPatterns=[/Tracing already started/,/^Unable to load the page/,/^You must provide a url to the runner/,/^You probably have multiple tabs open/,];Audits2.Audits2Panel.Preset;Audits2.Audits2Panel.Presets=[{setting:Common.settings.createSetting('audits2.cat_pwa',true),configID:'pwa',title:'Progressive Web App',description:'Does this page meet the standard of a Progressive Web App'},{setting:Common.settings.createSetting('audits2.cat_perf',true),configID:'performance',title:'Performance',description:'How long does this app take to show content and become usable'},{setting:Common.settings.createSetting('audits2.cat_best_practices',true),configID:'best-practices',title:'Best practices',description:'Does this page follow best practices for modern web development'},{setting:Common.settings.createSetting('audits2.cat_a11y',true),configID:'accessibility',title:'Accessibility',description:'Is this page usable by people with disabilities or impairments'},];Audits2.ProtocolService=class extends Common.Object{constructor(){super();this._rawConnection=null;this._backend=null;this._backendPromise=null;this._status=null;} -attach(){return SDK.targetManager.interceptMainConnection(this._dispatchProtocolMessage.bind(this)).then(rawConnection=>{this._rawConnection=rawConnection;});} -startLighthouse(inspectedURL,categoryIDs){return this._send('start',{url:inspectedURL,categoryIDs});} -detach(){return Promise.resolve().then(()=>this._send('stop')).then(()=>this._backend.dispose()).then(()=>{delete this._backend;delete this._backendPromise;return this._rawConnection.disconnect();});} -registerStatusCallback(callback){this._status=callback;} -_dispatchProtocolMessage(message){this._send('dispatchProtocolMessage',{message:message});} -_initWorker(){this._backendPromise=Services.serviceManager.createAppService('audits2_worker','Audits2Service').then(backend=>{if(this._backend) -return;this._backend=backend;this._backend.on('statusUpdate',result=>this._status(result.message));this._backend.on('sendProtocolMessage',result=>this._sendProtocolMessage(result.message));});} -_sendProtocolMessage(message){this._rawConnection.sendMessage(message);} -_send(method,params){if(!this._backendPromise) -this._initWorker();return this._backendPromise.then(_=>this._backend.send(method,params));}};Audits2.ReportSelector=class{constructor(){this._comboBox=new UI.ToolbarComboBox(this._handleChange.bind(this),'audits2-report');this._comboBox.setMaxWidth(270);this._comboBox.setMinWidth(200);this._itemByOptionElement=new Map();} -_handleChange(event){var item=this._selectedItem();if(item) -item.select();} -_selectedItem(){var option=this._comboBox.selectedOption();return this._itemByOptionElement.get(option);} -comboBox(){return this._comboBox;} -prepend(item){var optionEl=item.optionElement();var selectEl=this._comboBox.selectElement();this._itemByOptionElement.set(optionEl,item);selectEl.insertBefore(optionEl,selectEl.firstElementChild);this._comboBox.select(optionEl);item.select();} -clearAll(){for(var elem of this._comboBox.options()) -this._itemByOptionElement.get(elem).delete();} -downloadSelected(){var item=this._selectedItem();item.download();}};Audits2.ReportSelector.Item=class{constructor(lighthouseResult,resultsView,showLandingCallback){this._lighthouseResult=lighthouseResult;this._resultsView=resultsView;this._showLandingCallback=showLandingCallback;this._reportContainer=null;var url=new Common.ParsedURL(lighthouseResult.url);var timestamp=lighthouseResult.generatedTime;this._element=createElement('option');this._element.label=`${url.domain()} ${new Date(timestamp).toLocaleString()}`;} -select(){this._renderReport();} -optionElement(){return this._element;} -delete(){if(this._element) -this._element.remove();this._showLandingCallback();} -download(){var url=new Common.ParsedURL(this._lighthouseResult.url).domain();var timestamp=this._lighthouseResult.generatedTime;var fileName=`${url}-${new Date(timestamp).toISO8601Compact()}.json`;Workspace.fileManager.save(fileName,JSON.stringify(this._lighthouseResult),true);} -_renderReport(){this._resultsView.removeChildren();if(this._reportContainer){this._resultsView.appendChild(this._reportContainer);return;} -this._reportContainer=this._resultsView.createChild('div','lh-vars lh-root lh-devtools');var dom=new DOM((this._resultsView.ownerDocument));var detailsRenderer=new Audits2.DetailsRenderer(dom);var categoryRenderer=new CategoryRenderer(dom,detailsRenderer);var renderer=new Audits2.Audits2Panel.ReportRenderer(dom,categoryRenderer);var templatesHTML=Runtime.cachedResources['audits2/lighthouse/templates.html'];var templatesDOM=new DOMParser().parseFromString(templatesHTML,'text/html');if(!templatesDOM) -return;renderer.setTemplateContext(templatesDOM);renderer.renderReport(this._lighthouseResult,this._reportContainer);}};Audits2.DetailsRenderer=class extends DetailsRenderer{constructor(dom){super(dom);this._onMainFrameNavigatedPromise=null;} -renderNode(item){var element=super.renderNode(item);this._replaceWithDeferredNodeBlock(element,item);return element;} -async _replaceWithDeferredNodeBlock(origElement,detailsItem){var mainTarget=SDK.targetManager.mainTarget();if(!this._onMainFrameNavigatedPromise){var resourceTreeModel=mainTarget.model(SDK.ResourceTreeModel);this._onMainFrameNavigatedPromise=resourceTreeModel.once(SDK.ResourceTreeModel.Events.MainFrameNavigated);} -await this._onMainFrameNavigatedPromise;var domModel=mainTarget.model(SDK.DOMModel);if(!detailsItem.path) -return;var nodeId=await domModel.pushNodeByPathToFrontend(detailsItem.path);if(!nodeId) -return;var node=domModel.nodeForId(nodeId);if(!node) -return;var element=Components.DOMPresentationUtils.linkifyNodeReference(node,undefined,detailsItem.snippet);origElement.title='';origElement.textContent='';origElement.appendChild(element);}};;Runtime.cachedResources["audits2/audits2Dialog.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.audits2-view {\n margin: 7px 20px;\n flex: auto;\n align-items: center;\n}\n\n.audits2-view .dialog-close-button {\n position: absolute;\n top: 10px;\n right: 10px;\n}\n\nheader {\n color: #666;\n font-weight: bold;\n font-size: 14px;\n}\n\n.audits2-form label {\n display: flex;\n}\n\n.audits2-form label div {\n display: inline;\n}\n\n.audits2-status {\n flex: auto;\n align-items: center;\n color: #666;\n}\n\n.audits2-status .icon {\n width: 64px;\n height: 64px;\n margin: 20px;\n animation: spinner-animation 1200ms linear infinite;\n transform-origin: 50% 50%;\n padding: 4px;\n}\n\n.audits2-status .icon::before {\n display: inline-block;\n border: 4px solid #1565C0;\n border-radius: 28px;\n width: 56px;\n height: 56px;\n content: \"\";\n position: absolute;\n box-sizing: border-box;\n}\n\n.audits2-status .icon::after {\n display: inline-block;\n width: 24px;\n height: 28px;\n background: white;\n position: absolute;\n content: \"\";\n}\n\n.audits2-report-error {\n display: block;\n margin-top: 5px;\n}\n\nbutton {\n margin: 15px 10px;\n}\n\n.audits2-status .icon.error,\n.audits2-status .icon.error::before,\n.audits2-status .icon.error::after {\n display: none;\n}\n\n.audits2-launcher-row {\n padding: 6px;\n}\n\n.audits2-launcher-description {\n padding: 3px 0 0 22px;\n}\n\n.audits2-dialog-help-text {\n color: red;\n margin-top: 10px;\n}\n\n.audits2-dialog-buttons {\n justify-content: center;\n}\n\n@keyframes spinner-animation {\n from { transform: rotate(0); }\n to { transform: rotate(360deg); }\n\n/*# sourceURL=audits2/audits2Dialog.css */";Runtime.cachedResources["audits2/audits2Panel.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.toolbar {\n border-bottom: 1px solid #ccc;\n}\n\n.audits2-logo {\n width: 210px;\n height: 200px;\n flex-shrink: 0;\n background-repeat: no-repeat;\n background-size: contain;\n margin-top: 10px;\n background-image: url(Images/audits_logo.svg);\n}\n\n.audits2-landing-page {\n display: flex;\n align-items: center;\n justify-content: center;\n overflow: auto;\n}\n\n\n.audits2-landing-center {\n display: flex;\n align-items: center;\n justify-content: center;\n max-width: 400px;\n margin: 50px;\n}\n\n.audits2-landing-center > * {\n flex-shrink: 0;\n}\n\n.audits2-landing-text {\n color: #666;\n}\n\n.audits2-landing-bold-text {\n font-weight: bold;\n}\n\n.lh-root {\n --report-menu-width: 0;\n user-select: initial;\n background: #fff;\n}\n\n.lh-root .lh-container {\n word-wrap: normal;\n}\n\n.audits2-landing-center button {\n margin-top: 20px;\n}\n\n.audits2-results-container {\n overflow-y: scroll;\n position: relative;\n}\n\n/*# sourceURL=audits2/audits2Panel.css */";Runtime.cachedResources["audits2/lighthouse/report-styles.css"]="/**\n * @license Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n */\n\n.lh-vars {\n --text-font-family: Roboto, Helvetica, Arial, sans-serif;\n --monospace-font-family: 'Menlo', 'dejavu sans mono', 'Consolas', 'Lucida Console', monospace;\n --body-font-size: 14px;\n --body-line-height: 18px;\n --subheader-font-size: 16px;\n --subheader-line-height: 20px;\n --header-font-size: 20px;\n --header-line-height: 24px;\n --title-font-size: 24px;\n --title-line-height: 28px;\n --caption-font-size: 12px;\n --caption-line-height: 16px;\n --default-padding: 12px;\n --section-padding: 20px;\n --section-indent: 16px;\n --audit-group-indent: 16px;\n --audit-indent: 16px;\n --expandable-indent: 20px;\n --secondary-text-color: #565656;\n /*--accent-color: #3879d9;*/\n --fail-color: #df332f;\n --pass-color: #2b882f;\n --informative-color: #0c50c7;\n --manual-color: #757575;\n --average-color: #ef6c00; /* md orange 800 */\n --warning-color: #ffab00; /* md amber a700 */\n --report-border-color: #ccc;\n --report-secondary-border-color: #ebebeb;\n --metric-timeline-rule-color: #b3b3b3;\n --report-width: calc(60 * var(--body-font-size));\n --report-menu-width: calc(20 * var(--body-font-size));\n --report-content-width: calc(var(--report-width) + var(--report-menu-width));\n --navitem-font-size: var(--body-font-size);\n --navitem-line-height: var(--body-line-height);\n --navitem-hpadding: var(--body-font-size);\n --navitem-vpadding: calc(var(--navitem-line-height) / 2);\n --lh-score-highlight-bg: #fafafa;\n --lh-score-icon-background-size: 24px;\n --lh-score-margin: 12px;\n --lh-table-header-bg: #ccc;\n --lh-table-higlight-bg: #fafafa;\n --lh-sparkline-height: 5px;\n --lh-sparkline-thin-height: 3px;\n --lh-filmstrip-thumbnail-width: 60px;\n --lh-audit-score-width: calc(5 * var(--body-font-size));\n --lh-category-score-width: calc(5 * var(--body-font-size));\n --lh-audit-vpadding: 8px;\n --lh-audit-hgap: 12px;\n --lh-audit-group-vpadding: 12px;\n --lh-section-vpadding: 12px;\n --pass-icon-url: url('data:image/svg+xml;utf8,<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" xmlns=\"http://www.w3.org/2000/svg\"><path stroke=\"#007F04\" stroke-width=\"1.5\" d=\"M1 5.75l3.5 3.5 6.5-6.5\" fill=\"none\" fill-rule=\"evenodd\"/></svg>');\n --fail-icon-url: url('data:image/svg+xml;utf8,<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" xmlns=\"http://www.w3.org/2000/svg\"><g stroke=\"#EE1D0A\" stroke-width=\"1.5\" fill=\"none\" fill-rule=\"evenodd\"><path d=\"M2 10l8-8M10 10L2 2\"/></g></svg>');\n --collapsed-icon-url: url('data:image/svg+xml;utf8,<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" xmlns=\"http://www.w3.org/2000/svg\"><g fill=\"none\" fill-rule=\"evenodd\"><path fill=\"none\" d=\"M0 0h12v12H0z\"/><path fill=\"hsl(0, 0%, 60%)\" d=\"M3 2l6 4-6 4z\"/></g></svg>');\n --expanded-icon-url: url('data:image/svg+xml;utf8,<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" xmlns=\"http://www.w3.org/2000/svg\"><g fill=\"none\" fill-rule=\"evenodd\"><path fill=\"none\" d=\"M0 0h12v12H0z\"/><path fill=\"hsl(0, 0%, 60%)\" d=\"M10 3L6 9 2 3z\"/></g></svg>');\n}\n\n.lh-vars.lh-devtools {\n --text-font-family: '.SFNSDisplay-Regular', 'Helvetica Neue', 'Lucida Grande', sans-serif;\n --monospace-font-family: 'Menlo', 'dejavu sans mono', 'Consolas', 'Lucida Console', monospace;\n --body-font-size: 12px;\n --body-line-height: 16px;\n --subheader-font-size: 14px;\n --subheader-line-height: 18px;\n --header-font-size: 16px;\n --header-line-height: 20px;\n --title-font-size: 20px;\n --title-line-height: 24px;\n --caption-font-size: 11px;\n --caption-line-height: 14px;\n --default-padding: 12px;\n --section-padding: 16px;\n --section-indent: 16px;\n --audit-group-indent: 16px;\n --audit-indent: 16px;\n --expandable-indent: 16px;\n\n --lh-audit-vpadding: 4px;\n --lh-audit-hgap: 12px;\n --lh-audit-group-vpadding: 8px;\n --lh-section-vpadding: 8px;\n}\n\n@keyframes fadeIn {\n 0% { opacity: 0;}\n 100% { opacity: 0.6;}\n}\n\n.lh-root * {\n box-sizing: border-box;\n}\n\n.lh-root {\n font-family: var(--text-font-family);\n font-size: var(--body-font-size);\n margin: 0;\n line-height: var(--body-line-height);\n background: #f5f5f5;\n scroll-behavior: smooth;\n}\n\n.lh-root :focus {\n outline: -webkit-focus-ring-color auto 3px;\n}\n\n.lh-root [hidden] {\n display: none !important;\n}\n\na {\n color: #0c50c7;\n}\n\nsummary {\n cursor: pointer;\n}\n\n.lh-details {\n font-size: var(--body-font-size);\n margin-top: var(--default-padding);\n}\n\n.lh-details[open] summary {\n margin-bottom: var(--default-padding);\n}\n\n.lh-details summary::-webkit-details-marker {\n color: #9e9e9e;\n}\n\n.lh-details.flex .lh-code {\n max-width: 70%;\n}\n\n/* Report header */\n\n.report-icon {\n opacity: 0.7;\n}\n.report-icon:hover {\n opacity: 1;\n}\n.report-icon[disabled] {\n opacity: 0.3;\n pointer-events: none;\n}\n\n.report-icon--share {\n background-image: url('data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0z\"/><path d=\"M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z\"/></svg>');\n}\n.report-icon--print {\n background-image: url('data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path d=\"M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z\"/><path fill=\"none\" d=\"M0 0h24v24H0z\"/></svg>');\n}\n.report-icon--copy {\n background-image: url('data:image/svg+xml;utf8,<svg height=\"24\" viewBox=\"0 0 24 24\" width=\"24\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z\"/></svg>');\n}\n.report-icon--open {\n background-image: url('data:image/svg+xml;utf8,<svg height=\"24\" viewBox=\"0 0 24 24\" width=\"24\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h4v-2H5V8h14v10h-4v2h4c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm-7 6l-4 4h3v6h2v-6h3l-4-4z\"/></svg>');\n}\n.report-icon--download {\n background-image: url('data:image/svg+xml;utf8,<svg height=\"24\" viewBox=\"0 0 24 24\" width=\"24\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z\"/><path d=\"M0 0h24v24H0z\" fill=\"none\"/></svg>');\n}\n\n/* List */\n.lh-list {\n font-size: smaller;\n margin-top: var(--default-padding);\n}\n\n.lh-list__items {\n padding-left: var(--default-padding);\n}\n\n.lh-list__item {\n margin-bottom: 2px;\n}\n\n/* Node */\n.lh-node {\n display: block;\n font-family: var(--monospace-font-family);\n word-break: break-word;\n color: hsl(174, 100%, 27%);\n}\nspan.lh-node:hover {\n background: hsl(0, 0%, 98%);\n border-radius: 2px;\n}\n\n/* Card */\n.lh-scorecards {\n display: flex;\n flex-wrap: wrap;\n}\n.lh-scorecard {\n display: flex;\n align-items: center;\n justify-content: center;\n flex: 0 0 calc(12 * var(--body-font-size));\n flex-direction: column;\n padding: var(--default-padding);\n padding-top: calc(32px + var(--default-padding));\n border-radius: 3px;\n margin-right: var(--default-padding);\n position: relative;\n line-height: inherit;\n border: 1px solid #ebebeb;\n}\n.lh-scorecard__title {\n background-color: #eee;\n position: absolute;\n top: 0;\n right: 0;\n left: 0;\n display: flex;\n justify-content: center;\n align-items: center;\n padding: calc(var(--default-padding) / 2);\n}\n.lh-scorecard__value {\n font-size: calc(1.6 * var(--body-font-size));\n}\n.lh-scorecard__target {\n margin-top: calc(var(--default-padding) / 2);\n}\n\n/* Score */\n\n.lh-score {\n display: flex;\n align-items: flex-start;\n}\n\n.lh-score__value {\n flex: none;\n margin-left: var(--lh-score-margin);\n width: calc(var(--lh-audit-score-width) - var(--lh-score-margin));\n position: relative;\n font-weight: bold;\n top: 1px;\n text-align: right;\n}\n\n.lh-score__value::after {\n content: '';\n position: absolute;\n right: 0;\n top: 0;\n bottom: 0;\n border-radius: inherit;\n width: 16px;\n}\n\n.lh-score--informative .lh-score__value {\n color: var(--informative-color);\n border-radius: 50%;\n top: 3px;\n}\n\n.lh-score--informative .lh-score__value::after {\n display: none;\n background: url('data:image/svg+xml;utf8,<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title>info</title><path d=\"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z\" fill=\"hsl(218, 89%, 41%)\"/></svg>') no-repeat 50% 50%;\n background-size: var(--lh-score-icon-background-size);\n}\n\n.lh-score--manual .lh-score__value::after {\n background: url('data:image/svg+xml;utf8,<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" xmlns=\"http://www.w3.org/2000/svg\"><title>manual</title><path d=\"M2 5h8v2H2z\" fill=\"hsl(0, 0%, 100%)\" fill-rule=\"evenodd\"/></svg>') no-repeat 50% 50%;\n background-size: 18px;\n background-color: var(--manual-color);\n width: 20px;\n height: 20px;\n position: relative;\n}\n\n.lh-score__value--binary {\n color: transparent !important;\n}\n\n/* No icon for audits with number scores. */\n.lh-score__value:not(.lh-score__value--binary)::after {\n content: none;\n}\n\n.lh-score__value--pass {\n color: var(--pass-color);\n}\n\n.lh-score__value--pass::after {\n background: var(--pass-icon-url) no-repeat center center / 12px 12px;\n}\n\n.lh-score__value--average {\n color: var(--average-color);\n}\n\n.lh-score__value--average::after {\n background: none;\n content: '!';\n color: var(--average-color);\n display: flex;\n justify-content: center;\n align-items: center;\n font-weight: 500;\n font-size: 15px;\n}\n\n.lh-score__value--fail {\n color: var(--fail-color);\n}\n\n.lh-score__value--fail::after {\n background: var(--fail-icon-url) no-repeat center center / 12px 12px;\n}\n\n.lh-score__description {\n font-size: var(--body-font-size);\n color: var(--secondary-text-color);\n line-height: var(--body-line-height);\n}\n\n.lh-score__snippet {\n align-items: center;\n justify-content: space-between;\n /*outline: none;*/\n}\n\n.lh-score__snippet::-moz-list-bullet {\n display: none;\n}\n\n.lh-score__title {\n flex: 1;\n}\n\n.lh-toggle-arrow {\n background: var(--collapsed-icon-url) no-repeat center center / 12px 12px;\n background-color: transparent;\n width: 12px;\n height: 12px;\n flex: none;\n transition: transform 150ms ease-in-out;\n cursor: pointer;\n border: none;\n order: -1;\n margin-right: calc(var(--expandable-indent) - 12px);\n align-self: flex-start;\n}\n\n.lh-toggle-arrow-unexpandable {\n visibility: hidden;\n}\n\n/* Expandable Details (Audit Groups, Audits) */\n\n.lh-score__header {\n order: -1;\n flex: 1;\n}\n\n.lh-expandable-details {\n padding-left: var(--expandable-indent);\n}\n\n.lh-expandable-details__summary {\n display: flex;\n align-items: center;\n cursor: pointer;\n margin-left: calc(0px - var(--expandable-indent));\n}\n\n.lh-audit-group[open] > .lh-audit-group__summary > .lh-toggle-arrow,\n.lh-expandable-details[open] > .lh-expandable-details__summary > .lh-toggle-arrow {\n background-image: var(--expanded-icon-url);\n}\n\n.lh-audit-group__summary::-webkit-details-marker,\n.lh-expandable-details__summary::-webkit-details-marker {\n display: none;\n}\n\n.lh-score__snippet .lh-toggle-arrow {\n margin-top: calc((var(--body-line-height) - 12px) / 2);\n}\n\n/* Perf Timeline */\n\n.lh-timeline-container {\n overflow: hidden;\n border-top: 1px solid var(--metric-timeline-rule-color);\n}\n\n.lh-timeline {\n padding: 0;\n padding-bottom: 0;\n width: calc(var(--lh-filmstrip-thumbnail-width) * 10 + var(--default-padding) * 2);\n}\n\n.lh-narrow .lh-timeline-container {\n width: calc(100vw - var(--section-padding) * 2);\n overflow-x: scroll;\n}\n\n.lh-devtools .lh-timeline-container {\n width: 100%;\n overflow-x: scroll;\n}\n\n/* Perf Timeline Metric */\n\n.lh-timeline-metric {\n position: relative;\n margin-bottom: calc(2 * var(--lh-audit-vpadding));\n padding-top: var(--lh-audit-vpadding);\n border-top: 1px solid var(--report-secondary-border-color);\n}\n\n.lh-timeline-metric__header {\n display: flex;\n}\n\n.lh-timeline-metric__details {\n order: -1;\n}\n\n.lh-timeline-metric__title {\n font-size: var(--body-font-size);\n line-height: var(--body-line-height);\n display: flex;\n}\n\n.lh-timeline-metric__name {\n flex: 1;\n}\n\n.lh-timeline-metric__description {\n color: var(--secondary-text-color);\n}\n\n.lh-timeline-metric__value {\n width: var(--lh-audit-score-width);\n text-align: right;\n}\n\n.lh-timeline-metric--pass .lh-timeline-metric__value {\n color: var(--pass-color);\n}\n\n.lh-timeline-metric--average .lh-timeline-metric__value {\n color: var(--average-color);\n}\n\n.lh-timeline-metric--fail .lh-timeline-metric__value {\n color: var(--fail-color);\n}\n\n.lh-timeline-metric__sparkline {\n position: absolute;\n left: 0;\n right: 0;\n top: -1px;\n height: 3px;\n width: 100%;\n}\n\n.lh-timeline-metric__sparkline .lh-sparkline__bar {\n float: none;\n}\n\n.lh-timeline-metric--pass .lh-sparkline__bar {\n background: var(--pass-color);\n}\n\n.lh-timeline-metric--average .lh-sparkline__bar {\n background: var(--average-color);\n}\n\n.lh-timeline-metric--fail .lh-sparkline__bar {\n background: var(--fail-color);\n}\n\n.lh-timeline-metric .lh-debug {\n margin-left: var(--expandable-indent);\n}\n\n/* Perf Hint */\n\n.lh-perf-hint {\n padding-top: var(--lh-audit-vpadding);\n padding-bottom: var(--lh-audit-vpadding);\n border-top: 1px solid var(--report-secondary-border-color);\n}\n\n.lh-perf-hint:last-of-type {\n border-bottom: none;\n}\n\n.lh-perf-hint__summary {\n display: flex;\n align-items: flex-start;\n flex-wrap: wrap;\n min-height: calc(var(--body-line-height) + var(--caption-line-height));\n}\n\n.lh-perf-hint__summary .lh-toggle-arrow {\n margin-top: calc((var(--subheader-line-height) - 12px) / 2);\n}\n\n.lh-perf-hint__summary .lh-debug {\n width: calc(100% - var(--expandable-indent));\n margin: 0 var(--expandable-indent);\n}\n\n.lh-perf-hint__title {\n font-size: var(--body-font-size);\n flex: 10;\n}\n\n.lh-perf-hint__sparkline {\n flex: 0 0 50%;\n margin-top: calc((var(--body-line-height) - var(--lh-sparkline-height)) / 2);\n}\n\n.lh-perf-hint__sparkline .lh-sparkline {\n width: 100%;\n float: right;\n margin: 0;\n}\n\n.lh-perf-hint__stats {\n text-align: right;\n flex: 0 0 var(--lh-audit-score-width);\n}\n\n.lh-perf-hint__primary-stat {\n font-size: var(--body-font-size);\n line-height: var(--body-line-height);\n}\n\n.lh-perf-hint__secondary-stat {\n font-size: var(--caption-font-size);\n line-height: var(--caption-line-height);\n}\n\n.lh-perf-hint__description {\n color: var(--secondary-text-color);\n margin-top: calc(var(--default-padding) / 2);\n}\n\n.lh-perf-hint--pass .lh-perf-hint__stats {\n color: var(--pass-color);\n}\n\n.lh-perf-hint--pass .lh-sparkline__bar {\n background: var(--pass-color);\n}\n\n.lh-perf-hint--average .lh-sparkline__bar {\n background: var(--average-color);\n}\n\n.lh-perf-hint--average .lh-perf-hint__stats {\n color: var(--average-color);\n}\n\n.lh-perf-hint--fail .lh-sparkline__bar {\n background: var(--fail-color);\n}\n\n.lh-perf-hint--fail .lh-perf-hint__stats {\n color: var(--fail-color);\n}\n\n/* Filmstrip */\n\n.lh-filmstrip {\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n padding-bottom: var(--default-padding);\n}\n\n.lh-filmstrip__frame {\n text-align: right;\n position: relative;\n}\n\n.lh-filmstrip__timestamp {\n margin-bottom: calc(0.5 * var(--caption-line-height));\n font-size: var(--caption-font-size);\n line-height: var(--caption-line-height);\n padding-top: 1px;\n padding-right: 6px;\n}\n\n.lh-filmstrip__timestamp::before {\n content: '';\n height: 7px;\n width: 2px;\n background: var(--metric-timeline-rule-color);\n position: absolute;\n right: 0;\n top: -2px;\n}\n\n.lh-filmstrip__thumbnail {\n border: 1px solid var(--report-secondary-border-color);\n max-height: 100px;\n}\n\n/* Sparkline */\n\n.lh-sparkline {\n margin: 5px;\n height: var(--lh-sparkline-height);\n width: 100%;\n}\n\n.lh-sparkline--thin {\n height: calc(var(--lh-sparkline-height) / 2);\n}\n\n.lh-sparkline__bar {\n background: var(--warning-color);\n height: 100%;\n float: right;\n position: relative;\n}\n\n/* correlate metric end location with sparkline */\n.lh-timeline-metric:hover .lh-sparkline__bar::after {\n content: '';\n height: 100vh;\n width: 2px;\n background: inherit;\n position: absolute;\n right: 0;\n bottom: 0;\n opacity: 0;\n animation: fadeIn 150ms;\n animation-fill-mode: forwards;\n}\n\n/* Audit */\n\n.lh-audit {\n margin-bottom: var(--lh-audit-vpadding);\n padding-top: var(--lh-audit-vpadding);\n border-top: 1px solid var(--report-secondary-border-color);\n}\n\n.lh-audit:last-of-type {\n border-bottom: none;\n}\n\n.lh-audit > .lh-score {\n font-size: var(--body-font-size);\n}\n\n.lh-audit .lh-debug {\n margin-left: var(--expandable-indent);\n margin-right: var(--lh-audit-score-width);\n}\n\n/* Audit Group */\n\n.lh-audit-group {\n padding-top: var(--lh-audit-group-vpadding);\n border-top: 1px solid var(--report-secondary-border-color);\n padding-left: var(--expandable-indent);\n}\n\n.lh-audit-group__header {\n font-size: var(--subheader-font-size);\n line-height: var(--subheader-line-height);\n}\n\n.lh-audit-group__summary {\n display: flex;\n align-items: center;\n margin-bottom: var(--lh-audit-group-vpadding);\n margin-left: calc(0px - var(--expandable-indent));\n}\n\n.lh-audit-group__summary .lh-toggle-arrow {\n margin-top: calc((var(--subheader-line-height) - 12px) / 2);\n}\n\n.lh-audit-group__description {\n font-size: var(--body-font-size);\n color: var(--secondary-text-color);\n margin-top: calc(0px - var(--lh-audit-group-vpadding));\n margin-bottom: var(--lh-audit-group-vpadding);\n line-height: var(--body-line-height);\n}\n\n\n.lh-debug {\n font-size: var(--caption-font-size);\n line-height: var(--caption-line-height);\n color: var(--fail-color);\n margin-top: 3px;\n}\n\n.lh-debug::before {\n display: none;\n content: '';\n background: url('data:image/svg+xml;utf8,<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title>warn</title><path d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z\" fill=\"hsl(40, 100%, 50%)\"/></svg>') no-repeat 50% 50%;\n background-size: contain;\n width: 20px;\n height: 20px;\n position: relative;\n margin-right: calc(var(--default-padding) / 2);\n top: 5px;\n}\n\n\n/* Report */\n\n.lh-container {\n display: flex;\n max-width: var(--report-content-width);\n word-wrap: break-word;\n margin: 0 auto;\n}\n\n.lh-report {\n margin-left: var(--report-menu-width);\n background-color: #fff;\n padding-top: var(--report-header-height);\n}\n@media screen {\n .lh-report {\n width: var(--report-width);\n }\n}\n\n.lh-exception {\n font-size: large;\n}\n\n.lh-text__url {\n white-space: nowrap;\n}\n\n.lh-code {\n text-overflow: ellipsis;\n white-space: pre-line;\n margin-top: 0;\n}\n\n.lh-scores-header {\n display: flex;\n justify-content: center;\n overflow-x: hidden;\n padding: var(--section-padding);\n border-bottom: 1px solid var(--report-border-color);\n}\n.lh-scores-header__solo {\n padding: 0;\n border: 0;\n}\n\n.lh-categories {\n width: 100%;\n overflow: hidden;\n}\n\n.lh-category {\n padding: var(--section-padding);\n border-top: 1px solid var(--report-border-color);\n}\n\n/* section hash link jump should preserve fixed header\n https://css-tricks.com/hash-tag-links-padding/\n*/\n.lh-category > .lh-permalink {\n margin-top: calc((var(--report-header-height) + var(--default-padding)) * -1);\n padding-bottom: calc(var(--report-header-height) + var(--default-padding));\n display: block;\n visibility: hidden;\n}\n\n.lh-category:first-of-type {\n border: none;\n}\n\n.lh-category > .lh-score {\n font-size: var(--header-font-size);\n padding-bottom: var(--lh-section-vpadding);\n}\n\n.lh-category > .lh-score .lh-score__value,\n.lh-category > .lh-score .lh-score__gauge .lh-gauge__label {\n display: none;\n}\n\n.lh-category .lh-score__gauge {\n margin-left: var(--section-indent);\n flex-basis: var(--circle-size);\n flex-shrink: 0;\n}\n\n.lh-category .lh-score__gauge .lh-gauge {\n --circle-size: calc(2.5 * var(--header-font-size));\n}\n\n/* Category snippet shouldnt have pointer cursor. */\n.lh-category > .lh-score .lh-score__snippet {\n cursor: initial;\n}\n\n.lh-category > .lh-score .lh-score__title {\n font-size: var(--header-font-size);\n line-height: var(--header-line-height);\n}\n\n.lh-passed-audits[open] summary.lh-passed-audits-summary {\n margin-bottom: calc(var(--default-padding) * 2);\n}\n\nsummary.lh-passed-audits-summary {\n margin: calc(var(--default-padding) * 2) var(--default-padding);\n margin-left: var(--default-padding);\n margin-bottom: 0;\n font-size: 15px;\n display: flex;\n align-items: center;\n}\n\n#lh-log {\n position: fixed;\n background-color: #323232;\n color: #fff;\n min-height: 48px;\n min-width: 288px;\n padding: 16px 24px;\n box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);\n border-radius: 2px;\n margin: 12px;\n font-size: 14px;\n cursor: default;\n transition: transform 0.3s, opacity 0.3s;\n transform: translateY(100px);\n opacity: 0;\n -webkit-font-smoothing: antialiased;\n bottom: 0;\n left: 0;\n z-index: 3;\n}\n\n#lh-log.show {\n opacity: 1;\n transform: translateY(0);\n}\n\n/* 964 fits the min-width of the filmstrip */\n@media screen and (max-width: 964px) {\n .lh-report {\n margin-left: 0;\n width: 100%;\n min-width: 400px;\n }\n}\n\n@media print {\n body {\n -webkit-print-color-adjust: exact; /* print background colors */\n }\n .lh-container {\n display: block;\n }\n .lh-report {\n margin-left: 0;\n padding-top: 0;\n }\n .lh-categories {\n margin-top: 0;\n }\n}\n\n.lh-table {\n --image-preview-size: 24px;\n border: 1px solid var(--report-secondary-border-color);\n border-collapse: collapse;\n table-layout: fixed;\n width: 100%;\n}\n\n.lh-table thead {\n background: var(--lh-table-header-bg);\n}\n\n.lh-table tbody tr:nth-child(even) {\n background-color: var(--lh-table-higlight-bg);\n}\n\n.lh-table th,\n.lh-table td {\n padding: 10px;\n overflow: auto;\n}\n\n.lh-table-column--text {\n text-align: right;\n}\n\n.lh-table-column--thumbnail {\n width: calc(var(--image-preview-size) * 2);\n}\n\n.lh-table-column--url {\n text-align: left;\n min-width: 250px;\n white-space: nowrap;\n}\n\n.lh-thumbnail {\n height: var(--image-preview-size);\n width: var(--image-preview-size);\n object-fit: contain;\n}\n\n/*# sourceURL=report.styles.css */\n\n/*# sourceURL=audits2/lighthouse/report-styles.css */";Runtime.cachedResources["audits2/lighthouse/templates.html"]="<!-- Lighthouse category score -->\n<template id=\"tmpl-lh-category-score\">\n <div class=\"lh-score\">\n <div class=\"lh-score__value\"><!-- fill me --></div>\n <div class=\"lh-score__gauge\"></div>\n <div class=\"lh-score__header\">\n <div class=\"lh-score__snippet\">\n <span class=\"lh-score__title\"><!-- fill me --></span>\n </div>\n <div class=\"lh-score__description\"><!-- fill me --></div>\n </div>\n </div>\n</template>\n\n<!-- Lighthouse audit score -->\n<template id=\"tmpl-lh-audit-score\">\n <div class=\"lh-score\">\n <div class=\"lh-score__value\"><!-- fill me --></div>\n <details class=\"lh-score__header lh-expandable-details\">\n <summary class=\"lh-score__snippet lh-expandable-details__summary\">\n <span class=\"lh-score__title\"><!-- fill me --></span>\n <div class=\"lh-toggle-arrow\" title=\"See audits\"></div>\n </summary>\n <div class=\"lh-score__description\"><!-- fill me --></div>\n </details>\n </div>\n</template>\n\n<!-- Lighthouse timeline metric -->\n<template id=\"tmpl-lh-timeline-metric\">\n <div class=\"lh-timeline-metric\">\n <div class=\"lh-timeline-metric__sparkline\">\n <div class=\"lh-sparkline__bar\"></div>\n </div>\n <div class=\"lh-timeline-metric__header\">\n <div class=\"lh-timeline-metric__value\"><!-- fill me --></div>\n <details class=\"lh-timeline-metric__details lh-expandable-details\">\n <summary class=\"lh-timeline-metric__summary lh-expandable-details__summary\">\n <span class=\"lh-timeline-metric__title\"><!-- fill me --></span>\n <div class=\"lh-toggle-arrow\" title=\"See audits\"></div>\n </summary>\n <div class=\"lh-timeline-metric__description\"><!-- fill me --></div>\n </details>\n </div>\n </div>\n</template>\n\n<!-- Lighthouse left nav -->\n<template id=\"tmpl-lh-leftnav\">\n <style>\n .lh-leftnav {\n width: var(--report-menu-width);\n border-right: 1px solid var(--report-border-color);\n position: fixed;\n height: 100%;\n background: #fff;\n will-change: transform; /* prevent excessive paints */\n z-index: 2;\n }\n .lh-leftnav__item {\n padding: var(--navitem-vpadding) var(--navitem-hpadding);\n color: var(--secondary-text-color);\n font-size: var(--navitem-font-size);\n line-height: var(--navitem-line-height);\n display: flex;\n justify-content: space-between;\n text-decoration: none;\n color: inherit;\n }\n .leftnav-item__score {\n background: transparent;\n }\n .leftnav-item__score::after {\n content: '';\n }\n .leftnav-item__score.lh-score__value--pass {\n color: var(--pass-color);\n }\n .leftnav-item__score.lh-score__value--average {\n color: var(--average-color);\n }\n .leftnav-item__score.lh-score__value--fail {\n color: var(--fail-color);\n }\n .leftnav__header {\n padding: 0 20px;\n margin-bottom: var(--navitem-vpadding);\n height: 115px;\n font-size: 18px;\n display: flex;\n flex-direction: column;\n justify-content: center;\n background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZoAAADeCAYAAAAEuMatAABPH0lEQVR4Ae3dBZyk1ZX38d+59z5PSfv0uMPg7iQB4oRkIbrZbGSz7Js368mbrLtE1903nuzGVuIGgQgxCBbIAAPjru1d8sg9b091fxhBMsN0T1V13+/ncz5VNRaFP+ee89zi8QRBEARBEARBEARBEARBIARB0BTZuru7Be0HOoFYlcirAqgIiaoMGKtbAaWNBYFkD9/JzAuC4H3/57KeZKB0Wb/jea9YVrowFbNC0KVAj4Cr50olzTACCKCy11j/QLG/tlmEb5bXp18GdtFmgkDSy3lS7qxzLKsWzSfVcWCMIAiOzxfvuIZV3S+lp/hSUk5DYSzzCIcIkORKJcsQDqOg3gBgUj8qyP8YlU8DnyEI2oTsfc4ynkjvm65eaJ9z8cuMdQvwmoCpgAwiOlH2AERDCONABZUxICUIgob6R7/ynOz7D/+yjlRuEE8BryAccixBczQBUXCj+Xc73difhcAJ2oFUn1PmcV19dnfxZ1/yM2CXkucJIEeWGsCD1IAKSBUvIyCDGD0AphFEUz9fb9QcEATZvetPSd/7uT/2ef56CpFgDIecYNBMUSOAYES+YJ37XeA+WlQQyN6Xr+bxzP+XX3upJEPPIPdVnpwB5LBXEBQa5UHGgFGQUXIzBDIETFakg6B1IGMWCILq337+NfnajX8lxcISjDBl2oPmcCIMl7fXfh/4R1pQEMjwhX0cLfq5a1eUXn3lGxgZtSCeE2MeLcEAOZABOaIJyDAwAAxh4iFERqaCaQzrhwGlxQWBfv3+qP4/t/xZVo9+RZxhykkJGgCNDEZ4rxV5C1ChtQSho1nO0fr/6NWvMPN6Lif3dWaGABzVCZmpSoAaUMdSRRgGBkEGcbof0RGgAlIBMoKgSe5ev6KcRoVC18Z1C0758Hve7p39SZwBOMlBc4hFPmeM3AgM0iKCwEmqHK7nRef1miXzz6JST5k5etir50gCFIAiOX3AUkBAIUUQqaIyBhMlOlGMAIMoQzg9gGUMJQFSQDlOQbB7sLsDm5f/4+tXdW7b1rM0sqxQdInAotTbRV+9/8z+pEp3LnQV8aU/tz+39PSC70kkotly9MWo/9SY6XtNWIVuFYFsePHZHG78rTc+/fxz6jdQI6U1CWAOKwV8o+RgSRUYRhhBGUAZQnQIzBCqw+BrIYACgA994+m9Y2OF00yUnXLHnlWrvn3XmhVdsEpFVwBLKnWzMMuwIkxSEIFyQfEiGFL+2Pw6L+E/qVFGEYCmdjQABWrcaZ73wG8W/uPm3fPjnRbdirLJCI+IMAgoJ1EQyIpfyJnCaZ25fOqtf/36nrR6FpiE9iOPE0QeSBBJUFJEx0GGEBkE9qN+GBgDxhEZAZRgVvnSHWeVXSlddd8jq9d89vbzzi0V9FxVOXvTvu4VWUqXCOWCgUIBlENElMejQBXhzfLX/LK8m+qhkGmJoBGUAhU+ZH6Pf+U36aChKjAK7BR4QIW1ueUhYKsxbAH2MUOCQC55hTKFC/vW9r3/Tz76C4wXSoBn9pAnKIOQg1SBg1UBHQUZRBgAOYD3gwg1aFRK0NLW7Z7fsXt/39L33HTVeXGUP21guPviezb2L7OWJc7SFztAaYic8lRUEJ4nX+Ov5KcxeDIcQMsEDYAhx+L5Q/cRviYvpIjyBKoi7B4fZHNW415V+a6HtcBuYIBpEASy6gplCl/9t387/7SF219LEtWZO44MHhAmKQ2SIkxtwukoMAIyBAwjcgCfDwFZo0664LaHTu/64t1nnke9+MzP337uBanlTIFzvacIYA0UI0WZHhlCHwO817yMNTxEjRJAywUNQEyNHXIab7Zf4YD0EaE8EWMBYQqKss5Y1lq4R+EbKfJDYATwBMFxcvNW8ah0xK5iIcrcolMFkPMYKih9QD9gaNAcyFFyRGogI8AwRgbI/QDCKDCKyBAwzrQJ/ufWS1099pd86juXPX3z7r6nZXn89OFxWWYNrqOoOB5LmT4Z8Fp5L2ewlgqdtLKEIqv0QV6tf8/fyR8R8cR8zuEEOMvnnJXCjwO5ovtR7rQi30G402V8BxgjCI6BXH6DAvCMNevkz3//Yz8fj8kKkJTgyQjA46xoWwBEEqAO1EArIMPAIEYOkPv9wDhQmXr1BE/qextWnvuhW64+f/POeS9Yv2PeVRksLxcoOwMIGFFOhgThNDbwPvNiuhgmwwG0bEcDYMmoSwe/aG9ho5xKAWUaeOPZauCutCZf3rOOO1S4H1CC4HHIolUKwOtf84P+v/iNj7+RkVInkBNM53Hc4T+mIBXQcZAxiMeBySCSxkzoAFADkkbNQVv29/R84JZrTt+8e97131q79PkYLoosncZA7JRmUIQa8LvyB/y0/DPjdAK0fNCA0MEwn7Rv4S/MuyijTBcVEEAMVRV+oMLtqvIZ4F5gkCCYIhf8uALwyivvOeMPbvyv11MpekCZSYE5VCqAAh5BQXJgMnxERlAdBIanPg+hfgDVFPDMIg9tX1z87D1nPfPOh8684f7Ni5/rvZwLUC4orSBBWM5OPmReSB8HyHBtEjQQkTDAYt4U3cxOlhChzLBHVLnVeG4e7JObgRGCOc2NlGm48fnfWUg9ioAaMy3wUwUIj1IABOgCelA1gAFyIJ0skyCMggwh/gCqEyUjj86FoEKb+M7Dqwp/d8fVz9r24MIbSAo/tmsgXl0uYouRAkoryYBnyK0sZCdVOmgnGRGL2cIl+nU2y2uImHGni3A6lp/vqOpWb/nynsXyhTp8ExgimHPcvnk0dEWVhSCeoNl0qjyHSKNUC0AR6AFdgWJABEhAqqBVvKsiZnJF2+T7yQr70KgC1BBt+rU9P9i+oPjNe8666LaHlr30we2LXpqmnB1FIAK9nUorUoQIz/Pkc4DQbhQhw/Ec/2m+Yn8SxSAoM02BOGEl8HOnbNSf8ykbxg9wi4p8TOD7wDhzQuCWfRdWnlkR63QB4AlakR56fVyCahnoQFIBBAAPmBRE6iBjiB/BuxGIRoAhxA+QR/ungigDUmbIr9/03FOHHu77iVsfWPby2HIlQCGCUlFpdSmwWrazhnVkRLSjjIg1ej+djDBML5aTQ4WGXIAiazpXsgb05wTuxvNFKcgnpcBawDNrBXL5jcrPveBrpTdee/P/Y7wYFgFmJzlsJmSYlCPkqOSIVEGGER3EuwF8NAwMoYxQYBio8xR8/BsXlbfumn/DR799/ktG6/bFkdJdLihKe6kgvEBu5m/lddQoAgLQNjMaAINHEd7t3sPNcgNFlJYg1FX4qop8PEr57Oyc5wTOD0BhWHuBCFBmo0CBfLKERykCWFS7QHtQVkNisIkH6igJSp2IKsgAogOo3U9eGAYqCOPAKEf59HfPP+O9X73iVQ9unPdTKGd2laA7VgCU9mOg8dyMJQOEduQxdDDKGl3LFxtB0yKUgijXC3q9wmbj+S9V+ShwL7NG4Mgh7ZBefAiaNjQDt2jLoQCCMjllMuYBy0EEvEGq+VTQVIARjB1Mk6jy/YdPWfr7n7/2RYPbup9jnfbP68ypp5YkAxHBCIiAESaJIrQ2RXDASjbgsbQzwVPWYQytyRtW55bfENU3E3MzVt6rwteAUYK25rIesOQ9gANSggB0qiYJRxOMdwhd1Wph2cM7F527bseiC/YNdS99zXn34s8Xxusx47UCo9UiY7WDFTNaKTJUKTFWLZB7g5+ozINXEMAYpoJIaSUGWC5byLG0s5SYFWygm4wEh0VpNaIAFKnzYtCJ4h6FD8WpfBTYR9CWXDQEL7/qni6qBfukQRMEAhifgeZDo539D25dcvEjuxZfPBEgfaA46/EIAnQV6/SUapj+IUDJvWlU5i311DbCZqRSYvhg8NQKVA4G00SNVYtU6hGqNCiThEPdkIgy01KEjEkCdDLMyaAzfHzWowcQlCpgESLAoTwV3gtJDtZAZJVpJTQIXHywfKS/Jrl8RHM+DKwjaCtyyQuV7/7du14ex/kVQJ2jBYGgGJ+j6IGhrkVrty29aP2uhReN1wpdzipGPD+KAIgCIAKCYmSyEEgyO1GOWhJRT10jfIbGywxO1ESQUU0d9SSi2vh5g+pU6BxeAJx4ECUI8xnkeXyOpbINUF4qH6OL4RntanJVMq/MFEPOKPO41byCGmU2s4Zv6I8xQgcRyvHIvFBwGacu2sS+4QXsHemd+VsbBIADAh8zKv8KrCVoC/K6X97p3vuWD766GKVnAylBcDibZ6joroG+ZfdvXnbl5j3zz03SqGBNjjHK9DgUPiL66PsGARTqWcR4bbLrqUzUwSAaHi9PVImRarERTlluSHNLltMgAuY4u6AEYTWb+DPzc5zH9/E4QKhRQhFmmjBzFMHgialiUIScb3Mtv+3/hSH6j7mz8SqU4grv+Mm38dwLb2HrvlX84cf/mLs2nk/BKSfJuCqfVZW/B75H0NLkNW/a2fH+t3zotUVXXwmSEwQA1mcounugZ8n9m5dfuWnPgguT1EXOekSUk01EMVMloiiC9wfL4FWoJlFjHjRSKTJaK07OhyZq4nPjOC7NLKrgG3XUUZxRBFCEFOWP5Dd5lfwb4/Qx23UwxN/r2/lnfQsllGNRqQsvvuwW/vINb4U8gtIoX/r2T/LWD7yTcgFAOYkyVfkE8A/A7QQtyWW5iVHKIEoAhIBBNN83ETD3bFz19C17+8+vp67gjCdyOc2iKuQHiyMJYIzSWazTXaqxfP5kGOVeGt1NmrmJspMdUKV0MHgar9WDnVESUZnqkNIccqBb6pxu7ieVInAokWYrT8xF8j1U38KxEgOj1S7II3AJoAxXulGawono64BXCHxCkb8FfkDQUuR3fmv9oj964yd/puDSMqDMTYFRj/Hp0Ejn/B9sXHHlwzsXX1JLXCma6mDakYgicMRxXONVlCw31NKoETjVg4GTxAxVyoyOxfxK9Te5OPkmtawAaQZpDl7BCFjDbNLBKJ/hdfym/wfKKMdCAVXPG5/3YW648lNs2H42f/6ZX2fX4AKcVZpsTOAjxjQC52GCliB619+eyryR14I65p5AVLF5MjZe7vnBppVXrtu2+NLxetzlrMeIMlsdCqBDCwkopMScyoM8N/8spl4nq+ZQT9BaSj5Sw+8agiwHYQYICDPKyKH/XWPqjNHFm/3HuIOnUUCPq8OsZ1CMlCQTjNAImRYyCLzHO/kbYDdNFYhu/aOLyM0NgGOOCQHj06QeFddtW3reDzYvv3pwrGOBszlGlLlL8Ahnyf2ca+6lJFUQQUUoZGP4u9eh1QREmHbqwecgwkwQYLxeppoUEFF2sZz/0F/kq/pCIkBQjpeqtHTHK45NQzvkr8cH+AAwTlMEolvecTXePwewzClhk2z9jkVn3b1h9bP2DXetEFGs8QQAQoajSIUCdRTwavixp9/N/Pm7IQcQpp/C4B6ojoIYppUo2Ix//tKNfPS7z6cjVoboY5QCRQCU2cpYEOFuQd4BfJrjpB30qNIjUGRSAowCBwiOiejmt12HckUImjkyhxGf7RvsWXz3+tXXbNi94CJVcNYTPJbHoAgAuTe86nnfY9GqPaAWVJl2YiCrw96tkCUgMu1B8+7/eTP/dut1dBXAABZlLokyPm28vAu4kyfgu+jP+rjCC9dV53GONSxVZZ4IJSbVUYaBnSiPqHKLV24DdhI8LgdSBhWC2UsAmyfVaqF8z4aVz3pg67Kn1ZKo7GyOGJ5AYPAcouA9ZB48M8SDRFDug4HdIExv0KhifUYMRChzURLxMtDnCfKP3vCXwABTagu4uL6AnykrL1FhNYA9+iraQxYBZwDPFvhZa9iP50uqfBC4leBxg4bZLTwPs2H74jPvePjU5+8f6Vwa2ZzI5bSiQKHcA2NDkNRAhGB68xboAv0d43mJyeV3h5awTubzK7HwUx05HQoIx0mZj/B6EV4twmeBdwL3EjQ4lCIgBLNx2J8MT6wr377u1Gdt2LXgYo+Y2GW0sEAVrJ0Mm6QKCDMgUMBzbjqPTxfnMaDQjwflhEUKP64511W28Bfe86dAEoJGNEYJZhPjM/XG3Ld+9ZV3r1/17PFa3OOsx4knaJOwKXXAqIN82rfQAgUMZIuFvB9B6UeZPgpi6Ow6g7chXK7KzwK753jQMMuCJnQxBwa7F333oTXXbtk7/xwjvh2PyULQRAVwMeRVgukPmXQZ+D4gZ8b4FARu8I7Pbt3OK4GtzFEOJAYlaP9ZjM+NTHQxT7vnkVXPHU/izsjmBG0sLkK9AgjBNBHIlgq+F8hPUq55Ll9R5n+yUW4A9jAHORQHCG0tPHg5ONzV/50HTnvBxj0LznPG0+4hEwi4AiggBNPBQ7ZEyOcBOSeNerC9XObm8T6ElwEZc4wDNQTtyfgcFX1w87KLvrduzbXj1UJvGPbPEgJYByjBNPDgeyCfD3hOOvWNul7ht4B3Mcc4wBC0H5cnlWqh4ztrz3jBup2LLjNomMXMNiKNOkGBAhFkiwQE8DSNgd/0yufn2g3TDhFBlaBNiHpsnm7dvXDNtx847cf2j3QueZIbloMgUMjmgZaAnKZS6Eb4A+CVzCFhPtNOrM99buWuB0951l0bVj0nz20cu5xgFlLA+xOd0QQKWgDfJ+BpCQIvF8MzgW8yRzi8KiC0tsBlyeh4ufub9591/cbd88+LrMfZnGAWy1NOTCAKebegMa0UNCaHX8wM95cMw4CfC0dnHlVDSwvPxmzbveDU2x444/qBkY4lc6GLCRTSOgjBU6WgFnwXLUUB4/mJ2PNMEWoC6wVuQ7kF+C6zkAP1tKbAaK6ov/fh1U+fuKfsusybeI4M/AP1kNQAIXjqNAZfAjytxgJLMwWFU4EXAG+zwje85W+AzzGLOIQcpQWFBzBr9Tj+9trTrntw29IrrPU445kDAjFQG4P8hL4qINCpkLGAp2UJjzJeeY5mPAflw1h+HdjHLOBAUtBwsWYribL64GD3gq/df9ZLdg70rpljXUwgQHUMcg/G8AQCzyHCIXroVUtCuxEA4adRzspyXgVsoc050DrQRcsI85ituxas+fp9Z71spFrqD0/4zzEikNahMgJGCB6HBwxoGXwn+JKgEQ2iQB1MVbEjoBHtS7kisnwmHeF6YAdtzKEkBK0RMqLZ2k0rLv3W2tNfnHsTz8WQCQRGDkCeghiCo3jwXZD3C74TMBxBATrAi5AnoAJ42pfhQp/wntoOXgYk7dzRJDRXYHyuKnz3gdOfc+/Glc8VVKzxzDGBMVAZhfFhQDhMoIBAtkjIFwAG8I16QuoApa1pDoWFvKi0hJ8F/ok25RBTQb0CQnDy2TxLkjj6+n1n3vDwzsWXOBOe8p+TxEBah6E9oAoiBEeFzFIhnwco4PnRlFlBc8hzfgvhk8C+dn1gswIoQTNCJh2vljq/es85r9i6r/+MyOUISvMEXs0T/7gIGAGEaSUCSQ0GdkKegDVMOwGMoGLIgRzhaAYQlJajU7cu9wM5c9UK8bwC+DfakEO0gtIE4VLM/YM9C2/9wdmv3DvUtaz5ty4HRjwFk/B4cjFInkEtA2+YPgK1MRjci9brIMcwVJCncDONKNiMOB2nm1E6UQ5RFKFGGY9tzVuX+wHPnKbCq9s3aKwbJ8sITiKX1Xbt61/51XvPeeVIpbSg+evLQeojTu3cwrVLv0nuHQACIAKAihDtSknv2AtpBiJMH0VrCdkdD0Oag/Ckqt6TAsLxe3n9d3mReRuS8ShLTpUyb7cf4CE5nwilZRjI5wtICBrgfIFlwI42DJp0hEyU4OSIstq2ifXlm+8991XVetzd3PvKAhFFAGs8TnIilxIhAKgCuQfvIVd8LYPUQy4gTB9jIFG0kkGW/8gQ0zTDe0U4fmWp0SEKemTQVOjAkaAt2M34MuAJoFuFs9oyaP7s6y8e+ZUrv5LHJo0AZeYELq9v3Lb43FvuO+fHk8yWQsic1AfgAMXIZIkoAGnuqGeWSlZmODHQMUYuRUgydKLIPZr7Q4EjAobpZQSt1EEVjAHhyRnhqfJYHkvIcShCSxHIOwED5AQQAYtpQ+62HSuSt6jUgRKgBDMWMg9tWX7xN+4/4yW5N4Vwncz0E0DMkUHiveD1YBnSzDFSLTI6UePVmNFakZFKkbFagX3VLq5KDvATV27Gz18GWU6DMEVAhBkhgg6NQZaDs0wJDGhJwDMlUKVIG3IlmyagM3p7X3jaP68/sGnFZd/44ZkvQ8WGZ2ROIEhEpwoE5VECWW4Yqxao1GOqScxItcBwpcToeInhaolqPSLNLVluJkoeveHFCFQF8B72DcHC5WCEk0IEkhS/fxiMcJhAAMdhAoE6bcgZpA4yDgjB9BIU45O1G1de/s0fnvFSBGueNGQCEQA9LFR4tEPJvVBPo4ly1DPXCJShgyEyXn60M6klEbXUkUxUmoMRkEPVIICzekTzYBAwAjsH0NU1pFQA75lx1uB3DaDDVTCGKYGCGlDhkCATwx7akJNIEzSvAIZgehmf3rd+1dO//eDpP4aoNaIcEkwFCOZgGcWrkOV2srw5GBqNIBmplBrHXaO1AuMTVanFjNdjkswggB7R8RyqQqTHP5Sv1sk37sadtwoEUGaOEbSekm/YxWMF4kEAJUBAc4aTAzxAG3J33r9UudZVcLkhmM7LMev3r1/59G89ePr1ImrmYMgc6kamCkBVUAWvQiWJGKsWGas3AmSi4smjrkZ3UqSWOLwKuRe8BwWMHOpSIqtMO2PwW/fh+7swy/ohzZkxIuTrd6JDFXCGwwQCKJADjkBAPWtdDztoQ871wKc3Xjj66gtvU5ICJygQYGom860HTn+xiIoRneUzE4DJV+HQ5zS3jNViKvVCIzTGapMzk6GxcmMoX6nHjV+TZpYkE1TBmENBIgCiWHOwTmI6eiX/4VYoxpj+rukPGxFwQr5xD37THp7gP1zgQaqgRUDDkXJ9Fx+nTbn6Ltj5YHGIyzUlOeFONbB5/cGpwT+CGNFZtBoMcth6cJabRkjUs4gks42OZGi8fLAaQVKtxxMVUUliaqnF50fNSmSqgNgpLcPI5AOUd2/AXXQKZn4P5B5UOWFTKZpv2E3+4DYahODxKJhRxfdJyFzYVjX8D23KVQ2YNX6ElAxwIWhO7AvL1m1efuFEyLwUsEa0PWcmRhEUr2bq2MqQedvoQEarxcbcZOJ1alZSaAziD75muQCgOlkcdszljIKhfdjJeU1253rsmcuxKxeAtZDnPCUiYA1aT/HrtpNv2QcCiPAEAgN2DPIaaBHwzFmJ5y86lrOXNuU6lkOn+CGYCpqnLDzxv2nH4rO+PhEyCq4FQ+bILS4UAAUEIVeoJVEjMMarxcaR13C12JiXTA3jSb0hb6wGG3IPHD4zMYo1yqxiDGQ5+Q83o/uGsWuWIH2dYAAPqAfliclhSZvl+O37G52MDo+BtRyDIAV3QEmXC3ORCkSGr3QY3kMbc/McfHn9paOvPueu8c64WsIbguPksmT77vmn3nLv2a/Mc1O0xrfMarCgGFEUoZ5Z6knUCJTqRI1MBcnkcVeJetZYC278fJo/9u+VwiTTCBXmBpFG+d2D+P0jmAU9mGXzkJ4OpBhDZEAB1aN+D5Bk6HiC7h/B7ziAHxoD5XhCJrBgBsB2QN4H5MwdBiTlIfH8dAI12phLKvBIpS9PE7ePAguBnOMSrvrfvb9/2c33nPeqehp1nKxrZUSOnJmAkuWWqQcSG6ExVi0wWikx2JiZFKgmcWNuMvm8iUUfM9g/9HrUzCSwBrzH7xpolJQLSFcJKRehFCOxo0EVradotY6OTdRoBerpVGIbMARPgdulqBN8F5Az+1mQcYh2aJlElgF7aWNO1tNQNPk+wAIpwTGHzPBoZ9/BTqZSj3uczWfkKXgjCnJoNVhVSHLbWAkeO1jVIsOVIqPVwkQVD1YjVLyXRuUKqiACZqqcVYKnMmcRALSaoON1GgwgQoMCKPjD/gt3lhMQCJBBtFVJlwq+F9BGzT4GUDAD4HYrkrIS0f8GuRbY2L5B42lYu/b0PZc9424lNxyDwPqsXi8Uv3rv2T8+0TEsjI4zZARAjlwJFhQEBMi8aWxs1dJoagg/GSgjjWF8ufF5qoMhzQzZYU/BGwMCMDXYNwTTbSqxn3hNzxBMJwFyiLYr+biQ94MWOURpX8IkDzIG9gDYEaXBAHCqop/0yHXAAdqQy4WG/3rw9AOXPev2cepRDHieWGDU+8zYiZB5xc6B3tWxy580TI5+eNFMXaeSZo4ks40aqxcad3KN1A52JxOv40VqU9etVBtPwYPIVHHke2OUgiEIZjehwR5Q7DD4TvBdgi8CBlRAaDMeJAVTBRnVxiseMBxB4FKDfsyovAyo0GacUxpKqe73uR01sOBJgiYQnYD/+v1n3rBx98JzYpcBIKJHBIki5I3trIMlVJP40WtURiuNMGmsB1eSyZlJNXGgNCgcCieOuE4lCAID5GCGwAwrCKgFDO1FQXLAA8ok06jHJXCtyfWfXcYbAE8bcXFdAfjy7efVX3vdyr1nrN6+iCTiMQJB1OCy2n0Pn3rV+p2LrywXEqZQSx3j1UIjOMZrcePZkpFqibHGVfSFxtPxuZep4AFVMHLYMb5RjlEQBDJVUySjPcmhOhaZ48aJ2gC8gzbiakUeFTu/Gbhgzv9fVxFQAcyhH9c6pfruu3549iWfvf3C68brMaNTYTI8PvnAYpJaktyRpIbcHxkkIjSIKJGlBQUGD9SJKfB4shxUAWFGGQEB9InHgxOlyFN+KJcjWHIyHIKnbQlzgtDwNlFZD3yMNuGMClP4yNev2PIHr/9Uwuy+NFWYZB4twQAZUAcSIptgzSjKAdBBusoH6JAD7/i7Z57xpW+f87bhasEAiDz+avDUFfRBGxGgoh3s4HQqdPAYCj09OZEDVWaMAEkqZDlPqFY2pIBwfERgvOao1CKMKFMw5NQoUaMDIWgDoqLvSXLZCnybNiDn3KBM4fzVO6OP/+E/vpGx4nKElPZ2eJAI4B8tLznoGCoDGB0hZQjPCDCI6DAdpWEg5TB37Ty9+6ff+fJbNOOyMC+ZvQTlaKqQ5cJvvWGQs9ck1BNhpkRWueehIht2uCdZQReeCmeVBzYWeHBDTOR4HErQVjYoPBvYTotzh1+1/tC2JemB8d4t/XZ8Jd7S4g4dbSkCCJMEUESqwDDoOCmjwADIAIYBhnSIROuIJkDO0QarHO7OTSvNL3zs+vdIzmVxCJlZzWM4mgLWgnUCGBBhxhgFDNooZVoJGAMKqADa5qdPwRoR3q/Ii4E6LcwhwuE+e9OlP/yZF996pdStAErzCMBRQWIapQCSAOOI1ihQRWQYZB/4ARIGQSvAOGiVCE+D0tDPcfm/7/6pt2d59Kq5+7R86GjiWImsoqqgzBxVQJGpmk6C4owigKgSzALKtaL6V8CbaGFOvHK4j9125fb/88LbtiF6CirpSR7EW8CACkKGkjZeY6kBQygDCIP06jCiYyhDGB0FasyQt7//xT8+Xo1+p7usKHNRoAjOeVwjaGhbChijiBDMJsIvA3cD76dFOYQj7Bvt8A9tX37XWadsOYV6NF1dzZEdCQqgh90AmYKMgQ6BDONLI8DBGsDoAGUdATLAA5BwUrzjo88/7QP/e+k/9HaqUdpLkgkCRE45QYFC5MA52p41IKJMJ++FegJewVmIoxBmTfCXGLkXuJsW5DDC0f7iw1ev/dff3XxlZHQlXpLj3whXATFTr4KQA1NHWTKOxiMIA6gOYO0A3Z3DoAlQAzJawL++75LyP3/y0g8sXswSlLahCEkGK/r34L1lx8D8E3zYM1DAWW2UqtC2VLAWjIACwolLUqFYUC48c4zOzpRde4us21zGWbBGOTkCEfryTD+wa508Bxigxbgda3mMHWvPSn7r515w8xnLv/jTjJcdQgYIU47qTgyCAlNBIXXUjTVCRMwBvB8kYxiRCqpjwNgRWZLkUBmg1Xzq3vP+on8+V6NKO0kz5bVX/y8/+4J/w6vwL196E//zvRefwG3MgSrEUx2N0r4UsFYRAVVATjxkli+q80e/uJ5nXDIINmdsLOaTX1jKP3xsJV4FI8rMC1TBGC5Yfq7+A/A6Woxbfq7yeF79zms2/O/v3PXF1Wt2v4jUxkA+WeJBKogMgg7hoyHUjQIjiA6jdgCo8yhLu/n5v3rda9bt7PqleZ2KajuFjLC49wC/cO2/M3/eThDPm174L9x83/Op1EoYowTHTxUiB1Gbz2hQsAaMQK6cEK+Cs57ffeNGnnH5fsgsJI7Ocs4bfnIzewciPvDppZRLnFzBa9Nxvg38My3EpeM8oRf//ltv/9Nf+d+9jNpTERlD9AA+HkRdBUiBjFlmy76+0773yLK/6i0rqrQXgdw7kiwGkwNKksZ4b0A4AYFzOlG0PWMUkenoZuC8NVWedsEQeAteaMgEYuGFV+/nEzctIc/lZB+hhc4m5h1JVb4F3EeLcFkuPJlf/8sf3wRsYg5QT4zjX4pllghKu4mssm+kh7/5/Fv55Rf9UyNg/v6Lb2asVghHZyfc0SjOKr7dt86sRYQTHtKoh45yTqHgwXMUoaOUUyp4RsctJ1GgYCzzSt3670bluUCFFuA6ugim5J7fRvT5tLHYKV+4+3nc9tBVqAqj1UJTlwFUBQARbf+gcUo9EdqRGosKdGYDRMwjoYCgJ9DhwZZdRXbvK7B4aRUS4RDPI1vLDAxbirFy8gXqudKj7wbeSgtwXhUIRLka4bdpf41gqdSLyNT7Zq5YR/bQ+3buqiIH1tBmBDUWUOLxAboGNtAxvJWSXs8YBU5E5JSde2Pe8z/L+f1fegSJcyYpe3aXed//rsAaECFoEoU3Gy83AV+kyZx4Ya5TodOL/iNQYpawRpu+mPDMs2/nLTf8Lbka/v7zb+FbD13RnmEjUIg9SpsQwYtF1FMc20PngY2Uhndg8xqIwZkMPCesVFA+/uXFHBiOecXz9tDVnbJpa5kPf3YpD28pU4iVoKmMN/q3InInsJcmcmqZ88aL+q6OCheqMA0Cr0JXqcrvv/JdLFvyCAj89sv+gtf/wwcYrnTirNJOBCjGCtoOAeMwPqU8sp2u/esbQWN8hheLNxEGTyzptKw3i0DklC9/ex5fmag4gmodIkcImRahcHqk+hfAjU1eplHmMoe8IK/ySypMk0CByGV0FschiwDoKIwT2RSl/YhAIVaU1qQiYCwmS+gc3krnwEaKY3tBPdoIGAdTRJRIUqaLyGRnowqqQkdJCVqHACm83iBfAD5Jk7gcYa6q7qdHO/UvSiWmMW8DIzAw1sW/3/xGfunH/hFV4X23/h/2jvYRGdpSK/4TuopBxWKzKh0HNtF5YD1xdRDUo8aBGB5PbFJUpj+MRZSg9SgI6J/1WfkGsIcmcH2WOcsu5I9S5QJVgmm/JRg+/I3X8I0HngkKW/YvI7KKtHNHo7QEFYuKIUrG6BjcQsfAJqLa0KHhvxieiAAFk4ICAhB4FbwHY8CIMtsI4GH1/lz/FPg/NIHbnytz0f7N8rwFp+ibUGZAIALWwMa9yxAgsiAA7Ro0BW2JFWUQotownQObKQ9uJqqPosagxnFslILJmBTkXjAC/V1DDFV6yf3sfcBU4MahnfIZ4NOcZG54pzDXdPTTOREyfw5EzJhARCm42RGahQhQmmIqRIgrA435S3loKy6tomLwNuJ4CBwxowlLK2P81kv+mqed9W1uf/jp/PlnfoXhSs9sDRuZt1L/DOQbwCAnkZu3kjnH57wJ5RKC4JgoxYKiJ3uDzFhEtTHYn1xR3o7N6/ipAf9TFZGiBJU6/NTVn+cl13wU0iIvfuZ/sm7Hmfz7La+ho8Cs5DPOUOG3gd/iJHJ5ztxiOcegv6UEwY+mj3Y0Hj1J8xdvY0RzyiO76dr3CMWx3YetKDtOlCNlUhBFCQigFlAil6DKrCaqb/bCfwPf5yRxijJXjOzDdHbxp1KglyA4RgKNjgZlxqiZDJhiMkDf7g1UNhygo7bniBXl6aE4MiAoxfCZ79/AFWu+z0Vn3M4P7n0hn73reooRs5ooJYG/3LNIrgUSTgK3d6EwVxQjXhlV9cVKEBwjBZGZu8rH2wg1jrhygAWbv8Oy9V+gsm0F++rnoNaAGKaTAFYzILBGOTA6j//3gb+lv3sfB0bmU88cziqzmQoIPHPeADcC7zk5M5oB5oRinT4VfZtaguC4OAvOgSrTRPDWocZRHNnFwo3fYNGGWykObQeTomY1ahyQMt0UsJJjhGAqbNLcsvPAYowBZ5S5opDo74nwOWA3M8wVU2VOsLxVlbMIguOgCnGsWKOATEPARCDSeP5l4fpbWbDpNuLR3WAcuBhEmFmCJcOhKIKghAeMFWOZeyyr6qP8LvD/mGGuPs6sVx2Rs3qW6VtQguC4qApx5DEG9EQCxsWI+sb9Y4sfuZn5W76DrQyCdRCVOFkUsOKxeDIsc1egHlyZ/ytePgjczQxyUVGY7Uq9/F6W0kMQHCcF4miqo1GOi4ppBIzxGT277mPJRMDM2/Z9TG0EXAGiIiefYMmxkpOqRZjLAhHK4vhD4GXMICeO2U24Jkv11TwFQaAKhUgx5ngDpoBLK/RtuYOl675Ez64fIGl1KmBKNIsqOMlxkqEaEwSq+lLgBuDzzBCnqsxahkhy/hjBcYIUQEGEOSRQnepoLOixPAPjYqLaKAs33dY4Iuva8wD4DGzcCJhmUwRnPFY8KCAQBAp/LCq3AhVmgEOF2ao6yMvLffpcPE+ZKtQTwTmInFJPBfXh+zbm1tEZGDmWFeUB5j/y3YmA+Sod+x8B9eBiMI5W4iRvFEEwxSiX1or6U8C/MwNcvajMRuOdUuqp6++gJxYyWS68/Ln7eNWLdtE/r86mbR188H+X8937u8P3oc8FCoVDM5rHX1Ee3cPCTd9k0SO3UBzeCgjYCBBajQKWyaBRDgkCl/Mb1ZJ8Ehhimrk0FmajZQO8rlriIlWesloi3PiSXfzOLz5Cgworlla54txh/t+fns037+qlVFCC2b7e7LEWcn/kinJ5aBuL1t/C/E23URjZBcaBjQGhdQmWvFHKpCBQAZdyWlfK/wX+imnmukaYdayntyb66xiesjwXFs5L+ZmX7gAEEgNTip2TP37H/d14bzBGCWb31pkxkJoCeN+44LKxorz5W7jKAJipFeU2oIAjx5ATBIdTAUHfIiofAfYyjZww+9QtP2XhTE5AlsOKRTX6ulPIhSOosLLxczn7Bg3GEMxSquAKESZy9Gy9n4WPfJX5Ww+uKA+BmxrwtxXBkGPwIATBERRW5OjPA+9gGrkMZTYxnl5n+FUVTogxMDgSUU8MxY4ccg4RZWjMMV41GCGYzSwsGl3H2V/7AMUN9yFp5dCKctvyODIeTxAY4Ze95z3AbqaJQ5lVROQNKnoKJyhyyqadRb7y7QW86sXbwFjwAk4B4dO3LmJ4zFIuKsHspAhxDOft/SKlka+B6W0ETPsTXPg65ycWLDoYNsAfME2cEWYNL9Kj8ItME2fhbz6yEms91z9rH8VSxsBQzEc+s5z/umkxpQKzXTg2M9ARZ+BKoIbZIibjCQWB8EaQfwZ2MQ0cIswWBm4EPW36gkYZqzre9i+n8YFPL6e7K2XfQMyOPQWiSBEhmOWcKJ1RFVSYTSJJEeGJBMFihJ8F3j5NQcOs4A09NtdfUqaXs4pX2LSjiGoRYyCeEyETKOAkp2xq4IXZQoFIwtFZ8ORU9Y058i/APk6Qy5RZwRpepjlnMgOMTIbL3BNYySnNsqABIZYMEZ5QEAisMJbXAH/PCXLG0vb21Ijnj+mb4m5Qz7QIAgUMOUVqgDCbxCYlCJ6MKCj6i3sXynuBCifA7VlI2+sf4kVxlcvUM62CwOIpzLKgUaAgKUHwZFTA5py1bDs/AXyIE+CWbaetqSBi9Jc80y8IDDkFnX0dTWRShCD40bzTX1DkY0DCU+RyR3tTrhR4LtMsCBQQ9UR+tgWNEJERBMdEeRpWnw3cxFPkMEo7k1zeCDhmQBA4UqxPQZhVnKYEwbEynp8/oaAxnrY1ulNWdyzWV4ow7YJAgbJUEfGzbkZjJUNQguBYeOX6eUbOA37IU+B6RWhXbon+dAI9zIAgUKDLVTEos43B4yQnUxcCJ/iRBApDXt8A/CpPgRvySjvKPB3G8JPCzAgCVeiJK4goKLOCqEd8huCxeDKC4Ngo/DiedwCDHCennrZUynhuvcA5KDMiCBTojiogHlRmQcB48qhIre8UtsqZ1IcjBCUIjoUKKwuZ3AB8hOPk4kxoR2msbxRlxgSBBzpdFVBA2jZg0Jw87mS8dxXjfavJu/pIBgyqIEIQHBNRSGJ9AyL/ASjHwSUF2o7COaI8nxkUBKrQYaogSrsRnwNKVuhuhMvYvNVkhS5AcXlGJAYhIgiO09UevRL4HsfBeZR2EyfyijSmLMqMCoKSVAEPWFqfIt4DSlrqY2zeqYz3riCPO2BqNgOgBqwFhDYQqAoAIkqzCTjNedVxB43mtBeRUhbrT4oyo4JAgRLtcHSmiM9BDPWO+Yz1r6HSs4w8KjV+XHzG0Ywo1kDuQQhaVT0VjAHvQUSInTZ/Nd7wciPydmCIY+QiK7QTD89COY8ZFgQKFLUK+JYOGDWOWtcSRvtPo9azhNzEiOaYPOWJiIA1Sp4LCEELSjLhGWfexY3P+RC1pMQ/f+UXeGTXKURWaSphdZZyHfAJjpHLUtqKi/Q1npMjCCKtAdqCA36PGkeldxVj/adS61yEGjsZMD7lR5gKGoIWleXCgu5B/vAn3snKFWtBlN7SCG/8139GVZp6jGYE6jV97XEFTVpT2kWlLIvmwbWcDEEgEOU1UG2ZgBHNyV2RavcyxuafRq3cD2IOHZEdCwURMEYBIWg9uUJXcZwlvbugVgaXsWrBFiKXk+YOoXm8h2I31xRgNbCZY+B6umkfRZ7rKywRZlYQKIIViKUOSEsETBZ1UOld2ehgklLfoeG/ZhwPBYwBawkrzi0qsrDtwGL+5/ZX8MqrPkFWL/CRb76OauKIndJs6unLM7kO+DeOgcsToV10JPqaNAKUGRUECsQCJUlApWkryoKSxl2Mz1vdWFNOit0IiviMEyEyFTQErciIknvHn336N7jl/udRSwrcu/k8Iqu0iiTSVx9z0CSR0g6sl9UKzxBlVlIVVMEYJWg+VShaT9nVOal0MkTMRKWlHsbnncJ43yqyyRXlxo9PB0GxRglalzWKqvCtBy9FBAqR0kpEuRzkHOABfgQnKrSDzPI84+mfrYO/3EMhUqqJUIxaYmc+bJzZlLKtA4YZpx7yFGze2CA7sPAK0r7FZIetKE8nY8AaQAVQgtYkohRjWlWH8bwQeGDWfE2AoC9VZp/MC/O7Bnnri/+O5Qs3cfNdN/Cxb78SmrpZEqhCbNLJjsYLM0chq4MrMLz0Qg6cex2bRq9idE8nkWSYPGUmiIAxoDx1QaBWX6xe/hbwPAnnhZZnhGUqXI3Oxm4GfuY5H+alz/wPyGIuXXUfa7efxZ3rz6cY00xhRmMyimaGgkZzyBKISgysega7z7iWoaUXYYoF/P3SCBixyoxQEAPWKKBND/R6ImQ5GAPFOBwftxNVnqY5pwPr2v5mAF/gOnL6mIVEYGnfLvAOkhKURpnXMYQSND1oJKUgCSBMG59BnuALPQyccs1EwLyA4YVn402EzevYtIpoETAz/MVnYG1zj85yL3gPF505xtLFNUZGHfc+1M14zVCIlLYQFK3R639k0LT6QDDOReqi1ymzlMLHv/NKLjr1Hnq7DvD9e6/jro0XEzmCJlIgIqUgdVABmY6ASck6+tm36ir2nH4tY/PXAGDyFJvVTvrZvzWK0hzeC3Hk+fUbN/Gya/dQLKXgLXf8oJc//MfT2La7SBzCpi0oXBfJkx+fOSdCK6sYXWAyns0sVYiU7667jBv/4QMs6dvND7eeS6VewFklaC5HRsQJdjR5CupJuhaz99RnsWfNsxvPwogqJksApVmMBRGaolqHN7x8F69+yXbILSQODFxx8QF+942GN/3J2WiYU7YHy9N3bNCVwGaegNuxSWll3QvlilKPLvQ5zOaw2bp/KZv2LCWOCCHTAhSwpIgmIBwnfTRgaj0r2HPac9k7ETAHr4kRzRvdSytwTZrR5F7o6fQ8/8r9gEAuNHggt1xx/jCnr6zwwMaOMKdsA6p09S3l6U8aNH1LaWmurNf7nFkvsjpRBM2ioHrYew9RWod8CLQAGBALGECefEUZqCw4g12nP58Dq55GvTz/0PFYi9AmdjSqUIg9pWIOCEdQKERKuehRpU0ErsSLgY/xBJwr0bKMl06vejUzJAjUAwomAhuDLYEpCJGF8bifz5Vfy7xsiFXZVvrzfZT8IGBAYkBoUIW8DjZmdMn57DrzOg6suIIs7sLkSWPA33JUcFYx0pwHEQ8MOR7e0sGpp44Chkc5z/adJbbsLIY5ZTtRno5IHzDI43AgtKrhbs7sGuEMhGkXhIARIOqCeL4Q94DrBAyI0DDEIv5KfwUBYvWsTjdxcf1erqp9k/OT+8HXwAu4AgMrn8aeM17A4NKLyKMSJjsYMJXWPhq0IAIKCCePCIiBf//vFVxwxihLl40DAihp3fHPn1jJnoGIclFpE4GwMk64CPgaj8PFCS2rXOFpCDFtJvdCmoM1tNLdRMHhx2LdUFoO8TzBRICC6mGvgAARk3IMD8VruH+iPtXxEi6r3cWra//N6kUR209/IQMLz8Xb+NEV5XbgDJMUkJM/l3xoU5mff/u5vO76XaxeMc7wcMz/3rKI2+7qDSHTbhSTW572hEGTW1qWy/Q6lfa7TqYUJ5yxZBv7Ruazf7SHglOUoNnUgzFQPkUoLwOJQD1ozo8kQKwQA5lEfKP8NO6YqCsXJTx3YY0uWyfNarQNBWMUEVClKQqxsmlHiT/8p1MpxlBPwQgUC0r7CbzRFwB/wuNw3mirzmfmqeEStL06md6OYd792j/kmnNuY/2u0/id/3wXD2w/vQWu9g4hYwvQebpQWACaN+opMUBJIQe+sTlm+5DwE+emLOrISHKhHRx+dNZMkdOJAq9CqaCI0KYChQuNyjJgR9tcqpkZvUyURbSRegrPPe+bXHPBVyEtcdqp9/CKKz/N2m2/gSIIStCkkClC95kQzQPNmBYWsBY2DkV8+Ae9vP6CIRZ3tk/YWAMitAQjStsLenOjzwD+i6O43CgtyculiDraiAiMVLtALbgEUMaqXShB0yiYCLrOEKI+0IxpV7Cwa8zysR/2cONFQ/QVPKmn5VmryPQNaIJAQC5/3KABoQWJiD6DNlOI4Btrr+bfv/RLvOiyL/DDTRfxn996Nc4QupkmUYXOU4S4HzRjxhQsbBtxfOahbl53/hBGwCstSxWcDUdV0ysQ1SuACEg5jBNVWo0aehQuF23Db8VTx99+8Rf4l5t+niQXjEBkFeVkCzSHwgIoLQbNmXGxhR/ujbljR4lrVlWoZ0IrsyFoplkgcImKLDx6TuMQodWo5yKDLqQNGVEKDlSF2CoAStAMxkF5pYAAnhkngBG4bUsH5y6s013w5J6WJQLGMG2CQKEL1UseGzSqtJoCPD0BEdqXiBI0j+ZQXCJEXaCek8YZ2Fsx3LO7yAvXjJHkglfwKqiC0jrksK8LFmG6BMHVwOc4jKMFiXARylMTBArGQmERIJx0kYE7dpQpO09sob+c0V/K6Yg8CmReaAUi4CzTKghUuIijOBVai5euOnq28NQFgSkz2c3kzVkbHqwa/vfBbkTACI2gOXN+nYsX11jenTbCxitNZ4yiTJ8gEOV0PPOB/UxxktNajC4BziAIjpVyiDB1xYyABTxNYQQQUCZr77hlx1iZ7+8ocdXKKs9ePUZktHndjYaOZsYEq3CsOiJocLQUUTlPVQsEwZNQD3gQe7AO/Zjmk+U6QQyop6nksC7HArVc+PL6MttHHK88e4SuQt6UsFFABKxTQABlmgSBQeVC4C6mOFRoJap6OcGTCQEjU7cu9wuuA0x02LclVyAZVGwBUFqOFbBucg069T381PlDlCJP7oVmsAZUmV5BoHoZ8P6W3ToT5QIVguAxNAfbAR0rIZ4vGMckZZLQUFoqAGhOyyo6WLc/4qYNnbz8rBF8E3JRRDDWoEy7ILigZbfOjJcONXoqjyMIIRP3Q9fpgi3/iEsxDaC0vNjC7TtKnLewxhn9yUm8I01QY1HxdMkoTroAwzQKghWozAMGWu7oLDe6WmApRwtCyPRBz9mCONCMJ6e0BSNQz+FbWztYMy89aQGDeopje+k58DDl8Tob7fOoaBGDMk2CYKEYPR24HcCJUVpFlLIyjehGaQgC1anr/U8TJALNmVUiA1uGI/aMWRZ15swIEVQs4jNKwzvpPLCB0uhOnE9ItA8RBWU6BUExyzn10aDJclqGWDkdVYLgUR6KS8B1gubMOiIwlghbhmOWd1fImT4qBhWL8QkdQzvoPPAIhfF9GJ/jjWuU9YrBo0yvIBAjpzHFiRFaRS6cI8qkIFAwMRQXCeqZlQTIFfZXLF4B4cSJwRuDTauNgOkY2Eihsh9UUWMbAQOgCE4yLDkoIEybIDCiZzHFGVFahnI2QTBFPcTdgikwq1mBSmLIvOCsnlAHgxhsUqFraAudBzYS14ZQpmYzwmM0gkY8yjQLAuVsFRyQOaU1uFzKip7qDUETeS8T1TpXyLvyoQcvZzPlqVNjUQxRbZjOwc10TJSrjwHgjeOJKIIjx+CZAUGw0ov0AvudF6EVpJaVRukmaAqvQq0GnWWlsytj/1CEVyjGStMoiAMM4Jm1vEIpUqwoelwbZAaAuDpE54FNlIe24NIKKgY1lmNhJMdJxgwIgk6Tc2ojaExOSxDR1UAHJ13gPYDyhpfv5seevZeuUsb23UXe898ruWNtV1PDRhVQZjUR6C9lWAM5P5oaB+opjO2j6+AG2fAObF5DZWr+cpxiSZgBQVCY+vv6HU5EaQUCKxQsJ11QT4W3vHYrv/j6zUwSVq8a44IzR/nld57LnQ80L2x8Cujs7mY6ImV5T0rmBTH6I1aUc0oju+gcmAwYyTMwBm8inqqCpCjTLwgUVgO0zowmlZVprIhyEgVpJpyytMZrfmw3qEBqmGTo7k14/Yt3cPeDZ+IVjHByGchGFc0FDKDMOpmH1X0Zyzszcg/OPP6KsvUppeFtdB1YT2FsL+Iz1FjUOk6UI2O6BYEA3rMSwKmnJWSOlaKcZEGWw8oldXq7MsiFI8nEz9Xo6coZHXcYq5xMYiAbm6yoB1SZVRQwwFUrKjirJLkcETDeTq4ol4d3NI7I4vEDgJ8MGOOYLpGkTLcgUMAalgM4a2gB4lR0GcpJFlihMfiv1gylTg+ewygDQxGVqsUITaE5VHcqUY/Mutvs6xlcuqTOuQvqpF4A8DZqlEvG6TmwlY7BLcTVAfTR4b9jmp3kZYBwglBPQBWcg2KsiDBrKSxFKDkVmk6ML5PLYk66IIqUdZvLfP3OebzouTvBOfCAU/DCp29dRK0ulIpKM4iB+j6o90NxMfiMWaGew4runOvPGEWA3MSoGLoHN7Fo407qG8YoZSMogjeOmeQkZ+YF1bpw5uoq11wySKGY8+AjnXzr3j6YepxgllqoaIdTlGarDkix2MVSMZxkgchkvfu9p5Dm8OwrB+gqerbvjPnwp5bzpW/Np1hQmkYAhdENiikIUR9oDihtySskOazqyXj1+SN0dTqSXOjcv55F629h4ZavMbLvPHZkF854wAAIEEnGzApqdeG6Zwzwx7+0nr7+KgA+t/zXF5bwp+87FVUQYTZaVEil7Aqp0Gx5Kn0q2iMEzeCsMjQS8bt/dwanrajS1ZGxY0+BHftiSoUWaO0FfAIjDygda4TiQsCAekBpeQqoQuohtvC0FXWuOzOh23lKOx5iybovMW/7nZjaCDgldzGaGyBnmoX15ibIcmHZooTf/7kN9PXXIHEAGKf85Et2sHZjF5/48kLKRWUWKuYq/S5XodmiBSxTxRA0jXOKKjy8pYRXcJaW+j++GPAJjD6kJAegtERw3YCACCBMqyQFryCcGCOTVYqU8+alXLLSc3b3CL0772X+uluYt+MuSKtgY4hKIAknWyQpCDMkSFK49OxhFiyoQ2p5VCYQw9UXD/DpWxfgVTCizDZZzDKXxTSdKIsImk4ECrHSsgwNtT1Q36+4TiZKMDGIZVqoghG48oIaXR0e709s0aJgPf2dwpI+Yb4ZZuHOO5l3+0307F4LeQKu0AiYZookm8FLNQNVsJYnZI1iBJTZyaALnUFpNoWFBMExEgsopCOQDiso00YVIgfXvniMJfMzslxO6A6y3BZw4weYt/l7LHz4Zsr714PPwcbgirSCiJRg5hRiuOehLoYGY3r765AYGqwCyvfu76Val7Y9OvMqpBkgEFsQUQ6nqgucqtJsgixUjkMQCIgw7VTBRAoGqpkhzzluOvVdL8WRvSzcfBuLHrmF0uBmwICNwDlahU51NJEoiiBo697Fl4AIFCMQ0baagW7eUeQvPria3/+FDZQ6EiYJX7x1CZ+6ZRHFuH1DxpmcS864jyQp8sPtZ4OCCIeRBQ4kdDRBMAWFOAJrAeW4eBujYhoPWC7a8DUWTlQ8uhtEwBVpRYpgG0GTkmhMK8q9UIrrXHfhbVSTIt966Kq2m2cUC8r/3rKQrbtKPPfKA8RFz9p1nXzl2wtIMmmEUbtRBMj5rZf9Ba+6+uNkueNvPverfOjrr8VZEJQpCwwtwAvzaAFBoEAhVkSUYyIG7woTVaRzYCNrbn8PF375d1l+z38Sj+8DVwAb08ocOZFkKK3He8GahD985bv48zf8Cn//c2/iTS/8F9KMtlOMlbse6OLd71nN2/7xVP7nqwvJPW0ZMgB5Dsv79/LyKz4DanBRwque/t/0livknkkCqvQ6VZpOlE6EpgsCVaEQ+R89nBUhtwWMz+je+wBLHvoK87bdga0NgW0M+NvmP6+TqaBRQGgpaQ5nLNrNtRfcArlDTMZLLv8c//7V/0s9LSCibTav0YmaHbsXIjBaLbN/tJ8lS9aDydk1uIRa6jBMUUAoO4QmE2PQDqX5gkAV4lgx5skDxmZ1+rd9n8WP3Dy5opxUplaUy7QbQ44lR2k91sC+kXls3HsKZ53+PQAe2nEmlSTGGaVdCe3PGmVgrIff/eg7ef1zPkStXubfbv55amlMZJXDFB1NJlBSKNMigiCOwIg+ZoPM2xiXjLNg27dY/PBN9O66D/LkUAfTpiweR9a6DxOPd/JHn/wDXnfNR6kmZT74tRtRFUBpriCyyh3rL+LeTRfhFTIPBacohwiUndBcAkWFDlpAEKhCIVKMARTUOHIbE9cGGwP+JetuomP/w+CzyYBxRdqZIhjxWPEorSl2yg+3nslvfPhtKFBwEFtFCVrlfx+vgsjke+UxSo4mU7QAlFrlvFoEQAnmcNDECs6R2YjC6B7mb/oWi9Z/jfLABkDAxuAcs4WhETQt/zezyAkCQKuFTGBEeRKFVgiaSJC4Fb5l0hqmtkAEZxQlmItBExUs5epeFjz8NRZMBExhZCeIAVdkNjIohpxWJyhtKYgdTScRUKCJ0ly45uzvc8MVn2HX/uV88OuvZ6xWxhqCOSazcNaBW7ngy/+AHRoEE4ErMnsJIh5BUYJgRkSOJhOIgJgmSTJhzaJt/PXP/Bod3XvBZhSiOn/26bdgjRLMLWpgyeiDWLsbXC+znQIGj8UTBDMkNjRbk4Mm97Codw8dPXvx1R5IC5y9/CGMIZhjFCESiF0GJmKuEJTIJAhBMCMiQ/NZwNEkkYWHdpzO/euejimNkGcFPvv9G8g9wRwUCZRNDRDmCgVKUiMIZog1NJmCaf6efg9vfv/f8Jvv/1ve+I8f4LN3Xk/BKcEcXAQwSperg86loBFKUscQBDPCOppMwLTCQ2EHRnv57B3XYQRiByIEc4wCkcnocFVQw9whlEwVEYJgJhhH85lWeQLZWYK5HjSS02Frc6yjgYIkCMz0VwUEIWjCtT9B4CSnaOqQC8dFOUQf53OD8BjKkUQopoZC6ojE84QElEkqAPrYzwIKqChPToglQVAUYZoFgTiCIGhQwJFRliqoHBkEhz4fWQgIYISalamC1CmpUfKp8gdLFDUKoiQGcgEz9T4VsCi5y/lObZBNtW3E3gNgVbC5AcB4wXmDUcH6g2UO/djUZ+uFKDdEmcUdfM0doqACioKAF300hIxRSmSIF1QABESZLkHgaD5PEDSjiVYQBXJQD5qDoYDzOVVxJNaS2cmQGImVfSXYV1b2d+SMFXOqsSePcnKXkUQ5SexJo4xarNScklgltZ7MKrmdChvjwSgCgGJQhElGPE48t4449td3gXiekBfIDW6qotzi/KHPcWYppG6ibKNKqaNUjykljnI9oqtaaFR3NaazbqknVTSuQx4juWASAQU1gAGVqfcCoByHIPBy0Us9TXY5cAfTLQhUjggSD6iZLBHAebLOAbRnN653F65zP/0927h26acYLtXY36GMFjOSQoZzKc5mWJtOdSegoqiAoFgFg2JRppoWBBAVBEBpECbpobA7QiQ5Xxw+n021hSA5T0oO/0OPei+H/7wCwmFnaeAFUcGoNDqfqNJFPj4fV+0iGu8hGp2HrXQTjfcRjfbhKj1EI/3YpAAK4gEFODqIlCA4StoKQXMpcCdB8BSJCuoBD6qThUIeQVauYnp2E3Xtw3bvxS7YSLz0IQp92ykVR+gojBAVhzGFCiauYiQn80UiBTNVqIAeHg7CTIkl40vD57GpthgkY8Yc3ZmIB+NB/KH3KpAWkaSAyQrYtIAb7yUeWExxcDHx4BKikXlElV5cpQs31odNQAVo1KH3agCUYE6qt0LQXAzczY8UBALKZOVANvVSBDqHiUpDaP827Mr7KC9eR0fXHsqd+3A9uxvdSsHVKOIxKqgaUEER8FPvMYcCpUkKJuNLQ+excSpomk50KnwA/NRnPRRGWYSt9GCrnUQHQ2hwEcV9KylNVGFwSePHG1W3iIJaUAMqc+gYLqi2QtBcANwFOILgKOIFMvAecgsaK6Y4Sr70YeIV99HZu43SvK24JQ9T7N1BVzxKwSYgHgGMN6h34C2qgkdoYY2g+crQuayvLQHJaHmHh47kIBw6R0sj4pEFFBrdz2KK+1dQ2rOK4oEVuGoHkllMBmqYCiAlmJVGWyFozgLuJHz5WaACGaiCB0Qg7R6Fxesp9m+iOBEm8cp76Vn4CD3lfdjiGNYmRCqQOdQ7vBoUoV0VJOOmkXN4pLoEJKetiYLJD1UeIUkRk5Qp7l9KefepFPespjiwbOLzcqKxTlAmayp8VJS2Fww4mk1JEeohaOYgL6Cg+WRlRWDRdgrzdhCvvpPO075Lb/8GCr27iMqDlCTD5g4/FShkEaQxGS0pfO+KCuSuUQ2iqE3Jy0OMrz7A+Jp7AEEqXVPHbkvo2H4GHdvOojjxPh5eiK2aqW4HkDbteoKkFTqalcD3gCUEs5yABzLIPeRlj+3eg5x6Nx2n3E7vwocpLn2Acu8OOkyCqIC3jdKJ8gizXUEybhk5i4eqy0By5gSTH7aIoKBgR+dT3L+M0t5T6Nx6Dh07zsCN9+CqEQqoa6MFg2Cro9lEE1TqBLOTCqTgFdSBdowhp9xF54r76FjzXbpW3k1v+QDW1bCAZDE+dXgi5iIFDMqc4m2jDpeXhxk/ZT/jp/6A/Zd/HlProLTnFDq3nUV55xl0bD+LaLQbyQUEvANEaUlB6mg2lQSoE8wScsQDkHkBdPWDlFffQ/ncm5i/9Id09OxqrBTH3qBZAX/wtd5BTgAg4W+YR4WP4uMq46fcx/iauyEpNVapO3aeRtfGi+nYfnqj87F1QQ2TZQGUlhDUHU0nVdBx2legAgpkkCn4vmGi+ZspnPtV+k+/je5l99PRtZeCF/zUBpjWOsgQfrQQNIGACqQxEIN4su79DPfuYfi8b2LGeynuW9E4Yut+5DJKe1cRjXaCCGpb4IgtqDiaTJWawChCOwoBk0BmQDoqmDV3MO/8r9B12rfoXfQwHa6KKJDF+EawBNNwnXmgBvKD5QAa3U5l5QNUVq1l7zM+RXEiaDq2nU3PI5fSsfVcXKWMeEGjJm2xBVVHk4moIlRQ2kAgXvAZKJCX69izv0fvWd+k57yvMH/eBuLiKDaL8AfDJS8TnNyts3DMBrVFm6ktXc+BS25q3GLQs/5SujZdSOeW83DjRZCT+dxOIFBxQvPFhtFaDkLQumuqoBkkJcWdeg+dl36KBWd+na4F6ykXRjBpgdw7tNZJRvDUCQYFlOApyqLJEiXp38m+ieDZd8XnKexfTvdE6PSuu7KxUOCqFu9m+o62wAvjcuHLPE2n/JvAz9F6QsDUIY3ALNxG8cIv0H/el+k75Xa641HwDs0ivFqmRxBLzu3jp3DX2GoQzzQJxIPNwWaQxo2g6XnoSvoefAaFgcVIBj4KgTMTBD7ojNJ0CntoHUEm5DloZ43okptYfP5EuJzzVXo792BRNC2Q1ztpG+HoLFADmXm006mseIDKyrXsuep/6N54EX1rr6Z7/WW4aoQ3oE6ZHoHCPqe0At0DQhMFXtAMvIJfvIPOi77I/Cs+2lhHLkZVSErkB4tgJikgBDP/bFfh0UWCofO/ztDZ36G4dzXz7ns2vQ9dSXHfYhBQd+ILBIHucaA0ncouhGYJAZNAVlSiM+6m7+kfZdE5N9HTvwmXOfI8Jq91cvIERjwnSaAGkhKIUlu8kZ3L1rH3Gf9L9yNX0H/v8+ncdiYmOaGNtUDNbocamk2F3YJyEgVe8An4jhR74VdZds0HWXjm1+hwFchj/Jwb6oejs3Cha9SorGOYgUu/yMAFtza21frveR49D18xeawWh8A5XiLsdSI0XVHYU1e8giGYWbngM8g7a5Se/jn6n/FhFq2+nZKtomk5zF5C0AS5myxRRs+4g9E1dzeuvOm/+zp6H3wG0VgBHx3renSQ5exxWU7TeWHYGPYDCwlmjgc/byelSz7L4qf/J/1L7ydWJc+K5HkHrSEwBK3zQHIRUMZXPNCovU/7DP33PJ++tc/AjfeBEDy5cTE6+P8BW01E00mieO8AAAAASUVORK5CYII=) no-repeat 150% 100%;\n background-color: #2238b3;\n background-size: 205px;\n background-blend-mode: luminosity;\n }\n .leftnav__header__title {\n font-family: var(--text-font-family);\n font-size: var(--title-font-size);\n line-height: var(--title-line-height);\n font-weight: 300;\n color: #fff;\n margin: 0;\n padding: 0;\n }\n .leftnav__header__version {\n color: #aab3ed;\n font-family: var(--text-font-family);\n font-size: var(--body-font-size);\n line-height: var(--body-line-height);\n }\n @media screen and (max-width: 964px) {\n .lh-leftnav {\n display: none;\n }\n }\n @media print {\n .lh-leftnav {\n display: none;\n }\n }\n </style>\n <nav class=\"lh-leftnav\">\n <div class=\"leftnav__header\">\n <h1 class=\"leftnav__header__title\">Lighthouse</h1>\n <div class=\"leftnav__header__version\"><!-- fill me --></div>\n </div>\n <template id=\"tmpl-lh-leftnav__items\">\n <a href=\"#\" class=\"lh-leftnav__item\">\n <span class=\"leftnav-item__category\"><!-- fill me --></span>\n <span class=\"leftnav-item__score\"><!-- fill me --></span>\n </a>\n </template>\n </nav>\n</template>\n\n<!-- Lighthouse header -->\n<template id=\"tmpl-lh-heading\">\n <style>\n :root {\n --report-header-height: 58px;\n --report-header-bg-color: #fafafa;\n }\n .lh-header {\n display: flex;\n height: var(--report-header-height);\n left: 0;\n right: 0;\n max-width: 100%; /* support text-overflow on url */\n border-bottom: 1px solid var(--report-secondary-border-color);\n position: fixed;\n z-index: 1;\n will-change: transform;\n background-color: var(--report-header-bg-color);\n margin-left: var(--report-menu-width);\n align-items: center;\n padding: 0 calc(var(--default-padding) * 2);\n }\n .lh-metadata {\n flex: 1 1 0;\n padding-right: calc(var(--default-padding) / 2);\n line-height: 20px;\n color: var(--secondary-text-color);\n overflow-x: hidden;\n }\n .lh-metadata__results {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .lh-metadata__url {\n color: currentColor;\n }\n .lh-export {\n position: relative;\n }\n .lh-export__button {\n background-color: #fff;\n border: 1px solid var(--report-border-color);\n border-radius: 3px;\n cursor: pointer;\n outline: none;\n height: 32px;\n width: 48px;\n background-repeat: no-repeat;\n background-size: 20px;\n background-position: 50% 50%;\n }\n .lh-export__button:focus,\n .lh-export__button.active {\n box-shadow: 1px 1px 3px #ccc;\n }\n .lh-export__button.active + .lh-export__dropdown {\n opacity: 1;\n clip: rect(0, 164px, 200px, 0);\n }\n .lh-export__dropdown {\n position: absolute;\n background-color: #fff;\n border: 1px solid var(--report-border-color);\n border-radius: 3px;\n padding: calc(var(--default-padding) / 2) 0;\n cursor: pointer;\n top: 36px;\n right: 0;\n box-shadow: 1px 1px 3px #ccc;\n min-width: 125px;\n clip: rect(0, 164px, 0, 0);\n opacity: 0;\n transition: all 200ms cubic-bezier(0,0,0.2,1);\n }\n .lh-export__dropdown a {\n display: block;\n color: currentColor;\n text-decoration: none;\n white-space: nowrap;\n padding: 0 12px;\n line-height: 2;\n }\n .lh-export__dropdown a:hover,\n .lh-export__dropdown a:focus {\n background-color: #efefef;\n outline: none;\n }\n .lh-export__dropdown .report-icon {\n cursor: pointer;\n background-repeat: no-repeat;\n background-position: 8px 50%;\n background-size: 18px;\n background-color: transparent;\n text-indent: 18px;\n }\n /* copy icon needs slight adjustments to look great */\n .lh-export__dropdown .report-icon--copy {\n background-size: 16px;\n background-position: 9px 50%;\n }\n /* save-as-gist option hidden in report */\n .lh-export__dropdown .lh-export--gist {\n display: none;\n }\n .lh-config {\n display: flex;\n }\n .lh-env {\n padding: var(--default-padding) 0 var(--default-padding) calc(var(--default-padding) * 2);\n left: 0;\n top: 100%;\n position: absolute;\n width: 100%;\n background-color: var(--report-header-bg-color);\n border-top: 1px solid var(--report-secondary-border-color);\n border-bottom: 1px solid var(--report-secondary-border-color);\n }\n .lh-env__title {\n font-size: var(--header-font-size);\n }\n .lh-env__items {\n margin: var(--default-padding) 0 0 0;\n }\n .lh-config__timestamp {\n margin-right: 6px;\n }\n .lh-config__settings-toggle {\n margin-left: 6px;\n }\n .lh-config__timestamp,\n .lh-config__settings-toggle summary {\n color: var(--secondary-text-color);\n }\n .lh-config__settings-toggle summary {\n display: flex;\n align-items: center;\n }\n .lh-config__settings-toggle .lh-toggle-arrow {\n width: 16px;\n height: 16px;\n margin-left: 2px;\n }\n .lh-config__settings-toggle[open] .lh-toggle-arrow {\n transform: rotateZ(90deg);\n }\n .lh-config__settings-toggle summary::-moz-list-bullet {\n display: none;\n }\n .lh-config__settings-toggle summary::-webkit-details-marker {\n display: none;\n }\n @media screen and (min-width: 965px) {\n .lh-header {\n width: var(--report-width);\n right: initial;\n left: initial;\n }\n }\n @media screen and (max-width: 964px) {\n .lh-export__dropdown {\n right: 0;\n left: initial;\n }\n .lh-header {\n padding: 0 var(--default-padding);\n margin-left: 0;\n }\n }\n @media print {\n .lh-header {\n position: static;\n margin-left: 0;\n }\n }\n </style>\n <div class=\"lh-header\">\n <div class=\"lh-metadata\">\n <div class=\"lh-metadata__results\">Results for: <a href=\"\" class=\"lh-metadata__url\" target=\"_blank\" rel=\"noopener\"><!-- fill me --></a></div>\n <div class=\"lh-config\">\n <span class=\"lh-config__timestamp\"><!-- fill me --></span> •\n <details class=\"lh-config__settings-toggle\">\n <summary>\n <span>Runtime settings</span>\n <span class=\"lh-toggle-arrow\" title=\"See report's runtime settings\"></span>\n </summary>\n <div class=\"lh-env\">\n <div class=\"lh-env__title\">Runtime environment</div>\n <ul class=\"lh-env__items\">\n <li class=\"lh-env__item\">\n <span class=\"lh-env__name\">User agent:</span>\n <b class=\"lh-env__item__ua\"><!-- fill me --></b>\n </li>\n <template id=\"tmpl-lh-env__items\">\n <li class=\"lh-env__item\">\n <span class=\"lh-env__name\"><!-- fill me --></span>\n <span class=\"lh-env__description\"><!-- fill me --></span>:\n <b class=\"lh-env__enabled\"><!-- fill me --></b>\n </li>\n </template>\n </ul>\n </div>\n </details>\n </div>\n </div>\n <div class=\"lh-export\">\n <button class=\"report-icon report-icon--share lh-export__button\" title=\"Export report\"></button>\n <div class=\"lh-export__dropdown\">\n <a href=\"#\" class=\"report-icon report-icon--print\" data-action=\"print\">Print...</a>\n <a href=\"#\" class=\"report-icon report-icon--copy\" data-action=\"copy\">Copy JSON</a>\n <a href=\"#\" class=\"report-icon report-icon--download\" data-action=\"save-html\">Save as HTML</a>\n <a href=\"#\" class=\"report-icon report-icon--download\" data-action=\"save-json\">Save as JSON</a>\n <a href=\"#\" class=\"report-icon report-icon--open lh-export--viewer\" data-action=\"open-viewer\">Open in Viewer</a>\n <a href=\"#\" class=\"report-icon report-icon--open lh-export--gist\" data-action=\"save-gist\">Save as Gist</a>\n </div>\n </div>\n </div>\n</template>\n\n<!-- Lighthouse footer -->\n<template id=\"tmpl-lh-footer\">\n <style>\n .lh-footer {\n min-height: 90px;\n display: flex;\n align-items: center;\n justify-content: center;\n background-color: var(--report-header-bg-color);\n border-top: 1px solid var(--report-secondary-border-color);\n }\n\n .lh-footer span {\n text-align: center;\n }\n </style>\n <footer class=\"lh-footer\">\n <span>\n Generated by <b>Lighthouse</b> <span class=\"lh-footer__version\"><!-- fill me --></span> on\n <span class=\"lh-footer__timestamp\"><!-- fill me --></span> |\n <a href=\"https://github.com/GoogleChrome/Lighthouse/issues\" target=\"_blank\" rel=\"noopener\">File an issue</a>\n </span>\n </footer>\n</template>\n\n<!-- Lighthouse score gauge -->\n<template id=\"tmpl-lh-gauge\">\n <style>\n .lh-gauge {\n --circle-size: calc(2.5 * var(--header-font-size));\n --circle-size-half: calc(var(--circle-size) / 2);\n --circle-background: #ccc;\n --circle-border-width: 2px;\n --inset-size: calc(var(--circle-size) - 2 * var(--circle-border-width));\n --inset-color: #fff;\n --transition-length: 1s;\n width: var(--circle-size);\n height: var(--circle-size);\n background-color: var(--circle-background);\n border-radius: 50%;\n }\n .lh-gauge--pass {\n --circle-color: var(--pass-color);\n color: var(--circle-color);\n }\n .lh-gauge--average {\n --circle-color: var(--average-color);\n color: var(--circle-color);\n }\n .lh-gauge--fail {\n --circle-color: var(--fail-color);\n color: var(--circle-color);\n }\n .lh-gauge__mask,\n .lh-gauge__fill {\n width: var(--circle-size);\n height: var(--circle-size);\n position: absolute;\n transition: transform var(--transition-length);\n border-radius: 50%;\n }\n .lh-gauge__mask {\n clip: rect(0px, var(--circle-size), var(--circle-size), var(--circle-size-half));\n }\n .lh-gauge__mask .lh-gauge__fill {\n clip: rect(0px, var(--circle-size-half), var(--circle-size), 0px);\n background-color: var(--circle-color);\n backface-visibility: hidden;\n }\n .lh-gauge__percentage {\n --spacer: calc((var(--circle-size) - var(--inset-size)) / 2);\n width: var(--inset-size);\n height: var(--inset-size);\n position: absolute;\n margin-left: var(--spacer);\n margin-top: var(--spacer);\n background-color: var(--inset-color);\n border-radius: inherit;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: var(--header-font-size);\n }\n .lh-gauge__wrapper {\n display: inline-flex;\n align-items: center;\n flex-direction: column;\n text-decoration: none;\n color: inherit;\n flex: 1;\n min-width: auto;\n position: relative;\n }\n .lh-scores-header .lh-gauge__wrapper {\n width: calc(10.5 * var(--body-font-size));\n }\n .lh-gauge__label {\n font-size: var(--body-font-size);\n line-height: var(--body-line-height);\n margin-top: calc(0.5 * var(--body-line-height));\n text-align: center;\n }\n </style>\n <a href=\"#\" class=\"lh-gauge__wrapper\">\n <div class=\"lh-gauge\" data-progress=\"0\">\n <div class=\"lh-gauge__circle\">\n <div class=\"lh-gauge__mask lh-gauge__mask--full\">\n <div class=\"lh-gauge__fill\"></div>\n </div>\n <div class=\"lh-gauge__mask lh-gauge__mask--half\">\n <div class=\"lh-gauge__fill\"></div>\n <div class=\"lh-gauge__fill lh-gauge__fill--fix\"></div>\n </div>\n </div>\n <div class=\"lh-gauge__percentage\"></div>\n </div>\n <div class=\"lh-gauge__label\"><!-- fill me --></div>\n </a>\n</template>\n\n<!-- Lighthouse crtiical request chains component -->\n<template id=\"tmpl-lh-crc\">\n <style>\n .lh-crc .tree-marker {\n width: 12px;\n height: 26px;\n display: block;\n float: left;\n background-position: top left;\n }\n .lh-crc .horiz-down {\n background: url('data:image/svg+xml;utf8,<svg width=\"16\" height=\"26\" viewBox=\"0 0 16 26\" xmlns=\"http://www.w3.org/2000/svg\"><g fill=\"#D8D8D8\" fill-rule=\"evenodd\"><path d=\"M16 12v2H-2v-2z\"/><path d=\"M9 12v14H7V12z\"/></g></svg>');\n }\n .lh-crc .right {\n background: url('data:image/svg+xml;utf8,<svg width=\"16\" height=\"26\" viewBox=\"0 0 16 26\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M16 12v2H0v-2z\" fill=\"#D8D8D8\" fill-rule=\"evenodd\"/></svg>');\n }\n .lh-crc .up-right {\n background: url('data:image/svg+xml;utf8,<svg width=\"16\" height=\"26\" viewBox=\"0 0 16 26\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M7 0h2v14H7zm2 12h7v2H9z\" fill=\"#D8D8D8\" fill-rule=\"evenodd\"/></svg>');\n }\n .lh-crc .vert-right {\n background: url('data:image/svg+xml;utf8,<svg width=\"16\" height=\"26\" viewBox=\"0 0 16 26\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M7 0h2v27H7zm2 12h7v2H9z\" fill=\"#D8D8D8\" fill-rule=\"evenodd\"/></svg>');\n }\n .lh-crc .vert {\n background: url('data:image/svg+xml;utf8,<svg width=\"16\" height=\"26\" viewBox=\"0 0 16 26\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M7 0h2v26H7z\" fill=\"#D8D8D8\" fill-rule=\"evenodd\"/></svg>');\n }\n .lh-crc .crc-tree {\n font-size: 14px;\n width: 100%;\n overflow-x: auto;\n }\n .lh-crc .crc-node {\n height: 26px;\n line-height: 26px;\n white-space: nowrap;\n }\n .lh-crc .crc-node__tree-value {\n margin-left: 10px;\n }\n .lh-crc .crc-node__chain-duration {\n font-weight: 700;\n }\n .lh-crc .crc-node__tree-hostname {\n color: #595959;\n }\n .lh-crc .crc-initial-nav {\n color: #595959;\n font-style: italic;\n }\n </style>\n <div class=\"lh-score__description\">\n Longest chain: <b class=\"lh-crc__longest_duration\"><!-- fill me: longestChain.duration --></b>\n over <b class=\"lh-crc__longest_length\"><!-- fill me: longestChain.length --></b> requests, totalling\n <b class=\"lh-crc__longest_transfersize\"><!-- fill me: longestChain.length --></b>\n </div>\n <div class=\"lh-crc\">\n <details class=\"lh-details\">\n <summary><!-- fill me --></summary>\n <div class=\"crc-initial-nav\">Initial Navigation</div>\n <!-- stamp for each chain -->\n <template id=\"tmpl-lh-crc__chains\">\n <div class=\"crc-node\">\n <span class=\"crc-node__tree-marker\">\n <!-- fill me -->\n </span>\n <span class=\"crc-node__tree-value\">\n <span class=\"crc-node__tree-file\"><!-- fill me: node.request.url.file --></span>\n <span class=\"crc-node__tree-hostname\">(<!-- fill me: node.request.url.host -->)</span>\n <!-- fill me -->\n </span>\n </div>\n </template>\n </details>\n </div>\n</template>\n\n/*# sourceURL=audits2/lighthouse/templates.html */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/audits2_worker.js b/src/cobalt/debug/content/devtools/audits2_worker.js deleted file mode 100644 index fd16039..0000000 --- a/src/cobalt/debug/content/devtools/audits2_worker.js +++ /dev/null
@@ -1,154 +0,0 @@ -var allDescriptors=[{"skip_compilation":["lighthouse/lighthouse-background.js"],"dependencies":["worker_service"],"extensions":[{"factoryName":"Audits2Service","type":"@Service","name":"Audits2Service"}],"name":"audits2_worker","scripts":["audits2_worker_module.js"]},{"name":"worker_service"}];var applicationDescriptor;var _loadedScripts={};for(var k of[]){} -(function(){var baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();var Runtime=class{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(var i=0;i<descriptors.length;++i) -this._registerModule(descriptors[i]);} -static loadResourcePromise(url){return new Promise(load);function load(fulfill,reject){var xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE) -return;if([0,200,304].indexOf(xhr.status)===-1) -reject(new Error('While loading from url '+url+' server responded with a status of '+xhr.status));else -fulfill(e.target.response);} -xhr.send(null);}} -static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1) -return path;var normalizedSegments=[];var segments=path.split('/');for(var i=0;i<segments.length;i++){var segment=segments[i];if(segment==='.') -continue;else if(segment==='..') -normalizedSegments.pop();else if(segment) -normalizedSegments.push(segment);} -var normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/') -return normalizedPath;if(path[0]==='/'&&normalizedPath) -normalizedPath='/'+normalizedPath;if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..')) -normalizedPath=normalizedPath+'/';return normalizedPath;} -static _loadScriptsPromise(scriptNames,base){var promises=[];var urls=[];var sources=new Array(scriptNames.length);var scriptToEval=0;for(var i=0;i<scriptNames.length;++i){var scriptName=scriptNames[i];var sourceURL=(base||self._importScriptPathPrefix)+scriptName;var schemaIndex=sourceURL.indexOf('://')+3;var pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1) -pathIndex=sourceURL.length;sourceURL=sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));if(_loadedScripts[sourceURL]) -continue;urls.push(sourceURL);promises.push(Runtime.loadResourcePromise(sourceURL).then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));} -return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}} -function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;} -self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}} -static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;} -var sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}} -static startApplication(appName){console.timeStamp('Runtime.startApplication');var allDescriptorsByName={};for(var i=0;i<allDescriptors.length;++i){var d=allDescriptors[i];allDescriptorsByName[d['name']]=d;} -var applicationPromise;if(applicationDescriptor) -applicationPromise=Promise.resolve(applicationDescriptor);else -applicationPromise=Runtime.loadResourcePromise(appName+'.json').then(JSON.parse.bind(JSON));return applicationPromise.then(parseModuleDescriptors);function parseModuleDescriptors(appDescriptor){var configuration=appDescriptor.modules;var moduleJSONPromises=[];var coreModuleNames=[];for(var i=0;i<configuration.length;++i){var descriptor=configuration[i];var name=descriptor['name'];var moduleJSON=allDescriptorsByName[name];if(moduleJSON) -moduleJSONPromises.push(Promise.resolve(moduleJSON));else -moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));if(descriptor['type']==='autostart') -coreModuleNames.push(name);} -return Promise.all(moduleJSONPromises).then(instantiateRuntime);function instantiateRuntime(moduleDescriptors){for(var i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';} -self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames) -return(self.runtime._loadAutoStartModules(coreModuleNames));return Promise.resolve();}}} -static startWorker(appName){return Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}} -static queryParam(name){return Runtime._queryParamsObject[name]||null;} -static queryParamsString(){return location.search;} -static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}} -static _assert(value,message){if(value) -return;Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);} -static setPlatform(platform){Runtime._platform=platform;} -static _isDescriptorEnabled(descriptor){var activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*') -return Runtime.experiments.supportEnabled();if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1))) -return false;if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment)) -return false;var condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition)) -return false;if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1))) -return false;return true;} -static resolveSourceURL(path){var sourceURL=self.location.href;if(self.location.search) -sourceURL=sourceURL.replace(self.location.search,'');sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';} -useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend')) -Runtime._remoteBase+='debug/';} -_registerModule(descriptor){var module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;} -loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();} -_loadAutoStartModules(moduleNames){var promises=[];for(var i=0;i<moduleNames.length;++i) -promises.push(this.loadModulePromise(moduleNames[i]));return Promise.all(promises);} -_checkExtensionApplicability(extension,predicate){if(!predicate) -return false;var contextTypes=extension.descriptor().contextTypes;if(!contextTypes) -return true;for(var i=0;i<contextTypes.length;++i){var contextType=this._resolve(contextTypes[i]);var isMatching=!!contextType&&predicate(contextType);if(isMatching) -return true;} -return false;} -isExtensionApplicableToContext(extension,context){if(!context) -return true;return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}} -isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes) -return true;return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}} -extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type) -return false;if(!extension.enabled()) -return false;return!context||extension.isApplicable(context);} -function orderComparator(extension1,extension2){var order1=extension1.descriptor()['order']||0;var order2=extension2.descriptor()['order']||0;return order1-order2;} -function titleComparator(extension1,extension2){var title1=extension1.title()||'';var title2=extension2.title()||'';return title1.localeCompare(title2);}} -extension(type,context){return this.extensions(type,context)[0]||null;} -allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));} -_resolve(typeName){if(!this._cachedTypeClasses[typeName]){var path=typeName.split('.');var object=self;for(var i=0;object&&(i<path.length);++i) -object=object[path[i]];if(object) -this._cachedTypeClasses[typeName]=(object);} -return this._cachedTypeClasses[typeName]||null;} -sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction) -return constructorFunction[Runtime._instanceSymbol];var instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}};Runtime._queryParamsObject={__proto__:null};Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';Runtime.ModuleDescriptor=class{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.condition;this.remote;}};Runtime.ExtensionDescriptor=class{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}};Runtime.Module=class{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();var extensions=(descriptor.extensions);for(var i=0;extensions&&i<extensions.length;++i){var extension=new Runtime.Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);} -this._loadedForTest=false;} -name(){return this._name;} -enabled(){return Runtime._isDescriptorEnabled(this._descriptor);} -resource(name){var fullName=this._name+'/'+name;var content=Runtime.cachedResources[fullName];if(!content) -throw new Error(fullName+' not preloaded. Check module.json');return content;} -_loadPromise(){if(!this.enabled()) -return Promise.reject(new Error('Module '+this._name+' is not enabled'));if(this._pendingLoadPromise) -return this._pendingLoadPromise;var dependencies=this._descriptor.dependencies;var dependencyPromises=[];for(var i=0;dependencies&&i<dependencies.length;++i) -dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;} -_loadResources(){var resources=this._descriptor['resources'];if(!resources||!resources.length) -return Promise.resolve();var promises=[];for(var i=0;i<resources.length;++i){var url=this._modularizeURL(resources[i]);promises.push(Runtime._loadResourceIntoCache(url,true));} -return Promise.all(promises).then(undefined);} -_loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length) -return Promise.resolve();const specialCases={'sdk':'SDK','ui':'UI','object_ui':'ObjectUI','perf_ui':'PerfUI','har_importer':'HARImporter','sass_test_runner':'SASSTestRunner','sdk_test_runner':'SDKTestRunner'};var namespace=specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());} -_modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);} -_remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;} -substituteURL(value){var base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}};Runtime.Extension=class{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;} -descriptor(){return this._descriptor;} -module(){return this._module;} -enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());} -_typeClass(){if(!this._hasTypeClass) -return null;return this._module._manager._resolve(this._type.substring(1));} -isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);} -instance(){return this._module._loadPromise().then(this._createInstance.bind(this));} -_createInstance(){var className=this._className||this._factoryName;if(!className) -throw new Error('Could not instantiate extension with no class');var constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function)) -throw new Error('Could not instantiate: '+className);if(this._className) -return this._module._manager.sharedInstance(constructorFunction);return new constructorFunction(this);} -title(){return this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];} -hasContextType(contextType){var contextTypes=this.descriptor().contextTypes;if(!contextTypes) -return false;for(var i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i])) -return true;} -return false;}};Runtime.ExperimentsSupport=class{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};} -allConfigurableExperiments(){var result=[];for(var i=0;i<this._experiments.length;i++){var experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name]) -result.push(experiment);} -return result;} -supportEnabled(){return this._supportEnabled;} -_setExperimentsSetting(value){if(!self.localStorage) -return;self.localStorage['experiments']=JSON.stringify(value);} -register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));} -isEnabled(experimentName){this._checkExperiment(experimentName);if(this._enabledTransiently[experimentName]) -return true;if(!this.supportEnabled()) -return false;return!!Runtime._experimentsSetting()[experimentName];} -setEnabled(experimentName,enabled){this._checkExperiment(experimentName);var experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);} -setDefaultExperiments(experimentNames){for(var i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}} -enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;} -clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};} -cleanUpStaleExperiments(){var experimentsSetting=Runtime._experimentsSetting();var cleanedUpExperimentSetting={};for(var i=0;i<this._experiments.length;++i){var experimentName=this._experiments[i].name;if(experimentsSetting[experimentName]) -cleanedUpExperimentSetting[experimentName]=true;} -this._setExperimentsSetting(cleanedUpExperimentSetting);} -_checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}};Runtime.Experiment=class{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;} -isEnabled(){return this._experiments.isEnabled(this.name);} -setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}};{(function parseQueryParameters(){var queryParams=Runtime.queryParamsString();if(!queryParams) -return;var params=queryParams.substring(1).split('&');for(var i=0;i<params.length;++i){var pair=params[i].split('=');var name=pair.shift();Runtime._queryParamsObject[name]=pair.join('=');}})();} -Runtime.experiments=new Runtime.ExperimentsSupport();Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('chrome-devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){var versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch) -Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}})();function ServicePort(){} -ServicePort.prototype={setHandlers(messageHandler,closeHandler){},send(message){},close(){}};var runtime;self['WorkerService']=self['WorkerService']||{};function Service(){} -Service.prototype={dispose(){},setNotify(notify){}};var ServiceDispatcher=class{constructor(port){this._objects=new Map();this._lastObjectId=1;this._port=port;this._port.setHandlers(this._dispatchMessageWrapped.bind(this),this._connectionClosed.bind(this));} -_dispatchMessageWrapped(data){try{var message=JSON.parse(data);if(!(message instanceof Object)){this._sendErrorResponse(message['id'],'Malformed message');return;} -this._dispatchMessage(message);}catch(e){this._sendErrorResponse(message['id'],e.toString()+' '+e.stack);}} -_dispatchMessage(message){var domainAndMethod=message['method'].split('.');var serviceName=domainAndMethod[0];var method=domainAndMethod[1];if(method==='create'){var extensions=self.runtime.extensions(Service).filter(extension=>extension.descriptor()['name']===serviceName);if(!extensions.length){this._sendErrorResponse(message['id'],'Could not resolve service \''+serviceName+'\'');return;} -extensions[0].instance().then(object=>{var id=String(this._lastObjectId++);object.setNotify(this._notify.bind(this,id,serviceName));this._objects.set(id,object);this._sendResponse(message['id'],{id:id});});}else if(method==='dispose'){var object=this._objects.get(message['params']['id']);if(!object){console.error('Could not look up object with id for '+JSON.stringify(message));return;} -this._objects.delete(message['params']['id']);object.dispose().then(()=>this._sendResponse(message['id'],{}));}else{if(!message['params']){console.error('No params in the message: '+JSON.stringify(message));return;} -var object=this._objects.get(message['params']['id']);if(!object){console.error('Could not look up object with id for '+JSON.stringify(message));return;} -var handler=object[method];if(!(handler instanceof Function)){console.error('Handler for \''+method+'\' is missing.');return;} -object[method](message['params']).then(result=>this._sendResponse(message['id'],result));}} -_connectionClosed(){for(var object of this._objects.values()) -object.dispose();this._objects.clear();} -_notify(objectId,serviceName,method,params){params['id']=objectId;var message={method:serviceName+'.'+method,params:params};this._port.send(JSON.stringify(message));} -_sendResponse(messageId,result){var message={id:messageId,result:result};this._port.send(JSON.stringify(message));} -_sendErrorResponse(messageId,error){var message={id:messageId,error:error};this._port.send(JSON.stringify(message));}};var WorkerServicePort=class{constructor(port){this._port=port;this._port.onmessage=this._onMessage.bind(this);this._port.onerror=console.error;} -setHandlers(messageHandler,closeHandler){this._messageHandler=messageHandler;this._closeHandler=closeHandler;} -send(data){this._port.postMessage(data);return Promise.resolve();} -close(){return Promise.resolve();} -_onMessage(event){this._messageHandler(event.data);}};var dispatchers=[];var worker=(self);var servicePort=new WorkerServicePort((worker));dispatchers.push(new ServiceDispatcher(servicePort));;applicationDescriptor={"has_html":false,"modules":[{"type":"remote","name":"audits2_worker"},{"type":"autostart","name":"worker_service"}]};if(!self.Runtime) -self.importScripts('Runtime.js');Runtime.startWorker('audits2_worker'); \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/changes/changes_module.js b/src/cobalt/debug/content/devtools/changes/changes_module.js deleted file mode 100644 index 222f89c..0000000 --- a/src/cobalt/debug/content/devtools/changes/changes_module.js +++ /dev/null
@@ -1,69 +0,0 @@ -Changes.ChangesHighlighter=function(config,parserConfig){var diffRows=parserConfig.diffRows;var baselineLines=parserConfig.baselineLines;var currentLines=parserConfig.currentLines;var syntaxHighlightMode=CodeMirror.getMode({},parserConfig.mimeType);function fastForward(state,baselineLineNumber,currentLineNumber){if(baselineLineNumber>state.baselineLineNumber){fastForwardSyntaxHighlighter(state.baselineSyntaxState,state.baselineLineNumber,baselineLineNumber,baselineLines);state.baselineLineNumber=baselineLineNumber;} -if(currentLineNumber>state.currentLineNumber){fastForwardSyntaxHighlighter(state.currentSyntaxState,state.currentLineNumber,currentLineNumber,currentLines);state.currentLineNumber=currentLineNumber;}} -function fastForwardSyntaxHighlighter(syntaxState,from,to,lines){var lineNumber=from;while(lineNumber<to&&lineNumber<lines.length){var stream=new CodeMirror.StringStream(lines[lineNumber]);if(stream.eol()&&syntaxHighlightMode.blankLine) -syntaxHighlightMode.blankLine(syntaxState);while(!stream.eol()){syntaxHighlightMode.token(stream,syntaxState);stream.start=stream.pos;} -lineNumber++;}} -return{startState:function(){return{rowNumber:0,diffTokenIndex:0,currentLineNumber:0,baselineLineNumber:0,currentSyntaxState:CodeMirror.startState(syntaxHighlightMode),baselineSyntaxState:CodeMirror.startState(syntaxHighlightMode),syntaxPosition:0,diffPosition:0,syntaxStyle:'',diffStyle:''};},token:function(stream,state){var diffRow=diffRows[state.rowNumber];if(!diffRow){stream.next();return'';} -fastForward(state,diffRow.baselineLineNumber-1,diffRow.currentLineNumber-1);var classes='';if(stream.pos===0) -classes+=' line-background-'+diffRow.type+' line-'+diffRow.type;var syntaxHighlighterNeedsRefresh=state.diffPosition>=state.syntaxPosition;if(state.diffPosition<=state.syntaxPosition){state.diffPosition+=diffRow.tokens[state.diffTokenIndex].text.length;state.diffStyle=diffRow.tokens[state.diffTokenIndex].className;state.diffTokenIndex++;} -if(syntaxHighlighterNeedsRefresh){if(diffRow.type===Changes.ChangesView.RowType.Deletion||diffRow.type===Changes.ChangesView.RowType.Addition||diffRow.type===Changes.ChangesView.RowType.Equal){state.syntaxStyle=syntaxHighlightMode.token(stream,diffRow.type===Changes.ChangesView.RowType.Deletion?state.baselineSyntaxState:state.currentSyntaxState);state.syntaxPosition=stream.pos;}else{state.syntaxStyle='';state.syntaxPosition=Infinity;}} -stream.pos=Math.min(state.syntaxPosition,state.diffPosition);classes+=' '+state.syntaxStyle;classes+=' '+state.diffStyle;if(stream.eol()){state.rowNumber++;if(diffRow.type===Changes.ChangesView.RowType.Deletion) -state.baselineLineNumber++;else -state.currentLineNumber++;state.diffPosition=0;state.syntaxPosition=0;state.diffTokenIndex=0;} -return classes;},blankLine:function(state){var diffRow=diffRows[state.rowNumber];state.rowNumber++;state.syntaxPosition=0;state.diffPosition=0;state.diffTokenIndex=0;if(!diffRow) -return'';var style='';if(syntaxHighlightMode.blankLine){if(diffRow.type===Changes.ChangesView.RowType.Equal||diffRow.type===Changes.ChangesView.RowType.Addition){style=syntaxHighlightMode.blankLine(state.currentSyntaxState);state.currentLineNumber++;}else if(diffRow.type===Changes.ChangesView.RowType.Deletion){style=syntaxHighlightMode.blankLine(state.baselineSyntaxState);state.baselineLineNumber++;}} -return style+' line-background-'+diffRow.type+' line-'+diffRow.type;},copyState:function(state){var newState=Object.assign({},state);newState.currentSyntaxState=CodeMirror.copyState(syntaxHighlightMode,state.currentSyntaxState);newState.baselineSyntaxState=CodeMirror.copyState(syntaxHighlightMode,state.baselineSyntaxState);return(newState);}};};Changes.ChangesHighlighter.DiffState;CodeMirror.defineMode('devtools-diff',Changes.ChangesHighlighter);;Changes.ChangesView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('changes/changesView.css');var splitWidget=new UI.SplitWidget(true,false);var mainWidget=new UI.Widget();splitWidget.setMainWidget(mainWidget);splitWidget.show(this.contentElement);this._emptyWidget=new UI.EmptyWidget(Common.UIString('No changes'));this._emptyWidget.show(mainWidget.element);this._workspaceDiff=WorkspaceDiff.workspaceDiff();this._changesSidebar=new Changes.ChangesSidebar(this._workspaceDiff);this._changesSidebar.addEventListener(Changes.ChangesSidebar.Events.SelectedUISourceCodeChanged,this._selectedUISourceCodeChanged,this);splitWidget.setSidebarWidget(this._changesSidebar);this._selectedUISourceCode=null;this._diffRows=[];this._maxLineDigits=1;this._editor=new TextEditor.CodeMirrorTextEditor({lineNumbers:true,lineWrapping:false,maxHighlightLength:Infinity});this._editor.setReadOnly(true);this._editor.show(mainWidget.element.createChild('div','editor-container'));this._editor.hideWidget();this._editor.element.addEventListener('click',this._click.bind(this),false);this._toolbar=new UI.Toolbar('changes-toolbar',mainWidget.element);var revertButton=new UI.ToolbarButton(Common.UIString('Revert all changes'),'largeicon-undo');revertButton.addEventListener(UI.ToolbarButton.Events.Click,this._revert.bind(this));this._toolbar.appendToolbarItem(revertButton);this._diffStats=new UI.ToolbarText('');this._toolbar.appendToolbarItem(this._diffStats);this._toolbar.setEnabled(false);this._selectedUISourceCodeChanged();} -_selectedUISourceCodeChanged(){this._revealUISourceCode(this._changesSidebar.selectedUISourceCode());} -_revert(){var uiSourceCode=this._selectedUISourceCode;if(!uiSourceCode) -return;uiSourceCode.requestOriginalContent().then(original=>uiSourceCode.addRevision(original||''));} -_click(event){var selection=this._editor.selection();if(!selection.isEmpty()) -return;var row=this._diffRows[selection.startLine];Common.Revealer.reveal(this._selectedUISourceCode.uiLocation(row.currentLineNumber-1,selection.startColumn),false);event.consume(true);} -_revealUISourceCode(uiSourceCode){if(this._selectedUISourceCode===uiSourceCode) -return;if(this._selectedUISourceCode) -this._workspaceDiff.unsubscribeFromDiffChange(this._selectedUISourceCode,this._refreshDiff,this);if(uiSourceCode&&this.isShowing()) -this._workspaceDiff.subscribeToDiffChange(uiSourceCode,this._refreshDiff,this);this._selectedUISourceCode=uiSourceCode;this._refreshDiff();} -wasShown(){this._refreshDiff();} -_refreshDiff(){if(!this.isShowing()) -return;if(!this._selectedUISourceCode){this._renderDiffRows(null);return;} -var uiSourceCode=this._selectedUISourceCode;this._workspaceDiff.requestDiff(uiSourceCode).then(diff=>{if(this._selectedUISourceCode!==uiSourceCode) -return;this._renderDiffRows(diff);});} -_renderDiffRows(diff){this._diffRows=[];if(!diff||(diff.length===1&&diff[0][0]===Diff.Diff.Operation.Equal)){this._diffStats.setText('');this._toolbar.setEnabled(false);this._editor.hideWidget();this._emptyWidget.showWidget();return;} -var insertions=0;var deletions=0;var currentLineNumber=0;var baselineLineNumber=0;var paddingLines=3;var originalLines=[];var currentLines=[];for(var i=0;i<diff.length;++i){var token=diff[i];switch(token[0]){case Diff.Diff.Operation.Equal:this._diffRows.pushAll(createEqualRows(token[1],i===0,i===diff.length-1));originalLines.pushAll(token[1]);currentLines.pushAll(token[1]);break;case Diff.Diff.Operation.Insert:for(var line of token[1]) -this._diffRows.push(createRow(line,Changes.ChangesView.RowType.Addition));insertions+=token[1].length;currentLines.pushAll(token[1]);break;case Diff.Diff.Operation.Delete:deletions+=token[1].length;originalLines.pushAll(token[1]);if(diff[i+1]&&diff[i+1][0]===Diff.Diff.Operation.Insert){i++;this._diffRows.pushAll(createModifyRows(token[1].join('\n'),diff[i][1].join('\n')));insertions+=diff[i][1].length;currentLines.pushAll(diff[i][1]);}else{for(var line of token[1]) -this._diffRows.push(createRow(line,Changes.ChangesView.RowType.Deletion));} -break;}} -this._maxLineDigits=Math.ceil(Math.log10(Math.max(currentLineNumber,baselineLineNumber)));this._diffStats.setText(Common.UIString('%d insertion%s (+), %d deletion%s (-)',insertions,insertions!==1?'s':'',deletions,deletions!==1?'s':''));this._toolbar.setEnabled(true);this._emptyWidget.hideWidget();this._editor.operation(()=>{this._editor.showWidget();this._editor.setHighlightMode({name:'devtools-diff',diffRows:this._diffRows,mimeType:(this._selectedUISourceCode).mimeType(),baselineLines:originalLines,currentLines:currentLines});this._editor.setText(this._diffRows.map(row=>row.tokens.map(t=>t.text).join('')).join('\n'));this._editor.setLineNumberFormatter(this._lineFormatter.bind(this));});function createEqualRows(lines,atStart,atEnd){var equalRows=[];if(!atStart){for(var i=0;i<paddingLines&&i<lines.length;i++) -equalRows.push(createRow(lines[i],Changes.ChangesView.RowType.Equal));if(lines.length>paddingLines*2+1&&!atEnd){equalRows.push(createRow(Common.UIString('( \u2026 Skipping ')+(lines.length-paddingLines*2)+ -Common.UIString(' matching lines \u2026 )'),Changes.ChangesView.RowType.Spacer));}} -if(!atEnd){var start=Math.max(lines.length-paddingLines-1,atStart?0:paddingLines);var skip=lines.length-paddingLines-1;if(!atStart) -skip-=paddingLines;if(skip>0){baselineLineNumber+=skip;currentLineNumber+=skip;} -for(var i=start;i<lines.length;i++) -equalRows.push(createRow(lines[i],Changes.ChangesView.RowType.Equal));} -return equalRows;} -function createModifyRows(before,after){var internalDiff=Diff.Diff.charDiff(before,after,true);var deletionRows=[createRow('',Changes.ChangesView.RowType.Deletion)];var insertionRows=[createRow('',Changes.ChangesView.RowType.Addition)];for(var token of internalDiff){var text=token[1];var type=token[0];var className=type===Diff.Diff.Operation.Equal?'':'inner-diff';var lines=text.split('\n');for(var i=0;i<lines.length;i++){if(i>0&&type!==Diff.Diff.Operation.Insert) -deletionRows.push(createRow('',Changes.ChangesView.RowType.Deletion));if(i>0&&type!==Diff.Diff.Operation.Delete) -insertionRows.push(createRow('',Changes.ChangesView.RowType.Addition));if(!lines[i]) -continue;if(type!==Diff.Diff.Operation.Insert) -deletionRows[deletionRows.length-1].tokens.push({text:lines[i],className});if(type!==Diff.Diff.Operation.Delete) -insertionRows[insertionRows.length-1].tokens.push({text:lines[i],className});}} -return deletionRows.concat(insertionRows);} -function createRow(text,type){if(type===Changes.ChangesView.RowType.Addition) -currentLineNumber++;if(type===Changes.ChangesView.RowType.Deletion) -baselineLineNumber++;if(type===Changes.ChangesView.RowType.Equal){baselineLineNumber++;currentLineNumber++;} -return{baselineLineNumber,currentLineNumber,tokens:text?[{text,className:'inner-diff'}]:[],type};}} -_lineFormatter(lineNumber){var row=this._diffRows[lineNumber-1];var showBaseNumber=row.type===Changes.ChangesView.RowType.Deletion;var showCurrentNumber=row.type===Changes.ChangesView.RowType.Addition;if(row.type===Changes.ChangesView.RowType.Equal){showBaseNumber=true;showCurrentNumber=true;} -var base=showBaseNumber?numberToStringWithSpacesPadding(row.baselineLineNumber,this._maxLineDigits):spacesPadding(this._maxLineDigits);var current=showCurrentNumber?numberToStringWithSpacesPadding(row.currentLineNumber,this._maxLineDigits):spacesPadding(this._maxLineDigits);return base+spacesPadding(1)+current;}};Changes.ChangesView.Row;Changes.ChangesView.RowType={Deletion:'deletion',Addition:'addition',Equal:'equal',Spacer:'spacer'};;Changes.ChangesSidebar=class extends UI.Widget{constructor(workspaceDiff){super();this._treeoutline=new UI.TreeOutlineInShadow();this._treeoutline.registerRequiredCSS('changes/changesSidebar.css');this._treeoutline.setComparator((a,b)=>a.titleAsText().compareTo(b.titleAsText()));this._treeoutline.addEventListener(UI.TreeOutline.Events.ElementSelected,this._selectionChanged,this);this.element.appendChild(this._treeoutline.element);this._treeElements=new Map();this._workspaceDiff=workspaceDiff;this._workspaceDiff.modifiedUISourceCodes().forEach(this._addUISourceCode.bind(this));this._workspaceDiff.addEventListener(WorkspaceDiff.Events.ModifiedStatusChanged,this._uiSourceCodeMofiedStatusChanged,this);} -selectedUISourceCode(){return this._treeoutline.selectedTreeElement?this._treeoutline.selectedTreeElement.uiSourceCode:null;} -_selectionChanged(){this.dispatchEventToListeners(Changes.ChangesSidebar.Events.SelectedUISourceCodeChanged);} -_uiSourceCodeMofiedStatusChanged(event){if(event.data.isModified) -this._addUISourceCode(event.data.uiSourceCode);else -this._removeUISourceCode(event.data.uiSourceCode);} -_removeUISourceCode(uiSourceCode){var treeElement=this._treeElements.get(uiSourceCode);this._treeElements.delete(uiSourceCode);if(this._treeoutline.selectedTreeElement===treeElement){var nextElementToSelect=treeElement.previousSibling||treeElement.nextSibling;if(nextElementToSelect){nextElementToSelect.select(true);}else{treeElement.deselect();this._selectionChanged();}} -this._treeoutline.removeChild(treeElement);treeElement.dispose();} -_addUISourceCode(uiSourceCode){var treeElement=new Changes.ChangesSidebar.UISourceCodeTreeElement(uiSourceCode);this._treeElements.set(uiSourceCode,treeElement);this._treeoutline.appendChild(treeElement);if(!this._treeoutline.selectedTreeElement) -treeElement.select(true);}};Changes.ChangesSidebar.Events={SelectedUISourceCodeChanged:Symbol('SelectedUISourceCodeChanged')};Changes.ChangesSidebar.UISourceCodeTreeElement=class extends UI.TreeElement{constructor(uiSourceCode){super();this.uiSourceCode=uiSourceCode;this.listItemElement.classList.add('navigator-'+uiSourceCode.contentType().name()+'-tree-item');var iconType='largeicon-navigator-file';if(this.uiSourceCode.contentType()===Common.resourceTypes.Snippet) -iconType='largeicon-navigator-snippet';var defaultIcon=UI.Icon.create(iconType,'icon');this.setLeadingIcons([defaultIcon]);this._eventListeners=[uiSourceCode.addEventListener(Workspace.UISourceCode.Events.TitleChanged,this._updateTitle,this),uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._updateTitle,this),uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._updateTitle,this)];this._updateTitle();} -_updateTitle(){var titleText=this.uiSourceCode.displayName();if(this.uiSourceCode.isDirty()) -titleText='*'+titleText;this.title=titleText;var tooltip=this.uiSourceCode.url();if(this.uiSourceCode.contentType().isFromSourceMap()) -tooltip=Common.UIString('%s (from source map)',this.uiSourceCode.displayName());this.tooltip=tooltip;} -dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);}};;Runtime.cachedResources["changes/changesView.css"]="/*\n * Copyright (c) 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n.insertion-point-main{\n flex-direction: column;\n display: flex;\n}\n\n.insertion-point-sidebar {\n overflow: auto;\n}\n.editor-container{\n flex: 1;\n}\n\n:focus.selected {\n background-color: rgb(56, 121, 217);\n color: #FFF;\n}\n\n.CodeMirror-lines:not(:active) {\n cursor: default !important;\n}\n\n.CodeMirror-line:hover {\n cursor: default !important;\n background-color: rgba(0,0,255,0.05);\n}\n\n.CodeMirror .CodeMirror-linebackground.spacer {\n text-align: center;\n color: rgba(0, 0, 0, 0.5);\n background-color: rgba(0, 0, 255, 0.1);\n}\n\n.CodeMirror .equal > span > span {\n opacity: .5;\n}\n\n.CodeMirror .CodeMirror-selectedtext:not(.CodeMirror-persist-highlight) {\n opacity: 1.0;\n}\n\n.CodeMirror .CodeMirror-linebackground.addition, -theme-preserve {\n background-color: hsla(144, 55%, 49%, .2);\n}\n\n.CodeMirror .CodeMirror-linebackground.deletion, -theme-preserve {\n background-color: rgba(255, 0, 0, .2);\n}\n\n.CodeMirror .addition .cm-inner-diff:not(.CodeMirror-selectedtext), -theme-preserve {\n background-color: hsla(144, 55%, 49%, .3);\n}\n\n.CodeMirror .deletion .cm-inner-diff:not(.CodeMirror-selectedtext), -theme-preserve {\n background-color: rgba(255, 0, 0, .3);\n}\n\n.changes-toolbar {\n background-color: #f3f3f3;\n border-top: 1px solid #dadada;\n}\n\n/*# sourceURL=changes/changesView.css */";Runtime.cachedResources["changes/changesSidebar.css"]="li .icon {\n margin: -3px -5px -3px -5px;\n background: linear-gradient(45deg, hsl(0, 0%, 50%), hsl(0, 0%, 70%));\n}\n\n.tree-outline li {\n min-height: 20px;\n}\n\n.tree-outline li:hover:not(.selected) .selection {\n display: block;\n background-color: rgba(56, 121, 217, 0.1);\n}\n\n.navigator-fs-tree-item .icon{\n background: linear-gradient(45deg, hsl(28, 75%, 50%), hsl(28, 75%, 70%));\n}\n\n.navigator-sm-script-tree-item .icon,\n.navigator-script-tree-item .icon,\n.navigator-snippet-tree-item .icon {\n background: linear-gradient(45deg, hsl(48, 70%, 50%), hsl(48, 70%, 70%));\n}\n\n.navigator-sm-stylesheet-tree-item .icon,\n.navigator-stylesheet-tree-item .icon {\n background: linear-gradient(45deg, hsl(256, 50%, 50%), hsl(256, 50%, 70%));\n}\n\n.navigator-image-tree-item .icon,\n.navigator-font-tree-item .icon {\n background: linear-gradient(45deg, hsl(109, 33%, 50%), hsl(109, 33%, 70%));\n}\n/*# sourceURL=changes/changesSidebar.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/cm/cm_module.js b/src/cobalt/debug/content/devtools/cm/cm_module.js deleted file mode 100644 index 96d97a3..0000000 --- a/src/cobalt/debug/content/devtools/cm/cm_module.js +++ /dev/null
@@ -1,4175 +0,0 @@ -(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global.CodeMirror=factory());}(this,(function(){'use strict';var userAgent=navigator.userAgent -var platform=navigator.platform -var gecko=/gecko\/\d/i.test(userAgent) -var ie_upto10=/MSIE \d/.test(userAgent) -var ie_11up=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent) -var edge=/Edge\/(\d+)/.exec(userAgent) -var ie=ie_upto10||ie_11up||edge -var ie_version=ie&&(ie_upto10?document.documentMode||6:+(edge||ie_11up)[1]) -var webkit=!edge&&/WebKit\//.test(userAgent) -var qtwebkit=webkit&&/Qt\/\d+\.\d+/.test(userAgent) -var chrome=!edge&&/Chrome\//.test(userAgent) -var presto=/Opera\//.test(userAgent) -var safari=/Apple Computer/.test(navigator.vendor) -var mac_geMountainLion=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent) -var phantom=/PhantomJS/.test(userAgent) -var ios=!edge&&/AppleWebKit/.test(userAgent)&&/Mobile\/\w+/.test(userAgent) -var android=/Android/.test(userAgent) -var mobile=ios||android||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent) -var mac=ios||/Mac/.test(platform) -var chromeOS=/\bCrOS\b/.test(userAgent) -var windows=/win/i.test(platform) -var presto_version=presto&&userAgent.match(/Version\/(\d*\.\d*)/) -if(presto_version){presto_version=Number(presto_version[1])} -if(presto_version&&presto_version>=15){presto=false;webkit=true} -var flipCtrlCmd=mac&&(qtwebkit||presto&&(presto_version==null||presto_version<12.11)) -var captureRightClick=gecko||(ie&&ie_version>=9) -function classTest(cls){return new RegExp("(^|\\s)"+cls+"(?:$|\\s)\\s*")} -var rmClass=function(node,cls){var current=node.className -var match=classTest(cls).exec(current) -if(match){var after=current.slice(match.index+match[0].length) -node.className=current.slice(0,match.index)+(after?match[1]+after:"")}} -function removeChildren(e){for(var count=e.childNodes.length;count>0;--count) -{e.removeChild(e.firstChild)} -return e} -function removeChildrenAndAdd(parent,e){return removeChildren(parent).appendChild(e)} -function elt(tag,content,className,style){var e=document.createElement(tag) -if(className){e.className=className} -if(style){e.style.cssText=style} -if(typeof content=="string"){e.appendChild(document.createTextNode(content))} -else if(content){for(var i=0;i<content.length;++i){e.appendChild(content[i])}} -return e} -function eltP(tag,content,className,style){var e=elt(tag,content,className,style) -e.setAttribute("role","presentation") -return e} -var range -if(document.createRange){range=function(node,start,end,endNode){var r=document.createRange() -r.setEnd(endNode||node,end) -r.setStart(node,start) -return r}} -else{range=function(node,start,end){var r=document.body.createTextRange() -try{r.moveToElementText(node.parentNode)} -catch(e){return r} -r.collapse(true) -r.moveEnd("character",end) -r.moveStart("character",start) -return r}} -function contains(parent,child){if(child.nodeType==3) -{child=child.parentNode} -if(parent.contains) -{return parent.contains(child)} -do{if(child.nodeType==11){child=child.host} -if(child==parent){return true}}while(child=child.parentNode)} -function activeElt(){var activeElement -try{activeElement=document.activeElement}catch(e){activeElement=document.body||null} -while(activeElement&&activeElement.shadowRoot&&activeElement.shadowRoot.activeElement) -{activeElement=activeElement.shadowRoot.activeElement} -return activeElement} -function addClass(node,cls){var current=node.className -if(!classTest(cls).test(current)){node.className+=(current?" ":"")+cls}} -function joinClasses(a,b){var as=a.split(" ") -for(var i=0;i<as.length;i++) -{if(as[i]&&!classTest(as[i]).test(b)){b+=" "+as[i]}} -return b} -var selectInput=function(node){node.select()} -if(ios) -{selectInput=function(node){node.selectionStart=0;node.selectionEnd=node.value.length}} -else if(ie) -{selectInput=function(node){try{node.select()}catch(_e){}}} -function bind(f){var args=Array.prototype.slice.call(arguments,1) -return function(){return f.apply(null,args)}} -function copyObj(obj,target,overwrite){if(!target){target={}} -for(var prop in obj) -{if(obj.hasOwnProperty(prop)&&(overwrite!==false||!target.hasOwnProperty(prop))) -{target[prop]=obj[prop]}} -return target} -function countColumn(string,end,tabSize,startIndex,startValue){if(end==null){end=string.search(/[^\s\u00a0]/) -if(end==-1){end=string.length}} -for(var i=startIndex||0,n=startValue||0;;){var nextTab=string.indexOf("\t",i) -if(nextTab<0||nextTab>=end) -{return n+(end-i)} -n+=nextTab-i -n+=tabSize-(n%tabSize) -i=nextTab+1}} -var Delayed=function Delayed(){this.id=null};Delayed.prototype.set=function set(ms,f){clearTimeout(this.id) -this.id=setTimeout(f,ms)};function indexOf(array,elt){for(var i=0;i<array.length;++i) -{if(array[i]==elt){return i}} -return-1} -var scrollerGap=30 -var Pass={toString:function(){return"CodeMirror.Pass"}} -var sel_dontScroll={scroll:false};var sel_mouse={origin:"*mouse"};var sel_move={origin:"+move"};function findColumn(string,goal,tabSize){for(var pos=0,col=0;;){var nextTab=string.indexOf("\t",pos) -if(nextTab==-1){nextTab=string.length} -var skipped=nextTab-pos -if(nextTab==string.length||col+skipped>=goal) -{return pos+Math.min(skipped,goal-col)} -col+=nextTab-pos -col+=tabSize-(col%tabSize) -pos=nextTab+1 -if(col>=goal){return pos}}} -var spaceStrs=[""] -function spaceStr(n){while(spaceStrs.length<=n) -{spaceStrs.push(lst(spaceStrs)+" ")} -return spaceStrs[n]} -function lst(arr){return arr[arr.length-1]} -function map(array,f){var out=[] -for(var i=0;i<array.length;i++){out[i]=f(array[i],i)} -return out} -function insertSorted(array,value,score){var pos=0,priority=score(value) -while(pos<array.length&&score(array[pos])<=priority){pos++} -array.splice(pos,0,value)} -function nothing(){} -function createObj(base,props){var inst -if(Object.create){inst=Object.create(base)}else{nothing.prototype=base -inst=new nothing()} -if(props){copyObj(props,inst)} -return inst} -var nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/ -function isWordCharBasic(ch){return/\w/.test(ch)||ch>"\x80"&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch))} -function isWordChar(ch,helper){if(!helper){return isWordCharBasic(ch)} -if(helper.source.indexOf("\\w")>-1&&isWordCharBasic(ch)){return true} -return helper.test(ch)} -function isEmpty(obj){for(var n in obj){if(obj.hasOwnProperty(n)&&obj[n]){return false}} -return true} -var extendingChars=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/ -function isExtendingChar(ch){return ch.charCodeAt(0)>=768&&extendingChars.test(ch)} -function skipExtendingChars(str,pos,dir){while((dir<0?pos>0:pos<str.length)&&isExtendingChar(str.charAt(pos))){pos+=dir} -return pos} -function findFirst(pred,from,to){for(;;){if(Math.abs(from-to)<=1){return pred(from)?from:to} -var mid=Math.floor((from+to)/2) -if(pred(mid)){to=mid} -else{from=mid}}} -function Display(place,doc,input){var d=this -this.input=input -d.scrollbarFiller=elt("div",null,"CodeMirror-scrollbar-filler") -d.scrollbarFiller.setAttribute("cm-not-content","true") -d.gutterFiller=elt("div",null,"CodeMirror-gutter-filler") -d.gutterFiller.setAttribute("cm-not-content","true") -d.lineDiv=eltP("div",null,"CodeMirror-code") -d.selectionDiv=elt("div",null,null,"position: relative; z-index: 1") -d.cursorDiv=elt("div",null,"CodeMirror-cursors") -d.measure=elt("div",null,"CodeMirror-measure") -d.lineMeasure=elt("div",null,"CodeMirror-measure") -d.lineSpace=eltP("div",[d.measure,d.lineMeasure,d.selectionDiv,d.cursorDiv,d.lineDiv],null,"position: relative; outline: none") -var lines=eltP("div",[d.lineSpace],"CodeMirror-lines") -d.mover=elt("div",[lines],null,"position: relative") -d.sizer=elt("div",[d.mover],"CodeMirror-sizer") -d.sizerWidth=null -d.heightForcer=elt("div",null,null,"position: absolute; height: "+scrollerGap+"px; width: 1px;") -d.gutters=elt("div",null,"CodeMirror-gutters") -d.lineGutter=null -d.scroller=elt("div",[d.sizer,d.heightForcer,d.gutters],"CodeMirror-scroll") -d.scroller.setAttribute("tabIndex","-1") -d.wrapper=elt("div",[d.scrollbarFiller,d.gutterFiller,d.scroller],"CodeMirror") -if(ie&&ie_version<8){d.gutters.style.zIndex=-1;d.scroller.style.paddingRight=0} -if(!webkit&&!(gecko&&mobile)){d.scroller.draggable=true} -if(place){if(place.appendChild){place.appendChild(d.wrapper)} -else{place(d.wrapper)}} -d.viewFrom=d.viewTo=doc.first -d.reportedViewFrom=d.reportedViewTo=doc.first -d.view=[] -d.renderedView=null -d.externalMeasured=null -d.viewOffset=0 -d.lastWrapHeight=d.lastWrapWidth=0 -d.updateLineNumbers=null -d.nativeBarWidth=d.barHeight=d.barWidth=0 -d.scrollbarsClipped=false -d.lineNumWidth=d.lineNumInnerWidth=d.lineNumChars=null -d.alignWidgets=false -d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null -d.maxLine=null -d.maxLineLength=0 -d.maxLineChanged=false -d.wheelDX=d.wheelDY=d.wheelStartX=d.wheelStartY=null -d.shift=false -d.selForContextMenu=null -d.activeTouch=null -input.init(d)} -function getLine(doc,n){n-=doc.first -if(n<0||n>=doc.size){throw new Error("There is no line "+(n+doc.first)+" in the document.")} -var chunk=doc -while(!chunk.lines){for(var i=0;;++i){var child=chunk.children[i],sz=child.chunkSize() -if(n<sz){chunk=child;break} -n-=sz}} -return chunk.lines[n]} -function getBetween(doc,start,end){var out=[],n=start.line -doc.iter(start.line,end.line+1,function(line){var text=line.text -if(n==end.line){text=text.slice(0,end.ch)} -if(n==start.line){text=text.slice(start.ch)} -out.push(text) -++n}) -return out} -function getLines(doc,from,to){var out=[] -doc.iter(from,to,function(line){out.push(line.text)}) -return out} -function updateLineHeight(line,height){var diff=height-line.height -if(diff){for(var n=line;n;n=n.parent){n.height+=diff}}} -function lineNo(line){if(line.parent==null){return null} -var cur=line.parent,no=indexOf(cur.lines,line) -for(var chunk=cur.parent;chunk;cur=chunk,chunk=chunk.parent){for(var i=0;;++i){if(chunk.children[i]==cur){break} -no+=chunk.children[i].chunkSize()}} -return no+cur.first} -function lineAtHeight(chunk,h){var n=chunk.first -outer:do{for(var i$1=0;i$1<chunk.children.length;++i$1){var child=chunk.children[i$1],ch=child.height -if(h<ch){chunk=child;continue outer} -h-=ch -n+=child.chunkSize()} -return n}while(!chunk.lines) -var i=0 -for(;i<chunk.lines.length;++i){var line=chunk.lines[i],lh=line.height -if(h<lh){break} -h-=lh} -return n+i} -function isLine(doc,l){return l>=doc.first&&l<doc.first+doc.size} -function lineNumberFor(options,i){return String(options.lineNumberFormatter(i+options.firstLineNumber))} -function Pos(line,ch,sticky){if(sticky===void 0)sticky=null;if(!(this instanceof Pos)){return new Pos(line,ch,sticky)} -this.line=line -this.ch=ch -this.sticky=sticky} -function cmp(a,b){return a.line-b.line||a.ch-b.ch} -function equalCursorPos(a,b){return a.sticky==b.sticky&&cmp(a,b)==0} -function copyPos(x){return Pos(x.line,x.ch)} -function maxPos(a,b){return cmp(a,b)<0?b:a} -function minPos(a,b){return cmp(a,b)<0?a:b} -function clipLine(doc,n){return Math.max(doc.first,Math.min(n,doc.first+doc.size-1))} -function clipPos(doc,pos){if(pos.line<doc.first){return Pos(doc.first,0)} -var last=doc.first+doc.size-1 -if(pos.line>last){return Pos(last,getLine(doc,last).text.length)} -return clipToLen(pos,getLine(doc,pos.line).text.length)} -function clipToLen(pos,linelen){var ch=pos.ch -if(ch==null||ch>linelen){return Pos(pos.line,linelen)} -else if(ch<0){return Pos(pos.line,0)} -else{return pos}} -function clipPosArray(doc,array){var out=[] -for(var i=0;i<array.length;i++){out[i]=clipPos(doc,array[i])} -return out} -var sawReadOnlySpans=false;var sawCollapsedSpans=false;function seeReadOnlySpans(){sawReadOnlySpans=true} -function seeCollapsedSpans(){sawCollapsedSpans=true} -function MarkedSpan(marker,from,to){this.marker=marker -this.from=from;this.to=to} -function getMarkedSpanFor(spans,marker){if(spans){for(var i=0;i<spans.length;++i){var span=spans[i] -if(span.marker==marker){return span}}}} -function removeMarkedSpan(spans,span){var r -for(var i=0;i<spans.length;++i) -{if(spans[i]!=span){(r||(r=[])).push(spans[i])}} -return r} -function addMarkedSpan(line,span){line.markedSpans=line.markedSpans?line.markedSpans.concat([span]):[span] -span.marker.attachLine(line)} -function markedSpansBefore(old,startCh,isInsert){var nw -if(old){for(var i=0;i<old.length;++i){var span=old[i],marker=span.marker -var startsBefore=span.from==null||(marker.inclusiveLeft?span.from<=startCh:span.from<startCh) -if(startsBefore||span.from==startCh&&marker.type=="bookmark"&&(!isInsert||!span.marker.insertLeft)){var endsAfter=span.to==null||(marker.inclusiveRight?span.to>=startCh:span.to>startCh);(nw||(nw=[])).push(new MarkedSpan(marker,span.from,endsAfter?null:span.to))}}} -return nw} -function markedSpansAfter(old,endCh,isInsert){var nw -if(old){for(var i=0;i<old.length;++i){var span=old[i],marker=span.marker -var endsAfter=span.to==null||(marker.inclusiveRight?span.to>=endCh:span.to>endCh) -if(endsAfter||span.from==endCh&&marker.type=="bookmark"&&(!isInsert||span.marker.insertLeft)){var startsBefore=span.from==null||(marker.inclusiveLeft?span.from<=endCh:span.from<endCh);(nw||(nw=[])).push(new MarkedSpan(marker,startsBefore?null:span.from-endCh,span.to==null?null:span.to-endCh))}}} -return nw} -function stretchSpansOverChange(doc,change){if(change.full){return null} -var oldFirst=isLine(doc,change.from.line)&&getLine(doc,change.from.line).markedSpans -var oldLast=isLine(doc,change.to.line)&&getLine(doc,change.to.line).markedSpans -if(!oldFirst&&!oldLast){return null} -var startCh=change.from.ch,endCh=change.to.ch,isInsert=cmp(change.from,change.to)==0 -var first=markedSpansBefore(oldFirst,startCh,isInsert) -var last=markedSpansAfter(oldLast,endCh,isInsert) -var sameLine=change.text.length==1,offset=lst(change.text).length+(sameLine?startCh:0) -if(first){for(var i=0;i<first.length;++i){var span=first[i] -if(span.to==null){var found=getMarkedSpanFor(last,span.marker) -if(!found){span.to=startCh} -else if(sameLine){span.to=found.to==null?null:found.to+offset}}}} -if(last){for(var i$1=0;i$1<last.length;++i$1){var span$1=last[i$1] -if(span$1.to!=null){span$1.to+=offset} -if(span$1.from==null){var found$1=getMarkedSpanFor(first,span$1.marker) -if(!found$1){span$1.from=offset -if(sameLine){(first||(first=[])).push(span$1)}}}else{span$1.from+=offset -if(sameLine){(first||(first=[])).push(span$1)}}}} -if(first){first=clearEmptySpans(first)} -if(last&&last!=first){last=clearEmptySpans(last)} -var newMarkers=[first] -if(!sameLine){var gap=change.text.length-2,gapMarkers -if(gap>0&&first) -{for(var i$2=0;i$2<first.length;++i$2) -{if(first[i$2].to==null) -{(gapMarkers||(gapMarkers=[])).push(new MarkedSpan(first[i$2].marker,null,null))}}} -for(var i$3=0;i$3<gap;++i$3) -{newMarkers.push(gapMarkers)} -newMarkers.push(last)} -return newMarkers} -function clearEmptySpans(spans){for(var i=0;i<spans.length;++i){var span=spans[i] -if(span.from!=null&&span.from==span.to&&span.marker.clearWhenEmpty!==false) -{spans.splice(i--,1)}} -if(!spans.length){return null} -return spans} -function removeReadOnlyRanges(doc,from,to){var markers=null -doc.iter(from.line,to.line+1,function(line){if(line.markedSpans){for(var i=0;i<line.markedSpans.length;++i){var mark=line.markedSpans[i].marker -if(mark.readOnly&&(!markers||indexOf(markers,mark)==-1)) -{(markers||(markers=[])).push(mark)}}}}) -if(!markers){return null} -var parts=[{from:from,to:to}] -for(var i=0;i<markers.length;++i){var mk=markers[i],m=mk.find(0) -for(var j=0;j<parts.length;++j){var p=parts[j] -if(cmp(p.to,m.from)<0||cmp(p.from,m.to)>0){continue} -var newParts=[j,1],dfrom=cmp(p.from,m.from),dto=cmp(p.to,m.to) -if(dfrom<0||!mk.inclusiveLeft&&!dfrom) -{newParts.push({from:p.from,to:m.from})} -if(dto>0||!mk.inclusiveRight&&!dto) -{newParts.push({from:m.to,to:p.to})} -parts.splice.apply(parts,newParts) -j+=newParts.length-3}} -return parts} -function detachMarkedSpans(line){var spans=line.markedSpans -if(!spans){return} -for(var i=0;i<spans.length;++i) -{spans[i].marker.detachLine(line)} -line.markedSpans=null} -function attachMarkedSpans(line,spans){if(!spans){return} -for(var i=0;i<spans.length;++i) -{spans[i].marker.attachLine(line)} -line.markedSpans=spans} -function extraLeft(marker){return marker.inclusiveLeft?-1:0} -function extraRight(marker){return marker.inclusiveRight?1:0} -function compareCollapsedMarkers(a,b){var lenDiff=a.lines.length-b.lines.length -if(lenDiff!=0){return lenDiff} -var aPos=a.find(),bPos=b.find() -var fromCmp=cmp(aPos.from,bPos.from)||extraLeft(a)-extraLeft(b) -if(fromCmp){return-fromCmp} -var toCmp=cmp(aPos.to,bPos.to)||extraRight(a)-extraRight(b) -if(toCmp){return toCmp} -return b.id-a.id} -function collapsedSpanAtSide(line,start){var sps=sawCollapsedSpans&&line.markedSpans,found -if(sps){for(var sp=(void 0),i=0;i<sps.length;++i){sp=sps[i] -if(sp.marker.collapsed&&(start?sp.from:sp.to)==null&&(!found||compareCollapsedMarkers(found,sp.marker)<0)) -{found=sp.marker}}} -return found} -function collapsedSpanAtStart(line){return collapsedSpanAtSide(line,true)} -function collapsedSpanAtEnd(line){return collapsedSpanAtSide(line,false)} -function conflictingCollapsedRange(doc,lineNo,from,to,marker){var line=getLine(doc,lineNo) -var sps=sawCollapsedSpans&&line.markedSpans -if(sps){for(var i=0;i<sps.length;++i){var sp=sps[i] -if(!sp.marker.collapsed){continue} -var found=sp.marker.find(0) -var fromCmp=cmp(found.from,from)||extraLeft(sp.marker)-extraLeft(marker) -var toCmp=cmp(found.to,to)||extraRight(sp.marker)-extraRight(marker) -if(fromCmp>=0&&toCmp<=0||fromCmp<=0&&toCmp>=0){continue} -if(fromCmp<=0&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?cmp(found.to,from)>=0:cmp(found.to,from)>0)||fromCmp>=0&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?cmp(found.from,to)<=0:cmp(found.from,to)<0)) -{return true}}}} -function visualLine(line){var merged -while(merged=collapsedSpanAtStart(line)) -{line=merged.find(-1,true).line} -return line} -function visualLineEnd(line){var merged -while(merged=collapsedSpanAtEnd(line)) -{line=merged.find(1,true).line} -return line} -function visualLineContinued(line){var merged,lines -while(merged=collapsedSpanAtEnd(line)){line=merged.find(1,true).line;(lines||(lines=[])).push(line)} -return lines} -function visualLineNo(doc,lineN){var line=getLine(doc,lineN),vis=visualLine(line) -if(line==vis){return lineN} -return lineNo(vis)} -function visualLineEndNo(doc,lineN){if(lineN>doc.lastLine()){return lineN} -var line=getLine(doc,lineN),merged -if(!lineIsHidden(doc,line)){return lineN} -while(merged=collapsedSpanAtEnd(line)) -{line=merged.find(1,true).line} -return lineNo(line)+1} -function lineIsHidden(doc,line){var sps=sawCollapsedSpans&&line.markedSpans -if(sps){for(var sp=(void 0),i=0;i<sps.length;++i){sp=sps[i] -if(!sp.marker.collapsed){continue} -if(sp.from==null){return true} -if(sp.marker.widgetNode){continue} -if(sp.from==0&&sp.marker.inclusiveLeft&&lineIsHiddenInner(doc,line,sp)) -{return true}}}} -function lineIsHiddenInner(doc,line,span){if(span.to==null){var end=span.marker.find(1,true) -return lineIsHiddenInner(doc,end.line,getMarkedSpanFor(end.line.markedSpans,span.marker))} -if(span.marker.inclusiveRight&&span.to==line.text.length) -{return true} -for(var sp=(void 0),i=0;i<line.markedSpans.length;++i){sp=line.markedSpans[i] -if(sp.marker.collapsed&&!sp.marker.widgetNode&&sp.from==span.to&&(sp.to==null||sp.to!=span.from)&&(sp.marker.inclusiveLeft||span.marker.inclusiveRight)&&lineIsHiddenInner(doc,line,sp)){return true}}} -function heightAtLine(lineObj){lineObj=visualLine(lineObj) -var h=0,chunk=lineObj.parent -for(var i=0;i<chunk.lines.length;++i){var line=chunk.lines[i] -if(line==lineObj){break} -else{h+=line.height}} -for(var p=chunk.parent;p;chunk=p,p=chunk.parent){for(var i$1=0;i$1<p.children.length;++i$1){var cur=p.children[i$1] -if(cur==chunk){break} -else{h+=cur.height}}} -return h} -function lineLength(line){if(line.height==0){return 0} -var len=line.text.length,merged,cur=line -while(merged=collapsedSpanAtStart(cur)){var found=merged.find(0,true) -cur=found.from.line -len+=found.from.ch-found.to.ch} -cur=line -while(merged=collapsedSpanAtEnd(cur)){var found$1=merged.find(0,true) -len-=cur.text.length-found$1.from.ch -cur=found$1.to.line -len+=cur.text.length-found$1.to.ch} -return len} -function findMaxLine(cm){var d=cm.display,doc=cm.doc -d.maxLine=getLine(doc,doc.first) -d.maxLineLength=lineLength(d.maxLine) -d.maxLineChanged=true -doc.iter(function(line){var len=lineLength(line) -if(len>d.maxLineLength){d.maxLineLength=len -d.maxLine=line}})} -function iterateBidiSections(order,from,to,f){if(!order){return f(from,to,"ltr")} -var found=false -for(var i=0;i<order.length;++i){var part=order[i] -if(part.from<to&&part.to>from||from==to&&part.to==from){f(Math.max(part.from,from),Math.min(part.to,to),part.level==1?"rtl":"ltr") -found=true}} -if(!found){f(from,to,"ltr")}} -var bidiOther=null -function getBidiPartAt(order,ch,sticky){var found -bidiOther=null -for(var i=0;i<order.length;++i){var cur=order[i] -if(cur.from<ch&&cur.to>ch){return i} -if(cur.to==ch){if(cur.from!=cur.to&&sticky=="before"){found=i} -else{bidiOther=i}} -if(cur.from==ch){if(cur.from!=cur.to&&sticky!="before"){found=i} -else{bidiOther=i}}} -return found!=null?found:bidiOther} -var bidiOrdering=(function(){var lowTypes="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN" -var arabicTypes="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111" -function charType(code){if(code<=0xf7){return lowTypes.charAt(code)} -else if(0x590<=code&&code<=0x5f4){return"R"} -else if(0x600<=code&&code<=0x6f9){return arabicTypes.charAt(code-0x600)} -else if(0x6ee<=code&&code<=0x8ac){return"r"} -else if(0x2000<=code&&code<=0x200b){return"w"} -else if(code==0x200c){return"b"} -else{return"L"}} -var bidiRE=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/ -var isNeutral=/[stwN]/,isStrong=/[LRr]/,countsAsLeft=/[Lb1n]/,countsAsNum=/[1n]/ -function BidiSpan(level,from,to){this.level=level -this.from=from;this.to=to} -return function(str,direction){var outerType=direction=="ltr"?"L":"R" -if(str.length==0||direction=="ltr"&&!bidiRE.test(str)){return false} -var len=str.length,types=[] -for(var i=0;i<len;++i) -{types.push(charType(str.charCodeAt(i)))} -for(var i$1=0,prev=outerType;i$1<len;++i$1){var type=types[i$1] -if(type=="m"){types[i$1]=prev} -else{prev=type}} -for(var i$2=0,cur=outerType;i$2<len;++i$2){var type$1=types[i$2] -if(type$1=="1"&&cur=="r"){types[i$2]="n"} -else if(isStrong.test(type$1)){cur=type$1;if(type$1=="r"){types[i$2]="R"}}} -for(var i$3=1,prev$1=types[0];i$3<len-1;++i$3){var type$2=types[i$3] -if(type$2=="+"&&prev$1=="1"&&types[i$3+1]=="1"){types[i$3]="1"} -else if(type$2==","&&prev$1==types[i$3+1]&&(prev$1=="1"||prev$1=="n")){types[i$3]=prev$1} -prev$1=type$2} -for(var i$4=0;i$4<len;++i$4){var type$3=types[i$4] -if(type$3==","){types[i$4]="N"} -else if(type$3=="%"){var end=(void 0) -for(end=i$4+1;end<len&&types[end]=="%";++end){} -var replace=(i$4&&types[i$4-1]=="!")||(end<len&&types[end]=="1")?"1":"N" -for(var j=i$4;j<end;++j){types[j]=replace} -i$4=end-1}} -for(var i$5=0,cur$1=outerType;i$5<len;++i$5){var type$4=types[i$5] -if(cur$1=="L"&&type$4=="1"){types[i$5]="L"} -else if(isStrong.test(type$4)){cur$1=type$4}} -for(var i$6=0;i$6<len;++i$6){if(isNeutral.test(types[i$6])){var end$1=(void 0) -for(end$1=i$6+1;end$1<len&&isNeutral.test(types[end$1]);++end$1){} -var before=(i$6?types[i$6-1]:outerType)=="L" -var after=(end$1<len?types[end$1]:outerType)=="L" -var replace$1=before==after?(before?"L":"R"):outerType -for(var j$1=i$6;j$1<end$1;++j$1){types[j$1]=replace$1} -i$6=end$1-1}} -var order=[],m -for(var i$7=0;i$7<len;){if(countsAsLeft.test(types[i$7])){var start=i$7 -for(++i$7;i$7<len&&countsAsLeft.test(types[i$7]);++i$7){} -order.push(new BidiSpan(0,start,i$7))}else{var pos=i$7,at=order.length -for(++i$7;i$7<len&&types[i$7]!="L";++i$7){} -for(var j$2=pos;j$2<i$7;){if(countsAsNum.test(types[j$2])){if(pos<j$2){order.splice(at,0,new BidiSpan(1,pos,j$2))} -var nstart=j$2 -for(++j$2;j$2<i$7&&countsAsNum.test(types[j$2]);++j$2){} -order.splice(at,0,new BidiSpan(2,nstart,j$2)) -pos=j$2}else{++j$2}} -if(pos<i$7){order.splice(at,0,new BidiSpan(1,pos,i$7))}}} -if(order[0].level==1&&(m=str.match(/^\s+/))){order[0].from=m[0].length -order.unshift(new BidiSpan(0,0,m[0].length))} -if(lst(order).level==1&&(m=str.match(/\s+$/))){lst(order).to-=m[0].length -order.push(new BidiSpan(0,len-m[0].length,len))} -return direction=="rtl"?order.reverse():order}})() -function getOrder(line,direction){var order=line.order -if(order==null){order=line.order=bidiOrdering(line.text,direction)} -return order} -function moveCharLogically(line,ch,dir){var target=skipExtendingChars(line.text,ch+dir,dir) -return target<0||target>line.text.length?null:target} -function moveLogically(line,start,dir){var ch=moveCharLogically(line,start.ch,dir) -return ch==null?null:new Pos(start.line,ch,dir<0?"after":"before")} -function endOfLine(visually,cm,lineObj,lineNo,dir){if(visually){var order=getOrder(lineObj,cm.doc.direction) -if(order){var part=dir<0?lst(order):order[0] -var moveInStorageOrder=(dir<0)==(part.level==1) -var sticky=moveInStorageOrder?"after":"before" -var ch -if(part.level>0){var prep=prepareMeasureForLine(cm,lineObj) -ch=dir<0?lineObj.text.length-1:0 -var targetTop=measureCharPrepared(cm,prep,ch).top -ch=findFirst(function(ch){return measureCharPrepared(cm,prep,ch).top==targetTop;},(dir<0)==(part.level==1)?part.from:part.to-1,ch) -if(sticky=="before"){ch=moveCharLogically(lineObj,ch,1,true)}}else{ch=dir<0?part.to:part.from} -return new Pos(lineNo,ch,sticky)}} -return new Pos(lineNo,dir<0?lineObj.text.length:0,dir<0?"before":"after")} -function moveVisually(cm,line,start,dir){var bidi=getOrder(line,cm.doc.direction) -if(!bidi){return moveLogically(line,start,dir)} -if(start.ch>=line.text.length){start.ch=line.text.length -start.sticky="before"}else if(start.ch<=0){start.ch=0 -start.sticky="after"} -var partPos=getBidiPartAt(bidi,start.ch,start.sticky),part=bidi[partPos] -if(cm.doc.direction=="ltr"&&part.level%2==0&&(dir>0?part.to>start.ch:part.from<start.ch)){return moveLogically(line,start,dir)} -var mv=function(pos,dir){return moveCharLogically(line,pos instanceof Pos?pos.ch:pos,dir);} -var prep -var getWrappedLineExtent=function(ch){if(!cm.options.lineWrapping){return{begin:0,end:line.text.length}} -prep=prep||prepareMeasureForLine(cm,line) -return wrappedLineExtentChar(cm,line,prep,ch)} -var wrappedLineExtent=getWrappedLineExtent(start.sticky=="before"?mv(start,-1):start.ch) -if(cm.doc.direction=="rtl"||part.level==1){var moveInStorageOrder=(part.level==1)==(dir<0) -var ch=mv(start,moveInStorageOrder?1:-1) -if(ch!=null&&(!moveInStorageOrder?ch>=part.from&&ch>=wrappedLineExtent.begin:ch<=part.to&&ch<=wrappedLineExtent.end)){var sticky=moveInStorageOrder?"before":"after" -return new Pos(start.line,ch,sticky)}} -var searchInVisualLine=function(partPos,dir,wrappedLineExtent){var getRes=function(ch,moveInStorageOrder){return moveInStorageOrder?new Pos(start.line,mv(ch,1),"before"):new Pos(start.line,ch,"after");} -for(;partPos>=0&&partPos<bidi.length;partPos+=dir){var part=bidi[partPos] -var moveInStorageOrder=(dir>0)==(part.level!=1) -var ch=moveInStorageOrder?wrappedLineExtent.begin:mv(wrappedLineExtent.end,-1) -if(part.from<=ch&&ch<part.to){return getRes(ch,moveInStorageOrder)} -ch=moveInStorageOrder?part.from:mv(part.to,-1) -if(wrappedLineExtent.begin<=ch&&ch<wrappedLineExtent.end){return getRes(ch,moveInStorageOrder)}}} -var res=searchInVisualLine(partPos+dir,dir,wrappedLineExtent) -if(res){return res} -var nextCh=dir>0?wrappedLineExtent.end:mv(wrappedLineExtent.begin,-1) -if(nextCh!=null&&!(dir>0&&nextCh==line.text.length)){res=searchInVisualLine(dir>0?0:bidi.length-1,dir,getWrappedLineExtent(nextCh)) -if(res){return res}} -return null} -var noHandlers=[] -var on=function(emitter,type,f){if(emitter.addEventListener){emitter.addEventListener(type,f,false)}else if(emitter.attachEvent){emitter.attachEvent("on"+type,f)}else{var map=emitter._handlers||(emitter._handlers={}) -map[type]=(map[type]||noHandlers).concat(f)}} -function getHandlers(emitter,type){return emitter._handlers&&emitter._handlers[type]||noHandlers} -function off(emitter,type,f){if(emitter.removeEventListener){emitter.removeEventListener(type,f,false)}else if(emitter.detachEvent){emitter.detachEvent("on"+type,f)}else{var map=emitter._handlers,arr=map&&map[type] -if(arr){var index=indexOf(arr,f) -if(index>-1) -{map[type]=arr.slice(0,index).concat(arr.slice(index+1))}}}} -function signal(emitter,type){var handlers=getHandlers(emitter,type) -if(!handlers.length){return} -var args=Array.prototype.slice.call(arguments,2) -for(var i=0;i<handlers.length;++i){handlers[i].apply(null,args)}} -function signalDOMEvent(cm,e,override){if(typeof e=="string") -{e={type:e,preventDefault:function(){this.defaultPrevented=true}}} -signal(cm,override||e.type,cm,e) -return e_defaultPrevented(e)||e.codemirrorIgnore} -function signalCursorActivity(cm){var arr=cm._handlers&&cm._handlers.cursorActivity -if(!arr){return} -var set=cm.curOp.cursorActivityHandlers||(cm.curOp.cursorActivityHandlers=[]) -for(var i=0;i<arr.length;++i){if(indexOf(set,arr[i])==-1) -{set.push(arr[i])}}} -function hasHandler(emitter,type){return getHandlers(emitter,type).length>0} -function eventMixin(ctor){ctor.prototype.on=function(type,f){on(this,type,f)} -ctor.prototype.off=function(type,f){off(this,type,f)}} -function e_preventDefault(e){if(e.preventDefault){e.preventDefault()} -else{e.returnValue=false}} -function e_stopPropagation(e){if(e.stopPropagation){e.stopPropagation()} -else{e.cancelBubble=true}} -function e_defaultPrevented(e){return e.defaultPrevented!=null?e.defaultPrevented:e.returnValue==false} -function e_stop(e){e_preventDefault(e);e_stopPropagation(e)} -function e_target(e){return e.target||e.srcElement} -function e_button(e){var b=e.which -if(b==null){if(e.button&1){b=1} -else if(e.button&2){b=3} -else if(e.button&4){b=2}} -if(mac&&e.ctrlKey&&b==1){b=3} -return b} -var dragAndDrop=function(){if(ie&&ie_version<9){return false} -var div=elt('div') -return"draggable"in div||"dragDrop"in div}() -var zwspSupported -function zeroWidthElement(measure){if(zwspSupported==null){var test=elt("span","\u200b") -removeChildrenAndAdd(measure,elt("span",[test,document.createTextNode("x")])) -if(measure.firstChild.offsetHeight!=0) -{zwspSupported=test.offsetWidth<=1&&test.offsetHeight>2&&!(ie&&ie_version<8)}} -var node=zwspSupported?elt("span","\u200b"):elt("span","\u00a0",null,"display: inline-block; width: 1px; margin-right: -1px") -node.setAttribute("cm-text","") -return node} -var badBidiRects -function hasBadBidiRects(measure){if(badBidiRects!=null){return badBidiRects} -var txt=removeChildrenAndAdd(measure,document.createTextNode("A\u062eA")) -var r0=range(txt,0,1).getBoundingClientRect() -var r1=range(txt,1,2).getBoundingClientRect() -removeChildren(measure) -if(!r0||r0.left==r0.right){return false} -return badBidiRects=(r1.right-r0.right<3)} -var splitLinesAuto="\n\nb".split(/\n/).length!=3?function(string){var pos=0,result=[],l=string.length -while(pos<=l){var nl=string.indexOf("\n",pos) -if(nl==-1){nl=string.length} -var line=string.slice(pos,string.charAt(nl-1)=="\r"?nl-1:nl) -var rt=line.indexOf("\r") -if(rt!=-1){result.push(line.slice(0,rt)) -pos+=rt+1}else{result.push(line) -pos=nl+1}} -return result}:function(string){return string.split(/\r\n?|\n/);} -var hasSelection=window.getSelection?function(te){try{return te.selectionStart!=te.selectionEnd} -catch(e){return false}}:function(te){var range -try{range=te.ownerDocument.selection.createRange()} -catch(e){} -if(!range||range.parentElement()!=te){return false} -return range.compareEndPoints("StartToEnd",range)!=0} -var hasCopyEvent=(function(){var e=elt("div") -if("oncopy"in e){return true} -e.setAttribute("oncopy","return;") -return typeof e.oncopy=="function"})() -var badZoomedRects=null -function hasBadZoomedRects(measure){if(badZoomedRects!=null){return badZoomedRects} -var node=removeChildrenAndAdd(measure,elt("span","x")) -var normal=node.getBoundingClientRect() -var fromRange=range(node,0,1).getBoundingClientRect() -return badZoomedRects=Math.abs(normal.left-fromRange.left)>1} -var modes={};var mimeModes={};function defineMode(name,mode){if(arguments.length>2) -{mode.dependencies=Array.prototype.slice.call(arguments,2)} -modes[name]=mode} -function defineMIME(mime,spec){mimeModes[mime]=spec} -function resolveMode(spec){if(typeof spec=="string"&&mimeModes.hasOwnProperty(spec)){spec=mimeModes[spec]}else if(spec&&typeof spec.name=="string"&&mimeModes.hasOwnProperty(spec.name)){var found=mimeModes[spec.name] -if(typeof found=="string"){found={name:found}} -spec=createObj(found,spec) -spec.name=found.name}else if(typeof spec=="string"&&/^[\w\-]+\/[\w\-]+\+xml$/.test(spec)){return resolveMode("application/xml")}else if(typeof spec=="string"&&/^[\w\-]+\/[\w\-]+\+json$/.test(spec)){return resolveMode("application/json")} -if(typeof spec=="string"){return{name:spec}} -else{return spec||{name:"null"}}} -function getMode(options,spec){spec=resolveMode(spec) -var mfactory=modes[spec.name] -if(!mfactory){return getMode(options,"text/plain")} -var modeObj=mfactory(options,spec) -if(modeExtensions.hasOwnProperty(spec.name)){var exts=modeExtensions[spec.name] -for(var prop in exts){if(!exts.hasOwnProperty(prop)){continue} -if(modeObj.hasOwnProperty(prop)){modeObj["_"+prop]=modeObj[prop]} -modeObj[prop]=exts[prop]}} -modeObj.name=spec.name -if(spec.helperType){modeObj.helperType=spec.helperType} -if(spec.modeProps){for(var prop$1 in spec.modeProps) -{modeObj[prop$1]=spec.modeProps[prop$1]}} -return modeObj} -var modeExtensions={} -function extendMode(mode,properties){var exts=modeExtensions.hasOwnProperty(mode)?modeExtensions[mode]:(modeExtensions[mode]={}) -copyObj(properties,exts)} -function copyState(mode,state){if(state===true){return state} -if(mode.copyState){return mode.copyState(state)} -var nstate={} -for(var n in state){var val=state[n] -if(val instanceof Array){val=val.concat([])} -nstate[n]=val} -return nstate} -function innerMode(mode,state){var info -while(mode.innerMode){info=mode.innerMode(state) -if(!info||info.mode==mode){break} -state=info.state -mode=info.mode} -return info||{mode:mode,state:state}} -function startState(mode,a1,a2){return mode.startState?mode.startState(a1,a2):true} -var StringStream=function StringStream(string,tabSize){this.pos=this.start=0 -this.string=string -this.tabSize=tabSize||8 -this.lastColumnPos=this.lastColumnValue=0 -this.lineStart=0};StringStream.prototype.eol=function eol(){return this.pos>=this.string.length};StringStream.prototype.sol=function sol(){return this.pos==this.lineStart};StringStream.prototype.peek=function peek(){return this.string.charAt(this.pos)||undefined};StringStream.prototype.next=function next(){if(this.pos<this.string.length) -{return this.string.charAt(this.pos++)}};StringStream.prototype.eat=function eat(match){var ch=this.string.charAt(this.pos) -var ok -if(typeof match=="string"){ok=ch==match} -else{ok=ch&&(match.test?match.test(ch):match(ch))} -if(ok){++this.pos;return ch}};StringStream.prototype.eatWhile=function eatWhile(match){var start=this.pos -while(this.eat(match)){} -return this.pos>start};StringStream.prototype.eatSpace=function eatSpace(){var this$1=this;var start=this.pos -while(/[\s\u00a0]/.test(this.string.charAt(this.pos))){++this$1.pos} -return this.pos>start};StringStream.prototype.skipToEnd=function skipToEnd(){this.pos=this.string.length};StringStream.prototype.skipTo=function skipTo(ch){var found=this.string.indexOf(ch,this.pos) -if(found>-1){this.pos=found;return true}};StringStream.prototype.backUp=function backUp(n){this.pos-=n};StringStream.prototype.column=function column(){if(this.lastColumnPos<this.start){this.lastColumnValue=countColumn(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue) -this.lastColumnPos=this.start} -return this.lastColumnValue-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)};StringStream.prototype.indentation=function indentation(){return countColumn(this.string,null,this.tabSize)- -(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)};StringStream.prototype.match=function match(pattern,consume,caseInsensitive){if(typeof pattern=="string"){var cased=function(str){return caseInsensitive?str.toLowerCase():str;} -var substr=this.string.substr(this.pos,pattern.length) -if(cased(substr)==cased(pattern)){if(consume!==false){this.pos+=pattern.length} -return true}}else{var match=this.string.slice(this.pos).match(pattern) -if(match&&match.index>0){return null} -if(match&&consume!==false){this.pos+=match[0].length} -return match}};StringStream.prototype.current=function current(){return this.string.slice(this.start,this.pos)};StringStream.prototype.hideFirstChars=function hideFirstChars(n,inner){this.lineStart+=n -try{return inner()} -finally{this.lineStart-=n}};function highlightLine(cm,line,state,forceToEnd){var st=[cm.state.modeGen],lineClasses={} -runMode(cm,line.text,cm.doc.mode,state,function(end,style){return st.push(end,style);},lineClasses,forceToEnd) -var loop=function(o){var overlay=cm.state.overlays[o],i=1,at=0 -runMode(cm,line.text,overlay.mode,true,function(end,style){var start=i -while(at<end){var i_end=st[i] -if(i_end>end) -{st.splice(i,1,end,st[i+1],i_end)} -i+=2 -at=Math.min(end,i_end)} -if(!style){return} -if(overlay.opaque){st.splice(start,i-start,end,"overlay "+style) -i=start+2}else{for(;start<i;start+=2){var cur=st[start+1] -st[start+1]=(cur?cur+" ":"")+"overlay "+style}}},lineClasses)};for(var o=0;o<cm.state.overlays.length;++o)loop(o);return{styles:st,classes:lineClasses.bgClass||lineClasses.textClass?lineClasses:null}} -function getLineStyles(cm,line,updateFrontier){if(!line.styles||line.styles[0]!=cm.state.modeGen){var state=getStateBefore(cm,lineNo(line)) -var result=highlightLine(cm,line,line.text.length>cm.options.maxHighlightLength?copyState(cm.doc.mode,state):state) -line.stateAfter=state -line.styles=result.styles -if(result.classes){line.styleClasses=result.classes} -else if(line.styleClasses){line.styleClasses=null} -if(updateFrontier===cm.doc.frontier){cm.doc.frontier++}} -return line.styles} -function getStateBefore(cm,n,precise){var doc=cm.doc,display=cm.display -if(!doc.mode.startState){return true} -var pos=findStartLine(cm,n,precise),state=pos>doc.first&&getLine(doc,pos-1).stateAfter -if(!state){state=startState(doc.mode)} -else{state=copyState(doc.mode,state)} -doc.iter(pos,n,function(line){processLine(cm,line.text,state) -var save=pos==n-1||pos%5==0||pos>=display.viewFrom&&pos<display.viewTo -line.stateAfter=save?copyState(doc.mode,state):null -++pos}) -if(precise){doc.frontier=pos} -return state} -function processLine(cm,text,state,startAt){var mode=cm.doc.mode -var stream=new StringStream(text,cm.options.tabSize) -stream.start=stream.pos=startAt||0 -if(text==""){callBlankLine(mode,state)} -while(!stream.eol()){readToken(mode,stream,state) -stream.start=stream.pos}} -function callBlankLine(mode,state){if(mode.blankLine){return mode.blankLine(state)} -if(!mode.innerMode){return} -var inner=innerMode(mode,state) -if(inner.mode.blankLine){return inner.mode.blankLine(inner.state)}} -function readToken(mode,stream,state,inner){for(var i=0;i<10;i++){if(inner){inner[0]=innerMode(mode,state).mode} -var style=mode.token(stream,state) -if(stream.pos>stream.start){return style}} -throw new Error("Mode "+mode.name+" failed to advance stream.")} -function takeToken(cm,pos,precise,asArray){var getObj=function(copy){return({start:stream.start,end:stream.pos,string:stream.current(),type:style||null,state:copy?copyState(doc.mode,state):state});} -var doc=cm.doc,mode=doc.mode,style -pos=clipPos(doc,pos) -var line=getLine(doc,pos.line),state=getStateBefore(cm,pos.line,precise) -var stream=new StringStream(line.text,cm.options.tabSize),tokens -if(asArray){tokens=[]} -while((asArray||stream.pos<pos.ch)&&!stream.eol()){stream.start=stream.pos -style=readToken(mode,stream,state) -if(asArray){tokens.push(getObj(true))}} -return asArray?tokens:getObj()} -function extractLineClasses(type,output){if(type){for(;;){var lineClass=type.match(/(?:^|\s+)line-(background-)?(\S+)/) -if(!lineClass){break} -type=type.slice(0,lineClass.index)+type.slice(lineClass.index+lineClass[0].length) -var prop=lineClass[1]?"bgClass":"textClass" -if(output[prop]==null) -{output[prop]=lineClass[2]} -else if(!(new RegExp("(?:^|\s)"+lineClass[2]+"(?:$|\s)")).test(output[prop])) -{output[prop]+=" "+lineClass[2]}}} -return type} -function runMode(cm,text,mode,state,f,lineClasses,forceToEnd){var flattenSpans=mode.flattenSpans -if(flattenSpans==null){flattenSpans=cm.options.flattenSpans} -var curStart=0,curStyle=null -var stream=new StringStream(text,cm.options.tabSize),style -var inner=cm.options.addModeClass&&[null] -if(text==""){extractLineClasses(callBlankLine(mode,state),lineClasses)} -while(!stream.eol()){if(stream.pos>cm.options.maxHighlightLength){flattenSpans=false -if(forceToEnd){processLine(cm,text,state,stream.pos)} -stream.pos=text.length -style=null}else{style=extractLineClasses(readToken(mode,stream,state,inner),lineClasses)} -if(inner){var mName=inner[0].name -if(mName){style="m-"+(style?mName+" "+style:mName)}} -if(!flattenSpans||curStyle!=style){while(curStart<stream.start){curStart=Math.min(stream.start,curStart+5000) -f(curStart,curStyle)} -curStyle=style} -stream.start=stream.pos} -while(curStart<stream.pos){var pos=Math.min(stream.pos,curStart+5000) -f(pos,curStyle) -curStart=pos}} -function findStartLine(cm,n,precise){var minindent,minline,doc=cm.doc -var lim=precise?-1:n-(cm.doc.mode.innerMode?1000:100) -for(var search=n;search>lim;--search){if(search<=doc.first){return doc.first} -var line=getLine(doc,search-1) -if(line.stateAfter&&(!precise||search<=doc.frontier)){return search} -var indented=countColumn(line.text,null,cm.options.tabSize) -if(minline==null||minindent>indented){minline=search-1 -minindent=indented}} -return minline} -var Line=function Line(text,markedSpans,estimateHeight){this.text=text -attachMarkedSpans(this,markedSpans) -this.height=estimateHeight?estimateHeight(this):1};Line.prototype.lineNo=function lineNo$1(){return lineNo(this)};eventMixin(Line) -function updateLine(line,text,markedSpans,estimateHeight){line.text=text -if(line.stateAfter){line.stateAfter=null} -if(line.styles){line.styles=null} -if(line.order!=null){line.order=null} -detachMarkedSpans(line) -attachMarkedSpans(line,markedSpans) -var estHeight=estimateHeight?estimateHeight(line):1 -if(estHeight!=line.height){updateLineHeight(line,estHeight)}} -function cleanUpLine(line){line.parent=null -detachMarkedSpans(line)} -var styleToClassCache={};var styleToClassCacheWithMode={};function interpretTokenStyle(style,options){if(!style||/^\s*$/.test(style)){return null} -var cache=options.addModeClass?styleToClassCacheWithMode:styleToClassCache -return cache[style]||(cache[style]=style.replace(/\S+/g,"cm-$&"))} -function buildLineContent(cm,lineView){var content=eltP("span",null,null,webkit?"padding-right: .1px":null) -var builder={pre:eltP("pre",[content],"CodeMirror-line"),content:content,col:0,pos:0,cm:cm,trailingSpace:false,splitSpaces:(ie||webkit)&&cm.getOption("lineWrapping")} -lineView.measure={} -for(var i=0;i<=(lineView.rest?lineView.rest.length:0);i++){var line=i?lineView.rest[i-1]:lineView.line,order=(void 0) -builder.pos=0 -builder.addToken=buildToken -if(hasBadBidiRects(cm.display.measure)&&(order=getOrder(line,cm.doc.direction))) -{builder.addToken=buildTokenBadBidi(builder.addToken,order)} -builder.map=[] -var allowFrontierUpdate=lineView!=cm.display.externalMeasured&&lineNo(line) -insertLineContent(line,builder,getLineStyles(cm,line,allowFrontierUpdate)) -if(line.styleClasses){if(line.styleClasses.bgClass) -{builder.bgClass=joinClasses(line.styleClasses.bgClass,builder.bgClass||"")} -if(line.styleClasses.textClass) -{builder.textClass=joinClasses(line.styleClasses.textClass,builder.textClass||"")}} -if(builder.map.length==0) -{builder.map.push(0,0,builder.content.appendChild(zeroWidthElement(cm.display.measure)))} -if(i==0){lineView.measure.map=builder.map -lineView.measure.cache={}}else{;(lineView.measure.maps||(lineView.measure.maps=[])).push(builder.map);(lineView.measure.caches||(lineView.measure.caches=[])).push({})}} -if(webkit){var last=builder.content.lastChild -if(/\bcm-tab\b/.test(last.className)||(last.querySelector&&last.querySelector(".cm-tab"))) -{builder.content.className="cm-tab-wrap-hack"}} -signal(cm,"renderLine",cm,lineView.line,builder.pre) -if(builder.pre.className) -{builder.textClass=joinClasses(builder.pre.className,builder.textClass||"")} -return builder} -function defaultSpecialCharPlaceholder(ch){var token=elt("span","\u2022","cm-invalidchar") -token.title="\\u"+ch.charCodeAt(0).toString(16) -token.setAttribute("aria-label",token.title) -return token} -function buildToken(builder,text,style,startStyle,endStyle,title,css){if(!text){return} -var displayText=builder.splitSpaces?splitSpaces(text,builder.trailingSpace):text -var special=builder.cm.state.specialChars,mustWrap=false -var content -if(!special.test(text)){builder.col+=text.length -content=document.createTextNode(displayText) -builder.map.push(builder.pos,builder.pos+text.length,content) -if(ie&&ie_version<9){mustWrap=true} -builder.pos+=text.length}else{content=document.createDocumentFragment() -var pos=0 -while(true){special.lastIndex=pos -var m=special.exec(text) -var skipped=m?m.index-pos:text.length-pos -if(skipped){var txt=document.createTextNode(displayText.slice(pos,pos+skipped)) -if(ie&&ie_version<9){content.appendChild(elt("span",[txt]))} -else{content.appendChild(txt)} -builder.map.push(builder.pos,builder.pos+skipped,txt) -builder.col+=skipped -builder.pos+=skipped} -if(!m){break} -pos+=skipped+1 -var txt$1=(void 0) -if(m[0]=="\t"){var tabSize=builder.cm.options.tabSize,tabWidth=tabSize-builder.col%tabSize -txt$1=content.appendChild(elt("span",spaceStr(tabWidth),"cm-tab")) -txt$1.setAttribute("role","presentation") -txt$1.setAttribute("cm-text","\t") -builder.col+=tabWidth}else if(m[0]=="\r"||m[0]=="\n"){txt$1=content.appendChild(elt("span",m[0]=="\r"?"\u240d":"\u2424","cm-invalidchar")) -txt$1.setAttribute("cm-text",m[0]) -builder.col+=1}else{txt$1=builder.cm.options.specialCharPlaceholder(m[0]) -txt$1.setAttribute("cm-text",m[0]) -if(ie&&ie_version<9){content.appendChild(elt("span",[txt$1]))} -else{content.appendChild(txt$1)} -builder.col+=1} -builder.map.push(builder.pos,builder.pos+1,txt$1) -builder.pos++}} -builder.trailingSpace=displayText.charCodeAt(text.length-1)==32 -if(style||startStyle||endStyle||mustWrap||css){var fullStyle=style||"" -if(startStyle){fullStyle+=startStyle} -if(endStyle){fullStyle+=endStyle} -var token=elt("span",[content],fullStyle,css) -if(title){token.title=title} -return builder.content.appendChild(token)} -builder.content.appendChild(content)} -function splitSpaces(text,trailingBefore){if(text.length>1&&!/ /.test(text)){return text} -var spaceBefore=trailingBefore,result="" -for(var i=0;i<text.length;i++){var ch=text.charAt(i) -if(ch==" "&&spaceBefore&&(i==text.length-1||text.charCodeAt(i+1)==32)) -{ch="\u00a0"} -result+=ch -spaceBefore=ch==" "} -return result} -function buildTokenBadBidi(inner,order){return function(builder,text,style,startStyle,endStyle,title,css){style=style?style+" cm-force-border":"cm-force-border" -var start=builder.pos,end=start+text.length -for(;;){var part=(void 0) -for(var i=0;i<order.length;i++){part=order[i] -if(part.to>start&&part.from<=start){break}} -if(part.to>=end){return inner(builder,text,style,startStyle,endStyle,title,css)} -inner(builder,text.slice(0,part.to-start),style,startStyle,null,title,css) -startStyle=null -text=text.slice(part.to-start) -start=part.to}}} -function buildCollapsedSpan(builder,size,marker,ignoreWidget){var widget=!ignoreWidget&&marker.widgetNode -if(widget){builder.map.push(builder.pos,builder.pos+size,widget)} -if(!ignoreWidget&&builder.cm.display.input.needsContentAttribute){if(!widget) -{widget=builder.content.appendChild(document.createElement("span"))} -widget.setAttribute("cm-marker",marker.id)} -if(widget){builder.cm.display.input.setUneditable(widget) -builder.content.appendChild(widget)} -builder.pos+=size -builder.trailingSpace=false} -function insertLineContent(line,builder,styles){var spans=line.markedSpans,allText=line.text,at=0 -if(!spans){for(var i$1=1;i$1<styles.length;i$1+=2) -{builder.addToken(builder,allText.slice(at,at=styles[i$1]),interpretTokenStyle(styles[i$1+1],builder.cm.options))} -return} -var len=allText.length,pos=0,i=1,text="",style,css -var nextChange=0,spanStyle,spanEndStyle,spanStartStyle,title,collapsed -for(;;){if(nextChange==pos){spanStyle=spanEndStyle=spanStartStyle=title=css="" -collapsed=null;nextChange=Infinity -var foundBookmarks=[],endStyles=(void 0) -for(var j=0;j<spans.length;++j){var sp=spans[j],m=sp.marker -if(m.type=="bookmark"&&sp.from==pos&&m.widgetNode){foundBookmarks.push(m)}else if(sp.from<=pos&&(sp.to==null||sp.to>pos||m.collapsed&&sp.to==pos&&sp.from==pos)){if(sp.to!=null&&sp.to!=pos&&nextChange>sp.to){nextChange=sp.to -spanEndStyle=""} -if(m.className){spanStyle+=" "+m.className} -if(m.css){css=(css?css+";":"")+m.css} -if(m.startStyle&&sp.from==pos){spanStartStyle+=" "+m.startStyle} -if(m.endStyle&&sp.to==nextChange){(endStyles||(endStyles=[])).push(m.endStyle,sp.to)} -if(m.title&&!title){title=m.title} -if(m.collapsed&&(!collapsed||compareCollapsedMarkers(collapsed.marker,m)<0)) -{collapsed=sp}}else if(sp.from>pos&&nextChange>sp.from){nextChange=sp.from}} -if(endStyles){for(var j$1=0;j$1<endStyles.length;j$1+=2) -{if(endStyles[j$1+1]==nextChange){spanEndStyle+=" "+endStyles[j$1]}}} -if(!collapsed||collapsed.from==pos){for(var j$2=0;j$2<foundBookmarks.length;++j$2) -{buildCollapsedSpan(builder,0,foundBookmarks[j$2])}} -if(collapsed&&(collapsed.from||0)==pos){buildCollapsedSpan(builder,(collapsed.to==null?len+1:collapsed.to)-pos,collapsed.marker,collapsed.from==null) -if(collapsed.to==null){return} -if(collapsed.to==pos){collapsed=false}}} -if(pos>=len){break} -var upto=Math.min(len,nextChange) -while(true){if(text){var end=pos+text.length -if(!collapsed){var tokenText=end>upto?text.slice(0,upto-pos):text -builder.addToken(builder,tokenText,style?style+spanStyle:spanStyle,spanStartStyle,pos+tokenText.length==nextChange?spanEndStyle:"",title,css)} -if(end>=upto){text=text.slice(upto-pos);pos=upto;break} -pos=end -spanStartStyle=""} -text=allText.slice(at,at=styles[i++]) -style=interpretTokenStyle(styles[i++],builder.cm.options)}}} -function LineView(doc,line,lineN){this.line=line -this.rest=visualLineContinued(line) -this.size=this.rest?lineNo(lst(this.rest))-lineN+1:1 -this.node=this.text=null -this.hidden=lineIsHidden(doc,line)} -function buildViewArray(cm,from,to){var array=[],nextPos -for(var pos=from;pos<to;pos=nextPos){var view=new LineView(cm.doc,getLine(cm.doc,pos),pos) -nextPos=pos+view.size -array.push(view)} -return array} -var operationGroup=null -function pushOperation(op){if(operationGroup){operationGroup.ops.push(op)}else{op.ownsGroup=operationGroup={ops:[op],delayedCallbacks:[]}}} -function fireCallbacksForOps(group){var callbacks=group.delayedCallbacks,i=0 -do{for(;i<callbacks.length;i++) -{callbacks[i].call(null)} -for(var j=0;j<group.ops.length;j++){var op=group.ops[j] -if(op.cursorActivityHandlers) -{while(op.cursorActivityCalled<op.cursorActivityHandlers.length) -{op.cursorActivityHandlers[op.cursorActivityCalled++].call(null,op.cm)}}}}while(i<callbacks.length)} -function finishOperation(op,endCb){var group=op.ownsGroup -if(!group){return} -try{fireCallbacksForOps(group)} -finally{operationGroup=null -endCb(group)}} -var orphanDelayedCallbacks=null -function signalLater(emitter,type){var arr=getHandlers(emitter,type) -if(!arr.length){return} -var args=Array.prototype.slice.call(arguments,2),list -if(operationGroup){list=operationGroup.delayedCallbacks}else if(orphanDelayedCallbacks){list=orphanDelayedCallbacks}else{list=orphanDelayedCallbacks=[] -setTimeout(fireOrphanDelayed,0)} -var loop=function(i){list.push(function(){return arr[i].apply(null,args);})};for(var i=0;i<arr.length;++i) -loop(i);} -function fireOrphanDelayed(){var delayed=orphanDelayedCallbacks -orphanDelayedCallbacks=null -for(var i=0;i<delayed.length;++i){delayed[i]()}} -function updateLineForChanges(cm,lineView,lineN,dims){for(var j=0;j<lineView.changes.length;j++){var type=lineView.changes[j] -if(type=="text"){updateLineText(cm,lineView)} -else if(type=="gutter"){updateLineGutter(cm,lineView,lineN,dims)} -else if(type=="class"){updateLineClasses(cm,lineView)} -else if(type=="widget"){updateLineWidgets(cm,lineView,dims)}} -lineView.changes=null} -function ensureLineWrapped(lineView){if(lineView.node==lineView.text){lineView.node=elt("div",null,null,"position: relative") -if(lineView.text.parentNode) -{lineView.text.parentNode.replaceChild(lineView.node,lineView.text)} -lineView.node.appendChild(lineView.text) -if(ie&&ie_version<8){lineView.node.style.zIndex=2}} -return lineView.node} -function updateLineBackground(cm,lineView){var cls=lineView.bgClass?lineView.bgClass+" "+(lineView.line.bgClass||""):lineView.line.bgClass -if(cls){cls+=" CodeMirror-linebackground"} -if(lineView.background){if(cls){lineView.background.className=cls} -else{lineView.background.parentNode.removeChild(lineView.background);lineView.background=null}}else if(cls){var wrap=ensureLineWrapped(lineView) -lineView.background=wrap.insertBefore(elt("div",null,cls),wrap.firstChild) -cm.display.input.setUneditable(lineView.background)}} -function getLineContent(cm,lineView){var ext=cm.display.externalMeasured -if(ext&&ext.line==lineView.line){cm.display.externalMeasured=null -lineView.measure=ext.measure -return ext.built} -return buildLineContent(cm,lineView)} -function updateLineText(cm,lineView){var cls=lineView.text.className -var built=getLineContent(cm,lineView) -if(lineView.text==lineView.node){lineView.node=built.pre} -lineView.text.parentNode.replaceChild(built.pre,lineView.text) -lineView.text=built.pre -if(built.bgClass!=lineView.bgClass||built.textClass!=lineView.textClass){lineView.bgClass=built.bgClass -lineView.textClass=built.textClass -updateLineClasses(cm,lineView)}else if(cls){lineView.text.className=cls}} -function updateLineClasses(cm,lineView){updateLineBackground(cm,lineView) -if(lineView.line.wrapClass) -{ensureLineWrapped(lineView).className=lineView.line.wrapClass} -else if(lineView.node!=lineView.text) -{lineView.node.className=""} -var textClass=lineView.textClass?lineView.textClass+" "+(lineView.line.textClass||""):lineView.line.textClass -lineView.text.className=textClass||""} -function updateLineGutter(cm,lineView,lineN,dims){if(lineView.gutter){lineView.node.removeChild(lineView.gutter) -lineView.gutter=null} -if(lineView.gutterBackground){lineView.node.removeChild(lineView.gutterBackground) -lineView.gutterBackground=null} -if(lineView.line.gutterClass){var wrap=ensureLineWrapped(lineView) -lineView.gutterBackground=elt("div",null,"CodeMirror-gutter-background "+lineView.line.gutterClass,("left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px; width: "+(dims.gutterTotalWidth)+"px")) -cm.display.input.setUneditable(lineView.gutterBackground) -wrap.insertBefore(lineView.gutterBackground,lineView.text)} -var markers=lineView.line.gutterMarkers -if(cm.options.lineNumbers||markers){var wrap$1=ensureLineWrapped(lineView) -var gutterWrap=lineView.gutter=elt("div",null,"CodeMirror-gutter-wrapper",("left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px")) -cm.display.input.setUneditable(gutterWrap) -wrap$1.insertBefore(gutterWrap,lineView.text) -if(lineView.line.gutterClass) -{gutterWrap.className+=" "+lineView.line.gutterClass} -if(cm.options.lineNumbers&&(!markers||!markers["CodeMirror-linenumbers"])) -{lineView.lineNumber=gutterWrap.appendChild(elt("div",lineNumberFor(cm.options,lineN),"CodeMirror-linenumber CodeMirror-gutter-elt",("left: "+(dims.gutterLeft["CodeMirror-linenumbers"])+"px; width: "+(cm.display.lineNumInnerWidth)+"px")))} -if(markers){for(var k=0;k<cm.options.gutters.length;++k){var id=cm.options.gutters[k],found=markers.hasOwnProperty(id)&&markers[id] -if(found) -{gutterWrap.appendChild(elt("div",[found],"CodeMirror-gutter-elt",("left: "+(dims.gutterLeft[id])+"px; width: "+(dims.gutterWidth[id])+"px")))}}}}} -function updateLineWidgets(cm,lineView,dims){if(lineView.alignable){lineView.alignable=null} -for(var node=lineView.node.firstChild,next=(void 0);node;node=next){next=node.nextSibling -if(node.className=="CodeMirror-linewidget") -{lineView.node.removeChild(node)}} -insertLineWidgets(cm,lineView,dims)} -function buildLineElement(cm,lineView,lineN,dims){var built=getLineContent(cm,lineView) -lineView.text=lineView.node=built.pre -if(built.bgClass){lineView.bgClass=built.bgClass} -if(built.textClass){lineView.textClass=built.textClass} -updateLineClasses(cm,lineView) -updateLineGutter(cm,lineView,lineN,dims) -insertLineWidgets(cm,lineView,dims) -return lineView.node} -function insertLineWidgets(cm,lineView,dims){insertLineWidgetsFor(cm,lineView.line,lineView,dims,true) -if(lineView.rest){for(var i=0;i<lineView.rest.length;i++) -{insertLineWidgetsFor(cm,lineView.rest[i],lineView,dims,false)}}} -function insertLineWidgetsFor(cm,line,lineView,dims,allowAbove){if(!line.widgets){return} -var wrap=ensureLineWrapped(lineView) -for(var i=0,ws=line.widgets;i<ws.length;++i){var widget=ws[i],node=elt("div",[widget.node],"CodeMirror-linewidget") -if(!widget.handleMouseEvents){node.setAttribute("cm-ignore-events","true")} -positionLineWidget(widget,node,lineView,dims) -cm.display.input.setUneditable(node) -if(allowAbove&&widget.above) -{wrap.insertBefore(node,lineView.gutter||lineView.text)} -else -{wrap.appendChild(node)} -signalLater(widget,"redraw")}} -function positionLineWidget(widget,node,lineView,dims){if(widget.noHScroll){;(lineView.alignable||(lineView.alignable=[])).push(node) -var width=dims.wrapperWidth -node.style.left=dims.fixedPos+"px" -if(!widget.coverGutter){width-=dims.gutterTotalWidth -node.style.paddingLeft=dims.gutterTotalWidth+"px"} -node.style.width=width+"px"} -if(widget.coverGutter){node.style.zIndex=5 -node.style.position="relative" -if(!widget.noHScroll){node.style.marginLeft=-dims.gutterTotalWidth+"px"}}} -function widgetHeight(widget){if(widget.height!=null){return widget.height} -var cm=widget.doc.cm -if(!cm){return 0} -if(!contains(document.body,widget.node)){var parentStyle="position: relative;" -if(widget.coverGutter) -{parentStyle+="margin-left: -"+cm.display.gutters.offsetWidth+"px;"} -if(widget.noHScroll) -{parentStyle+="width: "+cm.display.wrapper.clientWidth+"px;"} -removeChildrenAndAdd(cm.display.measure,elt("div",[widget.node],null,parentStyle))} -return widget.height=widget.node.parentNode.offsetHeight} -function eventInWidget(display,e){for(var n=e_target(e);n!=display.wrapper;n=n.parentNode){if(!n||(n.nodeType==1&&n.getAttribute("cm-ignore-events")=="true")||(n.parentNode==display.sizer&&n!=display.mover)) -{return true}}} -function paddingTop(display){return display.lineSpace.offsetTop} -function paddingVert(display){return display.mover.offsetHeight-display.lineSpace.offsetHeight} -function paddingH(display){if(display.cachedPaddingH){return display.cachedPaddingH} -var e=removeChildrenAndAdd(display.measure,elt("pre","x")) -var style=window.getComputedStyle?window.getComputedStyle(e):e.currentStyle -var data={left:parseInt(style.paddingLeft),right:parseInt(style.paddingRight)} -if(!isNaN(data.left)&&!isNaN(data.right)){display.cachedPaddingH=data} -return data} -function scrollGap(cm){return scrollerGap-cm.display.nativeBarWidth} -function displayWidth(cm){return cm.display.scroller.clientWidth-scrollGap(cm)-cm.display.barWidth} -function displayHeight(cm){return cm.display.scroller.clientHeight-scrollGap(cm)-cm.display.barHeight} -function ensureLineHeights(cm,lineView,rect){var wrapping=cm.options.lineWrapping -var curWidth=wrapping&&displayWidth(cm) -if(!lineView.measure.heights||wrapping&&lineView.measure.width!=curWidth){var heights=lineView.measure.heights=[] -if(wrapping){lineView.measure.width=curWidth -var rects=lineView.text.firstChild.getClientRects() -for(var i=0;i<rects.length-1;i++){var cur=rects[i],next=rects[i+1] -if(Math.abs(cur.bottom-next.bottom)>2) -{heights.push((cur.bottom+next.top)/2-rect.top)}}} -heights.push(rect.bottom-rect.top)}} -function mapFromLineView(lineView,line,lineN){if(lineView.line==line) -{return{map:lineView.measure.map,cache:lineView.measure.cache}} -for(var i=0;i<lineView.rest.length;i++) -{if(lineView.rest[i]==line) -{return{map:lineView.measure.maps[i],cache:lineView.measure.caches[i]}}} -for(var i$1=0;i$1<lineView.rest.length;i$1++) -{if(lineNo(lineView.rest[i$1])>lineN) -{return{map:lineView.measure.maps[i$1],cache:lineView.measure.caches[i$1],before:true}}}} -function updateExternalMeasurement(cm,line){line=visualLine(line) -var lineN=lineNo(line) -var view=cm.display.externalMeasured=new LineView(cm.doc,line,lineN) -view.lineN=lineN -var built=view.built=buildLineContent(cm,view) -view.text=built.pre -removeChildrenAndAdd(cm.display.lineMeasure,built.pre) -return view} -function measureChar(cm,line,ch,bias){return measureCharPrepared(cm,prepareMeasureForLine(cm,line),ch,bias)} -function findViewForLine(cm,lineN){if(lineN>=cm.display.viewFrom&&lineN<cm.display.viewTo) -{return cm.display.view[findViewIndex(cm,lineN)]} -var ext=cm.display.externalMeasured -if(ext&&lineN>=ext.lineN&&lineN<ext.lineN+ext.size) -{return ext}} -function prepareMeasureForLine(cm,line){var lineN=lineNo(line) -var view=findViewForLine(cm,lineN) -if(view&&!view.text){view=null}else if(view&&view.changes){updateLineForChanges(cm,view,lineN,getDimensions(cm)) -cm.curOp.forceUpdate=true} -if(!view) -{view=updateExternalMeasurement(cm,line)} -var info=mapFromLineView(view,line,lineN) -return{line:line,view:view,rect:null,map:info.map,cache:info.cache,before:info.before,hasHeights:false}} -function measureCharPrepared(cm,prepared,ch,bias,varHeight){if(prepared.before){ch=-1} -var key=ch+(bias||""),found -if(prepared.cache.hasOwnProperty(key)){found=prepared.cache[key]}else{if(!prepared.rect) -{prepared.rect=prepared.view.text.getBoundingClientRect()} -if(!prepared.hasHeights){ensureLineHeights(cm,prepared.view,prepared.rect) -prepared.hasHeights=true} -found=measureCharInner(cm,prepared,ch,bias) -if(!found.bogus){prepared.cache[key]=found}} -return{left:found.left,right:found.right,top:varHeight?found.rtop:found.top,bottom:varHeight?found.rbottom:found.bottom}} -var nullRect={left:0,right:0,top:0,bottom:0} -function nodeAndOffsetInLineMap(map,ch,bias){var node,start,end,collapse,mStart,mEnd -for(var i=0;i<map.length;i+=3){mStart=map[i] -mEnd=map[i+1] -if(ch<mStart){start=0;end=1 -collapse="left"}else if(ch<mEnd){start=ch-mStart -end=start+1}else if(i==map.length-3||ch==mEnd&&map[i+3]>ch){end=mEnd-mStart -start=end-1 -if(ch>=mEnd){collapse="right"}} -if(start!=null){node=map[i+2] -if(mStart==mEnd&&bias==(node.insertLeft?"left":"right")) -{collapse=bias} -if(bias=="left"&&start==0) -{while(i&&map[i-2]==map[i-3]&&map[i-1].insertLeft){node=map[(i-=3)+2] -collapse="left"}} -if(bias=="right"&&start==mEnd-mStart) -{while(i<map.length-3&&map[i+3]==map[i+4]&&!map[i+5].insertLeft){node=map[(i+=3)+2] -collapse="right"}} -break}} -return{node:node,start:start,end:end,collapse:collapse,coverStart:mStart,coverEnd:mEnd}} -function getUsefulRect(rects,bias){var rect=nullRect -if(bias=="left"){for(var i=0;i<rects.length;i++){if((rect=rects[i]).left!=rect.right){break}}}else{for(var i$1=rects.length-1;i$1>=0;i$1--){if((rect=rects[i$1]).left!=rect.right){break}}} -return rect} -function measureCharInner(cm,prepared,ch,bias){var place=nodeAndOffsetInLineMap(prepared.map,ch,bias) -var node=place.node,start=place.start,end=place.end,collapse=place.collapse -var rect -if(node.nodeType==3){for(var i$1=0;i$1<4;i$1++){while(start&&isExtendingChar(prepared.line.text.charAt(place.coverStart+start))){--start} -while(place.coverStart+end<place.coverEnd&&isExtendingChar(prepared.line.text.charAt(place.coverStart+end))){++end} -if(ie&&ie_version<9&&start==0&&end==place.coverEnd-place.coverStart) -{rect=node.parentNode.getBoundingClientRect()} -else -{rect=getUsefulRect(range(node,start,end).getClientRects(),bias)} -if(rect.left||rect.right||start==0){break} -end=start -start=start-1 -collapse="right"} -if(ie&&ie_version<11){rect=maybeUpdateRectForZooming(cm.display.measure,rect)}}else{if(start>0){collapse=bias="right"} -var rects -if(cm.options.lineWrapping&&(rects=node.getClientRects()).length>1) -{rect=rects[bias=="right"?rects.length-1:0]} -else -{rect=node.getBoundingClientRect()}} -if(ie&&ie_version<9&&!start&&(!rect||!rect.left&&!rect.right)){var rSpan=node.parentNode.getClientRects()[0] -if(rSpan) -{rect={left:rSpan.left,right:rSpan.left+charWidth(cm.display),top:rSpan.top,bottom:rSpan.bottom}} -else -{rect=nullRect}} -var rtop=rect.top-prepared.rect.top,rbot=rect.bottom-prepared.rect.top -var mid=(rtop+rbot)/2 -var heights=prepared.view.measure.heights -var i=0 -for(;i<heights.length-1;i++) -{if(mid<heights[i]){break}} -var top=i?heights[i-1]:0,bot=heights[i] -var result={left:(collapse=="right"?rect.right:rect.left)-prepared.rect.left,right:(collapse=="left"?rect.left:rect.right)-prepared.rect.left,top:top,bottom:bot} -if(!rect.left&&!rect.right){result.bogus=true} -if(!cm.options.singleCursorHeightPerLine){result.rtop=rtop;result.rbottom=rbot} -return result} -function maybeUpdateRectForZooming(measure,rect){if(!window.screen||screen.logicalXDPI==null||screen.logicalXDPI==screen.deviceXDPI||!hasBadZoomedRects(measure)) -{return rect} -var scaleX=screen.logicalXDPI/screen.deviceXDPI -var scaleY=screen.logicalYDPI/screen.deviceYDPI -return{left:rect.left*scaleX,right:rect.right*scaleX,top:rect.top*scaleY,bottom:rect.bottom*scaleY}} -function clearLineMeasurementCacheFor(lineView){if(lineView.measure){lineView.measure.cache={} -lineView.measure.heights=null -if(lineView.rest){for(var i=0;i<lineView.rest.length;i++) -{lineView.measure.caches[i]={}}}}} -function clearLineMeasurementCache(cm){cm.display.externalMeasure=null -removeChildren(cm.display.lineMeasure) -for(var i=0;i<cm.display.view.length;i++) -{clearLineMeasurementCacheFor(cm.display.view[i])}} -function clearCaches(cm){clearLineMeasurementCache(cm) -cm.display.cachedCharWidth=cm.display.cachedTextHeight=cm.display.cachedPaddingH=null -if(!cm.options.lineWrapping){cm.display.maxLineChanged=true} -cm.display.lineNumChars=null} -function pageScrollX(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft} -function pageScrollY(){return window.pageYOffset||(document.documentElement||document.body).scrollTop} -function intoCoordSystem(cm,lineObj,rect,context,includeWidgets){if(!includeWidgets&&lineObj.widgets){for(var i=0;i<lineObj.widgets.length;++i){if(lineObj.widgets[i].above){var size=widgetHeight(lineObj.widgets[i]) -rect.top+=size;rect.bottom+=size}}} -if(context=="line"){return rect} -if(!context){context="local"} -var yOff=heightAtLine(lineObj) -if(context=="local"){yOff+=paddingTop(cm.display)} -else{yOff-=cm.display.viewOffset} -if(context=="page"||context=="window"){var lOff=cm.display.lineSpace.getBoundingClientRect() -yOff+=lOff.top+(context=="window"?0:pageScrollY()) -var xOff=lOff.left+(context=="window"?0:pageScrollX()) -rect.left+=xOff;rect.right+=xOff} -rect.top+=yOff;rect.bottom+=yOff -return rect} -function fromCoordSystem(cm,coords,context){if(context=="div"){return coords} -var left=coords.left,top=coords.top -if(context=="page"){left-=pageScrollX() -top-=pageScrollY()}else if(context=="local"||!context){var localBox=cm.display.sizer.getBoundingClientRect() -left+=localBox.left -top+=localBox.top} -var lineSpaceBox=cm.display.lineSpace.getBoundingClientRect() -return{left:left-lineSpaceBox.left,top:top-lineSpaceBox.top}} -function charCoords(cm,pos,context,lineObj,bias){if(!lineObj){lineObj=getLine(cm.doc,pos.line)} -return intoCoordSystem(cm,lineObj,measureChar(cm,lineObj,pos.ch,bias),context)} -function cursorCoords(cm,pos,context,lineObj,preparedMeasure,varHeight){lineObj=lineObj||getLine(cm.doc,pos.line) -if(!preparedMeasure){preparedMeasure=prepareMeasureForLine(cm,lineObj)} -function get(ch,right){var m=measureCharPrepared(cm,preparedMeasure,ch,right?"right":"left",varHeight) -if(right){m.left=m.right;}else{m.right=m.left} -return intoCoordSystem(cm,lineObj,m,context)} -var order=getOrder(lineObj,cm.doc.direction),ch=pos.ch,sticky=pos.sticky -if(ch>=lineObj.text.length){ch=lineObj.text.length -sticky="before"}else if(ch<=0){ch=0 -sticky="after"} -if(!order){return get(sticky=="before"?ch-1:ch,sticky=="before")} -function getBidi(ch,partPos,invert){var part=order[partPos],right=(part.level%2)!=0 -return get(invert?ch-1:ch,right!=invert)} -var partPos=getBidiPartAt(order,ch,sticky) -var other=bidiOther -var val=getBidi(ch,partPos,sticky=="before") -if(other!=null){val.other=getBidi(ch,other,sticky!="before")} -return val} -function estimateCoords(cm,pos){var left=0 -pos=clipPos(cm.doc,pos) -if(!cm.options.lineWrapping){left=charWidth(cm.display)*pos.ch} -var lineObj=getLine(cm.doc,pos.line) -var top=heightAtLine(lineObj)+paddingTop(cm.display) -return{left:left,right:left,top:top,bottom:top+lineObj.height}} -function PosWithInfo(line,ch,sticky,outside,xRel){var pos=Pos(line,ch,sticky) -pos.xRel=xRel -if(outside){pos.outside=true} -return pos} -function coordsChar(cm,x,y){var doc=cm.doc -y+=cm.display.viewOffset -if(y<0){return PosWithInfo(doc.first,0,null,true,-1)} -var lineN=lineAtHeight(doc,y),last=doc.first+doc.size-1 -if(lineN>last) -{return PosWithInfo(doc.first+doc.size-1,getLine(doc,last).text.length,null,true,1)} -if(x<0){x=0} -var lineObj=getLine(doc,lineN) -for(;;){var found=coordsCharInner(cm,lineObj,lineN,x,y) -var merged=collapsedSpanAtEnd(lineObj) -var mergedPos=merged&&merged.find(0,true) -if(merged&&(found.ch>mergedPos.from.ch||found.ch==mergedPos.from.ch&&found.xRel>0)) -{lineN=lineNo(lineObj=mergedPos.to.line)} -else -{return found}}} -function wrappedLineExtent(cm,lineObj,preparedMeasure,y){var measure=function(ch){return intoCoordSystem(cm,lineObj,measureCharPrepared(cm,preparedMeasure,ch),"line");} -var end=lineObj.text.length -var begin=findFirst(function(ch){return measure(ch-1).bottom<=y;},end,0) -end=findFirst(function(ch){return measure(ch).top>y;},begin,end) -return{begin:begin,end:end}} -function wrappedLineExtentChar(cm,lineObj,preparedMeasure,target){var targetTop=intoCoordSystem(cm,lineObj,measureCharPrepared(cm,preparedMeasure,target),"line").top -return wrappedLineExtent(cm,lineObj,preparedMeasure,targetTop)} -function coordsCharInner(cm,lineObj,lineNo,x,y){y-=heightAtLine(lineObj) -var begin=0,end=lineObj.text.length -var preparedMeasure=prepareMeasureForLine(cm,lineObj) -var pos -var order=getOrder(lineObj,cm.doc.direction) -if(order){if(cm.options.lineWrapping){;var assign;((assign=wrappedLineExtent(cm,lineObj,preparedMeasure,y),begin=assign.begin,end=assign.end))} -pos=new Pos(lineNo,begin) -var beginLeft=cursorCoords(cm,pos,"line",lineObj,preparedMeasure).left -var dir=beginLeft<x?1:-1 -var prevDiff,diff=beginLeft-x,prevPos -do{prevDiff=diff -prevPos=pos -pos=moveVisually(cm,lineObj,pos,dir) -if(pos==null||pos.ch<begin||end<=(pos.sticky=="before"?pos.ch-1:pos.ch)){pos=prevPos -break} -diff=cursorCoords(cm,pos,"line",lineObj,preparedMeasure).left-x}while((dir<0)!=(diff<0)&&(Math.abs(diff)<=Math.abs(prevDiff))) -if(Math.abs(diff)>Math.abs(prevDiff)){if((diff<0)==(prevDiff<0)){throw new Error("Broke out of infinite loop in coordsCharInner")} -pos=prevPos}}else{var ch=findFirst(function(ch){var box=intoCoordSystem(cm,lineObj,measureCharPrepared(cm,preparedMeasure,ch),"line") -if(box.top>y){end=Math.min(ch,end) -return true} -else if(box.bottom<=y){return false} -else if(box.left>x){return true} -else if(box.right<x){return false} -else{return(x-box.left<box.right-x)}},begin,end) -ch=skipExtendingChars(lineObj.text,ch,1) -pos=new Pos(lineNo,ch,ch==end?"before":"after")} -var coords=cursorCoords(cm,pos,"line",lineObj,preparedMeasure) -if(y<coords.top||coords.bottom<y){pos.outside=true} -pos.xRel=x<coords.left?-1:(x>coords.right?1:0) -return pos} -var measureText -function textHeight(display){if(display.cachedTextHeight!=null){return display.cachedTextHeight} -if(measureText==null){measureText=elt("pre") -for(var i=0;i<49;++i){measureText.appendChild(document.createTextNode("x")) -measureText.appendChild(elt("br"))} -measureText.appendChild(document.createTextNode("x"))} -removeChildrenAndAdd(display.measure,measureText) -var height=measureText.offsetHeight/50 -if(height>3){display.cachedTextHeight=height} -removeChildren(display.measure) -return height||1} -function charWidth(display){if(display.cachedCharWidth!=null){return display.cachedCharWidth} -var anchor=elt("span","xxxxxxxxxx") -var pre=elt("pre",[anchor]) -removeChildrenAndAdd(display.measure,pre) -var rect=anchor.getBoundingClientRect(),width=(rect.right-rect.left)/10 -if(width>2){display.cachedCharWidth=width} -return width||10} -function getDimensions(cm){var d=cm.display,left={},width={} -var gutterLeft=d.gutters.clientLeft -for(var n=d.gutters.firstChild,i=0;n;n=n.nextSibling,++i){left[cm.options.gutters[i]]=n.offsetLeft+n.clientLeft+gutterLeft -width[cm.options.gutters[i]]=n.clientWidth} -return{fixedPos:compensateForHScroll(d),gutterTotalWidth:d.gutters.offsetWidth,gutterLeft:left,gutterWidth:width,wrapperWidth:d.wrapper.clientWidth}} -function compensateForHScroll(display){return display.scroller.getBoundingClientRect().left-display.sizer.getBoundingClientRect().left} -function estimateHeight(cm){var th=textHeight(cm.display),wrapping=cm.options.lineWrapping -var perLine=wrapping&&Math.max(5,cm.display.scroller.clientWidth/charWidth(cm.display)-3) -return function(line){if(lineIsHidden(cm.doc,line)){return 0} -var widgetsHeight=0 -if(line.widgets){for(var i=0;i<line.widgets.length;i++){if(line.widgets[i].height){widgetsHeight+=line.widgets[i].height}}} -if(wrapping) -{return widgetsHeight+(Math.ceil(line.text.length/perLine)||1)*th} -else -{return widgetsHeight+th}}} -function estimateLineHeights(cm){var doc=cm.doc,est=estimateHeight(cm) -doc.iter(function(line){var estHeight=est(line) -if(estHeight!=line.height){updateLineHeight(line,estHeight)}})} -function posFromMouse(cm,e,liberal,forRect){var display=cm.display -if(!liberal&&e_target(e).getAttribute("cm-not-content")=="true"){return null} -var x,y,space=display.lineSpace.getBoundingClientRect() -try{x=e.clientX-space.left;y=e.clientY-space.top} -catch(e){return null} -var coords=coordsChar(cm,x,y),line -if(forRect&&coords.xRel==1&&(line=getLine(cm.doc,coords.line).text).length==coords.ch){var colDiff=countColumn(line,line.length,cm.options.tabSize)-line.length -coords=Pos(coords.line,Math.max(0,Math.round((x-paddingH(cm.display).left)/charWidth(cm.display))-colDiff))} -return coords} -function findViewIndex(cm,n){if(n>=cm.display.viewTo){return null} -n-=cm.display.viewFrom -if(n<0){return null} -var view=cm.display.view -for(var i=0;i<view.length;i++){n-=view[i].size -if(n<0){return i}}} -function updateSelection(cm){cm.display.input.showSelection(cm.display.input.prepareSelection())} -function prepareSelection(cm,primary){var doc=cm.doc,result={} -var curFragment=result.cursors=document.createDocumentFragment() -var selFragment=result.selection=document.createDocumentFragment() -for(var i=0;i<doc.sel.ranges.length;i++){if(primary===false&&i==doc.sel.primIndex){continue} -var range=doc.sel.ranges[i] -if(range.from().line>=cm.display.viewTo||range.to().line<cm.display.viewFrom){continue} -var collapsed=range.empty() -if(collapsed||cm.options.showCursorWhenSelecting) -{drawSelectionCursor(cm,range.head,curFragment)} -if(!collapsed) -{drawSelectionRange(cm,range,selFragment)}} -return result} -function drawSelectionCursor(cm,head,output){var pos=cursorCoords(cm,head,"div",null,null,!cm.options.singleCursorHeightPerLine) -var cursor=output.appendChild(elt("div","\u00a0","CodeMirror-cursor")) -cursor.style.left=pos.left+"px" -cursor.style.top=pos.top+"px" -cursor.style.height=Math.max(0,pos.bottom-pos.top)*cm.options.cursorHeight+"px" -if(pos.other){var otherCursor=output.appendChild(elt("div","\u00a0","CodeMirror-cursor CodeMirror-secondarycursor")) -otherCursor.style.display="" -otherCursor.style.left=pos.other.left+"px" -otherCursor.style.top=pos.other.top+"px" -otherCursor.style.height=(pos.other.bottom-pos.other.top)*.85+"px"}} -function drawSelectionRange(cm,range,output){var display=cm.display,doc=cm.doc -var fragment=document.createDocumentFragment() -var padding=paddingH(cm.display),leftSide=padding.left -var rightSide=Math.max(display.sizerWidth,displayWidth(cm)-display.sizer.offsetLeft)-padding.right -function add(left,top,width,bottom){if(top<0){top=0} -top=Math.round(top) -bottom=Math.round(bottom) -fragment.appendChild(elt("div",null,"CodeMirror-selected",("position: absolute; left: "+left+"px;\n top: "+top+"px; width: "+(width==null?rightSide-left:width)+"px;\n height: "+(bottom-top)+"px")))} -function drawForLine(line,fromArg,toArg){var lineObj=getLine(doc,line) -var lineLen=lineObj.text.length -var start,end -function coords(ch,bias){return charCoords(cm,Pos(line,ch),"div",lineObj,bias)} -iterateBidiSections(getOrder(lineObj,doc.direction),fromArg||0,toArg==null?lineLen:toArg,function(from,to,dir){var leftPos=coords(from,"left"),rightPos,left,right -if(from==to){rightPos=leftPos -left=right=leftPos.left}else{rightPos=coords(to-1,"right") -if(dir=="rtl"){var tmp=leftPos;leftPos=rightPos;rightPos=tmp} -left=leftPos.left -right=rightPos.right} -if(fromArg==null&&from==0){left=leftSide} -if(rightPos.top-leftPos.top>3){add(left,leftPos.top,null,leftPos.bottom) -left=leftSide -if(leftPos.bottom<rightPos.top){add(left,leftPos.bottom,null,rightPos.top)}} -if(toArg==null&&to==lineLen){right=rightSide} -if(!start||leftPos.top<start.top||leftPos.top==start.top&&leftPos.left<start.left) -{start=leftPos} -if(!end||rightPos.bottom>end.bottom||rightPos.bottom==end.bottom&&rightPos.right>end.right) -{end=rightPos} -if(left<leftSide+1){left=leftSide} -add(left,rightPos.top,right-left,rightPos.bottom)}) -return{start:start,end:end}} -var sFrom=range.from(),sTo=range.to() -if(sFrom.line==sTo.line){drawForLine(sFrom.line,sFrom.ch,sTo.ch)}else{var fromLine=getLine(doc,sFrom.line),toLine=getLine(doc,sTo.line) -var singleVLine=visualLine(fromLine)==visualLine(toLine) -var leftEnd=drawForLine(sFrom.line,sFrom.ch,singleVLine?fromLine.text.length+1:null).end -var rightStart=drawForLine(sTo.line,singleVLine?0:null,sTo.ch).start -if(singleVLine){if(leftEnd.top<rightStart.top-2){add(leftEnd.right,leftEnd.top,null,leftEnd.bottom) -add(leftSide,rightStart.top,rightStart.left,rightStart.bottom)}else{add(leftEnd.right,leftEnd.top,rightStart.left-leftEnd.right,leftEnd.bottom)}} -if(leftEnd.bottom<rightStart.top) -{add(leftSide,leftEnd.bottom,null,rightStart.top)}} -output.appendChild(fragment)} -function restartBlink(cm){if(!cm.state.focused){return} -var display=cm.display -clearInterval(display.blinker) -var on=true -display.cursorDiv.style.visibility="" -if(cm.options.cursorBlinkRate>0) -{display.blinker=setInterval(function(){return display.cursorDiv.style.visibility=(on=!on)?"":"hidden";},cm.options.cursorBlinkRate)} -else if(cm.options.cursorBlinkRate<0) -{display.cursorDiv.style.visibility="hidden"}} -function ensureFocus(cm){if(!cm.state.focused){cm.display.input.focus();onFocus(cm)}} -function delayBlurEvent(cm){cm.state.delayingBlurEvent=true -setTimeout(function(){if(cm.state.delayingBlurEvent){cm.state.delayingBlurEvent=false -onBlur(cm)}},100)} -function onFocus(cm,e){if(cm.state.delayingBlurEvent){cm.state.delayingBlurEvent=false} -if(cm.options.readOnly=="nocursor"){return} -if(!cm.state.focused){signal(cm,"focus",cm,e) -cm.state.focused=true -addClass(cm.display.wrapper,"CodeMirror-focused") -if(!cm.curOp&&cm.display.selForContextMenu!=cm.doc.sel){cm.display.input.reset() -if(webkit){setTimeout(function(){return cm.display.input.reset(true);},20)}} -cm.display.input.receivedFocus()} -restartBlink(cm)} -function onBlur(cm,e){if(cm.state.delayingBlurEvent){return} -if(cm.state.focused){signal(cm,"blur",cm,e) -cm.state.focused=false -rmClass(cm.display.wrapper,"CodeMirror-focused")} -clearInterval(cm.display.blinker) -setTimeout(function(){if(!cm.state.focused){cm.display.shift=false}},150)} -function alignHorizontally(cm){var display=cm.display,view=display.view -if(!display.alignWidgets&&(!display.gutters.firstChild||!cm.options.fixedGutter)){return} -var comp=compensateForHScroll(display)-display.scroller.scrollLeft+cm.doc.scrollLeft -var gutterW=display.gutters.offsetWidth,left=comp+"px" -for(var i=0;i<view.length;i++){if(!view[i].hidden){if(cm.options.fixedGutter){if(view[i].gutter) -{view[i].gutter.style.left=left} -if(view[i].gutterBackground) -{view[i].gutterBackground.style.left=left}} -var align=view[i].alignable -if(align){for(var j=0;j<align.length;j++) -{align[j].style.left=left}}}} -if(cm.options.fixedGutter) -{display.gutters.style.left=(comp+gutterW)+"px"}} -function maybeUpdateLineNumberWidth(cm){if(!cm.options.lineNumbers){return false} -var doc=cm.doc,last=lineNumberFor(cm.options,doc.first+doc.size-1),display=cm.display -if(last.length!=display.lineNumChars){var test=display.measure.appendChild(elt("div",[elt("div",last)],"CodeMirror-linenumber CodeMirror-gutter-elt")) -var innerW=test.firstChild.offsetWidth,padding=test.offsetWidth-innerW -display.lineGutter.style.width="" -display.lineNumInnerWidth=Math.max(innerW,display.lineGutter.offsetWidth-padding)+1 -display.lineNumWidth=display.lineNumInnerWidth+padding -display.lineNumChars=display.lineNumInnerWidth?last.length:-1 -display.lineGutter.style.width=display.lineNumWidth+"px" -updateGutterSpace(cm) -return true} -return false} -function updateHeightsInViewport(cm){var display=cm.display -var prevBottom=display.lineDiv.offsetTop -for(var i=0;i<display.view.length;i++){var cur=display.view[i],height=(void 0) -if(cur.hidden){continue} -if(ie&&ie_version<8){var bot=cur.node.offsetTop+cur.node.offsetHeight -height=bot-prevBottom -prevBottom=bot}else{var box=cur.node.getBoundingClientRect() -height=box.bottom-box.top} -var diff=cur.line.height-height -if(height<2){height=textHeight(display)} -if(diff>.001||diff<-.001){updateLineHeight(cur.line,height) -updateWidgetHeight(cur.line) -if(cur.rest){for(var j=0;j<cur.rest.length;j++) -{updateWidgetHeight(cur.rest[j])}}}}} -function updateWidgetHeight(line){if(line.widgets){for(var i=0;i<line.widgets.length;++i) -{line.widgets[i].height=line.widgets[i].node.parentNode.offsetHeight}}} -function visibleLines(display,doc,viewport){var top=viewport&&viewport.top!=null?Math.max(0,viewport.top):display.scroller.scrollTop -top=Math.floor(top-paddingTop(display)) -var bottom=viewport&&viewport.bottom!=null?viewport.bottom:top+display.wrapper.clientHeight -var from=lineAtHeight(doc,top),to=lineAtHeight(doc,bottom) -if(viewport&&viewport.ensure){var ensureFrom=viewport.ensure.from.line,ensureTo=viewport.ensure.to.line -if(ensureFrom<from){from=ensureFrom -to=lineAtHeight(doc,heightAtLine(getLine(doc,ensureFrom))+display.wrapper.clientHeight)}else if(Math.min(ensureTo,doc.lastLine())>=to){from=lineAtHeight(doc,heightAtLine(getLine(doc,ensureTo))-display.wrapper.clientHeight) -to=ensureTo}} -return{from:from,to:Math.max(to,from+1)}} -function setScrollTop(cm,val){if(Math.abs(cm.doc.scrollTop-val)<2){return} -cm.doc.scrollTop=val -if(!gecko){updateDisplaySimple(cm,{top:val})} -if(cm.display.scroller.scrollTop!=val){cm.display.scroller.scrollTop=val} -cm.display.scrollbars.setScrollTop(val) -if(gecko){updateDisplaySimple(cm)} -startWorker(cm,100)} -function setScrollLeft(cm,val,isScroller){if(isScroller?val==cm.doc.scrollLeft:Math.abs(cm.doc.scrollLeft-val)<2){return} -val=Math.min(val,cm.display.scroller.scrollWidth-cm.display.scroller.clientWidth) -cm.doc.scrollLeft=val -alignHorizontally(cm) -if(cm.display.scroller.scrollLeft!=val){cm.display.scroller.scrollLeft=val} -cm.display.scrollbars.setScrollLeft(val)} -var wheelSamples=0;var wheelPixelsPerUnit=null;if(ie){wheelPixelsPerUnit=-.53} -else if(gecko){wheelPixelsPerUnit=15} -else if(chrome){wheelPixelsPerUnit=-.7} -else if(safari){wheelPixelsPerUnit=-1/3} -function wheelEventDelta(e){var dx=e.wheelDeltaX,dy=e.wheelDeltaY -if(dx==null&&e.detail&&e.axis==e.HORIZONTAL_AXIS){dx=e.detail} -if(dy==null&&e.detail&&e.axis==e.VERTICAL_AXIS){dy=e.detail} -else if(dy==null){dy=e.wheelDelta} -return{x:dx,y:dy}} -function wheelEventPixels(e){var delta=wheelEventDelta(e) -delta.x*=wheelPixelsPerUnit -delta.y*=wheelPixelsPerUnit -return delta} -function onScrollWheel(cm,e){var delta=wheelEventDelta(e),dx=delta.x,dy=delta.y -var display=cm.display,scroll=display.scroller -var canScrollX=scroll.scrollWidth>scroll.clientWidth -var canScrollY=scroll.scrollHeight>scroll.clientHeight -if(!(dx&&canScrollX||dy&&canScrollY)){return} -if(dy&&mac&&webkit){outer:for(var cur=e.target,view=display.view;cur!=scroll;cur=cur.parentNode){for(var i=0;i<view.length;i++){if(view[i].node==cur){cm.display.currentWheelTarget=cur -break outer}}}} -if(dx&&!gecko&&!presto&&wheelPixelsPerUnit!=null){if(dy&&canScrollY) -{setScrollTop(cm,Math.max(0,Math.min(scroll.scrollTop+dy*wheelPixelsPerUnit,scroll.scrollHeight-scroll.clientHeight)))} -setScrollLeft(cm,Math.max(0,Math.min(scroll.scrollLeft+dx*wheelPixelsPerUnit,scroll.scrollWidth-scroll.clientWidth))) -if(!dy||(dy&&canScrollY)) -{e_preventDefault(e)} -display.wheelStartX=null -return} -if(dy&&wheelPixelsPerUnit!=null){var pixels=dy*wheelPixelsPerUnit -var top=cm.doc.scrollTop,bot=top+display.wrapper.clientHeight -if(pixels<0){top=Math.max(0,top+pixels-50)} -else{bot=Math.min(cm.doc.height,bot+pixels+50)} -updateDisplaySimple(cm,{top:top,bottom:bot})} -if(wheelSamples<20){if(display.wheelStartX==null){display.wheelStartX=scroll.scrollLeft;display.wheelStartY=scroll.scrollTop -display.wheelDX=dx;display.wheelDY=dy -setTimeout(function(){if(display.wheelStartX==null){return} -var movedX=scroll.scrollLeft-display.wheelStartX -var movedY=scroll.scrollTop-display.wheelStartY -var sample=(movedY&&display.wheelDY&&movedY/display.wheelDY)||(movedX&&display.wheelDX&&movedX/display.wheelDX) -display.wheelStartX=display.wheelStartY=null -if(!sample){return} -wheelPixelsPerUnit=(wheelPixelsPerUnit*wheelSamples+sample)/(wheelSamples+1) -++wheelSamples},200)}else{display.wheelDX+=dx;display.wheelDY+=dy}}} -function measureForScrollbars(cm){var d=cm.display,gutterW=d.gutters.offsetWidth -var docH=Math.round(cm.doc.height+paddingVert(cm.display)) -return{clientHeight:d.scroller.clientHeight,viewHeight:d.wrapper.clientHeight,scrollWidth:d.scroller.scrollWidth,clientWidth:d.scroller.clientWidth,viewWidth:d.wrapper.clientWidth,barLeft:cm.options.fixedGutter?gutterW:0,docHeight:docH,scrollHeight:docH+scrollGap(cm)+d.barHeight,nativeBarWidth:d.nativeBarWidth,gutterWidth:gutterW}} -var NativeScrollbars=function NativeScrollbars(place,scroll,cm){this.cm=cm -var vert=this.vert=elt("div",[elt("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar") -var horiz=this.horiz=elt("div",[elt("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar") -place(vert);place(horiz) -on(vert,"scroll",function(){if(vert.clientHeight){scroll(vert.scrollTop,"vertical")}}) -on(horiz,"scroll",function(){if(horiz.clientWidth){scroll(horiz.scrollLeft,"horizontal")}}) -this.checkedZeroWidth=false -if(ie&&ie_version<8){this.horiz.style.minHeight=this.vert.style.minWidth="18px"}};NativeScrollbars.prototype.update=function update(measure){var needsH=measure.scrollWidth>measure.clientWidth+1 -var needsV=measure.scrollHeight>measure.clientHeight+1 -var sWidth=measure.nativeBarWidth -if(needsV){this.vert.style.display="block" -this.vert.style.bottom=needsH?sWidth+"px":"0" -var totalHeight=measure.viewHeight-(needsH?sWidth:0) -this.vert.firstChild.style.height=Math.max(0,measure.scrollHeight-measure.clientHeight+totalHeight)+"px"}else{this.vert.style.display="" -this.vert.firstChild.style.height="0"} -if(needsH){this.horiz.style.display="block" -this.horiz.style.right=needsV?sWidth+"px":"0" -this.horiz.style.left=measure.barLeft+"px" -var totalWidth=measure.viewWidth-measure.barLeft-(needsV?sWidth:0) -this.horiz.firstChild.style.width=Math.max(0,measure.scrollWidth-measure.clientWidth+totalWidth)+"px"}else{this.horiz.style.display="" -this.horiz.firstChild.style.width="0"} -if(!this.checkedZeroWidth&&measure.clientHeight>0){if(sWidth==0){this.zeroWidthHack()} -this.checkedZeroWidth=true} -return{right:needsV?sWidth:0,bottom:needsH?sWidth:0}};NativeScrollbars.prototype.setScrollLeft=function setScrollLeft$1(pos){if(this.horiz.scrollLeft!=pos){this.horiz.scrollLeft=pos} -if(this.disableHoriz){this.enableZeroWidthBar(this.horiz,this.disableHoriz)}};NativeScrollbars.prototype.setScrollTop=function setScrollTop$1(pos){if(this.vert.scrollTop!=pos){this.vert.scrollTop=pos} -if(this.disableVert){this.enableZeroWidthBar(this.vert,this.disableVert)}};NativeScrollbars.prototype.zeroWidthHack=function zeroWidthHack(){var w=mac&&!mac_geMountainLion?"12px":"18px" -this.horiz.style.height=this.vert.style.width=w -this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none" -this.disableHoriz=new Delayed -this.disableVert=new Delayed};NativeScrollbars.prototype.enableZeroWidthBar=function enableZeroWidthBar(bar,delay){bar.style.pointerEvents="auto" -function maybeDisable(){var box=bar.getBoundingClientRect() -var elt=document.elementFromPoint(box.left+1,box.bottom-1) -if(elt!=bar){bar.style.pointerEvents="none"} -else{delay.set(1000,maybeDisable)}} -delay.set(1000,maybeDisable)};NativeScrollbars.prototype.clear=function clear(){var parent=this.horiz.parentNode -parent.removeChild(this.horiz) -parent.removeChild(this.vert)};var NullScrollbars=function NullScrollbars(){};NullScrollbars.prototype.update=function update(){return{bottom:0,right:0}};NullScrollbars.prototype.setScrollLeft=function setScrollLeft$2(){};NullScrollbars.prototype.setScrollTop=function setScrollTop$2(){};NullScrollbars.prototype.clear=function clear(){};function updateScrollbars(cm,measure){if(!measure){measure=measureForScrollbars(cm)} -var startWidth=cm.display.barWidth,startHeight=cm.display.barHeight -updateScrollbarsInner(cm,measure) -for(var i=0;i<4&&startWidth!=cm.display.barWidth||startHeight!=cm.display.barHeight;i++){if(startWidth!=cm.display.barWidth&&cm.options.lineWrapping) -{updateHeightsInViewport(cm)} -updateScrollbarsInner(cm,measureForScrollbars(cm)) -startWidth=cm.display.barWidth;startHeight=cm.display.barHeight}} -function updateScrollbarsInner(cm,measure){var d=cm.display -var sizes=d.scrollbars.update(measure) -d.sizer.style.paddingRight=(d.barWidth=sizes.right)+"px" -d.sizer.style.paddingBottom=(d.barHeight=sizes.bottom)+"px" -d.heightForcer.style.borderBottom=sizes.bottom+"px solid transparent" -if(sizes.right&&sizes.bottom){d.scrollbarFiller.style.display="block" -d.scrollbarFiller.style.height=sizes.bottom+"px" -d.scrollbarFiller.style.width=sizes.right+"px"}else{d.scrollbarFiller.style.display=""} -if(sizes.bottom&&cm.options.coverGutterNextToScrollbar&&cm.options.fixedGutter){d.gutterFiller.style.display="block" -d.gutterFiller.style.height=sizes.bottom+"px" -d.gutterFiller.style.width=measure.gutterWidth+"px"}else{d.gutterFiller.style.display=""}} -var scrollbarModel={"native":NativeScrollbars,"null":NullScrollbars} -function initScrollbars(cm){if(cm.display.scrollbars){cm.display.scrollbars.clear() -if(cm.display.scrollbars.addClass) -{rmClass(cm.display.wrapper,cm.display.scrollbars.addClass)}} -cm.display.scrollbars=new scrollbarModel[cm.options.scrollbarStyle](function(node){cm.display.wrapper.insertBefore(node,cm.display.scrollbarFiller) -on(node,"mousedown",function(){if(cm.state.focused){setTimeout(function(){return cm.display.input.focus();},0)}}) -node.setAttribute("cm-not-content","true")},function(pos,axis){if(axis=="horizontal"){setScrollLeft(cm,pos)} -else{setScrollTop(cm,pos)}},cm) -if(cm.display.scrollbars.addClass) -{addClass(cm.display.wrapper,cm.display.scrollbars.addClass)}} -function maybeScrollWindow(cm,rect){if(signalDOMEvent(cm,"scrollCursorIntoView")){return} -var display=cm.display,box=display.sizer.getBoundingClientRect(),doScroll=null -if(rect.top+box.top<0){doScroll=true} -else if(rect.bottom+box.top>(window.innerHeight||document.documentElement.clientHeight)){doScroll=false} -if(doScroll!=null&&!phantom){var scrollNode=elt("div","\u200b",null,("position: absolute;\n top: "+(rect.top-display.viewOffset-paddingTop(cm.display))+"px;\n height: "+(rect.bottom-rect.top+scrollGap(cm)+display.barHeight)+"px;\n left: "+(rect.left)+"px; width: "+(Math.max(2,rect.right-rect.left))+"px;")) -cm.display.lineSpace.appendChild(scrollNode) -scrollNode.scrollIntoView(doScroll) -cm.display.lineSpace.removeChild(scrollNode)}} -function scrollPosIntoView(cm,pos,end,margin){if(margin==null){margin=0} -var rect -for(var limit=0;limit<5;limit++){var changed=false -var coords=cursorCoords(cm,pos) -var endCoords=!end||end==pos?coords:cursorCoords(cm,end) -rect={left:Math.min(coords.left,endCoords.left),top:Math.min(coords.top,endCoords.top)-margin,right:Math.max(coords.left,endCoords.left),bottom:Math.max(coords.bottom,endCoords.bottom)+margin} -var scrollPos=calculateScrollPos(cm,rect) -var startTop=cm.doc.scrollTop,startLeft=cm.doc.scrollLeft -if(scrollPos.scrollTop!=null){setScrollTop(cm,scrollPos.scrollTop) -if(Math.abs(cm.doc.scrollTop-startTop)>1){changed=true}} -if(scrollPos.scrollLeft!=null){setScrollLeft(cm,scrollPos.scrollLeft) -if(Math.abs(cm.doc.scrollLeft-startLeft)>1){changed=true}} -if(!changed){break}} -return rect} -function scrollIntoView(cm,rect){var scrollPos=calculateScrollPos(cm,rect) -if(scrollPos.scrollTop!=null){setScrollTop(cm,scrollPos.scrollTop)} -if(scrollPos.scrollLeft!=null){setScrollLeft(cm,scrollPos.scrollLeft)}} -function calculateScrollPos(cm,rect){var display=cm.display,snapMargin=textHeight(cm.display) -if(rect.top<0){rect.top=0} -var screentop=cm.curOp&&cm.curOp.scrollTop!=null?cm.curOp.scrollTop:display.scroller.scrollTop -var screen=displayHeight(cm),result={} -if(rect.bottom-rect.top>screen){rect.bottom=rect.top+screen} -var docBottom=cm.doc.height+paddingVert(display) -var atTop=rect.top<snapMargin,atBottom=rect.bottom>docBottom-snapMargin -if(rect.top<screentop){result.scrollTop=atTop?0:rect.top}else if(rect.bottom>screentop+screen){var newTop=Math.min(rect.top,(atBottom?docBottom:rect.bottom)-screen) -if(newTop!=screentop){result.scrollTop=newTop}} -var screenleft=cm.curOp&&cm.curOp.scrollLeft!=null?cm.curOp.scrollLeft:display.scroller.scrollLeft -var screenw=displayWidth(cm)-(cm.options.fixedGutter?display.gutters.offsetWidth:0) -var tooWide=rect.right-rect.left>screenw -if(tooWide){rect.right=rect.left+screenw} -if(rect.left<10) -{result.scrollLeft=0} -else if(rect.left<screenleft) -{result.scrollLeft=Math.max(0,rect.left-(tooWide?0:10))} -else if(rect.right>screenw+screenleft-3) -{result.scrollLeft=rect.right+(tooWide?0:10)-screenw} -return result} -function addToScrollPos(cm,left,top){if(left!=null||top!=null){resolveScrollToPos(cm)} -if(left!=null) -{cm.curOp.scrollLeft=(cm.curOp.scrollLeft==null?cm.doc.scrollLeft:cm.curOp.scrollLeft)+left} -if(top!=null) -{cm.curOp.scrollTop=(cm.curOp.scrollTop==null?cm.doc.scrollTop:cm.curOp.scrollTop)+top}} -function ensureCursorVisible(cm){resolveScrollToPos(cm) -var cur=cm.getCursor(),from=cur,to=cur -if(!cm.options.lineWrapping){from=cur.ch?Pos(cur.line,cur.ch-1):cur -to=Pos(cur.line,cur.ch+1)} -cm.curOp.scrollToPos={from:from,to:to,margin:cm.options.cursorScrollMargin}} -function resolveScrollToPos(cm){var range=cm.curOp.scrollToPos -if(range){cm.curOp.scrollToPos=null -var from=estimateCoords(cm,range.from),to=estimateCoords(cm,range.to) -var sPos=calculateScrollPos(cm,{left:Math.min(from.left,to.left),top:Math.min(from.top,to.top)-range.margin,right:Math.max(from.right,to.right),bottom:Math.max(from.bottom,to.bottom)+range.margin}) -cm.scrollTo(sPos.scrollLeft,sPos.scrollTop)}} -var nextOpId=0 -function startOperation(cm){cm.curOp={cm:cm,viewChanged:false,startHeight:cm.doc.height,forceUpdate:false,updateInput:null,typing:false,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:false,updateMaxLine:false,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:false,id:++nextOpId} -pushOperation(cm.curOp)} -function endOperation(cm){var op=cm.curOp -finishOperation(op,function(group){for(var i=0;i<group.ops.length;i++) -{group.ops[i].cm.curOp=null} -endOperations(group)})} -function endOperations(group){var ops=group.ops -for(var i=0;i<ops.length;i++) -{endOperation_R1(ops[i])} -for(var i$1=0;i$1<ops.length;i$1++) -{endOperation_W1(ops[i$1])} -for(var i$2=0;i$2<ops.length;i$2++) -{endOperation_R2(ops[i$2])} -for(var i$3=0;i$3<ops.length;i$3++) -{endOperation_W2(ops[i$3])} -for(var i$4=0;i$4<ops.length;i$4++) -{endOperation_finish(ops[i$4])}} -function endOperation_R1(op){var cm=op.cm,display=cm.display -maybeClipScrollbars(cm) -if(op.updateMaxLine){findMaxLine(cm)} -op.mustUpdate=op.viewChanged||op.forceUpdate||op.scrollTop!=null||op.scrollToPos&&(op.scrollToPos.from.line<display.viewFrom||op.scrollToPos.to.line>=display.viewTo)||display.maxLineChanged&&cm.options.lineWrapping -op.update=op.mustUpdate&&new DisplayUpdate(cm,op.mustUpdate&&{top:op.scrollTop,ensure:op.scrollToPos},op.forceUpdate)} -function endOperation_W1(op){op.updatedDisplay=op.mustUpdate&&updateDisplayIfNeeded(op.cm,op.update)} -function endOperation_R2(op){var cm=op.cm,display=cm.display -if(op.updatedDisplay){updateHeightsInViewport(cm)} -op.barMeasure=measureForScrollbars(cm) -if(display.maxLineChanged&&!cm.options.lineWrapping){op.adjustWidthTo=measureChar(cm,display.maxLine,display.maxLine.text.length).left+3 -cm.display.sizerWidth=op.adjustWidthTo -op.barMeasure.scrollWidth=Math.max(display.scroller.clientWidth,display.sizer.offsetLeft+op.adjustWidthTo+scrollGap(cm)+cm.display.barWidth) -op.maxScrollLeft=Math.max(0,display.sizer.offsetLeft+op.adjustWidthTo-displayWidth(cm))} -if(op.updatedDisplay||op.selectionChanged) -{op.preparedSelection=display.input.prepareSelection(op.focus)}} -function endOperation_W2(op){var cm=op.cm -if(op.adjustWidthTo!=null){cm.display.sizer.style.minWidth=op.adjustWidthTo+"px" -if(op.maxScrollLeft<cm.doc.scrollLeft) -{setScrollLeft(cm,Math.min(cm.display.scroller.scrollLeft,op.maxScrollLeft),true)} -cm.display.maxLineChanged=false} -var takeFocus=op.focus&&op.focus==activeElt()&&(!document.hasFocus||document.hasFocus()) -if(op.preparedSelection) -{cm.display.input.showSelection(op.preparedSelection,takeFocus)} -if(op.updatedDisplay||op.startHeight!=cm.doc.height) -{updateScrollbars(cm,op.barMeasure)} -if(op.updatedDisplay) -{setDocumentHeight(cm,op.barMeasure)} -if(op.selectionChanged){restartBlink(cm)} -if(cm.state.focused&&op.updateInput) -{cm.display.input.reset(op.typing)} -if(takeFocus){ensureFocus(op.cm)}} -function endOperation_finish(op){var cm=op.cm,display=cm.display,doc=cm.doc -if(op.updatedDisplay){postUpdateDisplay(cm,op.update)} -if(display.wheelStartX!=null&&(op.scrollTop!=null||op.scrollLeft!=null||op.scrollToPos)) -{display.wheelStartX=display.wheelStartY=null} -if(op.scrollTop!=null&&(display.scroller.scrollTop!=op.scrollTop||op.forceScroll)){doc.scrollTop=Math.max(0,Math.min(display.scroller.scrollHeight-display.scroller.clientHeight,op.scrollTop)) -display.scrollbars.setScrollTop(doc.scrollTop) -display.scroller.scrollTop=doc.scrollTop} -if(op.scrollLeft!=null&&(display.scroller.scrollLeft!=op.scrollLeft||op.forceScroll)){doc.scrollLeft=Math.max(0,Math.min(display.scroller.scrollWidth-display.scroller.clientWidth,op.scrollLeft)) -display.scrollbars.setScrollLeft(doc.scrollLeft) -display.scroller.scrollLeft=doc.scrollLeft -alignHorizontally(cm)} -if(op.scrollToPos){var rect=scrollPosIntoView(cm,clipPos(doc,op.scrollToPos.from),clipPos(doc,op.scrollToPos.to),op.scrollToPos.margin) -maybeScrollWindow(cm,rect)} -var hidden=op.maybeHiddenMarkers,unhidden=op.maybeUnhiddenMarkers -if(hidden){for(var i=0;i<hidden.length;++i) -{if(!hidden[i].lines.length){signal(hidden[i],"hide")}}} -if(unhidden){for(var i$1=0;i$1<unhidden.length;++i$1) -{if(unhidden[i$1].lines.length){signal(unhidden[i$1],"unhide")}}} -if(display.wrapper.offsetHeight) -{doc.scrollTop=cm.display.scroller.scrollTop} -if(op.changeObjs) -{signal(cm,"changes",cm,op.changeObjs)} -if(op.update) -{op.update.finish()}} -function runInOp(cm,f){if(cm.curOp){return f()} -startOperation(cm) -try{return f()} -finally{endOperation(cm)}} -function operation(cm,f){return function(){if(cm.curOp){return f.apply(cm,arguments)} -startOperation(cm) -try{return f.apply(cm,arguments)} -finally{endOperation(cm)}}} -function methodOp(f){return function(){if(this.curOp){return f.apply(this,arguments)} -startOperation(this) -try{return f.apply(this,arguments)} -finally{endOperation(this)}}} -function docMethodOp(f){return function(){var cm=this.cm -if(!cm||cm.curOp){return f.apply(this,arguments)} -startOperation(cm) -try{return f.apply(this,arguments)} -finally{endOperation(cm)}}} -function regChange(cm,from,to,lendiff){if(from==null){from=cm.doc.first} -if(to==null){to=cm.doc.first+cm.doc.size} -if(!lendiff){lendiff=0} -var display=cm.display -if(lendiff&&to<display.viewTo&&(display.updateLineNumbers==null||display.updateLineNumbers>from)) -{display.updateLineNumbers=from} -cm.curOp.viewChanged=true -if(from>=display.viewTo){if(sawCollapsedSpans&&visualLineNo(cm.doc,from)<display.viewTo) -{resetView(cm)}}else if(to<=display.viewFrom){if(sawCollapsedSpans&&visualLineEndNo(cm.doc,to+lendiff)>display.viewFrom){resetView(cm)}else{display.viewFrom+=lendiff -display.viewTo+=lendiff}}else if(from<=display.viewFrom&&to>=display.viewTo){resetView(cm)}else if(from<=display.viewFrom){var cut=viewCuttingPoint(cm,to,to+lendiff,1) -if(cut){display.view=display.view.slice(cut.index) -display.viewFrom=cut.lineN -display.viewTo+=lendiff}else{resetView(cm)}}else if(to>=display.viewTo){var cut$1=viewCuttingPoint(cm,from,from,-1) -if(cut$1){display.view=display.view.slice(0,cut$1.index) -display.viewTo=cut$1.lineN}else{resetView(cm)}}else{var cutTop=viewCuttingPoint(cm,from,from,-1) -var cutBot=viewCuttingPoint(cm,to,to+lendiff,1) -if(cutTop&&cutBot){display.view=display.view.slice(0,cutTop.index).concat(buildViewArray(cm,cutTop.lineN,cutBot.lineN)).concat(display.view.slice(cutBot.index)) -display.viewTo+=lendiff}else{resetView(cm)}} -var ext=display.externalMeasured -if(ext){if(to<ext.lineN) -{ext.lineN+=lendiff} -else if(from<ext.lineN+ext.size) -{display.externalMeasured=null}}} -function regLineChange(cm,line,type){cm.curOp.viewChanged=true -var display=cm.display,ext=cm.display.externalMeasured -if(ext&&line>=ext.lineN&&line<ext.lineN+ext.size) -{display.externalMeasured=null} -if(line<display.viewFrom||line>=display.viewTo){return} -var lineView=display.view[findViewIndex(cm,line)] -if(lineView.node==null){return} -var arr=lineView.changes||(lineView.changes=[]) -if(indexOf(arr,type)==-1){arr.push(type)}} -function resetView(cm){cm.display.viewFrom=cm.display.viewTo=cm.doc.first -cm.display.view=[] -cm.display.viewOffset=0} -function viewCuttingPoint(cm,oldN,newN,dir){var index=findViewIndex(cm,oldN),diff,view=cm.display.view -if(!sawCollapsedSpans||newN==cm.doc.first+cm.doc.size) -{return{index:index,lineN:newN}} -var n=cm.display.viewFrom -for(var i=0;i<index;i++) -{n+=view[i].size} -if(n!=oldN){if(dir>0){if(index==view.length-1){return null} -diff=(n+view[index].size)-oldN -index++}else{diff=n-oldN} -oldN+=diff;newN+=diff} -while(visualLineNo(cm.doc,newN)!=newN){if(index==(dir<0?0:view.length-1)){return null} -newN+=dir*view[index-(dir<0?1:0)].size -index+=dir} -return{index:index,lineN:newN}} -function adjustView(cm,from,to){var display=cm.display,view=display.view -if(view.length==0||from>=display.viewTo||to<=display.viewFrom){display.view=buildViewArray(cm,from,to) -display.viewFrom=from}else{if(display.viewFrom>from) -{display.view=buildViewArray(cm,from,display.viewFrom).concat(display.view)} -else if(display.viewFrom<from) -{display.view=display.view.slice(findViewIndex(cm,from))} -display.viewFrom=from -if(display.viewTo<to) -{display.view=display.view.concat(buildViewArray(cm,display.viewTo,to))} -else if(display.viewTo>to) -{display.view=display.view.slice(0,findViewIndex(cm,to))}} -display.viewTo=to} -function countDirtyView(cm){var view=cm.display.view,dirty=0 -for(var i=0;i<view.length;i++){var lineView=view[i] -if(!lineView.hidden&&(!lineView.node||lineView.changes)){++dirty}} -return dirty} -function startWorker(cm,time){if(cm.doc.mode.startState&&cm.doc.frontier<cm.display.viewTo) -{cm.state.highlight.set(time,bind(highlightWorker,cm))}} -function highlightWorker(cm){var doc=cm.doc -if(doc.frontier<doc.first){doc.frontier=doc.first} -if(doc.frontier>=cm.display.viewTo){return} -var end=+new Date+cm.options.workTime -var state=copyState(doc.mode,getStateBefore(cm,doc.frontier)) -var changedLines=[] -doc.iter(doc.frontier,Math.min(doc.first+doc.size,cm.display.viewTo+500),function(line){if(doc.frontier>=cm.display.viewFrom){var oldStyles=line.styles,tooLong=line.text.length>cm.options.maxHighlightLength -var highlighted=highlightLine(cm,line,tooLong?copyState(doc.mode,state):state,true) -line.styles=highlighted.styles -var oldCls=line.styleClasses,newCls=highlighted.classes -if(newCls){line.styleClasses=newCls} -else if(oldCls){line.styleClasses=null} -var ischange=!oldStyles||oldStyles.length!=line.styles.length||oldCls!=newCls&&(!oldCls||!newCls||oldCls.bgClass!=newCls.bgClass||oldCls.textClass!=newCls.textClass) -for(var i=0;!ischange&&i<oldStyles.length;++i){ischange=oldStyles[i]!=line.styles[i]} -if(ischange){changedLines.push(doc.frontier)} -line.stateAfter=tooLong?state:copyState(doc.mode,state)}else{if(line.text.length<=cm.options.maxHighlightLength) -{processLine(cm,line.text,state)} -line.stateAfter=doc.frontier%5==0?copyState(doc.mode,state):null} -++doc.frontier -if(+new Date>end){startWorker(cm,cm.options.workDelay) -return true}}) -if(changedLines.length){runInOp(cm,function(){for(var i=0;i<changedLines.length;i++) -{regLineChange(cm,changedLines[i],"text")}})}} -var DisplayUpdate=function DisplayUpdate(cm,viewport,force){var display=cm.display -this.viewport=viewport -this.visible=visibleLines(display,cm.doc,viewport) -this.editorIsHidden=!display.wrapper.offsetWidth -this.wrapperHeight=display.wrapper.clientHeight -this.wrapperWidth=display.wrapper.clientWidth -this.oldDisplayWidth=displayWidth(cm) -this.force=force -this.dims=getDimensions(cm) -this.events=[]};DisplayUpdate.prototype.signal=function signal$1(emitter,type){if(hasHandler(emitter,type)) -{this.events.push(arguments)}};DisplayUpdate.prototype.finish=function finish(){var this$1=this;for(var i=0;i<this.events.length;i++) -{signal.apply(null,this$1.events[i])}};function maybeClipScrollbars(cm){var display=cm.display -if(!display.scrollbarsClipped&&display.scroller.offsetWidth){display.nativeBarWidth=display.scroller.offsetWidth-display.scroller.clientWidth -display.heightForcer.style.height=scrollGap(cm)+"px" -display.sizer.style.marginBottom=-display.nativeBarWidth+"px" -display.sizer.style.borderRightWidth=scrollGap(cm)+"px" -display.scrollbarsClipped=true}} -function updateDisplayIfNeeded(cm,update){var display=cm.display,doc=cm.doc -if(update.editorIsHidden){resetView(cm) -return false} -if(!update.force&&update.visible.from>=display.viewFrom&&update.visible.to<=display.viewTo&&(display.updateLineNumbers==null||display.updateLineNumbers>=display.viewTo)&&display.renderedView==display.view&&countDirtyView(cm)==0) -{return false} -if(maybeUpdateLineNumberWidth(cm)){resetView(cm) -update.dims=getDimensions(cm)} -var end=doc.first+doc.size -var from=Math.max(update.visible.from-cm.options.viewportMargin,doc.first) -var to=Math.min(end,update.visible.to+cm.options.viewportMargin) -if(display.viewFrom<from&&from-display.viewFrom<20){from=Math.max(doc.first,display.viewFrom)} -if(display.viewTo>to&&display.viewTo-to<20){to=Math.min(end,display.viewTo)} -if(sawCollapsedSpans){from=visualLineNo(cm.doc,from) -to=visualLineEndNo(cm.doc,to)} -var different=from!=display.viewFrom||to!=display.viewTo||display.lastWrapHeight!=update.wrapperHeight||display.lastWrapWidth!=update.wrapperWidth -adjustView(cm,from,to) -display.viewOffset=heightAtLine(getLine(cm.doc,display.viewFrom)) -cm.display.mover.style.top=display.viewOffset+"px" -var toUpdate=countDirtyView(cm) -if(!different&&toUpdate==0&&!update.force&&display.renderedView==display.view&&(display.updateLineNumbers==null||display.updateLineNumbers>=display.viewTo)) -{return false} -var focused=activeElt() -if(toUpdate>4){display.lineDiv.style.display="none"} -patchDisplay(cm,display.updateLineNumbers,update.dims) -if(toUpdate>4){display.lineDiv.style.display=""} -display.renderedView=display.view -if(focused&&activeElt()!=focused&&focused.offsetHeight){focused.focus()} -removeChildren(display.cursorDiv) -removeChildren(display.selectionDiv) -display.gutters.style.height=display.sizer.style.minHeight=0 -if(different){display.lastWrapHeight=update.wrapperHeight -display.lastWrapWidth=update.wrapperWidth -startWorker(cm,400)} -display.updateLineNumbers=null -return true} -function postUpdateDisplay(cm,update){var viewport=update.viewport -for(var first=true;;first=false){if(!first||!cm.options.lineWrapping||update.oldDisplayWidth==displayWidth(cm)){if(viewport&&viewport.top!=null) -{viewport={top:Math.min(cm.doc.height+paddingVert(cm.display)-displayHeight(cm),viewport.top)}} -update.visible=visibleLines(cm.display,cm.doc,viewport) -if(update.visible.from>=cm.display.viewFrom&&update.visible.to<=cm.display.viewTo) -{break}} -if(!updateDisplayIfNeeded(cm,update)){break} -updateHeightsInViewport(cm) -var barMeasure=measureForScrollbars(cm) -updateSelection(cm) -updateScrollbars(cm,barMeasure) -setDocumentHeight(cm,barMeasure)} -update.signal(cm,"update",cm) -if(cm.display.viewFrom!=cm.display.reportedViewFrom||cm.display.viewTo!=cm.display.reportedViewTo){update.signal(cm,"viewportChange",cm,cm.display.viewFrom,cm.display.viewTo) -cm.display.reportedViewFrom=cm.display.viewFrom;cm.display.reportedViewTo=cm.display.viewTo}} -function updateDisplaySimple(cm,viewport){var update=new DisplayUpdate(cm,viewport) -if(updateDisplayIfNeeded(cm,update)){updateHeightsInViewport(cm) -postUpdateDisplay(cm,update) -var barMeasure=measureForScrollbars(cm) -updateSelection(cm) -updateScrollbars(cm,barMeasure) -setDocumentHeight(cm,barMeasure) -update.finish()}} -function patchDisplay(cm,updateNumbersFrom,dims){var display=cm.display,lineNumbers=cm.options.lineNumbers -var container=display.lineDiv,cur=container.firstChild -function rm(node){var next=node.nextSibling -if(webkit&&mac&&cm.display.currentWheelTarget==node) -{node.style.display="none"} -else -{node.parentNode.removeChild(node)} -return next} -var view=display.view,lineN=display.viewFrom -for(var i=0;i<view.length;i++){var lineView=view[i] -if(lineView.hidden){}else if(!lineView.node||lineView.node.parentNode!=container){var node=buildLineElement(cm,lineView,lineN,dims) -container.insertBefore(node,cur)}else{while(cur!=lineView.node){cur=rm(cur)} -var updateNumber=lineNumbers&&updateNumbersFrom!=null&&updateNumbersFrom<=lineN&&lineView.lineNumber -if(lineView.changes){if(indexOf(lineView.changes,"gutter")>-1){updateNumber=false} -updateLineForChanges(cm,lineView,lineN,dims)} -if(updateNumber){removeChildren(lineView.lineNumber) -lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options,lineN)))} -cur=lineView.node.nextSibling} -lineN+=lineView.size} -while(cur){cur=rm(cur)}} -function updateGutterSpace(cm){var width=cm.display.gutters.offsetWidth -cm.display.sizer.style.marginLeft=width+"px"} -function setDocumentHeight(cm,measure){cm.display.sizer.style.minHeight=measure.docHeight+"px" -cm.display.heightForcer.style.top=measure.docHeight+"px" -cm.display.gutters.style.height=(measure.docHeight+cm.display.barHeight+scrollGap(cm))+"px"} -function updateGutters(cm){var gutters=cm.display.gutters,specs=cm.options.gutters -removeChildren(gutters) -var i=0 -for(;i<specs.length;++i){var gutterClass=specs[i] -var gElt=gutters.appendChild(elt("div",null,"CodeMirror-gutter "+gutterClass)) -if(gutterClass=="CodeMirror-linenumbers"){cm.display.lineGutter=gElt -gElt.style.width=(cm.display.lineNumWidth||1)+"px"}} -gutters.style.display=i?"":"none" -updateGutterSpace(cm)} -function setGuttersForLineNumbers(options){var found=indexOf(options.gutters,"CodeMirror-linenumbers") -if(found==-1&&options.lineNumbers){options.gutters=options.gutters.concat(["CodeMirror-linenumbers"])}else if(found>-1&&!options.lineNumbers){options.gutters=options.gutters.slice(0) -options.gutters.splice(found,1)}} -var Selection=function Selection(ranges,primIndex){this.ranges=ranges -this.primIndex=primIndex};Selection.prototype.primary=function primary(){return this.ranges[this.primIndex]};Selection.prototype.equals=function equals(other){var this$1=this;if(other==this){return true} -if(other.primIndex!=this.primIndex||other.ranges.length!=this.ranges.length){return false} -for(var i=0;i<this.ranges.length;i++){var here=this$1.ranges[i],there=other.ranges[i] -if(!equalCursorPos(here.anchor,there.anchor)||!equalCursorPos(here.head,there.head)){return false}} -return true};Selection.prototype.deepCopy=function deepCopy(){var this$1=this;var out=[] -for(var i=0;i<this.ranges.length;i++) -{out[i]=new Range(copyPos(this$1.ranges[i].anchor),copyPos(this$1.ranges[i].head))} -return new Selection(out,this.primIndex)};Selection.prototype.somethingSelected=function somethingSelected(){var this$1=this;for(var i=0;i<this.ranges.length;i++) -{if(!this$1.ranges[i].empty()){return true}} -return false};Selection.prototype.contains=function contains(pos,end){var this$1=this;if(!end){end=pos} -for(var i=0;i<this.ranges.length;i++){var range=this$1.ranges[i] -if(cmp(end,range.from())>=0&&cmp(pos,range.to())<=0) -{return i}} -return-1};var Range=function Range(anchor,head){this.anchor=anchor;this.head=head};Range.prototype.from=function from(){return minPos(this.anchor,this.head)};Range.prototype.to=function to(){return maxPos(this.anchor,this.head)};Range.prototype.empty=function empty(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch};function normalizeSelection(ranges,primIndex){var prim=ranges[primIndex] -ranges.sort(function(a,b){return cmp(a.from(),b.from());}) -primIndex=indexOf(ranges,prim) -for(var i=1;i<ranges.length;i++){var cur=ranges[i],prev=ranges[i-1] -if(cmp(prev.to(),cur.from())>=0){var from=minPos(prev.from(),cur.from()),to=maxPos(prev.to(),cur.to()) -var inv=prev.empty()?cur.from()==cur.head:prev.from()==prev.head -if(i<=primIndex){--primIndex} -ranges.splice(--i,2,new Range(inv?to:from,inv?from:to))}} -return new Selection(ranges,primIndex)} -function simpleSelection(anchor,head){return new Selection([new Range(anchor,head||anchor)],0)} -function changeEnd(change){if(!change.text){return change.to} -return Pos(change.from.line+change.text.length-1,lst(change.text).length+(change.text.length==1?change.from.ch:0))} -function adjustForChange(pos,change){if(cmp(pos,change.from)<0){return pos} -if(cmp(pos,change.to)<=0){return changeEnd(change)} -var line=pos.line+change.text.length-(change.to.line-change.from.line)-1,ch=pos.ch -if(pos.line==change.to.line){ch+=changeEnd(change).ch-change.to.ch} -return Pos(line,ch)} -function computeSelAfterChange(doc,change){var out=[] -for(var i=0;i<doc.sel.ranges.length;i++){var range=doc.sel.ranges[i] -out.push(new Range(adjustForChange(range.anchor,change),adjustForChange(range.head,change)))} -return normalizeSelection(out,doc.sel.primIndex)} -function offsetPos(pos,old,nw){if(pos.line==old.line) -{return Pos(nw.line,pos.ch-old.ch+nw.ch)} -else -{return Pos(nw.line+(pos.line-old.line),pos.ch)}} -function computeReplacedSel(doc,changes,hint){var out=[] -var oldPrev=Pos(doc.first,0),newPrev=oldPrev -for(var i=0;i<changes.length;i++){var change=changes[i] -var from=offsetPos(change.from,oldPrev,newPrev) -var to=offsetPos(changeEnd(change),oldPrev,newPrev) -oldPrev=change.to -newPrev=to -if(hint=="around"){var range=doc.sel.ranges[i],inv=cmp(range.head,range.anchor)<0 -out[i]=new Range(inv?to:from,inv?from:to)}else{out[i]=new Range(from,from)}} -return new Selection(out,doc.sel.primIndex)} -function loadMode(cm){cm.doc.mode=getMode(cm.options,cm.doc.modeOption) -resetModeState(cm)} -function resetModeState(cm){cm.doc.iter(function(line){if(line.stateAfter){line.stateAfter=null} -if(line.styles){line.styles=null}}) -cm.doc.frontier=cm.doc.first -startWorker(cm,100) -cm.state.modeGen++ -if(cm.curOp){regChange(cm)}} -function isWholeLineUpdate(doc,change){return change.from.ch==0&&change.to.ch==0&&lst(change.text)==""&&(!doc.cm||doc.cm.options.wholeLineUpdateBefore)} -function updateDoc(doc,change,markedSpans,estimateHeight){function spansFor(n){return markedSpans?markedSpans[n]:null} -function update(line,text,spans){updateLine(line,text,spans,estimateHeight) -signalLater(line,"change",line,change)} -function linesFor(start,end){var result=[] -for(var i=start;i<end;++i) -{result.push(new Line(text[i],spansFor(i),estimateHeight))} -return result} -var from=change.from,to=change.to,text=change.text -var firstLine=getLine(doc,from.line),lastLine=getLine(doc,to.line) -var lastText=lst(text),lastSpans=spansFor(text.length-1),nlines=to.line-from.line -if(change.full){doc.insert(0,linesFor(0,text.length)) -doc.remove(text.length,doc.size-text.length)}else if(isWholeLineUpdate(doc,change)){var added=linesFor(0,text.length-1) -update(lastLine,lastLine.text,lastSpans) -if(nlines){doc.remove(from.line,nlines)} -if(added.length){doc.insert(from.line,added)}}else if(firstLine==lastLine){if(text.length==1){update(firstLine,firstLine.text.slice(0,from.ch)+lastText+firstLine.text.slice(to.ch),lastSpans)}else{var added$1=linesFor(1,text.length-1) -added$1.push(new Line(lastText+firstLine.text.slice(to.ch),lastSpans,estimateHeight)) -update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0)) -doc.insert(from.line+1,added$1)}}else if(text.length==1){update(firstLine,firstLine.text.slice(0,from.ch)+text[0]+lastLine.text.slice(to.ch),spansFor(0)) -doc.remove(from.line+1,nlines)}else{update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0)) -update(lastLine,lastText+lastLine.text.slice(to.ch),lastSpans) -var added$2=linesFor(1,text.length-1) -if(nlines>1){doc.remove(from.line+1,nlines-1)} -doc.insert(from.line+1,added$2)} -signalLater(doc,"change",doc,change)} -function linkedDocs(doc,f,sharedHistOnly){function propagate(doc,skip,sharedHist){if(doc.linked){for(var i=0;i<doc.linked.length;++i){var rel=doc.linked[i] -if(rel.doc==skip){continue} -var shared=sharedHist&&rel.sharedHist -if(sharedHistOnly&&!shared){continue} -f(rel.doc,shared) -propagate(rel.doc,doc,shared)}}} -propagate(doc,null,true)} -function attachDoc(cm,doc){if(doc.cm){throw new Error("This document is already in use.")} -cm.doc=doc -doc.cm=cm -estimateLineHeights(cm) -loadMode(cm) -setDirectionClass(cm) -if(!cm.options.lineWrapping){findMaxLine(cm)} -cm.options.mode=doc.modeOption -regChange(cm)} -function setDirectionClass(cm){;(cm.doc.direction=="rtl"?addClass:rmClass)(cm.display.lineDiv,"CodeMirror-rtl")} -function directionChanged(cm){runInOp(cm,function(){setDirectionClass(cm) -regChange(cm)})} -function History(startGen){this.done=[];this.undone=[] -this.undoDepth=Infinity -this.lastModTime=this.lastSelTime=0 -this.lastOp=this.lastSelOp=null -this.lastOrigin=this.lastSelOrigin=null -this.generation=this.maxGeneration=startGen||1} -function historyChangeFromChange(doc,change){var histChange={from:copyPos(change.from),to:changeEnd(change),text:getBetween(doc,change.from,change.to)} -attachLocalSpans(doc,histChange,change.from.line,change.to.line+1) -linkedDocs(doc,function(doc){return attachLocalSpans(doc,histChange,change.from.line,change.to.line+1);},true) -return histChange} -function clearSelectionEvents(array){while(array.length){var last=lst(array) -if(last.ranges){array.pop()} -else{break}}} -function lastChangeEvent(hist,force){if(force){clearSelectionEvents(hist.done) -return lst(hist.done)}else if(hist.done.length&&!lst(hist.done).ranges){return lst(hist.done)}else if(hist.done.length>1&&!hist.done[hist.done.length-2].ranges){hist.done.pop() -return lst(hist.done)}} -function addChangeToHistory(doc,change,selAfter,opId){var hist=doc.history -hist.undone.length=0 -var time=+new Date,cur -var last -if((hist.lastOp==opId||hist.lastOrigin==change.origin&&change.origin&&((change.origin.charAt(0)=="+"&&doc.cm&&hist.lastModTime>time-doc.cm.options.historyEventDelay)||change.origin.charAt(0)=="*"))&&(cur=lastChangeEvent(hist,hist.lastOp==opId))){last=lst(cur.changes) -if(cmp(change.from,change.to)==0&&cmp(change.from,last.to)==0){last.to=changeEnd(change)}else{cur.changes.push(historyChangeFromChange(doc,change))}}else{var before=lst(hist.done) -if(!before||!before.ranges) -{pushSelectionToHistory(doc.sel,hist.done)} -cur={changes:[historyChangeFromChange(doc,change)],generation:hist.generation} -hist.done.push(cur) -while(hist.done.length>hist.undoDepth){hist.done.shift() -if(!hist.done[0].ranges){hist.done.shift()}}} -hist.done.push(selAfter) -hist.generation=++hist.maxGeneration -hist.lastModTime=hist.lastSelTime=time -hist.lastOp=hist.lastSelOp=opId -hist.lastOrigin=hist.lastSelOrigin=change.origin -if(!last){signal(doc,"historyAdded")}} -function selectionEventCanBeMerged(doc,origin,prev,sel){var ch=origin.charAt(0) -return ch=="*"||ch=="+"&&prev.ranges.length==sel.ranges.length&&prev.somethingSelected()==sel.somethingSelected()&&new Date-doc.history.lastSelTime<=(doc.cm?doc.cm.options.historyEventDelay:500)} -function addSelectionToHistory(doc,sel,opId,options){var hist=doc.history,origin=options&&options.origin -if(opId==hist.lastSelOp||(origin&&hist.lastSelOrigin==origin&&(hist.lastModTime==hist.lastSelTime&&hist.lastOrigin==origin||selectionEventCanBeMerged(doc,origin,lst(hist.done),sel)))) -{hist.done[hist.done.length-1]=sel} -else -{pushSelectionToHistory(sel,hist.done)} -hist.lastSelTime=+new Date -hist.lastSelOrigin=origin -hist.lastSelOp=opId -if(options&&options.clearRedo!==false) -{clearSelectionEvents(hist.undone)}} -function pushSelectionToHistory(sel,dest){var top=lst(dest) -if(!(top&&top.ranges&&top.equals(sel))) -{dest.push(sel)}} -function attachLocalSpans(doc,change,from,to){var existing=change["spans_"+doc.id],n=0 -doc.iter(Math.max(doc.first,from),Math.min(doc.first+doc.size,to),function(line){if(line.markedSpans) -{(existing||(existing=change["spans_"+doc.id]={}))[n]=line.markedSpans} -++n})} -function removeClearedSpans(spans){if(!spans){return null} -var out -for(var i=0;i<spans.length;++i){if(spans[i].marker.explicitlyCleared){if(!out){out=spans.slice(0,i)}} -else if(out){out.push(spans[i])}} -return!out?spans:out.length?out:null} -function getOldSpans(doc,change){var found=change["spans_"+doc.id] -if(!found){return null} -var nw=[] -for(var i=0;i<change.text.length;++i) -{nw.push(removeClearedSpans(found[i]))} -return nw} -function mergeOldSpans(doc,change){var old=getOldSpans(doc,change) -var stretched=stretchSpansOverChange(doc,change) -if(!old){return stretched} -if(!stretched){return old} -for(var i=0;i<old.length;++i){var oldCur=old[i],stretchCur=stretched[i] -if(oldCur&&stretchCur){spans:for(var j=0;j<stretchCur.length;++j){var span=stretchCur[j] -for(var k=0;k<oldCur.length;++k) -{if(oldCur[k].marker==span.marker){continue spans}} -oldCur.push(span)}}else if(stretchCur){old[i]=stretchCur}} -return old} -function copyHistoryArray(events,newGroup,instantiateSel){var copy=[] -for(var i=0;i<events.length;++i){var event=events[i] -if(event.ranges){copy.push(instantiateSel?Selection.prototype.deepCopy.call(event):event) -continue} -var changes=event.changes,newChanges=[] -copy.push({changes:newChanges}) -for(var j=0;j<changes.length;++j){var change=changes[j],m=(void 0) -newChanges.push({from:change.from,to:change.to,text:change.text}) -if(newGroup){for(var prop in change){if(m=prop.match(/^spans_(\d+)$/)){if(indexOf(newGroup,Number(m[1]))>-1){lst(newChanges)[prop]=change[prop] -delete change[prop]}}}}}} -return copy} -function extendRange(doc,range,head,other){if(doc.cm&&doc.cm.display.shift||doc.extend){var anchor=range.anchor -if(other){var posBefore=cmp(head,anchor)<0 -if(posBefore!=(cmp(other,anchor)<0)){anchor=head -head=other}else if(posBefore!=(cmp(head,other)<0)){head=other}} -return new Range(anchor,head)}else{return new Range(other||head,head)}} -function extendSelection(doc,head,other,options){setSelection(doc,new Selection([extendRange(doc,doc.sel.primary(),head,other)],0),options)} -function extendSelections(doc,heads,options){var out=[] -for(var i=0;i<doc.sel.ranges.length;i++) -{out[i]=extendRange(doc,doc.sel.ranges[i],heads[i],null)} -var newSel=normalizeSelection(out,doc.sel.primIndex) -setSelection(doc,newSel,options)} -function replaceOneSelection(doc,i,range,options){var ranges=doc.sel.ranges.slice(0) -ranges[i]=range -setSelection(doc,normalizeSelection(ranges,doc.sel.primIndex),options)} -function setSimpleSelection(doc,anchor,head,options){setSelection(doc,simpleSelection(anchor,head),options)} -function filterSelectionChange(doc,sel,options){var obj={ranges:sel.ranges,update:function(ranges){var this$1=this;this.ranges=[] -for(var i=0;i<ranges.length;i++) -{this$1.ranges[i]=new Range(clipPos(doc,ranges[i].anchor),clipPos(doc,ranges[i].head))}},origin:options&&options.origin} -signal(doc,"beforeSelectionChange",doc,obj) -if(doc.cm){signal(doc.cm,"beforeSelectionChange",doc.cm,obj)} -if(obj.ranges!=sel.ranges){return normalizeSelection(obj.ranges,obj.ranges.length-1)} -else{return sel}} -function setSelectionReplaceHistory(doc,sel,options){var done=doc.history.done,last=lst(done) -if(last&&last.ranges){done[done.length-1]=sel -setSelectionNoUndo(doc,sel,options)}else{setSelection(doc,sel,options)}} -function setSelection(doc,sel,options){setSelectionNoUndo(doc,sel,options) -addSelectionToHistory(doc,doc.sel,doc.cm?doc.cm.curOp.id:NaN,options)} -function setSelectionNoUndo(doc,sel,options){if(hasHandler(doc,"beforeSelectionChange")||doc.cm&&hasHandler(doc.cm,"beforeSelectionChange")) -{sel=filterSelectionChange(doc,sel,options)} -var bias=options&&options.bias||(cmp(sel.primary().head,doc.sel.primary().head)<0?-1:1) -setSelectionInner(doc,skipAtomicInSelection(doc,sel,bias,true)) -if(!(options&&options.scroll===false)&&doc.cm) -{ensureCursorVisible(doc.cm)}} -function setSelectionInner(doc,sel){if(sel.equals(doc.sel)){return} -doc.sel=sel -if(doc.cm){doc.cm.curOp.updateInput=doc.cm.curOp.selectionChanged=true -signalCursorActivity(doc.cm)} -signalLater(doc,"cursorActivity",doc)} -function reCheckSelection(doc){setSelectionInner(doc,skipAtomicInSelection(doc,doc.sel,null,false),sel_dontScroll)} -function skipAtomicInSelection(doc,sel,bias,mayClear){var out -for(var i=0;i<sel.ranges.length;i++){var range=sel.ranges[i] -var old=sel.ranges.length==doc.sel.ranges.length&&doc.sel.ranges[i] -var newAnchor=skipAtomic(doc,range.anchor,old&&old.anchor,bias,mayClear) -var newHead=skipAtomic(doc,range.head,old&&old.head,bias,mayClear) -if(out||newAnchor!=range.anchor||newHead!=range.head){if(!out){out=sel.ranges.slice(0,i)} -out[i]=new Range(newAnchor,newHead)}} -return out?normalizeSelection(out,sel.primIndex):sel} -function skipAtomicInner(doc,pos,oldPos,dir,mayClear){var line=getLine(doc,pos.line) -if(line.markedSpans){for(var i=0;i<line.markedSpans.length;++i){var sp=line.markedSpans[i],m=sp.marker -if((sp.from==null||(m.inclusiveLeft?sp.from<=pos.ch:sp.from<pos.ch))&&(sp.to==null||(m.inclusiveRight?sp.to>=pos.ch:sp.to>pos.ch))){if(mayClear){signal(m,"beforeCursorEnter") -if(m.explicitlyCleared){if(!line.markedSpans){break} -else{--i;continue}}} -if(!m.atomic){continue} -if(oldPos){var near=m.find(dir<0?1:-1),diff=(void 0) -if(dir<0?m.inclusiveRight:m.inclusiveLeft) -{near=movePos(doc,near,-dir,near&&near.line==pos.line?line:null)} -if(near&&near.line==pos.line&&(diff=cmp(near,oldPos))&&(dir<0?diff<0:diff>0)) -{return skipAtomicInner(doc,near,pos,dir,mayClear)}} -var far=m.find(dir<0?-1:1) -if(dir<0?m.inclusiveLeft:m.inclusiveRight) -{far=movePos(doc,far,dir,far.line==pos.line?line:null)} -return far?skipAtomicInner(doc,far,pos,dir,mayClear):null}}} -return pos} -function skipAtomic(doc,pos,oldPos,bias,mayClear){var dir=bias||1 -var found=skipAtomicInner(doc,pos,oldPos,dir,mayClear)||(!mayClear&&skipAtomicInner(doc,pos,oldPos,dir,true))||skipAtomicInner(doc,pos,oldPos,-dir,mayClear)||(!mayClear&&skipAtomicInner(doc,pos,oldPos,-dir,true)) -if(!found){doc.cantEdit=true -return Pos(doc.first,0)} -return found} -function movePos(doc,pos,dir,line){if(dir<0&&pos.ch==0){if(pos.line>doc.first){return clipPos(doc,Pos(pos.line-1))} -else{return null}}else if(dir>0&&pos.ch==(line||getLine(doc,pos.line)).text.length){if(pos.line<doc.first+doc.size-1){return Pos(pos.line+1,0)} -else{return null}}else{return new Pos(pos.line,pos.ch+dir)}} -function selectAll(cm){cm.setSelection(Pos(cm.firstLine(),0),Pos(cm.lastLine()),sel_dontScroll)} -function filterChange(doc,change,update){var obj={canceled:false,from:change.from,to:change.to,text:change.text,origin:change.origin,cancel:function(){return obj.canceled=true;}} -if(update){obj.update=function(from,to,text,origin){if(from){obj.from=clipPos(doc,from)} -if(to){obj.to=clipPos(doc,to)} -if(text){obj.text=text} -if(origin!==undefined){obj.origin=origin}}} -signal(doc,"beforeChange",doc,obj) -if(doc.cm){signal(doc.cm,"beforeChange",doc.cm,obj)} -if(obj.canceled){return null} -return{from:obj.from,to:obj.to,text:obj.text,origin:obj.origin}} -function makeChange(doc,change,ignoreReadOnly){if(doc.cm){if(!doc.cm.curOp){return operation(doc.cm,makeChange)(doc,change,ignoreReadOnly)} -if(doc.cm.state.suppressEdits){return}} -if(hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange")){change=filterChange(doc,change,true) -if(!change){return}} -var split=sawReadOnlySpans&&!ignoreReadOnly&&removeReadOnlyRanges(doc,change.from,change.to) -if(split){for(var i=split.length-1;i>=0;--i) -{makeChangeInner(doc,{from:split[i].from,to:split[i].to,text:i?[""]:change.text})}}else{makeChangeInner(doc,change)}} -function makeChangeInner(doc,change){if(change.text.length==1&&change.text[0]==""&&cmp(change.from,change.to)==0){return} -var selAfter=computeSelAfterChange(doc,change) -addChangeToHistory(doc,change,selAfter,doc.cm?doc.cm.curOp.id:NaN) -makeChangeSingleDoc(doc,change,selAfter,stretchSpansOverChange(doc,change)) -var rebased=[] -linkedDocs(doc,function(doc,sharedHist){if(!sharedHist&&indexOf(rebased,doc.history)==-1){rebaseHist(doc.history,change) -rebased.push(doc.history)} -makeChangeSingleDoc(doc,change,null,stretchSpansOverChange(doc,change))})} -function makeChangeFromHistory(doc,type,allowSelectionOnly){if(doc.cm&&doc.cm.state.suppressEdits&&!allowSelectionOnly){return} -var hist=doc.history,event,selAfter=doc.sel -var source=type=="undo"?hist.done:hist.undone,dest=type=="undo"?hist.undone:hist.done -var i=0 -for(;i<source.length;i++){event=source[i] -if(allowSelectionOnly?event.ranges&&!event.equals(doc.sel):!event.ranges) -{break}} -if(i==source.length){return} -hist.lastOrigin=hist.lastSelOrigin=null -for(;;){event=source.pop() -if(event.ranges){pushSelectionToHistory(event,dest) -if(allowSelectionOnly&&!event.equals(doc.sel)){setSelection(doc,event,{clearRedo:false}) -return} -selAfter=event} -else{break}} -var antiChanges=[] -pushSelectionToHistory(selAfter,dest) -dest.push({changes:antiChanges,generation:hist.generation}) -hist.generation=event.generation||++hist.maxGeneration -var filter=hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange") -var loop=function(i){var change=event.changes[i] -change.origin=type -if(filter&&!filterChange(doc,change,false)){source.length=0 -return{}} -antiChanges.push(historyChangeFromChange(doc,change)) -var after=i?computeSelAfterChange(doc,change):lst(source) -makeChangeSingleDoc(doc,change,after,mergeOldSpans(doc,change)) -if(!i&&doc.cm){doc.cm.scrollIntoView({from:change.from,to:changeEnd(change)})} -var rebased=[] -linkedDocs(doc,function(doc,sharedHist){if(!sharedHist&&indexOf(rebased,doc.history)==-1){rebaseHist(doc.history,change) -rebased.push(doc.history)} -makeChangeSingleDoc(doc,change,null,mergeOldSpans(doc,change))})};for(var i$1=event.changes.length-1;i$1>=0;--i$1){var returned=loop(i$1);if(returned)return returned.v;}} -function shiftDoc(doc,distance){if(distance==0){return} -doc.first+=distance -doc.sel=new Selection(map(doc.sel.ranges,function(range){return new Range(Pos(range.anchor.line+distance,range.anchor.ch),Pos(range.head.line+distance,range.head.ch));}),doc.sel.primIndex) -if(doc.cm){regChange(doc.cm,doc.first,doc.first-distance,distance) -for(var d=doc.cm.display,l=d.viewFrom;l<d.viewTo;l++) -{regLineChange(doc.cm,l,"gutter")}}} -function makeChangeSingleDoc(doc,change,selAfter,spans){if(doc.cm&&!doc.cm.curOp) -{return operation(doc.cm,makeChangeSingleDoc)(doc,change,selAfter,spans)} -if(change.to.line<doc.first){shiftDoc(doc,change.text.length-1-(change.to.line-change.from.line)) -return} -if(change.from.line>doc.lastLine()){return} -if(change.from.line<doc.first){var shift=change.text.length-1-(doc.first-change.from.line) -shiftDoc(doc,shift) -change={from:Pos(doc.first,0),to:Pos(change.to.line+shift,change.to.ch),text:[lst(change.text)],origin:change.origin}} -var last=doc.lastLine() -if(change.to.line>last){change={from:change.from,to:Pos(last,getLine(doc,last).text.length),text:[change.text[0]],origin:change.origin}} -change.removed=getBetween(doc,change.from,change.to) -if(!selAfter){selAfter=computeSelAfterChange(doc,change)} -if(doc.cm){makeChangeSingleDocInEditor(doc.cm,change,spans)} -else{updateDoc(doc,change,spans)} -setSelectionNoUndo(doc,selAfter,sel_dontScroll)} -function makeChangeSingleDocInEditor(cm,change,spans){var doc=cm.doc,display=cm.display,from=change.from,to=change.to -var recomputeMaxLength=false,checkWidthStart=from.line -if(!cm.options.lineWrapping){checkWidthStart=lineNo(visualLine(getLine(doc,from.line))) -doc.iter(checkWidthStart,to.line+1,function(line){if(line==display.maxLine){recomputeMaxLength=true -return true}})} -if(doc.sel.contains(change.from,change.to)>-1) -{signalCursorActivity(cm)} -updateDoc(doc,change,spans,estimateHeight(cm)) -if(!cm.options.lineWrapping){doc.iter(checkWidthStart,from.line+change.text.length,function(line){var len=lineLength(line) -if(len>display.maxLineLength){display.maxLine=line -display.maxLineLength=len -display.maxLineChanged=true -recomputeMaxLength=false}}) -if(recomputeMaxLength){cm.curOp.updateMaxLine=true}} -doc.frontier=Math.min(doc.frontier,from.line) -startWorker(cm,400) -var lendiff=change.text.length-(to.line-from.line)-1 -if(change.full) -{regChange(cm)} -else if(from.line==to.line&&change.text.length==1&&!isWholeLineUpdate(cm.doc,change)) -{regLineChange(cm,from.line,"text")} -else -{regChange(cm,from.line,to.line+1,lendiff)} -var changesHandler=hasHandler(cm,"changes"),changeHandler=hasHandler(cm,"change") -if(changeHandler||changesHandler){var obj={from:from,to:to,text:change.text,removed:change.removed,origin:change.origin} -if(changeHandler){signalLater(cm,"change",cm,obj)} -if(changesHandler){(cm.curOp.changeObjs||(cm.curOp.changeObjs=[])).push(obj)}} -cm.display.selForContextMenu=null} -function replaceRange(doc,code,from,to,origin){if(!to){to=from} -if(cmp(to,from)<0){var tmp=to;to=from;from=tmp} -if(typeof code=="string"){code=doc.splitLines(code)} -makeChange(doc,{from:from,to:to,text:code,origin:origin})} -function rebaseHistSelSingle(pos,from,to,diff){if(to<pos.line){pos.line+=diff}else if(from<pos.line){pos.line=from -pos.ch=0}} -function rebaseHistArray(array,from,to,diff){for(var i=0;i<array.length;++i){var sub=array[i],ok=true -if(sub.ranges){if(!sub.copied){sub=array[i]=sub.deepCopy();sub.copied=true} -for(var j=0;j<sub.ranges.length;j++){rebaseHistSelSingle(sub.ranges[j].anchor,from,to,diff) -rebaseHistSelSingle(sub.ranges[j].head,from,to,diff)} -continue} -for(var j$1=0;j$1<sub.changes.length;++j$1){var cur=sub.changes[j$1] -if(to<cur.from.line){cur.from=Pos(cur.from.line+diff,cur.from.ch) -cur.to=Pos(cur.to.line+diff,cur.to.ch)}else if(from<=cur.to.line){ok=false -break}} -if(!ok){array.splice(0,i+1) -i=0}}} -function rebaseHist(hist,change){var from=change.from.line,to=change.to.line,diff=change.text.length-(to-from)-1 -rebaseHistArray(hist.done,from,to,diff) -rebaseHistArray(hist.undone,from,to,diff)} -function changeLine(doc,handle,changeType,op){var no=handle,line=handle -if(typeof handle=="number"){line=getLine(doc,clipLine(doc,handle))} -else{no=lineNo(handle)} -if(no==null){return null} -if(op(line,no)&&doc.cm){regLineChange(doc.cm,no,changeType)} -return line} -var LeafChunk=function LeafChunk(lines){var this$1=this;this.lines=lines -this.parent=null -var height=0 -for(var i=0;i<lines.length;++i){lines[i].parent=this$1 -height+=lines[i].height} -this.height=height};LeafChunk.prototype.chunkSize=function chunkSize(){return this.lines.length};LeafChunk.prototype.removeInner=function removeInner(at,n){var this$1=this;for(var i=at,e=at+n;i<e;++i){var line=this$1.lines[i] -this$1.height-=line.height -cleanUpLine(line) -signalLater(line,"delete")} -this.lines.splice(at,n)};LeafChunk.prototype.collapse=function collapse(lines){lines.push.apply(lines,this.lines)};LeafChunk.prototype.insertInner=function insertInner(at,lines,height){var this$1=this;this.height+=height -this.lines=this.lines.slice(0,at).concat(lines).concat(this.lines.slice(at)) -for(var i=0;i<lines.length;++i){lines[i].parent=this$1}};LeafChunk.prototype.iterN=function iterN(at,n,op){var this$1=this;for(var e=at+n;at<e;++at) -{if(op(this$1.lines[at])){return true}}};var BranchChunk=function BranchChunk(children){var this$1=this;this.children=children -var size=0,height=0 -for(var i=0;i<children.length;++i){var ch=children[i] -size+=ch.chunkSize();height+=ch.height -ch.parent=this$1} -this.size=size -this.height=height -this.parent=null};BranchChunk.prototype.chunkSize=function chunkSize(){return this.size};BranchChunk.prototype.removeInner=function removeInner(at,n){var this$1=this;this.size-=n -for(var i=0;i<this.children.length;++i){var child=this$1.children[i],sz=child.chunkSize() -if(at<sz){var rm=Math.min(n,sz-at),oldHeight=child.height -child.removeInner(at,rm) -this$1.height-=oldHeight-child.height -if(sz==rm){this$1.children.splice(i--,1);child.parent=null} -if((n-=rm)==0){break} -at=0}else{at-=sz}} -if(this.size-n<25&&(this.children.length>1||!(this.children[0]instanceof LeafChunk))){var lines=[] -this.collapse(lines) -this.children=[new LeafChunk(lines)] -this.children[0].parent=this}};BranchChunk.prototype.collapse=function collapse(lines){var this$1=this;for(var i=0;i<this.children.length;++i){this$1.children[i].collapse(lines)}};BranchChunk.prototype.insertInner=function insertInner(at,lines,height){var this$1=this;this.size+=lines.length -this.height+=height -for(var i=0;i<this.children.length;++i){var child=this$1.children[i],sz=child.chunkSize() -if(at<=sz){child.insertInner(at,lines,height) -if(child.lines&&child.lines.length>50){var remaining=child.lines.length%25+25 -for(var pos=remaining;pos<child.lines.length;){var leaf=new LeafChunk(child.lines.slice(pos,pos+=25)) -child.height-=leaf.height -this$1.children.splice(++i,0,leaf) -leaf.parent=this$1} -child.lines=child.lines.slice(0,remaining) -this$1.maybeSpill()} -break} -at-=sz}};BranchChunk.prototype.maybeSpill=function maybeSpill(){if(this.children.length<=10){return} -var me=this -do{var spilled=me.children.splice(me.children.length-5,5) -var sibling=new BranchChunk(spilled) -if(!me.parent){var copy=new BranchChunk(me.children) -copy.parent=me -me.children=[copy,sibling] -me=copy}else{me.size-=sibling.size -me.height-=sibling.height -var myIndex=indexOf(me.parent.children,me) -me.parent.children.splice(myIndex+1,0,sibling)} -sibling.parent=me.parent}while(me.children.length>10) -me.parent.maybeSpill()};BranchChunk.prototype.iterN=function iterN(at,n,op){var this$1=this;for(var i=0;i<this.children.length;++i){var child=this$1.children[i],sz=child.chunkSize() -if(at<sz){var used=Math.min(n,sz-at) -if(child.iterN(at,used,op)){return true} -if((n-=used)==0){break} -at=0}else{at-=sz}}};var LineWidget=function LineWidget(doc,node,options){var this$1=this;if(options){for(var opt in options){if(options.hasOwnProperty(opt)) -{this$1[opt]=options[opt]}}} -this.doc=doc -this.node=node};LineWidget.prototype.clear=function clear(){var this$1=this;var cm=this.doc.cm,ws=this.line.widgets,line=this.line,no=lineNo(line) -if(no==null||!ws){return} -for(var i=0;i<ws.length;++i){if(ws[i]==this$1){ws.splice(i--,1)}} -if(!ws.length){line.widgets=null} -var height=widgetHeight(this) -updateLineHeight(line,Math.max(0,line.height-height)) -if(cm){runInOp(cm,function(){adjustScrollWhenAboveVisible(cm,line,-height) -regLineChange(cm,no,"widget")}) -signalLater(cm,"lineWidgetCleared",cm,this,no)}};LineWidget.prototype.changed=function changed(){var this$1=this;var oldH=this.height,cm=this.doc.cm,line=this.line -this.height=null -var diff=widgetHeight(this)-oldH -if(!diff){return} -updateLineHeight(line,line.height+diff) -if(cm){runInOp(cm,function(){cm.curOp.forceUpdate=true -adjustScrollWhenAboveVisible(cm,line,diff) -signalLater(cm,"lineWidgetChanged",cm,this$1,lineNo(line))})}};eventMixin(LineWidget) -function adjustScrollWhenAboveVisible(cm,line,diff){if(heightAtLine(line)<((cm.curOp&&cm.curOp.scrollTop)||cm.doc.scrollTop)) -{addToScrollPos(cm,null,diff)}} -function addLineWidget(doc,handle,node,options){var widget=new LineWidget(doc,node,options) -var cm=doc.cm -if(cm&&widget.noHScroll){cm.display.alignWidgets=true} -changeLine(doc,handle,"widget",function(line){var widgets=line.widgets||(line.widgets=[]) -if(widget.insertAt==null){widgets.push(widget)} -else{widgets.splice(Math.min(widgets.length-1,Math.max(0,widget.insertAt)),0,widget)} -widget.line=line -if(cm&&!lineIsHidden(doc,line)){var aboveVisible=heightAtLine(line)<doc.scrollTop -updateLineHeight(line,line.height+widgetHeight(widget)) -if(aboveVisible){addToScrollPos(cm,null,widget.height)} -cm.curOp.forceUpdate=true} -return true}) -signalLater(cm,"lineWidgetAdded",cm,widget,typeof handle=="number"?handle:lineNo(handle)) -return widget} -var nextMarkerId=0 -var TextMarker=function TextMarker(doc,type){this.lines=[] -this.type=type -this.doc=doc -this.id=++nextMarkerId};TextMarker.prototype.clear=function clear(){var this$1=this;if(this.explicitlyCleared){return} -var cm=this.doc.cm,withOp=cm&&!cm.curOp -if(withOp){startOperation(cm)} -if(hasHandler(this,"clear")){var found=this.find() -if(found){signalLater(this,"clear",found.from,found.to)}} -var min=null,max=null -for(var i=0;i<this.lines.length;++i){var line=this$1.lines[i] -var span=getMarkedSpanFor(line.markedSpans,this$1) -if(cm&&!this$1.collapsed){regLineChange(cm,lineNo(line),"text")} -else if(cm){if(span.to!=null){max=lineNo(line)} -if(span.from!=null){min=lineNo(line)}} -line.markedSpans=removeMarkedSpan(line.markedSpans,span) -if(span.from==null&&this$1.collapsed&&!lineIsHidden(this$1.doc,line)&&cm) -{updateLineHeight(line,textHeight(cm.display))}} -if(cm&&this.collapsed&&!cm.options.lineWrapping){for(var i$1=0;i$1<this.lines.length;++i$1){var visual=visualLine(this$1.lines[i$1]),len=lineLength(visual) -if(len>cm.display.maxLineLength){cm.display.maxLine=visual -cm.display.maxLineLength=len -cm.display.maxLineChanged=true}}} -if(min!=null&&cm&&this.collapsed){regChange(cm,min,max+1)} -this.lines.length=0 -this.explicitlyCleared=true -if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=false -if(cm){reCheckSelection(cm.doc)}} -if(cm){signalLater(cm,"markerCleared",cm,this,min,max)} -if(withOp){endOperation(cm)} -if(this.parent){this.parent.clear()}};TextMarker.prototype.find=function find(side,lineObj){var this$1=this;if(side==null&&this.type=="bookmark"){side=1} -var from,to -for(var i=0;i<this.lines.length;++i){var line=this$1.lines[i] -var span=getMarkedSpanFor(line.markedSpans,this$1) -if(span.from!=null){from=Pos(lineObj?line:lineNo(line),span.from) -if(side==-1){return from}} -if(span.to!=null){to=Pos(lineObj?line:lineNo(line),span.to) -if(side==1){return to}}} -return from&&{from:from,to:to}};TextMarker.prototype.changed=function changed(){var this$1=this;var pos=this.find(-1,true),widget=this,cm=this.doc.cm -if(!pos||!cm){return} -runInOp(cm,function(){var line=pos.line,lineN=lineNo(pos.line) -var view=findViewForLine(cm,lineN) -if(view){clearLineMeasurementCacheFor(view) -cm.curOp.selectionChanged=cm.curOp.forceUpdate=true} -cm.curOp.updateMaxLine=true -if(!lineIsHidden(widget.doc,line)&&widget.height!=null){var oldHeight=widget.height -widget.height=null -var dHeight=widgetHeight(widget)-oldHeight -if(dHeight) -{updateLineHeight(line,line.height+dHeight)}} -signalLater(cm,"markerChanged",cm,this$1)})};TextMarker.prototype.attachLine=function attachLine(line){if(!this.lines.length&&this.doc.cm){var op=this.doc.cm.curOp -if(!op.maybeHiddenMarkers||indexOf(op.maybeHiddenMarkers,this)==-1) -{(op.maybeUnhiddenMarkers||(op.maybeUnhiddenMarkers=[])).push(this)}} -this.lines.push(line)};TextMarker.prototype.detachLine=function detachLine(line){this.lines.splice(indexOf(this.lines,line),1) -if(!this.lines.length&&this.doc.cm){var op=this.doc.cm.curOp;(op.maybeHiddenMarkers||(op.maybeHiddenMarkers=[])).push(this)}};eventMixin(TextMarker) -function markText(doc,from,to,options,type){if(options&&options.shared){return markTextShared(doc,from,to,options,type)} -if(doc.cm&&!doc.cm.curOp){return operation(doc.cm,markText)(doc,from,to,options,type)} -var marker=new TextMarker(doc,type),diff=cmp(from,to) -if(options){copyObj(options,marker,false)} -if(diff>0||diff==0&&marker.clearWhenEmpty!==false) -{return marker} -if(marker.replacedWith){marker.collapsed=true -marker.widgetNode=eltP("span",[marker.replacedWith],"CodeMirror-widget") -if(!options.handleMouseEvents){marker.widgetNode.setAttribute("cm-ignore-events","true")} -if(options.insertLeft){marker.widgetNode.insertLeft=true}} -if(marker.collapsed){if(conflictingCollapsedRange(doc,from.line,from,to,marker)||from.line!=to.line&&conflictingCollapsedRange(doc,to.line,from,to,marker)) -{throw new Error("Inserting collapsed marker partially overlapping an existing one")} -seeCollapsedSpans()} -if(marker.addToHistory) -{addChangeToHistory(doc,{from:from,to:to,origin:"markText"},doc.sel,NaN)} -var curLine=from.line,cm=doc.cm,updateMaxLine -doc.iter(curLine,to.line+1,function(line){if(cm&&marker.collapsed&&!cm.options.lineWrapping&&visualLine(line)==cm.display.maxLine) -{updateMaxLine=true} -if(marker.collapsed&&curLine!=from.line){updateLineHeight(line,0)} -addMarkedSpan(line,new MarkedSpan(marker,curLine==from.line?from.ch:null,curLine==to.line?to.ch:null)) -++curLine}) -if(marker.collapsed){doc.iter(from.line,to.line+1,function(line){if(lineIsHidden(doc,line)){updateLineHeight(line,0)}})} -if(marker.clearOnEnter){on(marker,"beforeCursorEnter",function(){return marker.clear();})} -if(marker.readOnly){seeReadOnlySpans() -if(doc.history.done.length||doc.history.undone.length) -{doc.clearHistory()}} -if(marker.collapsed){marker.id=++nextMarkerId -marker.atomic=true} -if(cm){if(updateMaxLine){cm.curOp.updateMaxLine=true} -if(marker.collapsed) -{regChange(cm,from.line,to.line+1)} -else if(marker.className||marker.title||marker.startStyle||marker.endStyle||marker.css) -{for(var i=from.line;i<=to.line;i++){regLineChange(cm,i,"text")}} -if(marker.atomic){reCheckSelection(cm.doc)} -signalLater(cm,"markerAdded",cm,marker)} -return marker} -var SharedTextMarker=function SharedTextMarker(markers,primary){var this$1=this;this.markers=markers -this.primary=primary -for(var i=0;i<markers.length;++i) -{markers[i].parent=this$1}};SharedTextMarker.prototype.clear=function clear(){var this$1=this;if(this.explicitlyCleared){return} -this.explicitlyCleared=true -for(var i=0;i<this.markers.length;++i) -{this$1.markers[i].clear()} -signalLater(this,"clear")};SharedTextMarker.prototype.find=function find(side,lineObj){return this.primary.find(side,lineObj)};eventMixin(SharedTextMarker) -function markTextShared(doc,from,to,options,type){options=copyObj(options) -options.shared=false -var markers=[markText(doc,from,to,options,type)],primary=markers[0] -var widget=options.widgetNode -linkedDocs(doc,function(doc){if(widget){options.widgetNode=widget.cloneNode(true)} -markers.push(markText(doc,clipPos(doc,from),clipPos(doc,to),options,type)) -for(var i=0;i<doc.linked.length;++i) -{if(doc.linked[i].isParent){return}} -primary=lst(markers)}) -return new SharedTextMarker(markers,primary)} -function findSharedMarkers(doc){return doc.findMarks(Pos(doc.first,0),doc.clipPos(Pos(doc.lastLine())),function(m){return m.parent;})} -function copySharedMarkers(doc,markers){for(var i=0;i<markers.length;i++){var marker=markers[i],pos=marker.find() -var mFrom=doc.clipPos(pos.from),mTo=doc.clipPos(pos.to) -if(cmp(mFrom,mTo)){var subMark=markText(doc,mFrom,mTo,marker.primary,marker.primary.type) -marker.markers.push(subMark) -subMark.parent=marker}}} -function detachSharedMarkers(markers){var loop=function(i){var marker=markers[i],linked=[marker.primary.doc] -linkedDocs(marker.primary.doc,function(d){return linked.push(d);}) -for(var j=0;j<marker.markers.length;j++){var subMarker=marker.markers[j] -if(indexOf(linked,subMarker.doc)==-1){subMarker.parent=null -marker.markers.splice(j--,1)}}};for(var i=0;i<markers.length;i++)loop(i);} -var nextDocId=0 -var Doc=function(text,mode,firstLine,lineSep,direction){if(!(this instanceof Doc)){return new Doc(text,mode,firstLine,lineSep,direction)} -if(firstLine==null){firstLine=0} -BranchChunk.call(this,[new LeafChunk([new Line("",null)])]) -this.first=firstLine -this.scrollTop=this.scrollLeft=0 -this.cantEdit=false -this.cleanGeneration=1 -this.frontier=firstLine -var start=Pos(firstLine,0) -this.sel=simpleSelection(start) -this.history=new History(null) -this.id=++nextDocId -this.modeOption=mode -this.lineSep=lineSep -this.direction=(direction=="rtl")?"rtl":"ltr" -this.extend=false -if(typeof text=="string"){text=this.splitLines(text)} -updateDoc(this,{from:start,to:start,text:text}) -setSelection(this,simpleSelection(start),sel_dontScroll)} -Doc.prototype=createObj(BranchChunk.prototype,{constructor:Doc,iter:function(from,to,op){if(op){this.iterN(from-this.first,to-from,op)} -else{this.iterN(this.first,this.first+this.size,from)}},insert:function(at,lines){var height=0 -for(var i=0;i<lines.length;++i){height+=lines[i].height} -this.insertInner(at-this.first,lines,height)},remove:function(at,n){this.removeInner(at-this.first,n)},getValue:function(lineSep){var lines=getLines(this,this.first,this.first+this.size) -if(lineSep===false){return lines} -return lines.join(lineSep||this.lineSeparator())},setValue:docMethodOp(function(code){var top=Pos(this.first,0),last=this.first+this.size-1 -makeChange(this,{from:top,to:Pos(last,getLine(this,last).text.length),text:this.splitLines(code),origin:"setValue",full:true},true) -setSelection(this,simpleSelection(top))}),replaceRange:function(code,from,to,origin){from=clipPos(this,from) -to=to?clipPos(this,to):from -replaceRange(this,code,from,to,origin)},getRange:function(from,to,lineSep){var lines=getBetween(this,clipPos(this,from),clipPos(this,to)) -if(lineSep===false){return lines} -return lines.join(lineSep||this.lineSeparator())},getLine:function(line){var l=this.getLineHandle(line);return l&&l.text},getLineHandle:function(line){if(isLine(this,line)){return getLine(this,line)}},getLineNumber:function(line){return lineNo(line)},getLineHandleVisualStart:function(line){if(typeof line=="number"){line=getLine(this,line)} -return visualLine(line)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(pos){return clipPos(this,pos)},getCursor:function(start){var range=this.sel.primary(),pos -if(start==null||start=="head"){pos=range.head} -else if(start=="anchor"){pos=range.anchor} -else if(start=="end"||start=="to"||start===false){pos=range.to()} -else{pos=range.from()} -return pos},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:docMethodOp(function(line,ch,options){setSimpleSelection(this,clipPos(this,typeof line=="number"?Pos(line,ch||0):line),null,options)}),setSelection:docMethodOp(function(anchor,head,options){setSimpleSelection(this,clipPos(this,anchor),clipPos(this,head||anchor),options)}),extendSelection:docMethodOp(function(head,other,options){extendSelection(this,clipPos(this,head),other&&clipPos(this,other),options)}),extendSelections:docMethodOp(function(heads,options){extendSelections(this,clipPosArray(this,heads),options)}),extendSelectionsBy:docMethodOp(function(f,options){var heads=map(this.sel.ranges,f) -extendSelections(this,clipPosArray(this,heads),options)}),setSelections:docMethodOp(function(ranges,primary,options){var this$1=this;if(!ranges.length){return} -var out=[] -for(var i=0;i<ranges.length;i++) -{out[i]=new Range(clipPos(this$1,ranges[i].anchor),clipPos(this$1,ranges[i].head))} -if(primary==null){primary=Math.min(ranges.length-1,this.sel.primIndex)} -setSelection(this,normalizeSelection(out,primary),options)}),addSelection:docMethodOp(function(anchor,head,options){var ranges=this.sel.ranges.slice(0) -ranges.push(new Range(clipPos(this,anchor),clipPos(this,head||anchor))) -setSelection(this,normalizeSelection(ranges,ranges.length-1),options)}),getSelection:function(lineSep){var this$1=this;var ranges=this.sel.ranges,lines -for(var i=0;i<ranges.length;i++){var sel=getBetween(this$1,ranges[i].from(),ranges[i].to()) -lines=lines?lines.concat(sel):sel} -if(lineSep===false){return lines} -else{return lines.join(lineSep||this.lineSeparator())}},getSelections:function(lineSep){var this$1=this;var parts=[],ranges=this.sel.ranges -for(var i=0;i<ranges.length;i++){var sel=getBetween(this$1,ranges[i].from(),ranges[i].to()) -if(lineSep!==false){sel=sel.join(lineSep||this$1.lineSeparator())} -parts[i]=sel} -return parts},replaceSelection:function(code,collapse,origin){var dup=[] -for(var i=0;i<this.sel.ranges.length;i++) -{dup[i]=code} -this.replaceSelections(dup,collapse,origin||"+input")},replaceSelections:docMethodOp(function(code,collapse,origin){var this$1=this;var changes=[],sel=this.sel -for(var i=0;i<sel.ranges.length;i++){var range=sel.ranges[i] -changes[i]={from:range.from(),to:range.to(),text:this$1.splitLines(code[i]),origin:origin}} -var newSel=collapse&&collapse!="end"&&computeReplacedSel(this,changes,collapse) -for(var i$1=changes.length-1;i$1>=0;i$1--) -{makeChange(this$1,changes[i$1])} -if(newSel){setSelectionReplaceHistory(this,newSel)} -else if(this.cm){ensureCursorVisible(this.cm)}}),undo:docMethodOp(function(){makeChangeFromHistory(this,"undo")}),redo:docMethodOp(function(){makeChangeFromHistory(this,"redo")}),undoSelection:docMethodOp(function(){makeChangeFromHistory(this,"undo",true)}),redoSelection:docMethodOp(function(){makeChangeFromHistory(this,"redo",true)}),setExtending:function(val){this.extend=val},getExtending:function(){return this.extend},historySize:function(){var hist=this.history,done=0,undone=0 -for(var i=0;i<hist.done.length;i++){if(!hist.done[i].ranges){++done}} -for(var i$1=0;i$1<hist.undone.length;i$1++){if(!hist.undone[i$1].ranges){++undone}} -return{undo:done,redo:undone}},clearHistory:function(){this.history=new History(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(true)},changeGeneration:function(forceSplit){if(forceSplit) -{this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null} -return this.history.generation},isClean:function(gen){return this.history.generation==(gen||this.cleanGeneration)},getHistory:function(){return{done:copyHistoryArray(this.history.done),undone:copyHistoryArray(this.history.undone)}},setHistory:function(histData){var hist=this.history=new History(this.history.maxGeneration) -hist.done=copyHistoryArray(histData.done.slice(0),null,true) -hist.undone=copyHistoryArray(histData.undone.slice(0),null,true)},setGutterMarker:docMethodOp(function(line,gutterID,value){return changeLine(this,line,"gutter",function(line){var markers=line.gutterMarkers||(line.gutterMarkers={}) -markers[gutterID]=value -if(!value&&isEmpty(markers)){line.gutterMarkers=null} -return true})}),clearGutter:docMethodOp(function(gutterID){var this$1=this;this.iter(function(line){if(line.gutterMarkers&&line.gutterMarkers[gutterID]){changeLine(this$1,line,"gutter",function(){line.gutterMarkers[gutterID]=null -if(isEmpty(line.gutterMarkers)){line.gutterMarkers=null} -return true})}})}),lineInfo:function(line){var n -if(typeof line=="number"){if(!isLine(this,line)){return null} -n=line -line=getLine(this,line) -if(!line){return null}}else{n=lineNo(line) -if(n==null){return null}} -return{line:n,handle:line,text:line.text,gutterMarkers:line.gutterMarkers,textClass:line.textClass,bgClass:line.bgClass,wrapClass:line.wrapClass,widgets:line.widgets}},addLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,where=="gutter"?"gutter":"class",function(line){var prop=where=="text"?"textClass":where=="background"?"bgClass":where=="gutter"?"gutterClass":"wrapClass" -if(!line[prop]){line[prop]=cls} -else if(classTest(cls).test(line[prop])){return false} -else{line[prop]+=" "+cls} -return true})}),removeLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,where=="gutter"?"gutter":"class",function(line){var prop=where=="text"?"textClass":where=="background"?"bgClass":where=="gutter"?"gutterClass":"wrapClass" -var cur=line[prop] -if(!cur){return false} -else if(cls==null){line[prop]=null} -else{var found=cur.match(classTest(cls)) -if(!found){return false} -var end=found.index+found[0].length -line[prop]=cur.slice(0,found.index)+(!found.index||end==cur.length?"":" ")+cur.slice(end)||null} -return true})}),addLineWidget:docMethodOp(function(handle,node,options){return addLineWidget(this,handle,node,options)}),removeLineWidget:function(widget){widget.clear()},markText:function(from,to,options){return markText(this,clipPos(this,from),clipPos(this,to),options,options&&options.type||"range")},setBookmark:function(pos,options){var realOpts={replacedWith:options&&(options.nodeType==null?options.widget:options),insertLeft:options&&options.insertLeft,clearWhenEmpty:false,shared:options&&options.shared,handleMouseEvents:options&&options.handleMouseEvents} -pos=clipPos(this,pos) -return markText(this,pos,pos,realOpts,"bookmark")},findMarksAt:function(pos){pos=clipPos(this,pos) -var markers=[],spans=getLine(this,pos.line).markedSpans -if(spans){for(var i=0;i<spans.length;++i){var span=spans[i] -if((span.from==null||span.from<=pos.ch)&&(span.to==null||span.to>=pos.ch)) -{markers.push(span.marker.parent||span.marker)}}} -return markers},findMarks:function(from,to,filter){from=clipPos(this,from);to=clipPos(this,to) -var found=[],lineNo=from.line -this.iter(from.line,to.line+1,function(line){var spans=line.markedSpans -if(spans){for(var i=0;i<spans.length;i++){var span=spans[i] -if(!(span.to!=null&&lineNo==from.line&&from.ch>=span.to||span.from==null&&lineNo!=from.line||span.from!=null&&lineNo==to.line&&span.from>=to.ch)&&(!filter||filter(span.marker))) -{found.push(span.marker.parent||span.marker)}}} -++lineNo}) -return found},getAllMarks:function(){var markers=[] -this.iter(function(line){var sps=line.markedSpans -if(sps){for(var i=0;i<sps.length;++i) -{if(sps[i].from!=null){markers.push(sps[i].marker)}}}}) -return markers},posFromIndex:function(off){var ch,lineNo=this.first,sepSize=this.lineSeparator().length -this.iter(function(line){var sz=line.text.length+sepSize -if(sz>off){ch=off;return true} -off-=sz -++lineNo}) -return clipPos(this,Pos(lineNo,ch))},indexFromPos:function(coords){coords=clipPos(this,coords) -var index=coords.ch -if(coords.line<this.first||coords.ch<0){return 0} -var sepSize=this.lineSeparator().length -this.iter(this.first,coords.line,function(line){index+=line.text.length+sepSize}) -return index},copy:function(copyHistory){var doc=new Doc(getLines(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction) -doc.scrollTop=this.scrollTop;doc.scrollLeft=this.scrollLeft -doc.sel=this.sel -doc.extend=false -if(copyHistory){doc.history.undoDepth=this.history.undoDepth -doc.setHistory(this.getHistory())} -return doc},linkedDoc:function(options){if(!options){options={}} -var from=this.first,to=this.first+this.size -if(options.from!=null&&options.from>from){from=options.from} -if(options.to!=null&&options.to<to){to=options.to} -var copy=new Doc(getLines(this,from,to),options.mode||this.modeOption,from,this.lineSep,this.direction) -if(options.sharedHist){copy.history=this.history;}(this.linked||(this.linked=[])).push({doc:copy,sharedHist:options.sharedHist}) -copy.linked=[{doc:this,isParent:true,sharedHist:options.sharedHist}] -copySharedMarkers(copy,findSharedMarkers(this)) -return copy},unlinkDoc:function(other){var this$1=this;if(other instanceof CodeMirror){other=other.doc} -if(this.linked){for(var i=0;i<this.linked.length;++i){var link=this$1.linked[i] -if(link.doc!=other){continue} -this$1.linked.splice(i,1) -other.unlinkDoc(this$1) -detachSharedMarkers(findSharedMarkers(this$1)) -break}} -if(other.history==this.history){var splitIds=[other.id] -linkedDocs(other,function(doc){return splitIds.push(doc.id);},true) -other.history=new History(null) -other.history.done=copyHistoryArray(this.history.done,splitIds) -other.history.undone=copyHistoryArray(this.history.undone,splitIds)}},iterLinkedDocs:function(f){linkedDocs(this,f)},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(str){if(this.lineSep){return str.split(this.lineSep)} -return splitLinesAuto(str)},lineSeparator:function(){return this.lineSep||"\n"},setDirection:docMethodOp(function(dir){if(dir!="rtl"){dir="ltr"} -if(dir==this.direction){return} -this.direction=dir -this.iter(function(line){return line.order=null;}) -if(this.cm){directionChanged(this.cm)}})}) -Doc.prototype.eachLine=Doc.prototype.iter -var lastDrop=0 -function onDrop(e){var cm=this -clearDragCursor(cm) -if(signalDOMEvent(cm,e)||eventInWidget(cm.display,e)) -{return} -e_preventDefault(e) -if(ie){lastDrop=+new Date} -var pos=posFromMouse(cm,e,true),files=e.dataTransfer.files -if(!pos||cm.isReadOnly()){return} -if(files&&files.length&&window.FileReader&&window.File){var n=files.length,text=Array(n),read=0 -var loadFile=function(file,i){if(cm.options.allowDropFileTypes&&indexOf(cm.options.allowDropFileTypes,file.type)==-1) -{return} -var reader=new FileReader -reader.onload=operation(cm,function(){var content=reader.result -if(/[\x00-\x08\x0e-\x1f]{2}/.test(content)){content=""} -text[i]=content -if(++read==n){pos=clipPos(cm.doc,pos) -var change={from:pos,to:pos,text:cm.doc.splitLines(text.join(cm.doc.lineSeparator())),origin:"paste"} -makeChange(cm.doc,change) -setSelectionReplaceHistory(cm.doc,simpleSelection(pos,changeEnd(change)))}}) -reader.readAsText(file)} -for(var i=0;i<n;++i){loadFile(files[i],i)}}else{if(cm.state.draggingText&&cm.doc.sel.contains(pos)>-1){cm.state.draggingText(e) -setTimeout(function(){return cm.display.input.focus();},20) -return} -try{var text$1=e.dataTransfer.getData("Text") -if(text$1){var selected -if(cm.state.draggingText&&!cm.state.draggingText.copy) -{selected=cm.listSelections()} -setSelectionNoUndo(cm.doc,simpleSelection(pos,pos)) -if(selected){for(var i$1=0;i$1<selected.length;++i$1) -{replaceRange(cm.doc,"",selected[i$1].anchor,selected[i$1].head,"drag")}} -cm.replaceSelection(text$1,"around","paste") -cm.display.input.focus()}} -catch(e){}}} -function onDragStart(cm,e){if(ie&&(!cm.state.draggingText||+new Date-lastDrop<100)){e_stop(e);return} -if(signalDOMEvent(cm,e)||eventInWidget(cm.display,e)){return} -e.dataTransfer.setData("Text",cm.getSelection()) -e.dataTransfer.effectAllowed="copyMove" -if(e.dataTransfer.setDragImage&&!safari){var img=elt("img",null,null,"position: fixed; left: 0; top: 0;") -img.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" -if(presto){img.width=img.height=1 -cm.display.wrapper.appendChild(img) -img._top=img.offsetTop} -e.dataTransfer.setDragImage(img,0,0) -if(presto){img.parentNode.removeChild(img)}}} -function onDragOver(cm,e){var pos=posFromMouse(cm,e) -if(!pos){return} -var frag=document.createDocumentFragment() -drawSelectionCursor(cm,pos,frag) -if(!cm.display.dragCursor){cm.display.dragCursor=elt("div",null,"CodeMirror-cursors CodeMirror-dragcursors") -cm.display.lineSpace.insertBefore(cm.display.dragCursor,cm.display.cursorDiv)} -removeChildrenAndAdd(cm.display.dragCursor,frag)} -function clearDragCursor(cm){if(cm.display.dragCursor){cm.display.lineSpace.removeChild(cm.display.dragCursor) -cm.display.dragCursor=null}} -function forEachCodeMirror(f){if(!document.body.getElementsByClassName){return} -var byClass=document.body.getElementsByClassName("CodeMirror") -for(var i=0;i<byClass.length;i++){var cm=byClass[i].CodeMirror -if(cm){f(cm)}}} -var globalsRegistered=false -function ensureGlobalHandlers(){if(globalsRegistered){return} -registerGlobalHandlers() -globalsRegistered=true} -function registerGlobalHandlers(){var resizeTimer -on(window,"resize",function(){if(resizeTimer==null){resizeTimer=setTimeout(function(){resizeTimer=null -forEachCodeMirror(onResize)},100)}}) -on(window,"blur",function(){return forEachCodeMirror(onBlur);})} -function onResize(cm){var d=cm.display -if(d.lastWrapHeight==d.wrapper.clientHeight&&d.lastWrapWidth==d.wrapper.clientWidth) -{return} -d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null -d.scrollbarsClipped=false -cm.setSize()} -var keyNames={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"} -for(var i=0;i<10;i++){keyNames[i+48]=keyNames[i+96]=String(i)} -for(var i$1=65;i$1<=90;i$1++){keyNames[i$1]=String.fromCharCode(i$1)} -for(var i$2=1;i$2<=12;i$2++){keyNames[i$2+111]=keyNames[i$2+63235]="F"+i$2} -var keyMap={} -keyMap.basic={"Left":"goCharLeft","Right":"goCharRight","Up":"goLineUp","Down":"goLineDown","End":"goLineEnd","Home":"goLineStartSmart","PageUp":"goPageUp","PageDown":"goPageDown","Delete":"delCharAfter","Backspace":"delCharBefore","Shift-Backspace":"delCharBefore","Tab":"defaultTab","Shift-Tab":"indentAuto","Enter":"newlineAndIndent","Insert":"toggleOverwrite","Esc":"singleSelection"} -keyMap.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"} -keyMap.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"} -keyMap.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]} -keyMap["default"]=mac?keyMap.macDefault:keyMap.pcDefault -function normalizeKeyName(name){var parts=name.split(/-(?!$)/) -name=parts[parts.length-1] -var alt,ctrl,shift,cmd -for(var i=0;i<parts.length-1;i++){var mod=parts[i] -if(/^(cmd|meta|m)$/i.test(mod)){cmd=true} -else if(/^a(lt)?$/i.test(mod)){alt=true} -else if(/^(c|ctrl|control)$/i.test(mod)){ctrl=true} -else if(/^s(hift)?$/i.test(mod)){shift=true} -else{throw new Error("Unrecognized modifier name: "+mod)}} -if(alt){name="Alt-"+name} -if(ctrl){name="Ctrl-"+name} -if(cmd){name="Cmd-"+name} -if(shift){name="Shift-"+name} -return name} -function normalizeKeyMap(keymap){var copy={} -for(var keyname in keymap){if(keymap.hasOwnProperty(keyname)){var value=keymap[keyname] -if(/^(name|fallthrough|(de|at)tach)$/.test(keyname)){continue} -if(value=="..."){delete keymap[keyname];continue} -var keys=map(keyname.split(" "),normalizeKeyName) -for(var i=0;i<keys.length;i++){var val=(void 0),name=(void 0) -if(i==keys.length-1){name=keys.join(" ") -val=value}else{name=keys.slice(0,i+1).join(" ") -val="..."} -var prev=copy[name] -if(!prev){copy[name]=val} -else if(prev!=val){throw new Error("Inconsistent bindings for "+name)}} -delete keymap[keyname]}} -for(var prop in copy){keymap[prop]=copy[prop]} -return keymap} -function lookupKey(key,map,handle,context){map=getKeyMap(map) -var found=map.call?map.call(key,context):map[key] -if(found===false){return"nothing"} -if(found==="..."){return"multi"} -if(found!=null&&handle(found)){return"handled"} -if(map.fallthrough){if(Object.prototype.toString.call(map.fallthrough)!="[object Array]") -{return lookupKey(key,map.fallthrough,handle,context)} -for(var i=0;i<map.fallthrough.length;i++){var result=lookupKey(key,map.fallthrough[i],handle,context) -if(result){return result}}}} -function isModifierKey(value){var name=typeof value=="string"?value:keyNames[value.keyCode] -return name=="Ctrl"||name=="Alt"||name=="Shift"||name=="Mod"} -function keyName(event,noShift){if(presto&&event.keyCode==34&&event["char"]){return false} -var base=keyNames[event.keyCode],name=base -if(name==null||event.altGraphKey){return false} -if(event.altKey&&base!="Alt"){name="Alt-"+name} -if((flipCtrlCmd?event.metaKey:event.ctrlKey)&&base!="Ctrl"){name="Ctrl-"+name} -if((flipCtrlCmd?event.ctrlKey:event.metaKey)&&base!="Cmd"){name="Cmd-"+name} -if(!noShift&&event.shiftKey&&base!="Shift"){name="Shift-"+name} -return name} -function getKeyMap(val){return typeof val=="string"?keyMap[val]:val} -function deleteNearSelection(cm,compute){var ranges=cm.doc.sel.ranges,kill=[] -for(var i=0;i<ranges.length;i++){var toKill=compute(ranges[i]) -while(kill.length&&cmp(toKill.from,lst(kill).to)<=0){var replaced=kill.pop() -if(cmp(replaced.from,toKill.from)<0){toKill.from=replaced.from -break}} -kill.push(toKill)} -runInOp(cm,function(){for(var i=kill.length-1;i>=0;i--) -{replaceRange(cm.doc,"",kill[i].from,kill[i].to,"+delete")} -ensureCursorVisible(cm)})} -var commands={selectAll:selectAll,singleSelection:function(cm){return cm.setSelection(cm.getCursor("anchor"),cm.getCursor("head"),sel_dontScroll);},killLine:function(cm){return deleteNearSelection(cm,function(range){if(range.empty()){var len=getLine(cm.doc,range.head.line).text.length -if(range.head.ch==len&&range.head.line<cm.lastLine()) -{return{from:range.head,to:Pos(range.head.line+1,0)}} -else -{return{from:range.head,to:Pos(range.head.line,len)}}}else{return{from:range.from(),to:range.to()}}});},deleteLine:function(cm){return deleteNearSelection(cm,function(range){return({from:Pos(range.from().line,0),to:clipPos(cm.doc,Pos(range.to().line+1,0))});});},delLineLeft:function(cm){return deleteNearSelection(cm,function(range){return({from:Pos(range.from().line,0),to:range.from()});});},delWrappedLineLeft:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5 -var leftPos=cm.coordsChar({left:0,top:top},"div") -return{from:leftPos,to:range.from()}});},delWrappedLineRight:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5 -var rightPos=cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div") -return{from:range.from(),to:rightPos}});},undo:function(cm){return cm.undo();},redo:function(cm){return cm.redo();},undoSelection:function(cm){return cm.undoSelection();},redoSelection:function(cm){return cm.redoSelection();},goDocStart:function(cm){return cm.extendSelection(Pos(cm.firstLine(),0));},goDocEnd:function(cm){return cm.extendSelection(Pos(cm.lastLine()));},goLineStart:function(cm){return cm.extendSelectionsBy(function(range){return lineStart(cm,range.head.line);},{origin:"+move",bias:1});},goLineStartSmart:function(cm){return cm.extendSelectionsBy(function(range){return lineStartSmart(cm,range.head);},{origin:"+move",bias:1});},goLineEnd:function(cm){return cm.extendSelectionsBy(function(range){return lineEnd(cm,range.head.line);},{origin:"+move",bias:-1});},goLineRight:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5 -return cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div")},sel_move);},goLineLeft:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5 -return cm.coordsChar({left:0,top:top},"div")},sel_move);},goLineLeftSmart:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5 -var pos=cm.coordsChar({left:0,top:top},"div") -if(pos.ch<cm.getLine(pos.line).search(/\S/)){return lineStartSmart(cm,range.head)} -return pos},sel_move);},goLineUp:function(cm){return cm.moveV(-1,"line");},goLineDown:function(cm){return cm.moveV(1,"line");},goPageUp:function(cm){return cm.moveV(-1,"page");},goPageDown:function(cm){return cm.moveV(1,"page");},goCharLeft:function(cm){return cm.moveH(-1,"char");},goCharRight:function(cm){return cm.moveH(1,"char");},goColumnLeft:function(cm){return cm.moveH(-1,"column");},goColumnRight:function(cm){return cm.moveH(1,"column");},goWordLeft:function(cm){return cm.moveH(-1,"word");},goGroupRight:function(cm){return cm.moveH(1,"group");},goGroupLeft:function(cm){return cm.moveH(-1,"group");},goWordRight:function(cm){return cm.moveH(1,"word");},delCharBefore:function(cm){return cm.deleteH(-1,"char");},delCharAfter:function(cm){return cm.deleteH(1,"char");},delWordBefore:function(cm){return cm.deleteH(-1,"word");},delWordAfter:function(cm){return cm.deleteH(1,"word");},delGroupBefore:function(cm){return cm.deleteH(-1,"group");},delGroupAfter:function(cm){return cm.deleteH(1,"group");},indentAuto:function(cm){return cm.indentSelection("smart");},indentMore:function(cm){return cm.indentSelection("add");},indentLess:function(cm){return cm.indentSelection("subtract");},insertTab:function(cm){return cm.replaceSelection("\t");},insertSoftTab:function(cm){var spaces=[],ranges=cm.listSelections(),tabSize=cm.options.tabSize -for(var i=0;i<ranges.length;i++){var pos=ranges[i].from() -var col=countColumn(cm.getLine(pos.line),pos.ch,tabSize) -spaces.push(spaceStr(tabSize-col%tabSize))} -cm.replaceSelections(spaces)},defaultTab:function(cm){if(cm.somethingSelected()){cm.indentSelection("add")} -else{cm.execCommand("insertTab")}},transposeChars:function(cm){return runInOp(cm,function(){var ranges=cm.listSelections(),newSel=[] -for(var i=0;i<ranges.length;i++){if(!ranges[i].empty()){continue} -var cur=ranges[i].head,line=getLine(cm.doc,cur.line).text -if(line){if(cur.ch==line.length){cur=new Pos(cur.line,cur.ch-1)} -if(cur.ch>0){cur=new Pos(cur.line,cur.ch+1) -cm.replaceRange(line.charAt(cur.ch-1)+line.charAt(cur.ch-2),Pos(cur.line,cur.ch-2),cur,"+transpose")}else if(cur.line>cm.doc.first){var prev=getLine(cm.doc,cur.line-1).text -if(prev){cur=new Pos(cur.line,1) -cm.replaceRange(line.charAt(0)+cm.doc.lineSeparator()+ -prev.charAt(prev.length-1),Pos(cur.line-1,prev.length-1),cur,"+transpose")}}} -newSel.push(new Range(cur,cur))} -cm.setSelections(newSel)});},newlineAndIndent:function(cm){return runInOp(cm,function(){var sels=cm.listSelections() -for(var i=sels.length-1;i>=0;i--) -{cm.replaceRange(cm.doc.lineSeparator(),sels[i].anchor,sels[i].head,"+input")} -sels=cm.listSelections() -for(var i$1=0;i$1<sels.length;i$1++) -{cm.indentLine(sels[i$1].from().line,null,true)} -ensureCursorVisible(cm)});},openLine:function(cm){return cm.replaceSelection("\n","start");},toggleOverwrite:function(cm){return cm.toggleOverwrite();}} -function lineStart(cm,lineN){var line=getLine(cm.doc,lineN) -var visual=visualLine(line) -if(visual!=line){lineN=lineNo(visual)} -return endOfLine(true,cm,visual,lineN,1)} -function lineEnd(cm,lineN){var line=getLine(cm.doc,lineN) -var visual=visualLineEnd(line) -if(visual!=line){lineN=lineNo(visual)} -return endOfLine(true,cm,line,lineN,-1)} -function lineStartSmart(cm,pos){var start=lineStart(cm,pos.line) -var line=getLine(cm.doc,start.line) -var order=getOrder(line,cm.doc.direction) -if(!order||order[0].level==0){var firstNonWS=Math.max(0,line.text.search(/\S/)) -var inWS=pos.line==start.line&&pos.ch<=firstNonWS&&pos.ch -return Pos(start.line,inWS?0:firstNonWS,start.sticky)} -return start} -function doHandleBinding(cm,bound,dropShift){if(typeof bound=="string"){bound=commands[bound] -if(!bound){return false}} -cm.display.input.ensurePolled() -var prevShift=cm.display.shift,done=false -try{if(cm.isReadOnly()){cm.state.suppressEdits=true} -if(dropShift){cm.display.shift=false} -done=bound(cm)!=Pass}finally{cm.display.shift=prevShift -cm.state.suppressEdits=false} -return done} -function lookupKeyForEditor(cm,name,handle){for(var i=0;i<cm.state.keyMaps.length;i++){var result=lookupKey(name,cm.state.keyMaps[i],handle,cm) -if(result){return result}} -return(cm.options.extraKeys&&lookupKey(name,cm.options.extraKeys,handle,cm))||lookupKey(name,cm.options.keyMap,handle,cm)} -var stopSeq=new Delayed -function dispatchKey(cm,name,e,handle){var seq=cm.state.keySeq -if(seq){if(isModifierKey(name)){return"handled"} -stopSeq.set(50,function(){if(cm.state.keySeq==seq){cm.state.keySeq=null -cm.display.input.reset()}}) -name=seq+" "+name} -var result=lookupKeyForEditor(cm,name,handle) -if(result=="multi") -{cm.state.keySeq=name} -if(result=="handled") -{signalLater(cm,"keyHandled",cm,name,e)} -if(result=="handled"||result=="multi"){e_preventDefault(e) -restartBlink(cm)} -if(seq&&!result&&/\'$/.test(name)){e_preventDefault(e) -return true} -return!!result} -function handleKeyBinding(cm,e){var name=keyName(e,true) -if(!name){return false} -if(e.shiftKey&&!cm.state.keySeq){return dispatchKey(cm,"Shift-"+name,e,function(b){return doHandleBinding(cm,b,true);})||dispatchKey(cm,name,e,function(b){if(typeof b=="string"?/^go[A-Z]/.test(b):b.motion) -{return doHandleBinding(cm,b)}})}else{return dispatchKey(cm,name,e,function(b){return doHandleBinding(cm,b);})}} -function handleCharBinding(cm,e,ch){return dispatchKey(cm,"'"+ch+"'",e,function(b){return doHandleBinding(cm,b,true);})} -var lastStoppedKey=null -function onKeyDown(e){var cm=this -cm.curOp.focus=activeElt() -if(signalDOMEvent(cm,e)){return} -if(ie&&ie_version<11&&e.keyCode==27){e.returnValue=false} -var code=e.keyCode -cm.display.shift=code==16||e.shiftKey -var handled=handleKeyBinding(cm,e) -if(presto){lastStoppedKey=handled?code:null -if(!handled&&code==88&&!hasCopyEvent&&(mac?e.metaKey:e.ctrlKey)) -{cm.replaceSelection("",null,"cut")}} -if(code==18&&!/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) -{showCrossHair(cm)}} -function showCrossHair(cm){var lineDiv=cm.display.lineDiv -addClass(lineDiv,"CodeMirror-crosshair") -function up(e){if(e.keyCode==18||!e.altKey){rmClass(lineDiv,"CodeMirror-crosshair") -off(document,"keyup",up) -off(document,"mouseover",up)}} -on(document,"keyup",up) -on(document,"mouseover",up)} -function onKeyUp(e){if(e.keyCode==16){this.doc.sel.shift=false} -signalDOMEvent(this,e)} -function onKeyPress(e){var cm=this -if(eventInWidget(cm.display,e)||signalDOMEvent(cm,e)||e.ctrlKey&&!e.altKey||mac&&e.metaKey){return} -var keyCode=e.keyCode,charCode=e.charCode -if(presto&&keyCode==lastStoppedKey){lastStoppedKey=null;e_preventDefault(e);return} -if((presto&&(!e.which||e.which<10))&&handleKeyBinding(cm,e)){return} -var ch=String.fromCharCode(charCode==null?keyCode:charCode) -if(ch=="\x08"){return} -if(handleCharBinding(cm,e,ch)){return} -cm.display.input.onKeyPress(e)} -function onMouseDown(e){var cm=this,display=cm.display -if(signalDOMEvent(cm,e)||display.activeTouch&&display.input.supportsTouch()){return} -display.input.ensurePolled() -display.shift=e.shiftKey -if(eventInWidget(display,e)){if(!webkit){display.scroller.draggable=false -setTimeout(function(){return display.scroller.draggable=true;},100)} -return} -if(clickInGutter(cm,e)){return} -var start=posFromMouse(cm,e) -window.focus() -switch(e_button(e)){case 1:if(cm.state.selectingText) -{cm.state.selectingText(e)} -else if(start) -{leftButtonDown(cm,e,start)} -else if(e_target(e)==display.scroller) -{e_preventDefault(e)} -break -case 2:if(webkit){cm.state.lastMiddleDown=+new Date} -if(start){extendSelection(cm.doc,start)} -setTimeout(function(){return display.input.focus();},20) -e_preventDefault(e) -break -case 3:if(captureRightClick){onContextMenu(cm,e)} -else{delayBlurEvent(cm)} -break}} -var lastClick;var lastDoubleClick;function leftButtonDown(cm,e,start){if(ie){setTimeout(bind(ensureFocus,cm),0)} -else{cm.curOp.focus=activeElt()} -var now=+new Date,type -if(lastDoubleClick&&lastDoubleClick.time>now-400&&cmp(lastDoubleClick.pos,start)==0){type="triple"}else if(lastClick&&lastClick.time>now-400&&cmp(lastClick.pos,start)==0){type="double" -lastDoubleClick={time:now,pos:start}}else{type="single" -lastClick={time:now,pos:start}} -var sel=cm.doc.sel,modifier=mac?e.metaKey:e.ctrlKey,contained -if(cm.options.dragDrop&&dragAndDrop&&!cm.isReadOnly()&&type=="single"&&(contained=sel.contains(start))>-1&&(cmp((contained=sel.ranges[contained]).from(),start)<0||start.xRel>0)&&(cmp(contained.to(),start)>0||start.xRel<0)) -{leftButtonStartDrag(cm,e,start,modifier)} -else -{leftButtonSelect(cm,e,start,type,modifier)}} -function leftButtonStartDrag(cm,e,start,modifier){var display=cm.display,startTime=+new Date -var dragEnd=operation(cm,function(e2){if(webkit){display.scroller.draggable=false} -cm.state.draggingText=false -off(document,"mouseup",dragEnd) -off(display.scroller,"drop",dragEnd) -if(Math.abs(e.clientX-e2.clientX)+Math.abs(e.clientY-e2.clientY)<10){e_preventDefault(e2) -if(!modifier&&+new Date-200<startTime) -{extendSelection(cm.doc,start)} -if(webkit||ie&&ie_version==9) -{setTimeout(function(){document.body.focus();display.input.focus()},20)} -else -{display.input.focus()}}}) -if(webkit){display.scroller.draggable=true} -cm.state.draggingText=dragEnd -dragEnd.copy=mac?e.altKey:e.ctrlKey -if(display.scroller.dragDrop){display.scroller.dragDrop()} -on(document,"mouseup",dragEnd) -on(display.scroller,"drop",dragEnd)} -function leftButtonSelect(cm,e,start,type,addNew){var display=cm.display,doc=cm.doc -e_preventDefault(e) -var ourRange,ourIndex,startSel=doc.sel,ranges=startSel.ranges -if(addNew&&!e.shiftKey){ourIndex=doc.sel.contains(start) -if(ourIndex>-1) -{ourRange=ranges[ourIndex]} -else -{ourRange=new Range(start,start)}}else{ourRange=doc.sel.primary() -ourIndex=doc.sel.primIndex} -if(chromeOS?e.shiftKey&&e.metaKey:e.altKey){type="rect" -if(!addNew){ourRange=new Range(start,start)} -start=posFromMouse(cm,e,true,true) -ourIndex=-1}else if(type=="double"){var word=cm.findWordAt(start) -if(cm.display.shift||doc.extend) -{ourRange=extendRange(doc,ourRange,word.anchor,word.head)} -else -{ourRange=word}}else if(type=="triple"){var line=new Range(Pos(start.line,0),clipPos(doc,Pos(start.line+1,0))) -if(cm.display.shift||doc.extend) -{ourRange=extendRange(doc,ourRange,line.anchor,line.head)} -else -{ourRange=line}}else{ourRange=extendRange(doc,ourRange,start)} -if(!addNew){ourIndex=0 -setSelection(doc,new Selection([ourRange],0),sel_mouse) -startSel=doc.sel}else if(ourIndex==-1){ourIndex=ranges.length -setSelection(doc,normalizeSelection(ranges.concat([ourRange]),ourIndex),{scroll:false,origin:"*mouse"})}else if(ranges.length>1&&ranges[ourIndex].empty()&&type=="single"&&!e.shiftKey){setSelection(doc,normalizeSelection(ranges.slice(0,ourIndex).concat(ranges.slice(ourIndex+1)),0),{scroll:false,origin:"*mouse"}) -startSel=doc.sel}else{replaceOneSelection(doc,ourIndex,ourRange,sel_mouse)} -var lastPos=start -function extendTo(pos){if(cmp(lastPos,pos)==0){return} -lastPos=pos -if(type=="rect"){var ranges=[],tabSize=cm.options.tabSize -var startCol=countColumn(getLine(doc,start.line).text,start.ch,tabSize) -var posCol=countColumn(getLine(doc,pos.line).text,pos.ch,tabSize) -var left=Math.min(startCol,posCol),right=Math.max(startCol,posCol) -for(var line=Math.min(start.line,pos.line),end=Math.min(cm.lastLine(),Math.max(start.line,pos.line));line<=end;line++){var text=getLine(doc,line).text,leftPos=findColumn(text,left,tabSize) -if(left==right) -{ranges.push(new Range(Pos(line,leftPos),Pos(line,leftPos)))} -else if(text.length>leftPos) -{ranges.push(new Range(Pos(line,leftPos),Pos(line,findColumn(text,right,tabSize))))}} -if(!ranges.length){ranges.push(new Range(start,start))} -setSelection(doc,normalizeSelection(startSel.ranges.slice(0,ourIndex).concat(ranges),ourIndex),{origin:"*mouse",scroll:false}) -cm.scrollIntoView(pos)}else{var oldRange=ourRange -var anchor=oldRange.anchor,head=pos -if(type!="single"){var range -if(type=="double") -{range=cm.findWordAt(pos)} -else -{range=new Range(Pos(pos.line,0),clipPos(doc,Pos(pos.line+1,0)))} -if(cmp(range.anchor,anchor)>0){head=range.head -anchor=minPos(oldRange.from(),range.anchor)}else{head=range.anchor -anchor=maxPos(oldRange.to(),range.head)}} -var ranges$1=startSel.ranges.slice(0) -ranges$1[ourIndex]=new Range(clipPos(doc,anchor),head) -setSelection(doc,normalizeSelection(ranges$1,ourIndex),sel_mouse)}} -var editorSize=display.wrapper.getBoundingClientRect() -var counter=0 -function extend(e){var curCount=++counter -var cur=posFromMouse(cm,e,true,type=="rect") -if(!cur){return} -if(cmp(cur,lastPos)!=0){cm.curOp.focus=activeElt() -extendTo(cur) -var visible=visibleLines(display,doc) -if(cur.line>=visible.to||cur.line<visible.from) -{setTimeout(operation(cm,function(){if(counter==curCount){extend(e)}}),150)}}else{var outside=e.clientY<editorSize.top?-20:e.clientY>editorSize.bottom?20:0 -if(outside){setTimeout(operation(cm,function(){if(counter!=curCount){return} -display.scroller.scrollTop+=outside -extend(e)}),50)}}} -function done(e){cm.state.selectingText=false -counter=Infinity -e_preventDefault(e) -display.input.focus() -off(document,"mousemove",move) -off(document,"mouseup",up) -doc.history.lastSelOrigin=null} -var move=operation(cm,function(e){if(!e_button(e)){done(e)} -else{extend(e)}}) -var up=operation(cm,done) -cm.state.selectingText=up -on(document,"mousemove",move) -on(document,"mouseup",up)} -function gutterEvent(cm,e,type,prevent){var mX,mY -try{mX=e.clientX;mY=e.clientY} -catch(e){return false} -if(mX>=Math.floor(cm.display.gutters.getBoundingClientRect().right)){return false} -if(prevent){e_preventDefault(e)} -var display=cm.display -var lineBox=display.lineDiv.getBoundingClientRect() -if(mY>lineBox.bottom||!hasHandler(cm,type)){return e_defaultPrevented(e)} -mY-=lineBox.top-display.viewOffset -for(var i=0;i<cm.options.gutters.length;++i){var g=display.gutters.childNodes[i] -if(g&&g.getBoundingClientRect().right>=mX){var line=lineAtHeight(cm.doc,mY) -var gutter=cm.options.gutters[i] -signal(cm,type,cm,line,gutter,e) -return e_defaultPrevented(e)}}} -function clickInGutter(cm,e){return gutterEvent(cm,e,"gutterClick",true)} -function onContextMenu(cm,e){if(eventInWidget(cm.display,e)||contextMenuInGutter(cm,e)){return} -if(signalDOMEvent(cm,e,"contextmenu")){return} -cm.display.input.onContextMenu(e)} -function contextMenuInGutter(cm,e){if(!hasHandler(cm,"gutterContextMenu")){return false} -return gutterEvent(cm,e,"gutterContextMenu",false)} -function themeChanged(cm){cm.display.wrapper.className=cm.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+ -cm.options.theme.replace(/(^|\s)\s*/g," cm-s-") -clearCaches(cm)} -var Init={toString:function(){return"CodeMirror.Init"}} -var defaults={} -var optionHandlers={} -function defineOptions(CodeMirror){var optionHandlers=CodeMirror.optionHandlers -function option(name,deflt,handle,notOnInit){CodeMirror.defaults[name]=deflt -if(handle){optionHandlers[name]=notOnInit?function(cm,val,old){if(old!=Init){handle(cm,val,old)}}:handle}} -CodeMirror.defineOption=option -CodeMirror.Init=Init -option("value","",function(cm,val){return cm.setValue(val);},true) -option("mode",null,function(cm,val){cm.doc.modeOption=val -loadMode(cm)},true) -option("indentUnit",2,loadMode,true) -option("indentWithTabs",false) -option("smartIndent",true) -option("tabSize",4,function(cm){resetModeState(cm) -clearCaches(cm) -regChange(cm)},true) -option("lineSeparator",null,function(cm,val){cm.doc.lineSep=val -if(!val){return} -var newBreaks=[],lineNo=cm.doc.first -cm.doc.iter(function(line){for(var pos=0;;){var found=line.text.indexOf(val,pos) -if(found==-1){break} -pos=found+val.length -newBreaks.push(Pos(lineNo,found))} -lineNo++}) -for(var i=newBreaks.length-1;i>=0;i--) -{replaceRange(cm.doc,val,newBreaks[i],Pos(newBreaks[i].line,newBreaks[i].ch+val.length))}}) -option("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g,function(cm,val,old){cm.state.specialChars=new RegExp(val.source+(val.test("\t")?"":"|\t"),"g") -if(old!=Init){cm.refresh()}}) -option("specialCharPlaceholder",defaultSpecialCharPlaceholder,function(cm){return cm.refresh();},true) -option("electricChars",true) -option("inputStyle",mobile?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},true) -option("spellcheck",false,function(cm,val){return cm.getInputField().spellcheck=val;},true) -option("rtlMoveVisually",!windows) -option("wholeLineUpdateBefore",true) -option("theme","default",function(cm){themeChanged(cm) -guttersChanged(cm)},true) -option("keyMap","default",function(cm,val,old){var next=getKeyMap(val) -var prev=old!=Init&&getKeyMap(old) -if(prev&&prev.detach){prev.detach(cm,next)} -if(next.attach){next.attach(cm,prev||null)}}) -option("extraKeys",null) -option("lineWrapping",false,wrappingChanged,true) -option("gutters",[],function(cm){setGuttersForLineNumbers(cm.options) -guttersChanged(cm)},true) -option("fixedGutter",true,function(cm,val){cm.display.gutters.style.left=val?compensateForHScroll(cm.display)+"px":"0" -cm.refresh()},true) -option("coverGutterNextToScrollbar",false,function(cm){return updateScrollbars(cm);},true) -option("scrollbarStyle","native",function(cm){initScrollbars(cm) -updateScrollbars(cm) -cm.display.scrollbars.setScrollTop(cm.doc.scrollTop) -cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)},true) -option("lineNumbers",false,function(cm){setGuttersForLineNumbers(cm.options) -guttersChanged(cm)},true) -option("firstLineNumber",1,guttersChanged,true) -option("lineNumberFormatter",function(integer){return integer;},guttersChanged,true) -option("showCursorWhenSelecting",false,updateSelection,true) -option("resetSelectionOnContextMenu",true) -option("lineWiseCopyCut",true) -option("readOnly",false,function(cm,val){if(val=="nocursor"){onBlur(cm) -cm.display.input.blur() -cm.display.disabled=true}else{cm.display.disabled=false} -cm.display.input.readOnlyChanged(val)}) -option("disableInput",false,function(cm,val){if(!val){cm.display.input.reset()}},true) -option("dragDrop",true,dragDropChanged) -option("allowDropFileTypes",null) -option("cursorBlinkRate",530) -option("cursorScrollMargin",0) -option("cursorHeight",1,updateSelection,true) -option("singleCursorHeightPerLine",true,updateSelection,true) -option("workTime",100) -option("workDelay",100) -option("flattenSpans",true,resetModeState,true) -option("addModeClass",false,resetModeState,true) -option("pollInterval",100) -option("undoDepth",200,function(cm,val){return cm.doc.history.undoDepth=val;}) -option("historyEventDelay",1250) -option("viewportMargin",10,function(cm){return cm.refresh();},true) -option("maxHighlightLength",10000,resetModeState,true) -option("moveInputWithCursor",true,function(cm,val){if(!val){cm.display.input.resetPosition()}}) -option("tabindex",null,function(cm,val){return cm.display.input.getField().tabIndex=val||"";}) -option("autofocus",null) -option("direction","ltr",function(cm,val){return cm.doc.setDirection(val);},true)} -function guttersChanged(cm){updateGutters(cm) -regChange(cm) -alignHorizontally(cm)} -function dragDropChanged(cm,value,old){var wasOn=old&&old!=Init -if(!value!=!wasOn){var funcs=cm.display.dragFunctions -var toggle=value?on:off -toggle(cm.display.scroller,"dragstart",funcs.start) -toggle(cm.display.scroller,"dragenter",funcs.enter) -toggle(cm.display.scroller,"dragover",funcs.over) -toggle(cm.display.scroller,"dragleave",funcs.leave) -toggle(cm.display.scroller,"drop",funcs.drop)}} -function wrappingChanged(cm){if(cm.options.lineWrapping){addClass(cm.display.wrapper,"CodeMirror-wrap") -cm.display.sizer.style.minWidth="" -cm.display.sizerWidth=null}else{rmClass(cm.display.wrapper,"CodeMirror-wrap") -findMaxLine(cm)} -estimateLineHeights(cm) -regChange(cm) -clearCaches(cm) -setTimeout(function(){return updateScrollbars(cm);},100)} -function CodeMirror(place,options){var this$1=this;if(!(this instanceof CodeMirror)){return new CodeMirror(place,options)} -this.options=options=options?copyObj(options):{} -copyObj(defaults,options,false) -setGuttersForLineNumbers(options) -var doc=options.value -if(typeof doc=="string"){doc=new Doc(doc,options.mode,null,options.lineSeparator,options.direction)} -this.doc=doc -var input=new CodeMirror.inputStyles[options.inputStyle](this) -var display=this.display=new Display(place,doc,input) -display.wrapper.CodeMirror=this -updateGutters(this) -themeChanged(this) -if(options.lineWrapping) -{this.display.wrapper.className+=" CodeMirror-wrap"} -initScrollbars(this) -this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:false,delayingBlurEvent:false,focused:false,suppressEdits:false,pasteIncoming:false,cutIncoming:false,selectingText:false,draggingText:false,highlight:new Delayed(),keySeq:null,specialChars:null} -if(options.autofocus&&!mobile){display.input.focus()} -if(ie&&ie_version<11){setTimeout(function(){return this$1.display.input.reset(true);},20)} -registerEventHandlers(this) -ensureGlobalHandlers() -startOperation(this) -this.curOp.forceUpdate=true -attachDoc(this,doc) -if((options.autofocus&&!mobile)||this.hasFocus()) -{setTimeout(bind(onFocus,this),20)} -else -{onBlur(this)} -for(var opt in optionHandlers){if(optionHandlers.hasOwnProperty(opt)) -{optionHandlers[opt](this$1,options[opt],Init)}} -maybeUpdateLineNumberWidth(this) -if(options.finishInit){options.finishInit(this)} -for(var i=0;i<initHooks.length;++i){initHooks[i](this$1)} -endOperation(this) -if(webkit&&options.lineWrapping&&getComputedStyle(display.lineDiv).textRendering=="optimizelegibility") -{display.lineDiv.style.textRendering="auto"}} -CodeMirror.defaults=defaults -CodeMirror.optionHandlers=optionHandlers -function registerEventHandlers(cm){var d=cm.display -on(d.scroller,"mousedown",operation(cm,onMouseDown)) -if(ie&&ie_version<11) -{on(d.scroller,"dblclick",operation(cm,function(e){if(signalDOMEvent(cm,e)){return} -var pos=posFromMouse(cm,e) -if(!pos||clickInGutter(cm,e)||eventInWidget(cm.display,e)){return} -e_preventDefault(e) -var word=cm.findWordAt(pos) -extendSelection(cm.doc,word.anchor,word.head)}))} -else -{on(d.scroller,"dblclick",function(e){return signalDOMEvent(cm,e)||e_preventDefault(e);})} -if(!captureRightClick){on(d.scroller,"contextmenu",function(e){return onContextMenu(cm,e);})} -var touchFinished,prevTouch={end:0} -function finishTouch(){if(d.activeTouch){touchFinished=setTimeout(function(){return d.activeTouch=null;},1000) -prevTouch=d.activeTouch -prevTouch.end=+new Date}} -function isMouseLikeTouchEvent(e){if(e.touches.length!=1){return false} -var touch=e.touches[0] -return touch.radiusX<=1&&touch.radiusY<=1} -function farAway(touch,other){if(other.left==null){return true} -var dx=other.left-touch.left,dy=other.top-touch.top -return dx*dx+dy*dy>20*20} -on(d.scroller,"touchstart",function(e){if(!signalDOMEvent(cm,e)&&!isMouseLikeTouchEvent(e)){d.input.ensurePolled() -clearTimeout(touchFinished) -var now=+new Date -d.activeTouch={start:now,moved:false,prev:now-prevTouch.end<=300?prevTouch:null} -if(e.touches.length==1){d.activeTouch.left=e.touches[0].pageX -d.activeTouch.top=e.touches[0].pageY}}}) -on(d.scroller,"touchmove",function(){if(d.activeTouch){d.activeTouch.moved=true}}) -on(d.scroller,"touchend",function(e){var touch=d.activeTouch -if(touch&&!eventInWidget(d,e)&&touch.left!=null&&!touch.moved&&new Date-touch.start<300){var pos=cm.coordsChar(d.activeTouch,"page"),range -if(!touch.prev||farAway(touch,touch.prev)) -{range=new Range(pos,pos)} -else if(!touch.prev.prev||farAway(touch,touch.prev.prev)) -{range=cm.findWordAt(pos)} -else -{range=new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0)))} -cm.setSelection(range.anchor,range.head) -cm.focus() -e_preventDefault(e)} -finishTouch()}) -on(d.scroller,"touchcancel",finishTouch) -on(d.scroller,"scroll",function(){if(d.scroller.clientHeight){setScrollTop(cm,d.scroller.scrollTop) -setScrollLeft(cm,d.scroller.scrollLeft,true) -signal(cm,"scroll",cm)}}) -on(d.scroller,"mousewheel",function(e){return onScrollWheel(cm,e);}) -on(d.scroller,"DOMMouseScroll",function(e){return onScrollWheel(cm,e);}) -on(d.wrapper,"scroll",function(){return d.wrapper.scrollTop=d.wrapper.scrollLeft=0;}) -d.dragFunctions={enter:function(e){if(!signalDOMEvent(cm,e)){e_stop(e)}},over:function(e){if(!signalDOMEvent(cm,e)){onDragOver(cm,e);e_stop(e)}},start:function(e){return onDragStart(cm,e);},drop:operation(cm,onDrop),leave:function(e){if(!signalDOMEvent(cm,e)){clearDragCursor(cm)}}} -var inp=d.input.getField() -on(inp,"keyup",function(e){return onKeyUp.call(cm,e);}) -on(inp,"keydown",operation(cm,onKeyDown)) -on(inp,"keypress",operation(cm,onKeyPress)) -on(inp,"focus",function(e){return onFocus(cm,e);}) -on(inp,"blur",function(e){return onBlur(cm,e);})} -var initHooks=[] -CodeMirror.defineInitHook=function(f){return initHooks.push(f);} -function indentLine(cm,n,how,aggressive){var doc=cm.doc,state -if(how==null){how="add"} -if(how=="smart"){if(!doc.mode.indent){how="prev"} -else{state=getStateBefore(cm,n)}} -var tabSize=cm.options.tabSize -var line=getLine(doc,n),curSpace=countColumn(line.text,null,tabSize) -if(line.stateAfter){line.stateAfter=null} -var curSpaceString=line.text.match(/^\s*/)[0],indentation -if(!aggressive&&!/\S/.test(line.text)){indentation=0 -how="not"}else if(how=="smart"){indentation=doc.mode.indent(state,line.text.slice(curSpaceString.length),line.text) -if(indentation==Pass||indentation>150){if(!aggressive){return} -how="prev"}} -if(how=="prev"){if(n>doc.first){indentation=countColumn(getLine(doc,n-1).text,null,tabSize)} -else{indentation=0}}else if(how=="add"){indentation=curSpace+cm.options.indentUnit}else if(how=="subtract"){indentation=curSpace-cm.options.indentUnit}else if(typeof how=="number"){indentation=curSpace+how} -indentation=Math.max(0,indentation) -var indentString="",pos=0 -if(cm.options.indentWithTabs) -{for(var i=Math.floor(indentation/tabSize);i;--i){pos+=tabSize;indentString+="\t"}} -if(pos<indentation){indentString+=spaceStr(indentation-pos)} -if(indentString!=curSpaceString){replaceRange(doc,indentString,Pos(n,0),Pos(n,curSpaceString.length),"+input") -line.stateAfter=null -return true}else{for(var i$1=0;i$1<doc.sel.ranges.length;i$1++){var range=doc.sel.ranges[i$1] -if(range.head.line==n&&range.head.ch<curSpaceString.length){var pos$1=Pos(n,curSpaceString.length) -replaceOneSelection(doc,i$1,new Range(pos$1,pos$1)) -break}}}} -var lastCopied=null -function setLastCopied(newLastCopied){lastCopied=newLastCopied} -function applyTextInput(cm,inserted,deleted,sel,origin){var doc=cm.doc -cm.display.shift=false -if(!sel){sel=doc.sel} -var paste=cm.state.pasteIncoming||origin=="paste" -var textLines=splitLinesAuto(inserted),multiPaste=null -if(paste&&sel.ranges.length>1){if(lastCopied&&lastCopied.text.join("\n")==inserted){if(sel.ranges.length%lastCopied.text.length==0){multiPaste=[] -for(var i=0;i<lastCopied.text.length;i++) -{multiPaste.push(doc.splitLines(lastCopied.text[i]))}}}else if(textLines.length==sel.ranges.length){multiPaste=map(textLines,function(l){return[l];})}} -var updateInput -for(var i$1=sel.ranges.length-1;i$1>=0;i$1--){var range=sel.ranges[i$1] -var from=range.from(),to=range.to() -if(range.empty()){if(deleted&&deleted>0) -{from=Pos(from.line,from.ch-deleted)} -else if(cm.state.overwrite&&!paste) -{to=Pos(to.line,Math.min(getLine(doc,to.line).text.length,to.ch+lst(textLines).length))} -else if(lastCopied&&lastCopied.lineWise&&lastCopied.text.join("\n")==inserted) -{from=to=Pos(from.line,0)}} -updateInput=cm.curOp.updateInput -var changeEvent={from:from,to:to,text:multiPaste?multiPaste[i$1%multiPaste.length]:textLines,origin:origin||(paste?"paste":cm.state.cutIncoming?"cut":"+input")} -makeChange(cm.doc,changeEvent) -signalLater(cm,"inputRead",cm,changeEvent)} -if(inserted&&!paste) -{triggerElectric(cm,inserted)} -ensureCursorVisible(cm) -cm.curOp.updateInput=updateInput -cm.curOp.typing=true -cm.state.pasteIncoming=cm.state.cutIncoming=false} -function handlePaste(e,cm){var pasted=e.clipboardData&&e.clipboardData.getData("Text") -if(pasted){e.preventDefault() -if(!cm.isReadOnly()&&!cm.options.disableInput) -{runInOp(cm,function(){return applyTextInput(cm,pasted,0,null,"paste");})} -return true}} -function triggerElectric(cm,inserted){if(!cm.options.electricChars||!cm.options.smartIndent){return} -var sel=cm.doc.sel -for(var i=sel.ranges.length-1;i>=0;i--){var range=sel.ranges[i] -if(range.head.ch>100||(i&&sel.ranges[i-1].head.line==range.head.line)){continue} -var mode=cm.getModeAt(range.head) -var indented=false -if(mode.electricChars){for(var j=0;j<mode.electricChars.length;j++) -{if(inserted.indexOf(mode.electricChars.charAt(j))>-1){indented=indentLine(cm,range.head.line,"smart") -break}}}else if(mode.electricInput){if(mode.electricInput.test(getLine(cm.doc,range.head.line).text.slice(0,range.head.ch))) -{indented=indentLine(cm,range.head.line,"smart")}} -if(indented){signalLater(cm,"electricInput",cm,range.head.line)}}} -function copyableRanges(cm){var text=[],ranges=[] -for(var i=0;i<cm.doc.sel.ranges.length;i++){var line=cm.doc.sel.ranges[i].head.line -var lineRange={anchor:Pos(line,0),head:Pos(line+1,0)} -ranges.push(lineRange) -text.push(cm.getRange(lineRange.anchor,lineRange.head))} -return{text:text,ranges:ranges}} -function disableBrowserMagic(field,spellcheck){field.setAttribute("autocorrect","off") -field.setAttribute("autocapitalize","off") -field.setAttribute("spellcheck",!!spellcheck)} -function hiddenTextarea(){var te=elt("textarea",null,null,"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none") -var div=elt("div",[te],null,"overflow: hidden; position: relative; width: 3px; height: 0px;") -if(webkit){te.style.width="1000px"} -else{te.setAttribute("wrap","off")} -if(ios){te.style.border="1px solid black"} -disableBrowserMagic(te) -return div} -function addEditorMethods(CodeMirror){var optionHandlers=CodeMirror.optionHandlers -var helpers=CodeMirror.helpers={} -CodeMirror.prototype={constructor:CodeMirror,focus:function(){window.focus();this.display.input.focus()},setOption:function(option,value){var options=this.options,old=options[option] -if(options[option]==value&&option!="mode"){return} -options[option]=value -if(optionHandlers.hasOwnProperty(option)) -{operation(this,optionHandlers[option])(this,value,old)} -signal(this,"optionChange",this,option)},getOption:function(option){return this.options[option]},getDoc:function(){return this.doc},addKeyMap:function(map,bottom){this.state.keyMaps[bottom?"push":"unshift"](getKeyMap(map))},removeKeyMap:function(map){var maps=this.state.keyMaps -for(var i=0;i<maps.length;++i) -{if(maps[i]==map||maps[i].name==map){maps.splice(i,1) -return true}}},addOverlay:methodOp(function(spec,options){var mode=spec.token?spec:CodeMirror.getMode(this.options,spec) -if(mode.startState){throw new Error("Overlays may not be stateful.")} -insertSorted(this.state.overlays,{mode:mode,modeSpec:spec,opaque:options&&options.opaque,priority:(options&&options.priority)||0},function(overlay){return overlay.priority;}) -this.state.modeGen++ -regChange(this)}),removeOverlay:methodOp(function(spec){var this$1=this;var overlays=this.state.overlays -for(var i=0;i<overlays.length;++i){var cur=overlays[i].modeSpec -if(cur==spec||typeof spec=="string"&&cur.name==spec){overlays.splice(i,1) -this$1.state.modeGen++ -regChange(this$1) -return}}}),indentLine:methodOp(function(n,dir,aggressive){if(typeof dir!="string"&&typeof dir!="number"){if(dir==null){dir=this.options.smartIndent?"smart":"prev"} -else{dir=dir?"add":"subtract"}} -if(isLine(this.doc,n)){indentLine(this,n,dir,aggressive)}}),indentSelection:methodOp(function(how){var this$1=this;var ranges=this.doc.sel.ranges,end=-1 -for(var i=0;i<ranges.length;i++){var range=ranges[i] -if(!range.empty()){var from=range.from(),to=range.to() -var start=Math.max(end,from.line) -end=Math.min(this$1.lastLine(),to.line-(to.ch?0:1))+1 -for(var j=start;j<end;++j) -{indentLine(this$1,j,how)} -var newRanges=this$1.doc.sel.ranges -if(from.ch==0&&ranges.length==newRanges.length&&newRanges[i].from().ch>0) -{replaceOneSelection(this$1.doc,i,new Range(from,newRanges[i].to()),sel_dontScroll)}}else if(range.head.line>end){indentLine(this$1,range.head.line,how,true) -end=range.head.line -if(i==this$1.doc.sel.primIndex){ensureCursorVisible(this$1)}}}}),getTokenAt:function(pos,precise){return takeToken(this,pos,precise)},getLineTokens:function(line,precise){return takeToken(this,Pos(line),precise,true)},getTokenTypeAt:function(pos){pos=clipPos(this.doc,pos) -var styles=getLineStyles(this,getLine(this.doc,pos.line)) -var before=0,after=(styles.length-1)/2,ch=pos.ch -var type -if(ch==0){type=styles[2]} -else{for(;;){var mid=(before+after)>>1 -if((mid?styles[mid*2-1]:0)>=ch){after=mid} -else if(styles[mid*2+1]<ch){before=mid+1} -else{type=styles[mid*2+2];break}}} -var cut=type?type.indexOf("overlay "):-1 -return cut<0?type:cut==0?null:type.slice(0,cut-1)},getModeAt:function(pos){var mode=this.doc.mode -if(!mode.innerMode){return mode} -return CodeMirror.innerMode(mode,this.getTokenAt(pos).state).mode},getHelper:function(pos,type){return this.getHelpers(pos,type)[0]},getHelpers:function(pos,type){var this$1=this;var found=[] -if(!helpers.hasOwnProperty(type)){return found} -var help=helpers[type],mode=this.getModeAt(pos) -if(typeof mode[type]=="string"){if(help[mode[type]]){found.push(help[mode[type]])}}else if(mode[type]){for(var i=0;i<mode[type].length;i++){var val=help[mode[type][i]] -if(val){found.push(val)}}}else if(mode.helperType&&help[mode.helperType]){found.push(help[mode.helperType])}else if(help[mode.name]){found.push(help[mode.name])} -for(var i$1=0;i$1<help._global.length;i$1++){var cur=help._global[i$1] -if(cur.pred(mode,this$1)&&indexOf(found,cur.val)==-1) -{found.push(cur.val)}} -return found},getStateAfter:function(line,precise){var doc=this.doc -line=clipLine(doc,line==null?doc.first+doc.size-1:line) -return getStateBefore(this,line+1,precise)},cursorCoords:function(start,mode){var pos,range=this.doc.sel.primary() -if(start==null){pos=range.head} -else if(typeof start=="object"){pos=clipPos(this.doc,start)} -else{pos=start?range.from():range.to()} -return cursorCoords(this,pos,mode||"page")},charCoords:function(pos,mode){return charCoords(this,clipPos(this.doc,pos),mode||"page")},coordsChar:function(coords,mode){coords=fromCoordSystem(this,coords,mode||"page") -return coordsChar(this,coords.left,coords.top)},lineAtHeight:function(height,mode){height=fromCoordSystem(this,{top:height,left:0},mode||"page").top -return lineAtHeight(this.doc,height+this.display.viewOffset)},heightAtLine:function(line,mode,includeWidgets){var end=false,lineObj -if(typeof line=="number"){var last=this.doc.first+this.doc.size-1 -if(line<this.doc.first){line=this.doc.first} -else if(line>last){line=last;end=true} -lineObj=getLine(this.doc,line)}else{lineObj=line} -return intoCoordSystem(this,lineObj,{top:0,left:0},mode||"page",includeWidgets||end).top+ -(end?this.doc.height-heightAtLine(lineObj):0)},defaultTextHeight:function(){return textHeight(this.display)},defaultCharWidth:function(){return charWidth(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(pos,node,scroll,vert,horiz){var display=this.display -pos=cursorCoords(this,clipPos(this.doc,pos)) -var top=pos.bottom,left=pos.left -node.style.position="absolute" -node.setAttribute("cm-ignore-events","true") -this.display.input.setUneditable(node) -display.sizer.appendChild(node) -if(vert=="over"){top=pos.top}else if(vert=="above"||vert=="near"){var vspace=Math.max(display.wrapper.clientHeight,this.doc.height),hspace=Math.max(display.sizer.clientWidth,display.lineSpace.clientWidth) -if((vert=='above'||pos.bottom+node.offsetHeight>vspace)&&pos.top>node.offsetHeight) -{top=pos.top-node.offsetHeight} -else if(pos.bottom+node.offsetHeight<=vspace) -{top=pos.bottom} -if(left+node.offsetWidth>hspace) -{left=hspace-node.offsetWidth}} -node.style.top=top+"px" -node.style.left=node.style.right="" -if(horiz=="right"){left=display.sizer.clientWidth-node.offsetWidth -node.style.right="0px"}else{if(horiz=="left"){left=0} -else if(horiz=="middle"){left=(display.sizer.clientWidth-node.offsetWidth)/2} -node.style.left=left+"px"} -if(scroll) -{scrollIntoView(this,{left:left,top:top,right:left+node.offsetWidth,bottom:top+node.offsetHeight})}},triggerOnKeyDown:methodOp(onKeyDown),triggerOnKeyPress:methodOp(onKeyPress),triggerOnKeyUp:onKeyUp,execCommand:function(cmd){if(commands.hasOwnProperty(cmd)) -{return commands[cmd].call(null,this)}},triggerElectric:methodOp(function(text){triggerElectric(this,text)}),findPosH:function(from,amount,unit,visually){var this$1=this;var dir=1 -if(amount<0){dir=-1;amount=-amount} -var cur=clipPos(this.doc,from) -for(var i=0;i<amount;++i){cur=findPosH(this$1.doc,cur,dir,unit,visually) -if(cur.hitSide){break}} -return cur},moveH:methodOp(function(dir,unit){var this$1=this;this.extendSelectionsBy(function(range){if(this$1.display.shift||this$1.doc.extend||range.empty()) -{return findPosH(this$1.doc,range.head,dir,unit,this$1.options.rtlMoveVisually)} -else -{return dir<0?range.from():range.to()}},sel_move)}),deleteH:methodOp(function(dir,unit){var sel=this.doc.sel,doc=this.doc -if(sel.somethingSelected()) -{doc.replaceSelection("",null,"+delete")} -else -{deleteNearSelection(this,function(range){var other=findPosH(doc,range.head,dir,unit,false) -return dir<0?{from:other,to:range.head}:{from:range.head,to:other}})}}),findPosV:function(from,amount,unit,goalColumn){var this$1=this;var dir=1,x=goalColumn -if(amount<0){dir=-1;amount=-amount} -var cur=clipPos(this.doc,from) -for(var i=0;i<amount;++i){var coords=cursorCoords(this$1,cur,"div") -if(x==null){x=coords.left} -else{coords.left=x} -cur=findPosV(this$1,coords,dir,unit) -if(cur.hitSide){break}} -return cur},moveV:methodOp(function(dir,unit){var this$1=this;var doc=this.doc,goals=[] -var collapse=!this.display.shift&&!doc.extend&&doc.sel.somethingSelected() -doc.extendSelectionsBy(function(range){if(collapse) -{return dir<0?range.from():range.to()} -var headPos=cursorCoords(this$1,range.head,"div") -if(range.goalColumn!=null){headPos.left=range.goalColumn} -goals.push(headPos.left) -var pos=findPosV(this$1,headPos,dir,unit) -if(unit=="page"&&range==doc.sel.primary()) -{addToScrollPos(this$1,null,charCoords(this$1,pos,"div").top-headPos.top)} -return pos},sel_move) -if(goals.length){for(var i=0;i<doc.sel.ranges.length;i++) -{doc.sel.ranges[i].goalColumn=goals[i]}}}),findWordAt:function(pos){var doc=this.doc,line=getLine(doc,pos.line).text -var start=pos.ch,end=pos.ch -if(line){var helper=this.getHelper(pos,"wordChars") -if((pos.sticky=="before"||end==line.length)&&start){--start;}else{++end} -var startChar=line.charAt(start) -var check=isWordChar(startChar,helper)?function(ch){return isWordChar(ch,helper);}:/\s/.test(startChar)?function(ch){return/\s/.test(ch);}:function(ch){return(!/\s/.test(ch)&&!isWordChar(ch));} -while(start>0&&check(line.charAt(start-1))){--start} -while(end<line.length&&check(line.charAt(end))){++end}} -return new Range(Pos(pos.line,start),Pos(pos.line,end))},toggleOverwrite:function(value){if(value!=null&&value==this.state.overwrite){return} -if(this.state.overwrite=!this.state.overwrite) -{addClass(this.display.cursorDiv,"CodeMirror-overwrite")} -else -{rmClass(this.display.cursorDiv,"CodeMirror-overwrite")} -signal(this,"overwriteToggle",this,this.state.overwrite)},hasFocus:function(){return this.display.input.getField()==activeElt()},isReadOnly:function(){return!!(this.options.readOnly||this.doc.cantEdit)},scrollTo:methodOp(function(x,y){if(x!=null||y!=null){resolveScrollToPos(this)} -if(x!=null){this.curOp.scrollLeft=x} -if(y!=null){this.curOp.scrollTop=y}}),getScrollInfo:function(){var scroller=this.display.scroller -return{left:scroller.scrollLeft,top:scroller.scrollTop,height:scroller.scrollHeight-scrollGap(this)-this.display.barHeight,width:scroller.scrollWidth-scrollGap(this)-this.display.barWidth,clientHeight:displayHeight(this),clientWidth:displayWidth(this)}},scrollIntoView:methodOp(function(range,margin){if(range==null){range={from:this.doc.sel.primary().head,to:null} -if(margin==null){margin=this.options.cursorScrollMargin}}else if(typeof range=="number"){range={from:Pos(range,0),to:null}}else if(range.from==null){range={from:range,to:null}} -if(!range.to){range.to=range.from} -range.margin=margin||0 -if(range.from.line!=null){resolveScrollToPos(this) -this.curOp.scrollToPos=range}else{var sPos=calculateScrollPos(this,{left:Math.min(range.from.left,range.to.left),top:Math.min(range.from.top,range.to.top)-range.margin,right:Math.max(range.from.right,range.to.right),bottom:Math.max(range.from.bottom,range.to.bottom)+range.margin}) -this.scrollTo(sPos.scrollLeft,sPos.scrollTop)}}),setSize:methodOp(function(width,height){var this$1=this;var interpret=function(val){return typeof val=="number"||/^\d+$/.test(String(val))?val+"px":val;} -if(width!=null){this.display.wrapper.style.width=interpret(width)} -if(height!=null){this.display.wrapper.style.height=interpret(height)} -if(this.options.lineWrapping){clearLineMeasurementCache(this)} -var lineNo=this.display.viewFrom -this.doc.iter(lineNo,this.display.viewTo,function(line){if(line.widgets){for(var i=0;i<line.widgets.length;i++) -{if(line.widgets[i].noHScroll){regLineChange(this$1,lineNo,"widget");break}}} -++lineNo}) -this.curOp.forceUpdate=true -signal(this,"refresh",this)}),operation:function(f){return runInOp(this,f)},refresh:methodOp(function(){var oldHeight=this.display.cachedTextHeight -regChange(this) -this.curOp.forceUpdate=true -clearCaches(this) -this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop) -updateGutterSpace(this) -if(oldHeight==null||Math.abs(oldHeight-textHeight(this.display))>.5) -{estimateLineHeights(this)} -signal(this,"refresh",this)}),swapDoc:methodOp(function(doc){var old=this.doc -old.cm=null -attachDoc(this,doc) -clearCaches(this) -this.display.input.reset() -this.scrollTo(doc.scrollLeft,doc.scrollTop) -this.curOp.forceScroll=true -signalLater(this,"swapDoc",this,old) -return old}),getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}} -eventMixin(CodeMirror) -CodeMirror.registerHelper=function(type,name,value){if(!helpers.hasOwnProperty(type)){helpers[type]=CodeMirror[type]={_global:[]}} -helpers[type][name]=value} -CodeMirror.registerGlobalHelper=function(type,name,predicate,value){CodeMirror.registerHelper(type,name,value) -helpers[type]._global.push({pred:predicate,val:value})}} -function findPosH(doc,pos,dir,unit,visually){var oldPos=pos -var origDir=dir -var lineObj=getLine(doc,pos.line) -function findNextLine(){var l=pos.line+dir -if(l<doc.first||l>=doc.first+doc.size){return false} -pos=new Pos(l,pos.ch,pos.sticky) -return lineObj=getLine(doc,l)} -function moveOnce(boundToLine){var next -if(visually){next=moveVisually(doc.cm,lineObj,pos,dir)}else{next=moveLogically(lineObj,pos,dir)} -if(next==null){if(!boundToLine&&findNextLine()) -{pos=endOfLine(visually,doc.cm,lineObj,pos.line,dir)} -else -{return false}}else{pos=next} -return true} -if(unit=="char"){moveOnce()}else if(unit=="column"){moveOnce(true)}else if(unit=="word"||unit=="group"){var sawType=null,group=unit=="group" -var helper=doc.cm&&doc.cm.getHelper(pos,"wordChars") -for(var first=true;;first=false){if(dir<0&&!moveOnce(!first)){break} -var cur=lineObj.text.charAt(pos.ch)||"\n" -var type=isWordChar(cur,helper)?"w":group&&cur=="\n"?"n":!group||/\s/.test(cur)?null:"p" -if(group&&!first&&!type){type="s"} -if(sawType&&sawType!=type){if(dir<0){dir=1;moveOnce();pos.sticky="after"} -break} -if(type){sawType=type} -if(dir>0&&!moveOnce(!first)){break}}} -var result=skipAtomic(doc,pos,oldPos,origDir,true) -if(equalCursorPos(oldPos,result)){result.hitSide=true} -return result} -function findPosV(cm,pos,dir,unit){var doc=cm.doc,x=pos.left,y -if(unit=="page"){var pageSize=Math.min(cm.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight) -var moveAmount=Math.max(pageSize-.5*textHeight(cm.display),3) -y=(dir>0?pos.bottom:pos.top)+dir*moveAmount}else if(unit=="line"){y=dir>0?pos.bottom+3:pos.top-3} -var target -for(;;){target=coordsChar(cm,x,y) -if(!target.outside){break} -if(dir<0?y<=0:y>=doc.height){target.hitSide=true;break} -y+=dir*5} -return target} -var ContentEditableInput=function ContentEditableInput(cm){this.cm=cm -this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null -this.polling=new Delayed() -this.composing=null -this.gracePeriod=false -this.readDOMTimeout=null};ContentEditableInput.prototype.init=function init(display){var this$1=this;var input=this,cm=input.cm -var div=input.div=display.lineDiv -disableBrowserMagic(div,cm.options.spellcheck) -on(div,"paste",function(e){if(signalDOMEvent(cm,e)||handlePaste(e,cm)){return} -if(ie_version<=11){setTimeout(operation(cm,function(){return this$1.updateFromDOM();}),20)}}) -on(div,"compositionstart",function(e){this$1.composing={data:e.data,done:false}}) -on(div,"compositionupdate",function(e){if(!this$1.composing){this$1.composing={data:e.data,done:false}}}) -on(div,"compositionend",function(e){if(this$1.composing){if(e.data!=this$1.composing.data){this$1.readFromDOMSoon()} -this$1.composing.done=true}}) -on(div,"touchstart",function(){return input.forceCompositionEnd();}) -on(div,"input",function(){if(!this$1.composing){this$1.readFromDOMSoon()}}) -function onCopyCut(e){if(signalDOMEvent(cm,e)){return} -if(cm.somethingSelected()){setLastCopied({lineWise:false,text:cm.getSelections()}) -if(e.type=="cut"){cm.replaceSelection("",null,"cut")}}else if(!cm.options.lineWiseCopyCut){return}else{var ranges=copyableRanges(cm) -setLastCopied({lineWise:true,text:ranges.text}) -if(e.type=="cut"){cm.operation(function(){cm.setSelections(ranges.ranges,0,sel_dontScroll) -cm.replaceSelection("",null,"cut")})}} -if(e.clipboardData){e.clipboardData.clearData() -var content=lastCopied.text.join("\n") -e.clipboardData.setData("Text",content) -if(e.clipboardData.getData("Text")==content){e.preventDefault() -return}} -var kludge=hiddenTextarea(),te=kludge.firstChild -cm.display.lineSpace.insertBefore(kludge,cm.display.lineSpace.firstChild) -te.value=lastCopied.text.join("\n") -var hadFocus=document.activeElement -selectInput(te) -setTimeout(function(){cm.display.lineSpace.removeChild(kludge) -hadFocus.focus() -if(hadFocus==div){input.showPrimarySelection()}},50)} -on(div,"copy",onCopyCut) -on(div,"cut",onCopyCut)};ContentEditableInput.prototype.prepareSelection=function prepareSelection$1(){var result=prepareSelection(this.cm,false) -result.focus=this.cm.state.focused -return result};ContentEditableInput.prototype.showSelection=function showSelection(info,takeFocus){if(!info||!this.cm.display.view.length){return} -if(info.focus||takeFocus){this.showPrimarySelection()} -this.showMultipleSelections(info)};ContentEditableInput.prototype.showPrimarySelection=function showPrimarySelection(){var sel=window.getSelection(),prim=this.cm.doc.sel.primary() -var curAnchor=domToPos(this.cm,sel.anchorNode,sel.anchorOffset) -var curFocus=domToPos(this.cm,sel.focusNode,sel.focusOffset) -if(curAnchor&&!curAnchor.bad&&curFocus&&!curFocus.bad&&cmp(minPos(curAnchor,curFocus),prim.from())==0&&cmp(maxPos(curAnchor,curFocus),prim.to())==0) -{return} -var start=posToDOM(this.cm,prim.from()) -var end=posToDOM(this.cm,prim.to()) -if(!start&&!end){sel.removeAllRanges() -return} -var view=this.cm.display.view -var old=sel.rangeCount&&sel.getRangeAt(0) -if(!start){start={node:view[0].measure.map[2],offset:0}}else if(!end){var measure=view[view.length-1].measure -var map=measure.maps?measure.maps[measure.maps.length-1]:measure.map -end={node:map[map.length-1],offset:map[map.length-2]-map[map.length-3]}} -var rng -try{rng=range(start.node,start.offset,end.offset,end.node)} -catch(e){} -if(rng){if(!gecko&&this.cm.state.focused){sel.collapse(start.node,start.offset) -if(!rng.collapsed){sel.removeAllRanges() -sel.addRange(rng)}}else{sel.removeAllRanges() -sel.addRange(rng)} -if(old&&sel.anchorNode==null){sel.addRange(old)} -else if(gecko){this.startGracePeriod()}} -this.rememberSelection()};ContentEditableInput.prototype.startGracePeriod=function startGracePeriod(){var this$1=this;clearTimeout(this.gracePeriod) -this.gracePeriod=setTimeout(function(){this$1.gracePeriod=false -if(this$1.selectionChanged()) -{this$1.cm.operation(function(){return this$1.cm.curOp.selectionChanged=true;})}},20)};ContentEditableInput.prototype.showMultipleSelections=function showMultipleSelections(info){removeChildrenAndAdd(this.cm.display.cursorDiv,info.cursors) -removeChildrenAndAdd(this.cm.display.selectionDiv,info.selection)};ContentEditableInput.prototype.rememberSelection=function rememberSelection(){var sel=window.getSelection() -this.lastAnchorNode=sel.anchorNode;this.lastAnchorOffset=sel.anchorOffset -this.lastFocusNode=sel.focusNode;this.lastFocusOffset=sel.focusOffset};ContentEditableInput.prototype.selectionInEditor=function selectionInEditor(){var sel=window.getSelection() -if(!sel.rangeCount){return false} -var node=sel.getRangeAt(0).commonAncestorContainer -return contains(this.div,node)};ContentEditableInput.prototype.focus=function focus(){if(this.cm.options.readOnly!="nocursor"){if(!this.selectionInEditor()) -{this.showSelection(this.prepareSelection(),true)} -this.div.focus()}};ContentEditableInput.prototype.blur=function blur(){this.div.blur()};ContentEditableInput.prototype.getField=function getField(){return this.div};ContentEditableInput.prototype.supportsTouch=function supportsTouch(){return true};ContentEditableInput.prototype.receivedFocus=function receivedFocus(){var input=this -if(this.selectionInEditor()) -{this.pollSelection()} -else -{runInOp(this.cm,function(){return input.cm.curOp.selectionChanged=true;})} -function poll(){if(input.cm.state.focused){input.pollSelection() -input.polling.set(input.cm.options.pollInterval,poll)}} -this.polling.set(this.cm.options.pollInterval,poll)};ContentEditableInput.prototype.selectionChanged=function selectionChanged(){var sel=window.getSelection() -return sel.anchorNode!=this.lastAnchorNode||sel.anchorOffset!=this.lastAnchorOffset||sel.focusNode!=this.lastFocusNode||sel.focusOffset!=this.lastFocusOffset};ContentEditableInput.prototype.pollSelection=function pollSelection(){if(this.readDOMTimeout!=null||this.gracePeriod||!this.selectionChanged()){return} -var sel=window.getSelection(),cm=this.cm -if(android&&chrome&&this.cm.options.gutters.length&&isInGutter(sel.anchorNode)){this.cm.triggerOnKeyDown({type:"keydown",keyCode:8,preventDefault:Math.abs}) -this.blur() -this.focus() -return} -if(this.composing){return} -this.rememberSelection() -var anchor=domToPos(cm,sel.anchorNode,sel.anchorOffset) -var head=domToPos(cm,sel.focusNode,sel.focusOffset) -if(anchor&&head){runInOp(cm,function(){setSelection(cm.doc,simpleSelection(anchor,head),sel_dontScroll) -if(anchor.bad||head.bad){cm.curOp.selectionChanged=true}})}};ContentEditableInput.prototype.pollContent=function pollContent(){if(this.readDOMTimeout!=null){clearTimeout(this.readDOMTimeout) -this.readDOMTimeout=null} -var cm=this.cm,display=cm.display,sel=cm.doc.sel.primary() -var from=sel.from(),to=sel.to() -if(from.ch==0&&from.line>cm.firstLine()) -{from=Pos(from.line-1,getLine(cm.doc,from.line-1).length)} -if(to.ch==getLine(cm.doc,to.line).text.length&&to.line<cm.lastLine()) -{to=Pos(to.line+1,0)} -if(from.line<display.viewFrom||to.line>display.viewTo-1){return false} -var fromIndex,fromLine,fromNode -if(from.line==display.viewFrom||(fromIndex=findViewIndex(cm,from.line))==0){fromLine=lineNo(display.view[0].line) -fromNode=display.view[0].node}else{fromLine=lineNo(display.view[fromIndex].line) -fromNode=display.view[fromIndex-1].node.nextSibling} -var toIndex=findViewIndex(cm,to.line) -var toLine,toNode -if(toIndex==display.view.length-1){toLine=display.viewTo-1 -toNode=display.lineDiv.lastChild}else{toLine=lineNo(display.view[toIndex+1].line)-1 -toNode=display.view[toIndex+1].node.previousSibling} -if(!fromNode){return false} -var newText=cm.doc.splitLines(domTextBetween(cm,fromNode,toNode,fromLine,toLine)) -var oldText=getBetween(cm.doc,Pos(fromLine,0),Pos(toLine,getLine(cm.doc,toLine).text.length)) -while(newText.length>1&&oldText.length>1){if(lst(newText)==lst(oldText)){newText.pop();oldText.pop();toLine--} -else if(newText[0]==oldText[0]){newText.shift();oldText.shift();fromLine++} -else{break}} -var cutFront=0,cutEnd=0 -var newTop=newText[0],oldTop=oldText[0],maxCutFront=Math.min(newTop.length,oldTop.length) -while(cutFront<maxCutFront&&newTop.charCodeAt(cutFront)==oldTop.charCodeAt(cutFront)) -{++cutFront} -var newBot=lst(newText),oldBot=lst(oldText) -var maxCutEnd=Math.min(newBot.length-(newText.length==1?cutFront:0),oldBot.length-(oldText.length==1?cutFront:0)) -while(cutEnd<maxCutEnd&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1)) -{++cutEnd} -if(newText.length==1&&oldText.length==1&&fromLine==from.line){while(cutFront&&cutFront>from.ch&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1)){cutFront-- -cutEnd++}} -newText[newText.length-1]=newBot.slice(0,newBot.length-cutEnd).replace(/^\u200b+/,"") -newText[0]=newText[0].slice(cutFront).replace(/\u200b+$/,"") -var chFrom=Pos(fromLine,cutFront) -var chTo=Pos(toLine,oldText.length?lst(oldText).length-cutEnd:0) -if(newText.length>1||newText[0]||cmp(chFrom,chTo)){replaceRange(cm.doc,newText,chFrom,chTo,"+input") -return true}};ContentEditableInput.prototype.ensurePolled=function ensurePolled(){this.forceCompositionEnd()};ContentEditableInput.prototype.reset=function reset(){this.forceCompositionEnd()};ContentEditableInput.prototype.forceCompositionEnd=function forceCompositionEnd(){if(!this.composing){return} -clearTimeout(this.readDOMTimeout) -this.composing=null -this.updateFromDOM() -this.div.blur() -this.div.focus()};ContentEditableInput.prototype.readFromDOMSoon=function readFromDOMSoon(){var this$1=this;if(this.readDOMTimeout!=null){return} -this.readDOMTimeout=setTimeout(function(){this$1.readDOMTimeout=null -if(this$1.composing){if(this$1.composing.done){this$1.composing=null} -else{return}} -this$1.updateFromDOM()},80)};ContentEditableInput.prototype.updateFromDOM=function updateFromDOM(){var this$1=this;if(this.cm.isReadOnly()||!this.pollContent()) -{runInOp(this.cm,function(){return regChange(this$1.cm);})}};ContentEditableInput.prototype.setUneditable=function setUneditable(node){node.contentEditable="false"};ContentEditableInput.prototype.onKeyPress=function onKeyPress(e){if(e.charCode==0){return} -e.preventDefault() -if(!this.cm.isReadOnly()) -{operation(this.cm,applyTextInput)(this.cm,String.fromCharCode(e.charCode==null?e.keyCode:e.charCode),0)}};ContentEditableInput.prototype.readOnlyChanged=function readOnlyChanged(val){this.div.contentEditable=String(val!="nocursor")};ContentEditableInput.prototype.onContextMenu=function onContextMenu(){};ContentEditableInput.prototype.resetPosition=function resetPosition(){};ContentEditableInput.prototype.needsContentAttribute=true -function posToDOM(cm,pos){var view=findViewForLine(cm,pos.line) -if(!view||view.hidden){return null} -var line=getLine(cm.doc,pos.line) -var info=mapFromLineView(view,line,pos.line) -var order=getOrder(line,cm.doc.direction),side="left" -if(order){var partPos=getBidiPartAt(order,pos.ch) -side=partPos%2?"right":"left"} -var result=nodeAndOffsetInLineMap(info.map,pos.ch,side) -result.offset=result.collapse=="right"?result.end:result.start -return result} -function isInGutter(node){for(var scan=node;scan;scan=scan.parentNode) -{if(/CodeMirror-gutter-wrapper/.test(scan.className)){return true}} -return false} -function badPos(pos,bad){if(bad){pos.bad=true;}return pos} -function domTextBetween(cm,from,to,fromLine,toLine){var text="",closing=false,lineSep=cm.doc.lineSeparator() -function recognizeMarker(id){return function(marker){return marker.id==id;}} -function close(){if(closing){text+=lineSep -closing=false}} -function addText(str){if(str){close() -text+=str}} -function walk(node){if(node.nodeType==1){var cmText=node.getAttribute("cm-text") -if(cmText!=null){addText(cmText||node.textContent.replace(/\u200b/g,"")) -return} -var markerID=node.getAttribute("cm-marker"),range -if(markerID){var found=cm.findMarks(Pos(fromLine,0),Pos(toLine+1,0),recognizeMarker(+markerID)) -if(found.length&&(range=found[0].find())) -{addText(getBetween(cm.doc,range.from,range.to).join(lineSep))} -return} -if(node.getAttribute("contenteditable")=="false"){return} -var isBlock=/^(pre|div|p)$/i.test(node.nodeName) -if(isBlock){close()} -for(var i=0;i<node.childNodes.length;i++) -{walk(node.childNodes[i])} -if(isBlock){closing=true}}else if(node.nodeType==3){addText(node.nodeValue)}} -for(;;){walk(from) -if(from==to){break} -from=from.nextSibling} -return text} -function domToPos(cm,node,offset){var lineNode -if(node==cm.display.lineDiv){lineNode=cm.display.lineDiv.childNodes[offset] -if(!lineNode){return badPos(cm.clipPos(Pos(cm.display.viewTo-1)),true)} -node=null;offset=0}else{for(lineNode=node;;lineNode=lineNode.parentNode){if(!lineNode||lineNode==cm.display.lineDiv){return null} -if(lineNode.parentNode&&lineNode.parentNode==cm.display.lineDiv){break}}} -for(var i=0;i<cm.display.view.length;i++){var lineView=cm.display.view[i] -if(lineView.node==lineNode) -{return locateNodeInLineView(lineView,node,offset)}}} -function locateNodeInLineView(lineView,node,offset){var wrapper=lineView.text.firstChild,bad=false -if(!node||!contains(wrapper,node)){return badPos(Pos(lineNo(lineView.line),0),true)} -if(node==wrapper){bad=true -node=wrapper.childNodes[offset] -offset=0 -if(!node){var line=lineView.rest?lst(lineView.rest):lineView.line -return badPos(Pos(lineNo(line),line.text.length),bad)}} -var textNode=node.nodeType==3?node:null,topNode=node -if(!textNode&&node.childNodes.length==1&&node.firstChild.nodeType==3){textNode=node.firstChild -if(offset){offset=textNode.nodeValue.length}} -while(topNode.parentNode!=wrapper){topNode=topNode.parentNode} -var measure=lineView.measure,maps=measure.maps -function find(textNode,topNode,offset){for(var i=-1;i<(maps?maps.length:0);i++){var map=i<0?measure.map:maps[i] -for(var j=0;j<map.length;j+=3){var curNode=map[j+2] -if(curNode==textNode||curNode==topNode){var line=lineNo(i<0?lineView.line:lineView.rest[i]) -var ch=map[j]+offset -if(offset<0||curNode!=textNode){ch=map[j+(offset?1:0)]} -return Pos(line,ch)}}}} -var found=find(textNode,topNode,offset) -if(found){return badPos(found,bad)} -for(var after=topNode.nextSibling,dist=textNode?textNode.nodeValue.length-offset:0;after;after=after.nextSibling){found=find(after,after.firstChild,0) -if(found) -{return badPos(Pos(found.line,found.ch-dist),bad)} -else -{dist+=after.textContent.length}} -for(var before=topNode.previousSibling,dist$1=offset;before;before=before.previousSibling){found=find(before,before.firstChild,-1) -if(found) -{return badPos(Pos(found.line,found.ch+dist$1),bad)} -else -{dist$1+=before.textContent.length}}} -var TextareaInput=function TextareaInput(cm){this.cm=cm -this.prevInput="" -this.pollingFast=false -this.polling=new Delayed() -this.inaccurateSelection=false -this.hasSelection=false -this.composing=null};TextareaInput.prototype.init=function init(display){var this$1=this;var input=this,cm=this.cm -var div=this.wrapper=hiddenTextarea() -var te=this.textarea=div.firstChild -display.wrapper.insertBefore(div,display.wrapper.firstChild) -if(ios){te.style.width="0px"} -on(te,"input",function(){if(ie&&ie_version>=9&&this$1.hasSelection){this$1.hasSelection=null} -input.poll()}) -on(te,"paste",function(e){if(signalDOMEvent(cm,e)||handlePaste(e,cm)){return} -cm.state.pasteIncoming=true -input.fastPoll()}) -function prepareCopyCut(e){if(signalDOMEvent(cm,e)){return} -if(cm.somethingSelected()){setLastCopied({lineWise:false,text:cm.getSelections()}) -if(input.inaccurateSelection){input.prevInput="" -input.inaccurateSelection=false -te.value=lastCopied.text.join("\n") -selectInput(te)}}else if(!cm.options.lineWiseCopyCut){return}else{var ranges=copyableRanges(cm) -setLastCopied({lineWise:true,text:ranges.text}) -if(e.type=="cut"){cm.setSelections(ranges.ranges,null,sel_dontScroll)}else{input.prevInput="" -te.value=ranges.text.join("\n") -selectInput(te)}} -if(e.type=="cut"){cm.state.cutIncoming=true}} -on(te,"cut",prepareCopyCut) -on(te,"copy",prepareCopyCut) -on(display.scroller,"paste",function(e){if(eventInWidget(display,e)||signalDOMEvent(cm,e)){return} -cm.state.pasteIncoming=true -input.focus()}) -on(display.lineSpace,"selectstart",function(e){if(!eventInWidget(display,e)){e_preventDefault(e)}}) -on(te,"compositionstart",function(){var start=cm.getCursor("from") -if(input.composing){input.composing.range.clear()} -input.composing={start:start,range:cm.markText(start,cm.getCursor("to"),{className:"CodeMirror-composing"})}}) -on(te,"compositionend",function(){if(input.composing){input.poll() -input.composing.range.clear() -input.composing=null}})};TextareaInput.prototype.prepareSelection=function prepareSelection$1(){var cm=this.cm,display=cm.display,doc=cm.doc -var result=prepareSelection(cm) -if(cm.options.moveInputWithCursor){var headPos=cursorCoords(cm,doc.sel.primary().head,"div") -var wrapOff=display.wrapper.getBoundingClientRect(),lineOff=display.lineDiv.getBoundingClientRect() -result.teTop=Math.max(0,Math.min(display.wrapper.clientHeight-10,headPos.top+lineOff.top-wrapOff.top)) -result.teLeft=Math.max(0,Math.min(display.wrapper.clientWidth-10,headPos.left+lineOff.left-wrapOff.left))} -return result};TextareaInput.prototype.showSelection=function showSelection(drawn){var cm=this.cm,display=cm.display -removeChildrenAndAdd(display.cursorDiv,drawn.cursors) -removeChildrenAndAdd(display.selectionDiv,drawn.selection) -if(drawn.teTop!=null){this.wrapper.style.top=drawn.teTop+"px" -this.wrapper.style.left=drawn.teLeft+"px"}};TextareaInput.prototype.reset=function reset(typing){if(this.contextMenuPending){return} -var minimal,selected,cm=this.cm,doc=cm.doc -if(cm.somethingSelected()){this.prevInput="" -var range=doc.sel.primary() -minimal=hasCopyEvent&&(range.to().line-range.from().line>100||(selected=cm.getSelection()).length>1000) -var content=minimal?"-":selected||cm.getSelection() -this.textarea.value=content -if(cm.state.focused){selectInput(this.textarea)} -if(ie&&ie_version>=9){this.hasSelection=content}}else if(!typing){this.prevInput=this.textarea.value="" -if(ie&&ie_version>=9){this.hasSelection=null}} -this.inaccurateSelection=minimal};TextareaInput.prototype.getField=function getField(){return this.textarea};TextareaInput.prototype.supportsTouch=function supportsTouch(){return false};TextareaInput.prototype.focus=function focus(){if(this.cm.options.readOnly!="nocursor"&&(!mobile||activeElt()!=this.textarea)){try{this.textarea.focus()} -catch(e){}}};TextareaInput.prototype.blur=function blur(){this.textarea.blur()};TextareaInput.prototype.resetPosition=function resetPosition(){this.wrapper.style.top=this.wrapper.style.left=0};TextareaInput.prototype.receivedFocus=function receivedFocus(){this.slowPoll()};TextareaInput.prototype.slowPoll=function slowPoll(){var this$1=this;if(this.pollingFast){return} -this.polling.set(this.cm.options.pollInterval,function(){this$1.poll() -if(this$1.cm.state.focused){this$1.slowPoll()}})};TextareaInput.prototype.fastPoll=function fastPoll(){var missed=false,input=this -input.pollingFast=true -function p(){var changed=input.poll() -if(!changed&&!missed){missed=true;input.polling.set(60,p)} -else{input.pollingFast=false;input.slowPoll()}} -input.polling.set(20,p)};TextareaInput.prototype.poll=function poll(){var this$1=this;var cm=this.cm,input=this.textarea,prevInput=this.prevInput -if(this.contextMenuPending||!cm.state.focused||(hasSelection(input)&&!prevInput&&!this.composing)||cm.isReadOnly()||cm.options.disableInput||cm.state.keySeq) -{return false} -var text=input.value -if(text==prevInput&&!cm.somethingSelected()){return false} -if(ie&&ie_version>=9&&this.hasSelection===text||mac&&/[\uf700-\uf7ff]/.test(text)){cm.display.input.reset() -return false} -if(cm.doc.sel==cm.display.selForContextMenu){var first=text.charCodeAt(0) -if(first==0x200b&&!prevInput){prevInput="\u200b"} -if(first==0x21da){this.reset();return this.cm.execCommand("undo")}} -var same=0,l=Math.min(prevInput.length,text.length) -while(same<l&&prevInput.charCodeAt(same)==text.charCodeAt(same)){++same} -runInOp(cm,function(){applyTextInput(cm,text.slice(same),prevInput.length-same,null,this$1.composing?"*compose":null) -if(text.length>1000||text.indexOf("\n")>-1){input.value=this$1.prevInput=""} -else{this$1.prevInput=text} -if(this$1.composing){this$1.composing.range.clear() -this$1.composing.range=cm.markText(this$1.composing.start,cm.getCursor("to"),{className:"CodeMirror-composing"})}}) -return true};TextareaInput.prototype.ensurePolled=function ensurePolled(){if(this.pollingFast&&this.poll()){this.pollingFast=false}};TextareaInput.prototype.onKeyPress=function onKeyPress(){if(ie&&ie_version>=9){this.hasSelection=null} -this.fastPoll()};TextareaInput.prototype.onContextMenu=function onContextMenu(e){var input=this,cm=input.cm,display=cm.display,te=input.textarea -var pos=posFromMouse(cm,e),scrollPos=display.scroller.scrollTop -if(!pos||presto){return} -var reset=cm.options.resetSelectionOnContextMenu -if(reset&&cm.doc.sel.contains(pos)==-1) -{operation(cm,setSelection)(cm.doc,simpleSelection(pos),sel_dontScroll)} -var oldCSS=te.style.cssText,oldWrapperCSS=input.wrapper.style.cssText -input.wrapper.style.cssText="position: absolute" -var wrapperBox=input.wrapper.getBoundingClientRect() -te.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-wrapperBox.top-5)+"px; left: "+(e.clientX-wrapperBox.left-5)+"px;\n z-index: 1000; background: "+(ie?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);" -var oldScrollY -if(webkit){oldScrollY=window.scrollY} -display.input.focus() -if(webkit){window.scrollTo(null,oldScrollY)} -display.input.reset() -if(!cm.somethingSelected()){te.value=input.prevInput=" "} -input.contextMenuPending=true -display.selForContextMenu=cm.doc.sel -clearTimeout(display.detectingSelectAll) -function prepareSelectAllHack(){if(te.selectionStart!=null){var selected=cm.somethingSelected() -var extval="\u200b"+(selected?te.value:"") -te.value="\u21da" -te.value=extval -input.prevInput=selected?"":"\u200b" -te.selectionStart=1;te.selectionEnd=extval.length -display.selForContextMenu=cm.doc.sel}} -function rehide(){input.contextMenuPending=false -input.wrapper.style.cssText=oldWrapperCSS -te.style.cssText=oldCSS -if(ie&&ie_version<9){display.scrollbars.setScrollTop(display.scroller.scrollTop=scrollPos)} -if(te.selectionStart!=null){if(!ie||(ie&&ie_version<9)){prepareSelectAllHack()} -var i=0,poll=function(){if(display.selForContextMenu==cm.doc.sel&&te.selectionStart==0&&te.selectionEnd>0&&input.prevInput=="\u200b"){operation(cm,selectAll)(cm)}else if(i++<10){display.detectingSelectAll=setTimeout(poll,500)}else{display.selForContextMenu=null -display.input.reset()}} -display.detectingSelectAll=setTimeout(poll,200)}} -if(ie&&ie_version>=9){prepareSelectAllHack()} -if(captureRightClick){e_stop(e) -var mouseup=function(){off(window,"mouseup",mouseup) -setTimeout(rehide,20)} -on(window,"mouseup",mouseup)}else{setTimeout(rehide,50)}};TextareaInput.prototype.readOnlyChanged=function readOnlyChanged(val){if(!val){this.reset()}};TextareaInput.prototype.setUneditable=function setUneditable(){};TextareaInput.prototype.needsContentAttribute=false -function fromTextArea(textarea,options){options=options?copyObj(options):{} -options.value=textarea.value -if(!options.tabindex&&textarea.tabIndex) -{options.tabindex=textarea.tabIndex} -if(!options.placeholder&&textarea.placeholder) -{options.placeholder=textarea.placeholder} -if(options.autofocus==null){var hasFocus=activeElt() -options.autofocus=hasFocus==textarea||textarea.getAttribute("autofocus")!=null&&hasFocus==document.body} -function save(){textarea.value=cm.getValue()} -var realSubmit -if(textarea.form){on(textarea.form,"submit",save) -if(!options.leaveSubmitMethodAlone){var form=textarea.form -realSubmit=form.submit -try{var wrappedSubmit=form.submit=function(){save() -form.submit=realSubmit -form.submit() -form.submit=wrappedSubmit}}catch(e){}}} -options.finishInit=function(cm){cm.save=save -cm.getTextArea=function(){return textarea;} -cm.toTextArea=function(){cm.toTextArea=isNaN -save() -textarea.parentNode.removeChild(cm.getWrapperElement()) -textarea.style.display="" -if(textarea.form){off(textarea.form,"submit",save) -if(typeof textarea.form.submit=="function") -{textarea.form.submit=realSubmit}}}} -textarea.style.display="none" -var cm=CodeMirror(function(node){return textarea.parentNode.insertBefore(node,textarea.nextSibling);},options) -return cm} -function addLegacyProps(CodeMirror){CodeMirror.off=off -CodeMirror.on=on -CodeMirror.wheelEventPixels=wheelEventPixels -CodeMirror.Doc=Doc -CodeMirror.splitLines=splitLinesAuto -CodeMirror.countColumn=countColumn -CodeMirror.findColumn=findColumn -CodeMirror.isWordChar=isWordCharBasic -CodeMirror.Pass=Pass -CodeMirror.signal=signal -CodeMirror.Line=Line -CodeMirror.changeEnd=changeEnd -CodeMirror.scrollbarModel=scrollbarModel -CodeMirror.Pos=Pos -CodeMirror.cmpPos=cmp -CodeMirror.modes=modes -CodeMirror.mimeModes=mimeModes -CodeMirror.resolveMode=resolveMode -CodeMirror.getMode=getMode -CodeMirror.modeExtensions=modeExtensions -CodeMirror.extendMode=extendMode -CodeMirror.copyState=copyState -CodeMirror.startState=startState -CodeMirror.innerMode=innerMode -CodeMirror.commands=commands -CodeMirror.keyMap=keyMap -CodeMirror.keyName=keyName -CodeMirror.isModifierKey=isModifierKey -CodeMirror.lookupKey=lookupKey -CodeMirror.normalizeKeyMap=normalizeKeyMap -CodeMirror.StringStream=StringStream -CodeMirror.SharedTextMarker=SharedTextMarker -CodeMirror.TextMarker=TextMarker -CodeMirror.LineWidget=LineWidget -CodeMirror.e_preventDefault=e_preventDefault -CodeMirror.e_stopPropagation=e_stopPropagation -CodeMirror.e_stop=e_stop -CodeMirror.addClass=addClass -CodeMirror.contains=contains -CodeMirror.rmClass=rmClass -CodeMirror.keyNames=keyNames} -defineOptions(CodeMirror) -addEditorMethods(CodeMirror) -var dontDelegate="iter insert remove copy getEditor constructor".split(" ") -for(var prop in Doc.prototype){if(Doc.prototype.hasOwnProperty(prop)&&indexOf(dontDelegate,prop)<0) -{CodeMirror.prototype[prop]=(function(method){return function(){return method.apply(this.doc,arguments)}})(Doc.prototype[prop])}} -eventMixin(Doc) -CodeMirror.inputStyles={"textarea":TextareaInput,"contenteditable":ContentEditableInput} -CodeMirror.defineMode=function(name){if(!CodeMirror.defaults.mode&&name!="null"){CodeMirror.defaults.mode=name} -defineMode.apply(this,arguments)} -CodeMirror.defineMIME=defineMIME -CodeMirror.defineMode("null",function(){return({token:function(stream){return stream.skipToEnd();}});}) -CodeMirror.defineMIME("text/plain","null") -CodeMirror.defineExtension=function(name,func){CodeMirror.prototype[name]=func} -CodeMirror.defineDocExtension=function(name,func){Doc.prototype[name]=func} -CodeMirror.fromTextArea=fromTextArea -addLegacyProps(CodeMirror) -CodeMirror.version="5.25.1" -return CodeMirror;})));;(function(mod){if(typeof exports=="object"&&typeof module=="object") -mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd) -define(["../../lib/codemirror"],mod);else -mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.multiplexingMode=function(outer){var others=Array.prototype.slice.call(arguments,1);function indexOf(string,pattern,from,returnEnd){if(typeof pattern=="string"){var found=string.indexOf(pattern,from);return returnEnd&&found>-1?found+pattern.length:found;} -var m=pattern.exec(from?string.slice(from):string);return m?m.index+from+(returnEnd?m[0].length:0):-1;} -return{startState:function(){return{outer:CodeMirror.startState(outer),innerActive:null,inner:null};},copyState:function(state){return{outer:CodeMirror.copyState(outer,state.outer),innerActive:state.innerActive,inner:state.innerActive&&CodeMirror.copyState(state.innerActive.mode,state.inner)};},token:function(stream,state){if(!state.innerActive){var cutOff=Infinity,oldContent=stream.string;for(var i=0;i<others.length;++i){var other=others[i];var found=indexOf(oldContent,other.open,stream.pos);if(found==stream.pos){if(!other.parseDelimiters)stream.match(other.open);state.innerActive=other;state.inner=CodeMirror.startState(other.mode,outer.indent?outer.indent(state.outer,""):0);return other.delimStyle&&(other.delimStyle+" "+other.delimStyle+"-open");}else if(found!=-1&&found<cutOff){cutOff=found;}} -if(cutOff!=Infinity)stream.string=oldContent.slice(0,cutOff);var outerToken=outer.token(stream,state.outer);if(cutOff!=Infinity)stream.string=oldContent;return outerToken;}else{var curInner=state.innerActive,oldContent=stream.string;if(!curInner.close&&stream.sol()){state.innerActive=state.inner=null;return this.token(stream,state);} -var found=curInner.close?indexOf(oldContent,curInner.close,stream.pos,curInner.parseDelimiters):-1;if(found==stream.pos&&!curInner.parseDelimiters){stream.match(curInner.close);state.innerActive=state.inner=null;return curInner.delimStyle&&(curInner.delimStyle+" "+curInner.delimStyle+"-close");} -if(found>-1)stream.string=oldContent.slice(0,found);var innerToken=curInner.mode.token(stream,state.inner);if(found>-1)stream.string=oldContent;if(found==stream.pos&&curInner.parseDelimiters) -state.innerActive=state.inner=null;if(curInner.innerStyle){if(innerToken)innerToken=innerToken+" "+curInner.innerStyle;else innerToken=curInner.innerStyle;} -return innerToken;}},indent:function(state,textAfter){var mode=state.innerActive?state.innerActive.mode:outer;if(!mode.indent)return CodeMirror.Pass;return mode.indent(state.innerActive?state.inner:state.outer,textAfter);},blankLine:function(state){var mode=state.innerActive?state.innerActive.mode:outer;if(mode.blankLine){mode.blankLine(state.innerActive?state.inner:state.outer);} -if(!state.innerActive){for(var i=0;i<others.length;++i){var other=others[i];if(other.open==="\n"){state.innerActive=other;state.inner=CodeMirror.startState(other.mode,mode.indent?mode.indent(state.outer,""):0);}}}else if(state.innerActive.close==="\n"){state.innerActive=state.inner=null;}},electricChars:outer.electricChars,innerMode:function(state){return state.inner?{state:state.inner,mode:state.innerActive.mode}:{state:state.outer,mode:outer};}};};});;(function(mod){if(typeof exports=="object"&&typeof module=="object") -mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd) -define(["../../lib/codemirror"],mod);else -mod(CodeMirror);})(function(CodeMirror){var ie_lt8=/MSIE \d/.test(navigator.userAgent)&&(document.documentMode==null||document.documentMode<8);var Pos=CodeMirror.Pos;var matching={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"};function findMatchingBracket(cm,where,strict,config){var line=cm.getLineHandle(where.line),pos=where.ch-1;var match=(pos>=0&&matching[line.text.charAt(pos)])||matching[line.text.charAt(++pos)];if(!match)return null;var dir=match.charAt(1)==">"?1:-1;if(strict&&(dir>0)!=(pos==where.ch))return null;var style=cm.getTokenTypeAt(Pos(where.line,pos+1));var found=scanForBracket(cm,Pos(where.line,pos+(dir>0?1:0)),dir,style||null,config);if(found==null)return null;return{from:Pos(where.line,pos),to:found&&found.pos,match:found&&found.ch==match.charAt(0),forward:dir>0};} -function scanForBracket(cm,where,dir,style,config){var maxScanLen=(config&&config.maxScanLineLength)||10000;var maxScanLines=(config&&config.maxScanLines)||1000;var stack=[];var re=config&&config.bracketRegex?config.bracketRegex:/[(){}[\]]/;var lineEnd=dir>0?Math.min(where.line+maxScanLines,cm.lastLine()+1):Math.max(cm.firstLine()-1,where.line-maxScanLines);for(var lineNo=where.line;lineNo!=lineEnd;lineNo+=dir){var line=cm.getLine(lineNo);if(!line)continue;var pos=dir>0?0:line.length-1,end=dir>0?line.length:-1;if(line.length>maxScanLen)continue;if(lineNo==where.line)pos=where.ch-(dir<0?1:0);for(;pos!=end;pos+=dir){var ch=line.charAt(pos);if(re.test(ch)&&(style===undefined||cm.getTokenTypeAt(Pos(lineNo,pos+1))==style)){var match=matching[ch];if((match.charAt(1)==">")==(dir>0))stack.push(ch);else if(!stack.length)return{pos:Pos(lineNo,pos),ch:ch};else stack.pop();}}} -return lineNo-dir==(dir>0?cm.lastLine():cm.firstLine())?false:null;} -function matchBrackets(cm,autoclear,config){var maxHighlightLen=cm.state.matchBrackets.maxHighlightLineLength||1000;var marks=[],ranges=cm.listSelections();for(var i=0;i<ranges.length;i++){var match=ranges[i].empty()&&findMatchingBracket(cm,ranges[i].head,false,config);if(match&&cm.getLine(match.from.line).length<=maxHighlightLen){var style=match.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";marks.push(cm.markText(match.from,Pos(match.from.line,match.from.ch+1),{className:style}));if(match.to&&cm.getLine(match.to.line).length<=maxHighlightLen) -marks.push(cm.markText(match.to,Pos(match.to.line,match.to.ch+1),{className:style}));}} -if(marks.length){if(ie_lt8&&cm.state.focused)cm.focus();var clear=function(){cm.operation(function(){for(var i=0;i<marks.length;i++)marks[i].clear();});};if(autoclear)setTimeout(clear,800);else return clear;}} -var currentlyHighlighted=null;function doMatchBrackets(cm){cm.operation(function(){if(currentlyHighlighted){currentlyHighlighted();currentlyHighlighted=null;} -currentlyHighlighted=matchBrackets(cm,false,cm.state.matchBrackets);});} -CodeMirror.defineOption("matchBrackets",false,function(cm,val,old){if(old&&old!=CodeMirror.Init){cm.off("cursorActivity",doMatchBrackets);if(currentlyHighlighted){currentlyHighlighted();currentlyHighlighted=null;}} -if(val){cm.state.matchBrackets=typeof val=="object"?val:{};cm.on("cursorActivity",doMatchBrackets);}});CodeMirror.defineExtension("matchBrackets",function(){matchBrackets(this,true);});CodeMirror.defineExtension("findMatchingBracket",function(pos,strict,config){return findMatchingBracket(this,pos,strict,config);});CodeMirror.defineExtension("scanForBracket",function(pos,dir,style,config){return scanForBracket(this,pos,dir,style,config);});});;(function(mod){if(typeof exports=="object"&&typeof module=="object") -mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd) -define(["../../lib/codemirror"],mod);else -mod(CodeMirror);})(function(CodeMirror){var defaults={pairs:"()[]{}''\"\"",triples:"",explode:"[]{}"};var Pos=CodeMirror.Pos;CodeMirror.defineOption("autoCloseBrackets",false,function(cm,val,old){if(old&&old!=CodeMirror.Init){cm.removeKeyMap(keyMap);cm.state.closeBrackets=null;} -if(val){cm.state.closeBrackets=val;cm.addKeyMap(keyMap);}});function getOption(conf,name){if(name=="pairs"&&typeof conf=="string")return conf;if(typeof conf=="object"&&conf[name]!=null)return conf[name];return defaults[name];} -var bind=defaults.pairs+"`";var keyMap={Backspace:handleBackspace,Enter:handleEnter};for(var i=0;i<bind.length;i++) -keyMap["'"+bind.charAt(i)+"'"]=handler(bind.charAt(i));function handler(ch){return function(cm){return handleChar(cm,ch);};} -function getConfig(cm){var deflt=cm.state.closeBrackets;if(!deflt||deflt.override)return deflt;var mode=cm.getModeAt(cm.getCursor());return mode.closeBrackets||deflt;} -function handleBackspace(cm){var conf=getConfig(cm);if(!conf||cm.getOption("disableInput"))return CodeMirror.Pass;var pairs=getOption(conf,"pairs");var ranges=cm.listSelections();for(var i=0;i<ranges.length;i++){if(!ranges[i].empty())return CodeMirror.Pass;var around=charsAround(cm,ranges[i].head);if(!around||pairs.indexOf(around)%2!=0)return CodeMirror.Pass;} -for(var i=ranges.length-1;i>=0;i--){var cur=ranges[i].head;cm.replaceRange("",Pos(cur.line,cur.ch-1),Pos(cur.line,cur.ch+1),"+delete");}} -function handleEnter(cm){var conf=getConfig(cm);var explode=conf&&getOption(conf,"explode");if(!explode||cm.getOption("disableInput"))return CodeMirror.Pass;var ranges=cm.listSelections();for(var i=0;i<ranges.length;i++){if(!ranges[i].empty())return CodeMirror.Pass;var around=charsAround(cm,ranges[i].head);if(!around||explode.indexOf(around)%2!=0)return CodeMirror.Pass;} -cm.operation(function(){cm.replaceSelection("\n\n",null);cm.execCommand("goCharLeft");ranges=cm.listSelections();for(var i=0;i<ranges.length;i++){var line=ranges[i].head.line;cm.indentLine(line,null,true);cm.indentLine(line+1,null,true);}});} -function contractSelection(sel){var inverted=CodeMirror.cmpPos(sel.anchor,sel.head)>0;return{anchor:new Pos(sel.anchor.line,sel.anchor.ch+(inverted?-1:1)),head:new Pos(sel.head.line,sel.head.ch+(inverted?1:-1))};} -function handleChar(cm,ch){var conf=getConfig(cm);if(!conf||cm.getOption("disableInput"))return CodeMirror.Pass;var pairs=getOption(conf,"pairs");var pos=pairs.indexOf(ch);if(pos==-1)return CodeMirror.Pass;var triples=getOption(conf,"triples");var identical=pairs.charAt(pos+1)==ch;var ranges=cm.listSelections();var opening=pos%2==0;var type;for(var i=0;i<ranges.length;i++){var range=ranges[i],cur=range.head,curType;var next=cm.getRange(cur,Pos(cur.line,cur.ch+1));if(opening&&!range.empty()){curType="surround";}else if((identical||!opening)&&next==ch){if(identical&&stringStartsAfter(cm,cur)) -curType="both";else if(triples.indexOf(ch)>=0&&cm.getRange(cur,Pos(cur.line,cur.ch+3))==ch+ch+ch) -curType="skipThree";else -curType="skip";}else if(identical&&cur.ch>1&&triples.indexOf(ch)>=0&&cm.getRange(Pos(cur.line,cur.ch-2),cur)==ch+ch&&(cur.ch<=2||cm.getRange(Pos(cur.line,cur.ch-3),Pos(cur.line,cur.ch-2))!=ch)){curType="addFour";}else if(identical){if(!CodeMirror.isWordChar(next)&&enteringString(cm,cur,ch))curType="both";else return CodeMirror.Pass;}else if(opening&&(cm.getLine(cur.line).length==cur.ch||isClosingBracket(next,pairs)||/\s/.test(next))){curType="both";}else{return CodeMirror.Pass;} -if(!type)type=curType;else if(type!=curType)return CodeMirror.Pass;} -var left=pos%2?pairs.charAt(pos-1):ch;var right=pos%2?ch:pairs.charAt(pos+1);cm.operation(function(){if(type=="skip"){cm.execCommand("goCharRight");}else if(type=="skipThree"){for(var i=0;i<3;i++) -cm.execCommand("goCharRight");}else if(type=="surround"){var sels=cm.getSelections();for(var i=0;i<sels.length;i++) -sels[i]=left+sels[i]+right;cm.replaceSelections(sels,"around");sels=cm.listSelections().slice();for(var i=0;i<sels.length;i++) -sels[i]=contractSelection(sels[i]);cm.setSelections(sels);}else if(type=="both"){cm.replaceSelection(left+right,null);cm.triggerElectric(left+right);cm.execCommand("goCharLeft");}else if(type=="addFour"){cm.replaceSelection(left+left+left+left,"before");cm.execCommand("goCharRight");}});} -function isClosingBracket(ch,pairs){var pos=pairs.lastIndexOf(ch);return pos>-1&&pos%2==1;} -function charsAround(cm,pos){var str=cm.getRange(Pos(pos.line,pos.ch-1),Pos(pos.line,pos.ch+1));return str.length==2?str:null;} -function enteringString(cm,pos,ch){var line=cm.getLine(pos.line);var token=cm.getTokenAt(pos);if(/\bstring2?\b/.test(token.type)||stringStartsAfter(cm,pos))return false;var stream=new CodeMirror.StringStream(line.slice(0,pos.ch)+ch+line.slice(pos.ch),4);stream.pos=stream.start=token.start;for(;;){var type1=cm.getMode().token(stream,token.state);if(stream.pos>=pos.ch+1)return/\bstring2?\b/.test(type1);stream.start=stream.pos;}} -function stringStartsAfter(cm,pos){var token=cm.getTokenAt(Pos(pos.line,pos.ch+1)) -return/\bstring/.test(token.type)&&token.start==pos.ch}});;(function(mod){if(typeof exports=="object"&&typeof module=="object") -mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd) -define(["../../lib/codemirror"],mod);else -mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.defineOption("styleSelectedText",false,function(cm,val,old){var prev=old&&old!=CodeMirror.Init;if(val&&!prev){cm.state.markedSelection=[];cm.state.markedSelectionStyle=typeof val=="string"?val:"CodeMirror-selectedtext";reset(cm);cm.on("cursorActivity",onCursorActivity);cm.on("change",onChange);}else if(!val&&prev){cm.off("cursorActivity",onCursorActivity);cm.off("change",onChange);clear(cm);cm.state.markedSelection=cm.state.markedSelectionStyle=null;}});function onCursorActivity(cm){if(cm.state.markedSelection) -cm.operation(function(){update(cm);});} -function onChange(cm){if(cm.state.markedSelection&&cm.state.markedSelection.length) -cm.operation(function(){clear(cm);});} -var CHUNK_SIZE=8;var Pos=CodeMirror.Pos;var cmp=CodeMirror.cmpPos;function coverRange(cm,from,to,addAt){if(cmp(from,to)==0)return;var array=cm.state.markedSelection;var cls=cm.state.markedSelectionStyle;for(var line=from.line;;){var start=line==from.line?from:Pos(line,0);var endLine=line+CHUNK_SIZE,atEnd=endLine>=to.line;var end=atEnd?to:Pos(endLine,0);var mark=cm.markText(start,end,{className:cls});if(addAt==null)array.push(mark);else array.splice(addAt++,0,mark);if(atEnd)break;line=endLine;}} -function clear(cm){var array=cm.state.markedSelection;for(var i=0;i<array.length;++i)array[i].clear();array.length=0;} -function reset(cm){clear(cm);var ranges=cm.listSelections();for(var i=0;i<ranges.length;i++) -coverRange(cm,ranges[i].from(),ranges[i].to());} -function update(cm){if(!cm.somethingSelected())return clear(cm);if(cm.listSelections().length>1)return reset(cm);var from=cm.getCursor("start"),to=cm.getCursor("end");var array=cm.state.markedSelection;if(!array.length)return coverRange(cm,from,to);var coverStart=array[0].find(),coverEnd=array[array.length-1].find();if(!coverStart||!coverEnd||to.line-from.line<CHUNK_SIZE||cmp(from,coverEnd.to)>=0||cmp(to,coverStart.from)<=0) -return reset(cm);while(cmp(from,coverStart.from)>0){array.shift().clear();coverStart=array[0].find();} -if(cmp(from,coverStart.from)<0){if(coverStart.to.line-from.line<CHUNK_SIZE){array.shift().clear();coverRange(cm,from,coverStart.to,0);}else{coverRange(cm,from,coverStart.from,0);}} -while(cmp(to,coverEnd.to)<0){array.pop().clear();coverEnd=array[array.length-1].find();} -if(cmp(to,coverEnd.to)>0){if(to.line-coverEnd.from.line<CHUNK_SIZE){array.pop().clear();coverRange(cm,coverEnd.from,to);}else{coverRange(cm,coverEnd.to,to);}}}});;(function(mod){if(typeof exports=="object"&&typeof module=="object") -mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd) -define(["../../lib/codemirror"],mod);else -mod(CodeMirror);})(function(CodeMirror){"use strict";var noOptions={};var nonWS=/[^\s\u00a0]/;var Pos=CodeMirror.Pos;function firstNonWS(str){var found=str.search(nonWS);return found==-1?0:found;} -CodeMirror.commands.toggleComment=function(cm){cm.toggleComment();};CodeMirror.defineExtension("toggleComment",function(options){if(!options)options=noOptions;var cm=this;var minLine=Infinity,ranges=this.listSelections(),mode=null;for(var i=ranges.length-1;i>=0;i--){var from=ranges[i].from(),to=ranges[i].to();if(from.line>=minLine)continue;if(to.line>=minLine)to=Pos(minLine,0);minLine=from.line;if(mode==null){if(cm.uncomment(from,to,options))mode="un";else{cm.lineComment(from,to,options);mode="line";}}else if(mode=="un"){cm.uncomment(from,to,options);}else{cm.lineComment(from,to,options);}}});function probablyInsideString(cm,pos,line){return/\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line,0)))&&!/^[\'\"\`]/.test(line)} -function getMode(cm,pos){var mode=cm.getMode() -return mode.useInnerComments===false||!mode.innerMode?mode:cm.getModeAt(pos)} -CodeMirror.defineExtension("lineComment",function(from,to,options){if(!options)options=noOptions;var self=this,mode=getMode(self,from);var firstLine=self.getLine(from.line);if(firstLine==null||probablyInsideString(self,from,firstLine))return;var commentString=options.lineComment||mode.lineComment;if(!commentString){if(options.blockCommentStart||mode.blockCommentStart){options.fullLines=true;self.blockComment(from,to,options);} -return;} -var end=Math.min(to.ch!=0||to.line==from.line?to.line+1:to.line,self.lastLine()+1);var pad=options.padding==null?" ":options.padding;var blankLines=options.commentBlankLines||from.line==to.line;self.operation(function(){if(options.indent){var baseString=null;for(var i=from.line;i<end;++i){var line=self.getLine(i);var whitespace=line.slice(0,firstNonWS(line));if(baseString==null||baseString.length>whitespace.length){baseString=whitespace;}} -for(var i=from.line;i<end;++i){var line=self.getLine(i),cut=baseString.length;if(!blankLines&&!nonWS.test(line))continue;if(line.slice(0,cut)!=baseString)cut=firstNonWS(line);self.replaceRange(baseString+commentString+pad,Pos(i,0),Pos(i,cut));}}else{for(var i=from.line;i<end;++i){if(blankLines||nonWS.test(self.getLine(i))) -self.replaceRange(commentString+pad,Pos(i,0));}}});});CodeMirror.defineExtension("blockComment",function(from,to,options){if(!options)options=noOptions;var self=this,mode=getMode(self,from);var startString=options.blockCommentStart||mode.blockCommentStart;var endString=options.blockCommentEnd||mode.blockCommentEnd;if(!startString||!endString){if((options.lineComment||mode.lineComment)&&options.fullLines!=false) -self.lineComment(from,to,options);return;} -if(/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line,0))))return -var end=Math.min(to.line,self.lastLine());if(end!=from.line&&to.ch==0&&nonWS.test(self.getLine(end)))--end;var pad=options.padding==null?" ":options.padding;if(from.line>end)return;self.operation(function(){if(options.fullLines!=false){var lastLineHasText=nonWS.test(self.getLine(end));self.replaceRange(pad+endString,Pos(end));self.replaceRange(startString+pad,Pos(from.line,0));var lead=options.blockCommentLead||mode.blockCommentLead;if(lead!=null)for(var i=from.line+1;i<=end;++i) -if(i!=end||lastLineHasText) -self.replaceRange(lead+pad,Pos(i,0));}else{self.replaceRange(endString,to);self.replaceRange(startString,from);}});});CodeMirror.defineExtension("uncomment",function(from,to,options){if(!options)options=noOptions;var self=this,mode=getMode(self,from);var end=Math.min(to.ch!=0||to.line==from.line?to.line:to.line-1,self.lastLine()),start=Math.min(from.line,end);var lineString=options.lineComment||mode.lineComment,lines=[];var pad=options.padding==null?" ":options.padding,didSomething;lineComment:{if(!lineString)break lineComment;for(var i=start;i<=end;++i){var line=self.getLine(i);var found=line.indexOf(lineString);if(found>-1&&!/comment/.test(self.getTokenTypeAt(Pos(i,found+1))))found=-1;if(found==-1&&nonWS.test(line))break lineComment;if(found>-1&&nonWS.test(line.slice(0,found)))break lineComment;lines.push(line);} -self.operation(function(){for(var i=start;i<=end;++i){var line=lines[i-start];var pos=line.indexOf(lineString),endPos=pos+lineString.length;if(pos<0)continue;if(line.slice(endPos,endPos+pad.length)==pad)endPos+=pad.length;didSomething=true;self.replaceRange("",Pos(i,pos),Pos(i,endPos));}});if(didSomething)return true;} -var startString=options.blockCommentStart||mode.blockCommentStart;var endString=options.blockCommentEnd||mode.blockCommentEnd;if(!startString||!endString)return false;var lead=options.blockCommentLead||mode.blockCommentLead;var startLine=self.getLine(start),open=startLine.indexOf(startString) -if(open==-1)return false -var endLine=end==start?startLine:self.getLine(end) -var close=endLine.indexOf(endString,end==start?open+startString.length:0);if(close==-1&&start!=end){endLine=self.getLine(--end);close=endLine.indexOf(endString);} -var insideStart=Pos(start,open+1),insideEnd=Pos(end,close+1) -if(close==-1||!/comment/.test(self.getTokenTypeAt(insideStart))||!/comment/.test(self.getTokenTypeAt(insideEnd))||self.getRange(insideStart,insideEnd,"\n").indexOf(endString)>-1) -return false;var lastStart=startLine.lastIndexOf(startString,from.ch);var firstEnd=lastStart==-1?-1:startLine.slice(0,from.ch).indexOf(endString,lastStart+startString.length);if(lastStart!=-1&&firstEnd!=-1&&firstEnd+endString.length!=from.ch)return false;firstEnd=endLine.indexOf(endString,to.ch);var almostLastStart=endLine.slice(to.ch).lastIndexOf(startString,firstEnd-to.ch);lastStart=(firstEnd==-1||almostLastStart==-1)?-1:to.ch+almostLastStart;if(firstEnd!=-1&&lastStart!=-1&&lastStart!=to.ch)return false;self.operation(function(){self.replaceRange("",Pos(end,close-(pad&&endLine.slice(close-pad.length,close)==pad?pad.length:0)),Pos(end,close+endString.length));var openEnd=open+startString.length;if(pad&&startLine.slice(openEnd,openEnd+pad.length)==pad)openEnd+=pad.length;self.replaceRange("",Pos(start,open),Pos(start,openEnd));if(lead)for(var i=start+1;i<=end;++i){var line=self.getLine(i),found=line.indexOf(lead);if(found==-1||nonWS.test(line.slice(0,found)))continue;var foundEnd=found+lead.length;if(pad&&line.slice(foundEnd,foundEnd+pad.length)==pad)foundEnd+=pad.length;self.replaceRange("",Pos(i,found),Pos(i,foundEnd));}});return true;});});;(function(mod){if(typeof exports=="object"&&typeof module=="object") -mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd) -define(["../../lib/codemirror"],mod);else -mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.overlayMode=function(base,overlay,combine){return{startState:function(){return{base:CodeMirror.startState(base),overlay:CodeMirror.startState(overlay),basePos:0,baseCur:null,overlayPos:0,overlayCur:null,streamSeen:null};},copyState:function(state){return{base:CodeMirror.copyState(base,state.base),overlay:CodeMirror.copyState(overlay,state.overlay),basePos:state.basePos,baseCur:null,overlayPos:state.overlayPos,overlayCur:null};},token:function(stream,state){if(stream!=state.streamSeen||Math.min(state.basePos,state.overlayPos)<stream.start){state.streamSeen=stream;state.basePos=state.overlayPos=stream.start;} -if(stream.start==state.basePos){state.baseCur=base.token(stream,state.base);state.basePos=stream.pos;} -if(stream.start==state.overlayPos){stream.pos=stream.start;state.overlayCur=overlay.token(stream,state.overlay);state.overlayPos=stream.pos;} -stream.pos=Math.min(state.basePos,state.overlayPos);if(state.overlayCur==null)return state.baseCur;else if(state.baseCur!=null&&state.overlay.combineTokens||combine&&state.overlay.combineTokens==null) -return state.baseCur+" "+state.overlayCur;else return state.overlayCur;},indent:base.indent&&function(state,textAfter){return base.indent(state.base,textAfter);},electricChars:base.electricChars,innerMode:function(state){return{state:state.base,mode:base};},blankLine:function(state){var baseToken,overlayToken;if(base.blankLine)baseToken=base.blankLine(state.base);if(overlay.blankLine)overlayToken=overlay.blankLine(state.overlay);return overlayToken==null?baseToken:(combine&&baseToken!=null?baseToken+" "+overlayToken:overlayToken);}};};});;(function(mod){if(typeof exports=="object"&&typeof module=="object") -mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd) -define(["../../lib/codemirror"],mod);else -mod(CodeMirror);})(function(CodeMirror){"use strict";var WRAP_CLASS="CodeMirror-activeline";var BACK_CLASS="CodeMirror-activeline-background";var GUTT_CLASS="CodeMirror-activeline-gutter";CodeMirror.defineOption("styleActiveLine",false,function(cm,val,old){var prev=old==CodeMirror.Init?false:old;if(val==prev)return -if(prev){cm.off("beforeSelectionChange",selectionChange);clearActiveLines(cm);delete cm.state.activeLines;} -if(val){cm.state.activeLines=[];updateActiveLines(cm,cm.listSelections());cm.on("beforeSelectionChange",selectionChange);}});function clearActiveLines(cm){for(var i=0;i<cm.state.activeLines.length;i++){cm.removeLineClass(cm.state.activeLines[i],"wrap",WRAP_CLASS);cm.removeLineClass(cm.state.activeLines[i],"background",BACK_CLASS);cm.removeLineClass(cm.state.activeLines[i],"gutter",GUTT_CLASS);}} -function sameArray(a,b){if(a.length!=b.length)return false;for(var i=0;i<a.length;i++) -if(a[i]!=b[i])return false;return true;} -function updateActiveLines(cm,ranges){var active=[];for(var i=0;i<ranges.length;i++){var range=ranges[i];var option=cm.getOption("styleActiveLine");if(typeof option=="object"&&option.nonEmpty?range.anchor.line!=range.head.line:!range.empty()) -continue -var line=cm.getLineHandleVisualStart(range.head.line);if(active[active.length-1]!=line)active.push(line);} -if(sameArray(cm.state.activeLines,active))return;cm.operation(function(){clearActiveLines(cm);for(var i=0;i<active.length;i++){cm.addLineClass(active[i],"wrap",WRAP_CLASS);cm.addLineClass(active[i],"background",BACK_CLASS);cm.addLineClass(active[i],"gutter",GUTT_CLASS);} -cm.state.activeLines=active;});} -function selectionChange(cm,sel){updateActiveLines(cm,sel.ranges);}});;Runtime.cachedResources["cm/codemirror.css"]="/* BASICS */\n\n.CodeMirror {\n /* Set height, width, borders, and global font properties here */\n font-family: monospace;\n height: 300px;\n color: black;\n}\n\n/* PADDING */\n\n.CodeMirror-lines {\n padding: 4px 0; /* Vertical padding around content */\n}\n.CodeMirror pre {\n padding: 0 4px; /* Horizontal padding of content */\n}\n\n.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n background-color: white; /* The little square between H and V scrollbars */\n}\n\n/* GUTTER */\n\n.CodeMirror-gutters {\n border-right: 1px solid #ddd;\n background-color: #f7f7f7;\n white-space: nowrap;\n}\n.CodeMirror-linenumbers {}\n.CodeMirror-linenumber {\n padding: 0 3px 0 5px;\n min-width: 20px;\n text-align: right;\n color: #999;\n white-space: nowrap;\n}\n\n.CodeMirror-guttermarker { color: black; }\n.CodeMirror-guttermarker-subtle { color: #999; }\n\n/* CURSOR */\n\n.CodeMirror-cursor {\n border-left: 1px solid black;\n border-right: none;\n width: 0;\n}\n/* Shown when moving in bi-directional text */\n.CodeMirror div.CodeMirror-secondarycursor {\n border-left: 1px solid silver;\n}\n.cm-fat-cursor .CodeMirror-cursor {\n width: auto;\n border: 0 !important;\n background: #7e7;\n}\n.cm-fat-cursor div.CodeMirror-cursors {\n z-index: 1;\n}\n\n.cm-animate-fat-cursor {\n width: auto;\n border: 0;\n -webkit-animation: blink 1.06s steps(1) infinite;\n -moz-animation: blink 1.06s steps(1) infinite;\n animation: blink 1.06s steps(1) infinite;\n background-color: #7e7;\n}\n@-moz-keyframes blink {\n 0% {}\n 50% { background-color: transparent; }\n 100% {}\n}\n@-webkit-keyframes blink {\n 0% {}\n 50% { background-color: transparent; }\n 100% {}\n}\n@keyframes blink {\n 0% {}\n 50% { background-color: transparent; }\n 100% {}\n}\n\n/* Can style cursor different in overwrite (non-insert) mode */\n.CodeMirror-overwrite .CodeMirror-cursor {}\n\n.cm-tab { display: inline-block; text-decoration: inherit; }\n\n.CodeMirror-rulers {\n position: absolute;\n left: 0; right: 0; top: -50px; bottom: -20px;\n overflow: hidden;\n}\n.CodeMirror-ruler {\n border-left: 1px solid #ccc;\n top: 0; bottom: 0;\n position: absolute;\n}\n\n/* DEFAULT THEME */\n\n.cm-s-default .cm-header {color: blue;}\n.cm-s-default .cm-quote {color: #090;}\n.cm-negative {color: #d44;}\n.cm-positive {color: #292;}\n.cm-header, .cm-strong {font-weight: bold;}\n.cm-em {font-style: italic;}\n.cm-link {text-decoration: underline;}\n.cm-strikethrough {text-decoration: line-through;}\n\n.cm-s-default .cm-keyword {color: #708;}\n.cm-s-default .cm-atom {color: #219;}\n.cm-s-default .cm-number {color: #164;}\n.cm-s-default .cm-def {color: #00f;}\n.cm-s-default .cm-variable,\n.cm-s-default .cm-punctuation,\n.cm-s-default .cm-property,\n.cm-s-default .cm-operator {}\n.cm-s-default .cm-variable-2 {color: #05a;}\n.cm-s-default .cm-variable-3 {color: #085;}\n.cm-s-default .cm-comment {color: #a50;}\n.cm-s-default .cm-string {color: #a11;}\n.cm-s-default .cm-string-2 {color: #f50;}\n.cm-s-default .cm-meta {color: #555;}\n.cm-s-default .cm-qualifier {color: #555;}\n.cm-s-default .cm-builtin {color: #30a;}\n.cm-s-default .cm-bracket {color: #997;}\n.cm-s-default .cm-tag {color: #170;}\n.cm-s-default .cm-attribute {color: #00c;}\n.cm-s-default .cm-hr {color: #999;}\n.cm-s-default .cm-link {color: #00c;}\n\n.cm-s-default .cm-error {color: #f00;}\n.cm-invalidchar {color: #f00;}\n\n.CodeMirror-composing { border-bottom: 2px solid; }\n\n/* Default styles for common addons */\n\ndiv.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}\n.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }\n.CodeMirror-activeline-background {background: #e8f2ff;}\n\n/* STOP */\n\n/* The rest of this file contains styles related to the mechanics of\n the editor. You probably shouldn't touch them. */\n\n.CodeMirror {\n position: relative;\n overflow: hidden;\n background: white;\n}\n\n.CodeMirror-scroll {\n overflow: scroll !important; /* Things will break if this is overridden */\n /* 30px is the magic margin used to hide the element's real scrollbars */\n /* See overflow: hidden in .CodeMirror */\n margin-bottom: -30px; margin-right: -30px;\n padding-bottom: 30px;\n height: 100%;\n outline: none; /* Prevent dragging from highlighting the element */\n position: relative;\n}\n.CodeMirror-sizer {\n position: relative;\n border-right: 30px solid transparent;\n}\n\n/* The fake, visible scrollbars. Used to force redraw during scrolling\n before actual scrolling happens, thus preventing shaking and\n flickering artifacts. */\n.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n position: absolute;\n z-index: 6;\n display: none;\n}\n.CodeMirror-vscrollbar {\n right: 0; top: 0;\n overflow-x: hidden;\n overflow-y: scroll;\n}\n.CodeMirror-hscrollbar {\n bottom: 0; left: 0;\n overflow-y: hidden;\n overflow-x: scroll;\n}\n.CodeMirror-scrollbar-filler {\n right: 0; bottom: 0;\n}\n.CodeMirror-gutter-filler {\n left: 0; bottom: 0;\n}\n\n.CodeMirror-gutters {\n position: absolute; left: 0; top: 0;\n min-height: 100%;\n z-index: 3;\n}\n.CodeMirror-gutter {\n white-space: normal;\n height: 100%;\n display: inline-block;\n vertical-align: top;\n margin-bottom: -30px;\n}\n.CodeMirror-gutter-wrapper {\n position: absolute;\n z-index: 4;\n background: none !important;\n border: none !important;\n}\n.CodeMirror-gutter-background {\n position: absolute;\n top: 0; bottom: 0;\n z-index: 4;\n}\n.CodeMirror-gutter-elt {\n position: absolute;\n cursor: default;\n z-index: 4;\n}\n.CodeMirror-gutter-wrapper ::selection { background-color: transparent }\n.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }\n\n.CodeMirror-lines {\n cursor: text;\n min-height: 1px; /* prevents collapsing before first draw */\n}\n.CodeMirror pre {\n /* Reset some styles that the rest of the page might have set */\n -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;\n border-width: 0;\n background: transparent;\n font-family: inherit;\n font-size: inherit;\n margin: 0;\n white-space: pre;\n word-wrap: normal;\n line-height: inherit;\n color: inherit;\n z-index: 2;\n position: relative;\n overflow: visible;\n -webkit-tap-highlight-color: transparent;\n -webkit-font-variant-ligatures: contextual;\n font-variant-ligatures: contextual;\n}\n.CodeMirror-wrap pre {\n word-wrap: break-word;\n white-space: pre-wrap;\n word-break: normal;\n}\n\n.CodeMirror-linebackground {\n position: absolute;\n left: 0; right: 0; top: 0; bottom: 0;\n z-index: 0;\n}\n\n.CodeMirror-linewidget {\n position: relative;\n z-index: 2;\n overflow: auto;\n}\n\n.CodeMirror-widget {}\n\n.CodeMirror-rtl pre { direction: rtl; }\n\n.CodeMirror-code {\n outline: none;\n}\n\n/* Force content-box sizing for the elements where we expect it */\n.CodeMirror-scroll,\n.CodeMirror-sizer,\n.CodeMirror-gutter,\n.CodeMirror-gutters,\n.CodeMirror-linenumber {\n -moz-box-sizing: content-box;\n box-sizing: content-box;\n}\n\n.CodeMirror-measure {\n position: absolute;\n width: 100%;\n height: 0;\n overflow: hidden;\n visibility: hidden;\n}\n\n.CodeMirror-cursor {\n position: absolute;\n pointer-events: none;\n}\n.CodeMirror-measure pre { position: static; }\n\ndiv.CodeMirror-cursors {\n visibility: hidden;\n position: relative;\n z-index: 3;\n}\ndiv.CodeMirror-dragcursors {\n visibility: visible;\n}\n\n.CodeMirror-focused div.CodeMirror-cursors {\n visibility: visible;\n}\n\n.CodeMirror-selected { background: #d9d9d9; }\n.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }\n.CodeMirror-crosshair { cursor: crosshair; }\n.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }\n.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }\n\n.cm-searching {\n background: #ffa;\n background: rgba(255, 255, 0, .4);\n}\n\n/* Used to force a border model for a node */\n.cm-force-border { padding-right: .1px; }\n\n@media print {\n /* Hide the cursor when printing */\n .CodeMirror div.CodeMirror-cursors {\n visibility: hidden;\n }\n}\n\n/* See issue #2901 */\n.cm-tab-wrap-hack:after { content: ''; }\n\n/* Help users use markselection to safely style text background */\nspan.CodeMirror-selectedtext { background: none; }\n\n/*# sourceURL=cm/codemirror.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/color_picker/color_picker_module.js b/src/cobalt/debug/content/devtools/color_picker/color_picker_module.js deleted file mode 100644 index 0728f2f..0000000 --- a/src/cobalt/debug/content/devtools/color_picker/color_picker_module.js +++ /dev/null
@@ -1,203 +0,0 @@ -ColorPicker.ContrastInfo=class{constructor(){this._fgColor=null;this._bgColor=null;this._gradient=null;this._contrastRatio=null;this._contrastRatioThresholds=null;this._colorString='';} -setContrastInfo(contrastInfo){this._contrastRatio=null;this._contrastRatioThresholds=null;this._bgColor=null;this._gradient=null;if(contrastInfo.computedFontSize&&contrastInfo.computedFontWeight&&contrastInfo.computedBodyFontSize){var isLargeFont=ColorPicker.ContrastInfo.computeIsLargeFont(contrastInfo.computedFontSize,contrastInfo.computedFontWeight,contrastInfo.computedBodyFontSize);this._contrastRatioThresholds=ColorPicker.ContrastInfo._ContrastThresholds[(isLargeFont?'largeFont':'normalFont')];} -if(!contrastInfo.backgroundColors||!contrastInfo.backgroundColors.length) -return;if(contrastInfo.backgroundColors.length>1){this._gradient=[];for(var bgColorText of contrastInfo.backgroundColors){var bgColor=Common.Color.parse(bgColorText);if(bgColor) -this._gradient.push(bgColor);} -if(this._fgColor) -this._updateBgColorFromGradient();}else{var bgColorText=contrastInfo.backgroundColors[0];var bgColor=Common.Color.parse(bgColorText);if(bgColor) -this.setBgColor(bgColor);}} -setColor(hsva,colorString){this._fgColor=Common.Color.fromHSVA(hsva);this._colorString=colorString;if(this._gradient) -this._updateBgColorFromGradient();else -this._updateContrastRatio();} -contrastRatio(){return this._contrastRatio;} -colorString(){return this._colorString;} -hsva(){return this._fgColor.hsva();} -setBgColor(bgColor){this._bgColor=bgColor;if(!this._fgColor) -return;var fgRGBA=this._fgColor.rgba();if(bgColor.hasAlpha){var blendedRGBA=[];Common.Color.blendColors(bgColor.rgba(),fgRGBA,blendedRGBA);this._bgColor=new Common.Color(blendedRGBA,Common.Color.Format.RGBA);} -this._contrastRatio=Common.Color.calculateContrastRatio(fgRGBA,this._bgColor.rgba());} -bgColor(){return this._bgColor;} -gradient(){return this._gradient;} -_updateContrastRatio(){if(!this._bgColor||!this._fgColor) -return;this._contrastRatio=Common.Color.calculateContrastRatio(this._fgColor.rgba(),this._bgColor.rgba());} -_updateBgColorFromGradient(){if(!this._gradient||!this._fgColor) -return;var fgLuminance=Common.Color.luminance(this._fgColor.rgba());var luminanceDiff=2;var closestBgColor=null;for(var bgColor of this._gradient){var bgLuminance=Common.Color.luminance(bgColor.rgba());var currentLuminanceDiff=Math.abs(fgLuminance-bgLuminance);if(currentLuminanceDiff<luminanceDiff){closestBgColor=bgColor;luminanceDiff=currentLuminanceDiff;}} -if(closestBgColor) -this.setBgColor(closestBgColor);} -contrastRatioThreshold(level){if(!this._contrastRatioThresholds) -return null;return this._contrastRatioThresholds[level];} -static computeIsLargeFont(fontSize,fontWeight,bodyFontSize){const boldWeights=['bold','bolder','600','700','800','900'];var fontSizePx=parseFloat(fontSize.replace('px',''));var isBold=(boldWeights.indexOf(fontWeight)!==-1);if(bodyFontSize){var bodyFontSizePx=parseFloat(bodyFontSize.replace('px',''));if(isBold){if(fontSizePx>=(bodyFontSizePx*1.2)) -return true;}else if(fontSizePx>=(bodyFontSizePx*1.5)){return true;} -return false;} -var fontSizePt=Math.ceil(fontSizePx*72/96);if(isBold) -return fontSizePt>=14;else -return fontSizePt>=18;}};ColorPicker.ContrastInfo._ContrastThresholds={largeFont:{AA:3.0,AAA:4.5},normalFont:{AA:4.5,AAA:7.0}};ColorPicker.ContrastOverlay=class{constructor(colorElement,contentElement,toggleMainColorPickerCallback){this._contrastInfo=new ColorPicker.ContrastInfo();var contrastRatioSVG=colorElement.createSVGChild('svg','spectrum-contrast-container fill');this._contrastRatioLine=contrastRatioSVG.createSVGChild('path','spectrum-contrast-line');this._contrastValueBubble=colorElement.createChild('button','spectrum-contrast-info');this._contrastValueBubble.classList.add('force-white-icons');UI.ARIAUtils.setExpanded(this._contrastValueBubble,false);this._contrastValueBubble.createChild('span','low-contrast').textContent=Common.UIString('Low contrast');this._contrastValue=this._contrastValueBubble.createChild('span','value');this._contrastValueBubble.appendChild(UI.Icon.create('smallicon-contrast-ratio'));this._contrastValueBubble.title=Common.UIString('Click to toggle contrast ratio details');this._contrastValueBubble.addEventListener('mousedown',this._toggleContrastDetails.bind(this),true);this._contrastValueBubble.addEventListener('click',this._onToggleClick.bind(this),true);this._contrastValueBubbleBoxInWindow=new AnchorBox(0,0,0,0);this._contrastDetails=new ColorPicker.ContrastDetails(this._contrastInfo,contentElement,toggleMainColorPickerCallback,this._update.bind(this));UI.ARIAUtils.setControls(this._contrastValueBubble,this._contrastDetails.element());this._width=0;this._height=0;this._contrastRatioLineThrottler=new Common.Throttler(0);this._drawContrastRatioLineBound=this._drawContrastRatioLine.bind(this);this._hueForCurrentLine=null;this._alphaForCurrentLine=null;this._bgColorForCurrentLine=null;} -setContrastInfo(contrastInfo){this._contrastInfo.setContrastInfo(contrastInfo);this._update();} -setColor(hsva,colorString){this._contrastInfo.setColor(hsva,colorString);this._update();} -moveAwayFrom(x,y){if(!this._contrastValueBubbleBoxInWindow.width||!this._contrastValueBubbleBoxInWindow.height||!this._contrastValueBubbleBoxInWindow.contains(x,y)) -return;var bubble=this._contrastValueBubble;if(bubble.offsetWidth>((bubble.offsetParent.offsetWidth/2)-10)) -bubble.classList.toggle('contrast-info-top');else -bubble.classList.toggle('contrast-info-left');} -_update(){UI.ARIAUtils.setExpanded(this._contrastValueBubble,this._contrastDetails.visible());var AA=this._contrastInfo.contrastRatioThreshold('AA');if(!AA) -return;this._contrastValue.textContent='';if(this._contrastInfo.contrastRatio()!==null){this._contrastValue.textContent=this._contrastInfo.contrastRatio().toFixed(2);this._contrastRatioLineThrottler.schedule(this._drawContrastRatioLineBound);var passesAA=this._contrastInfo.contrastRatio()>=AA;this._contrastValueBubble.classList.toggle('contrast-fail',!passesAA);this._contrastValueBubble.classList.remove('contrast-unknown');}else{this._contrastValueBubble.classList.remove('contrast-fail');this._contrastValueBubble.classList.add('contrast-unknown');} -this._contrastValueBubbleBoxInWindow=this._contrastValueBubble.boxInWindow();this._contrastDetails.update();} -show(width,height,dragX,dragY){if(this._contrastInfo.contrastRatioThreshold('AA')===null){this.hide();return;} -this._width=width;this._height=height;this._update();this._contrastValueBubble.classList.remove('hidden');this.moveAwayFrom(dragX,dragY);} -hide(){this._contrastValueBubble.classList.add('hidden');} -_toggleContrastDetails(event){if('button'in event&&event.button!==0) -return;event.consume();this._contrastDetails.toggleVisible();UI.ARIAUtils.setExpanded(this._contrastValueBubble,this._contrastDetails.visible());} -_onToggleClick(event){if(event.screenX||event.screenY) -return;event.consume();this._toggleContrastDetails(event);} -_drawContrastRatioLine(){var width=this._width;var height=this._height;var requiredContrast=this._contrastInfo.contrastRatioThreshold('AA');if(!width||!height||!requiredContrast) -return Promise.resolve();const dS=0.02;const epsilon=0.0002;const H=0;const S=1;const V=2;const A=3;var hsva=this._contrastInfo.hsva();var bgColor=this._contrastInfo.bgColor();if(!hsva||!bgColor) -return Promise.resolve();var bgColorString=bgColor.asString(Common.Color.Format.RGBA);if(hsva[H]===this._hueForCurrentLine&&hsva[A]===this._alphaForCurrentLine&&bgColorString===this._bgColorForCurrentLine) -return Promise.resolve();var fgRGBA=[];Common.Color.hsva2rgba(hsva,fgRGBA);var bgRGBA=bgColor.rgba();var bgLuminance=Common.Color.luminance(bgRGBA);var blendedRGBA=[];Common.Color.blendColors(fgRGBA,bgRGBA,blendedRGBA);var fgLuminance=Common.Color.luminance(blendedRGBA);this._contrastValueBubble.classList.toggle('light',fgLuminance>0.5);var fgIsLighter=fgLuminance>bgLuminance;var desiredLuminance=Common.Color.desiredLuminance(bgLuminance,requiredContrast,fgIsLighter);var lastV=hsva[V];var currentSlope=0;var candidateHSVA=[hsva[H],0,0,hsva[A]];var pathBuilder=[];var candidateRGBA=[];Common.Color.hsva2rgba(candidateHSVA,candidateRGBA);Common.Color.blendColors(candidateRGBA,bgRGBA,blendedRGBA);function updateCandidateAndComputeDelta(index,x){candidateHSVA[index]=x;Common.Color.hsva2rgba(candidateHSVA,candidateRGBA);Common.Color.blendColors(candidateRGBA,bgRGBA,blendedRGBA);return Common.Color.luminance(blendedRGBA)-desiredLuminance;} -function approach(index){var x=candidateHSVA[index];var multiplier=1;var dLuminance=updateCandidateAndComputeDelta(index,x);var previousSign=Math.sign(dLuminance);for(var guard=100;guard;guard--){if(Math.abs(dLuminance)<epsilon) -return x;var sign=Math.sign(dLuminance);if(sign!==previousSign){multiplier/=2;previousSign=sign;}else if(x<0||x>1){return null;} -x+=multiplier*(index===V?-dLuminance:dLuminance);dLuminance=updateCandidateAndComputeDelta(index,x);} -console.error('Loop exited unexpectedly');return null;} -for(var s=0;s<1+dS;s+=dS){s=Math.min(1,s);candidateHSVA[S]=s;candidateHSVA[V]=lastV+currentSlope*dS;var v=approach(V);if(v===null) -break;currentSlope=s===0?0:(v-lastV)/dS;lastV=v;pathBuilder.push(pathBuilder.length?'L':'M');pathBuilder.push((s*width).toFixed(2));pathBuilder.push(((1-v)*height).toFixed(2));} -if(s<1+dS){s-=dS;candidateHSVA[V]=1;s=approach(S);if(s!==null) -pathBuilder=pathBuilder.concat(['L',(s*width).toFixed(2),'-0.1']);} -this._contrastRatioLine.setAttribute('d',pathBuilder.join(' '));this._bgColorForCurrentLine=bgColorString;this._hueForCurrentLine=hsva[H];this._alphaForCurrentLine=hsva[A];return Promise.resolve();}};ColorPicker.ContrastDetails=class{constructor(contrastInfo,contentElement,toggleMainColorPickerCallback,updateContrastOverlayCallback){this._contrastInfo=contrastInfo;this._toggleMainColorPicker=toggleMainColorPickerCallback;this._updateContrastOverlayCallback=updateContrastOverlayCallback;this._visible=false;this._contrastDetails=contentElement.createChild('div','spectrum-contrast-details');this._contrastDetails.id='contrast-ratio-details';var contrastValueRow=this._contrastDetails.createChild('div');contrastValueRow.createTextChild(Common.UIString('Contrast Ratio'));contrastValueRow.createTextChild(' ');var linkName=Common.UIString('Color and contrast on Web Fundamentals');var contrastLink=UI.createExternalLink('https://developers.google.com/web/fundamentals/accessibility/accessible-styles#color_and_contrast',linkName,'contrast-link');contrastLink.textContent='';contrastValueRow.appendChild(contrastLink);UI.ARIAUtils.setAccessibleName(contrastLink,linkName);contrastLink.appendChild(UI.Icon.create('mediumicon-info'));this._contrastValueBubble=contrastValueRow.createChild('span','contrast-details-value force-white-icons');this._contrastValue=this._contrastValueBubble.createChild('span');this._contrastValueBubbleIcons=[];this._contrastValueBubbleIcons.push(this._contrastValueBubble.appendChild(UI.Icon.create('smallicon-checkmark-square')));this._contrastValueBubbleIcons.push(this._contrastValueBubble.appendChild(UI.Icon.create('smallicon-checkmark-behind')));this._contrastValueBubbleIcons.push(this._contrastValueBubble.appendChild(UI.Icon.create('smallicon-no')));this._contrastValueBubble.addEventListener('mouseenter',this._toggleContrastValueHovered.bind(this));this._contrastValueBubble.addEventListener('mouseleave',this._toggleContrastValueHovered.bind(this));var toolbar=new UI.Toolbar('',contrastValueRow);var closeButton=new UI.ToolbarButton('Hide contrast ratio details','largeicon-delete');closeButton.addEventListener(UI.ToolbarButton.Events.Click,this.hide.bind(this));toolbar.appendToolbarItem(closeButton);this._chooseBgColor=this._contrastDetails.createChild('div','contrast-choose-bg-color');this._chooseBgColor.textContent=Common.UIString('Please select background color to compute contrast ratio.');this._contrastThresholds=this._contrastDetails.createChild('div','contrast-thresholds');this._contrastAA=this._contrastThresholds.createChild('div','contrast-threshold');this._contrastAA.appendChild(UI.Icon.create('smallicon-checkmark-square'));this._contrastAA.appendChild(UI.Icon.create('smallicon-no'));this._contrastPassFailAA=this._contrastAA.createChild('span','contrast-pass-fail');this._contrastAAA=this._contrastThresholds.createChild('div','contrast-threshold');this._contrastAAA.appendChild(UI.Icon.create('smallicon-checkmark-square'));this._contrastAAA.appendChild(UI.Icon.create('smallicon-no'));this._contrastPassFailAAA=this._contrastAAA.createChild('span','contrast-pass-fail');var bgColorRow=this._contrastDetails.createChild('div');bgColorRow.createTextChild(Common.UIString('Background color:'));this._bgColorSwatch=new ColorPicker.ContrastDetails.Swatch(bgColorRow);this._bgColorPicker=bgColorRow.createChild('button','background-color-picker');this._bgColorPicker.appendChild(UI.Icon.create('largeicon-eyedropper'));this._bgColorPicker.addEventListener('click',this._toggleBackgroundColorPicker.bind(this,undefined));this._bgColorPickedBound=this._bgColorPicked.bind(this);} -update(){var AA=this._contrastInfo.contrastRatioThreshold('AA');var AAA=this._contrastInfo.contrastRatioThreshold('AAA');if(!AA) -return;var contrastRatio=this._contrastInfo.contrastRatio();var bgColor=this._contrastInfo.bgColor();if(!contrastRatio||!bgColor){this._contrastValue.textContent='?';this._contrastValueBubble.classList.add('contrast-unknown');this._chooseBgColor.classList.remove('hidden');this._contrastThresholds.classList.add('hidden');return;} -this._chooseBgColor.classList.add('hidden');this._contrastThresholds.classList.remove('hidden');this._contrastValueBubble.classList.remove('contrast-unknown');this._contrastValue.textContent=contrastRatio.toFixed(2);var gradient=this._contrastInfo.gradient();if(gradient&&gradient.length){var darkest=null;var lightness=null;for(var color of gradient){var hsla=color.hsla();if(!darkest||hsla[2]<lightness){darkest=color;lightness=hsla[2];}} -var gradientStrings=gradient.map(color=>color.asString(Common.Color.Format.RGBA));var gradientString=String.sprintf('linear-gradient(90deg, %s)',gradientStrings.join(', '));this._bgColorSwatch.setColor((darkest),gradientString);}else{this._bgColorSwatch.setColor(bgColor);} -var passesAA=this._contrastInfo.contrastRatio()>=AA;this._contrastPassFailAA.textContent='';this._contrastPassFailAA.createTextChild(passesAA?Common.UIString('Passes '):Common.UIString('Fails '));this._contrastPassFailAA.createChild('strong').textContent=Common.UIString('AA (%s)',AA.toFixed(1));this._contrastAA.classList.toggle('pass',passesAA);this._contrastAA.classList.toggle('fail',!passesAA);var passesAAA=this._contrastInfo.contrastRatio()>=AAA;this._contrastPassFailAAA.textContent='';this._contrastPassFailAAA.createTextChild(passesAAA?Common.UIString('Passes '):Common.UIString('Fails '));this._contrastPassFailAAA.createChild('strong').textContent=Common.UIString('AAA (%s)',AAA.toFixed(1));this._contrastAAA.classList.toggle('pass',passesAAA);this._contrastAAA.classList.toggle('fail',!passesAAA);this._contrastValueBubble.classList.toggle('contrast-fail',!passesAA);this._contrastValueBubble.classList.toggle('contrast-aa',passesAA);this._contrastValueBubble.classList.toggle('contrast-aaa',passesAAA);this._contrastValueBubble.style.color=this._contrastInfo.colorString();for(var i=0;i<this._contrastValueBubbleIcons.length;i++) -this._contrastValueBubbleIcons[i].style.setProperty('background',this._contrastInfo.colorString(),'important');var isWhite=(this._contrastInfo.bgColor().hsla()[2]>0.9);this._contrastValueBubble.style.background=(this._contrastInfo.bgColor().asString(Common.Color.Format.RGBA));this._contrastValueBubble.classList.toggle('contrast-color-white',isWhite);if(isWhite){this._contrastValueBubble.style.removeProperty('border-color');}else{this._contrastValueBubble.style.borderColor=(this._contrastInfo.bgColor().asString(Common.Color.Format.RGBA));}} -toggleVisible(){this._visible=!this._visible;this._contrastDetails.classList.toggle('visible',this._visible);if(this._visible) -this._toggleMainColorPicker(false);else -this._toggleBackgroundColorPicker(false);} -hide(){this._contrastDetails.classList.remove('visible');this._toggleBackgroundColorPicker(false);this._updateContrastOverlayCallback();} -element(){return this._contrastDetails;} -visible(){return this._visible;} -_toggleBackgroundColorPicker(enabled){if(enabled===undefined){this._bgColorPicker.classList.toggle('active');enabled=this._bgColorPicker.classList.contains('active');}else{this._bgColorPicker.classList.toggle('active',enabled);} -UI.ARIAUtils.setPressed(this._bgColorPicker,enabled);InspectorFrontendHost.setEyeDropperActive(enabled);if(enabled){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._bgColorPickedBound);}else{InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._bgColorPickedBound);}} -_bgColorPicked(event){var rgbColor=(event.data);var rgba=[rgbColor.r,rgbColor.g,rgbColor.b,(rgbColor.a/2.55|0)/100];var color=Common.Color.fromRGBA(rgba);this._contrastInfo.setBgColor(color);this.update();this._updateContrastOverlayCallback();InspectorFrontendHost.bringToFront();} -_toggleContrastValueHovered(event){if(!this._contrastValueBubble.classList.contains('contrast-fail')) -return;if(event.type==='mouseenter'){this._contrastValueBubble.classList.add('hover');for(var i=0;i<this._contrastValueBubbleIcons.length;i++) -this._contrastValueBubbleIcons[i].style.setProperty('background','#333','important');}else{this._contrastValueBubble.classList.remove('hover');for(var i=0;i<this._contrastValueBubbleIcons.length;i++){this._contrastValueBubbleIcons[i].style.setProperty('background',this._contrastInfo.colorString(),'important');}}}};ColorPicker.ContrastDetails.Swatch=class{constructor(parentElement){this._parentElement=parentElement;this._swatchElement=parentElement.createChild('span','swatch contrast');this._swatchInnerElement=this._swatchElement.createChild('span','swatch-inner');} -setColor(color,colorString){if(!colorString) -colorString=(color.asString(Common.Color.Format.RGBA));this._swatchInnerElement.style.background=colorString;UI.ARIAUtils.setAccessibleName(this._swatchElement,colorString);this._swatchElement.classList.toggle('swatch-inner-white',color.hsla()[2]>0.9);}};;ColorPicker.Spectrum=class extends UI.VBox{constructor(){function appendSwitcherIcon(parentElement){var icon=parentElement.createSVGChild('svg');icon.setAttribute('height',16);icon.setAttribute('width',16);var path=icon.createSVGChild('path');path.setAttribute('d','M5,6 L11,6 L8,2 Z M5,10 L11,10 L8,14 Z');return icon;} -super(true);this.registerRequiredCSS('color_picker/spectrum.css');this.contentElement.tabIndex=0;this.setDefaultFocusedElement(this.contentElement);this._colorElement=this.contentElement.createChild('div','spectrum-color');this._colorDragElement=this._colorElement.createChild('div','spectrum-sat fill').createChild('div','spectrum-val fill').createChild('div','spectrum-dragger');this._dragX=0;this._dragY=0;if(Runtime.experiments.isEnabled('colorContrastRatio')){var boundToggleColorPicker=this._toggleColorPicker.bind(this);this._contrastOverlay=new ColorPicker.ContrastOverlay(this._colorElement,this.contentElement,boundToggleColorPicker);} -var toolbar=new UI.Toolbar('spectrum-eye-dropper',this.contentElement);this._colorPickerButton=new UI.ToolbarToggle(Common.UIString('Toggle color picker'),'largeicon-eyedropper');this._colorPickerButton.setToggled(true);this._colorPickerButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleColorPicker.bind(this,undefined));toolbar.appendToolbarItem(this._colorPickerButton);this._swatch=new ColorPicker.Spectrum.Swatch(this.contentElement);this._hueElement=this.contentElement.createChild('div','spectrum-hue');this._hueSlider=this._hueElement.createChild('div','spectrum-slider');this._alphaElement=this.contentElement.createChild('div','spectrum-alpha');this._alphaElementBackground=this._alphaElement.createChild('div','spectrum-alpha-background');this._alphaSlider=this._alphaElement.createChild('div','spectrum-slider');var displaySwitcher=this.contentElement.createChild('div','spectrum-display-switcher spectrum-switcher');appendSwitcherIcon(displaySwitcher);displaySwitcher.addEventListener('click',this._formatViewSwitch.bind(this));this._displayContainer=this.contentElement.createChild('div','spectrum-text source-code');this._textValues=[];for(var i=0;i<4;++i){var inputValue=UI.createInput('spectrum-text-value');this._displayContainer.appendChild(inputValue);inputValue.maxLength=4;this._textValues.push(inputValue);inputValue.addEventListener('keydown',this._inputChanged.bind(this),false);inputValue.addEventListener('input',this._inputChanged.bind(this),false);inputValue.addEventListener('mousewheel',this._inputChanged.bind(this),false);} -this._textLabels=this._displayContainer.createChild('div','spectrum-text-label');this._hexContainer=this.contentElement.createChild('div','spectrum-text spectrum-text-hex source-code');this._hexValue=UI.createInput('spectrum-text-value');this._hexContainer.appendChild(this._hexValue);this._hexValue.maxLength=9;this._hexValue.addEventListener('keydown',this._inputChanged.bind(this),false);this._hexValue.addEventListener('input',this._inputChanged.bind(this),false);this._hexValue.addEventListener('mousewheel',this._inputChanged.bind(this),false);var label=this._hexContainer.createChild('div','spectrum-text-label');label.textContent='HEX';UI.installDragHandle(this._hueElement,dragStart.bind(this,positionHue.bind(this)),positionHue.bind(this),null,'default');UI.installDragHandle(this._alphaElement,dragStart.bind(this,positionAlpha.bind(this)),positionAlpha.bind(this),null,'default');UI.installDragHandle(this._colorElement,dragStart.bind(this,positionColor.bind(this)),positionColor.bind(this),null,'default');this.element.classList.add('palettes-enabled','flex-none');this._palettes=new Map();this._palettePanel=this.contentElement.createChild('div','palette-panel');this._palettePanelShowing=false;this._paletteContainer=this.contentElement.createChild('div','spectrum-palette');this._paletteContainer.addEventListener('contextmenu',this._showPaletteColorContextMenu.bind(this,-1));this._shadesContainer=this.contentElement.createChild('div','palette-color-shades hidden');UI.installDragHandle(this._paletteContainer,this._paletteDragStart.bind(this),this._paletteDrag.bind(this),this._paletteDragEnd.bind(this),'default');var paletteSwitcher=this.contentElement.createChild('div','spectrum-palette-switcher spectrum-switcher');appendSwitcherIcon(paletteSwitcher);paletteSwitcher.addEventListener('click',this._togglePalettePanel.bind(this,true));this._deleteIconToolbar=new UI.Toolbar('delete-color-toolbar');this._deleteButton=new UI.ToolbarButton('','largeicon-trash-bin');this._deleteIconToolbar.appendToolbarItem(this._deleteButton);var overlay=this.contentElement.createChild('div','spectrum-overlay fill');overlay.addEventListener('click',this._togglePalettePanel.bind(this,false));this._addColorToolbar=new UI.Toolbar('add-color-toolbar');var addColorButton=new UI.ToolbarButton(Common.UIString('Add to palette'),'largeicon-add');addColorButton.addEventListener(UI.ToolbarButton.Events.Click,this._addColorToCustomPalette,this);this._addColorToolbar.appendToolbarItem(addColorButton);this._colorPickedBound=this._colorPicked.bind(this);this._loadPalettes();new ColorPicker.Spectrum.PaletteGenerator(this._generatedPaletteLoaded.bind(this));function dragStart(callback,event){this._hueAlphaLeft=this._hueElement.totalOffsetLeft();this._colorOffset=this._colorElement.totalOffset();callback(event);return true;} -function positionHue(event){var hsva=this._hsv.slice();hsva[0]=Number.constrain(1-(event.x-this._hueAlphaLeft)/this._hueAlphaWidth,0,1);this._innerSetColor(hsva,'',undefined,ColorPicker.Spectrum._ChangeSource.Other);} -function positionAlpha(event){var newAlpha=Math.round((event.x-this._hueAlphaLeft)/this._hueAlphaWidth*100)/100;var hsva=this._hsv.slice();hsva[3]=Number.constrain(newAlpha,0,1);this._innerSetColor(hsva,'',undefined,ColorPicker.Spectrum._ChangeSource.Other);} -function positionColor(event){var hsva=this._hsv.slice();hsva[1]=Number.constrain((event.x-this._colorOffset.left)/this.dragWidth,0,1);hsva[2]=Number.constrain(1-(event.y-this._colorOffset.top)/this.dragHeight,0,1);if(this._contrastOverlay) -this._contrastOverlay.moveAwayFrom(event.x,event.y);this._innerSetColor(hsva,'',undefined,ColorPicker.Spectrum._ChangeSource.Other);}} -_updatePalettePanel(){this._palettePanel.removeChildren();var title=this._palettePanel.createChild('div','palette-title');title.textContent=Common.UIString('Color Palettes');var toolbar=new UI.Toolbar('',this._palettePanel);var closeButton=new UI.ToolbarButton('Return to color picker','largeicon-delete');closeButton.addEventListener(UI.ToolbarButton.Events.Click,this._togglePalettePanel.bind(this,false));toolbar.appendToolbarItem(closeButton);for(var palette of this._palettes.values()) -this._palettePanel.appendChild(this._createPreviewPaletteElement(palette));} -_togglePalettePanel(show){if(this._palettePanelShowing===show) -return;if(show) -this._updatePalettePanel();this._focus();this._palettePanelShowing=show;this.contentElement.classList.toggle('palette-panel-showing',show);} -_focus(){if(this.isShowing()) -this.contentElement.focus();} -_createPaletteColor(colorText,animationDelay){var element=createElementWithClass('div','spectrum-palette-color');element.style.background=String.sprintf('linear-gradient(%s, %s), url(Images/checker.png)',colorText,colorText);if(animationDelay) -element.animate([{opacity:0},{opacity:1}],{duration:100,delay:animationDelay,fill:'backwards'});element.title=colorText;return element;} -_showPalette(palette,animate,event){this._resizeForSelectedPalette();this._paletteContainer.removeChildren();for(var i=0;i<palette.colors.length;i++){var animationDelay=animate?i*100/palette.colors.length:0;var colorElement=this._createPaletteColor(palette.colors[i],animationDelay);colorElement.addEventListener('mousedown',this._paletteColorSelected.bind(this,palette.colors[i],palette.matchUserFormat));if(palette.mutable){colorElement.__mutable=true;colorElement.__color=palette.colors[i];colorElement.addEventListener('contextmenu',this._showPaletteColorContextMenu.bind(this,i));}else if(palette===ColorPicker.Spectrum.MaterialPalette){colorElement.classList.add('has-material-shades');var shadow=colorElement.createChild('div','spectrum-palette-color spectrum-palette-color-shadow');shadow.style.background=palette.colors[i];shadow=colorElement.createChild('div','spectrum-palette-color spectrum-palette-color-shadow');shadow.style.background=palette.colors[i];colorElement.title=Common.UIString(palette.colors[i]+'. Long-click to show alternate shades.');new UI.LongClickController(colorElement,this._showLightnessShades.bind(this,colorElement,palette.colors[i]));} -this._paletteContainer.appendChild(colorElement);} -this._paletteContainerMutable=palette.mutable;if(palette.mutable){this._paletteContainer.appendChild(this._addColorToolbar.element);this._paletteContainer.appendChild(this._deleteIconToolbar.element);}else{this._addColorToolbar.element.remove();this._deleteIconToolbar.element.remove();} -this._togglePalettePanel(false);this._focus();} -_showLightnessShades(colorElement,colorText,event){function closeLightnessShades(element){this._shadesContainer.classList.add('hidden');element.classList.remove('spectrum-shades-shown');this._shadesContainer.ownerDocument.removeEventListener('mousedown',this._shadesCloseHandler,true);delete this._shadesCloseHandler;} -if(this._shadesCloseHandler) -this._shadesCloseHandler();this._shadesContainer.classList.remove('hidden');this._shadesContainer.removeChildren();this._shadesContainer.animate([{transform:'scaleY(0)',opacity:'0'},{transform:'scaleY(1)',opacity:'1'}],{duration:200,easing:'cubic-bezier(0.4, 0, 0.2, 1)'});this._shadesContainer.style.top=colorElement.offsetTop+colorElement.parentElement.offsetTop+'px';this._shadesContainer.style.left=colorElement.offsetLeft+'px';colorElement.classList.add('spectrum-shades-shown');var shades=ColorPicker.Spectrum.MaterialPaletteShades[colorText];for(var i=shades.length-1;i>=0;i--){var shadeElement=this._createPaletteColor(shades[i],i*200/shades.length+100);shadeElement.addEventListener('mousedown',this._paletteColorSelected.bind(this,shades[i],false));this._shadesContainer.appendChild(shadeElement);} -this._shadesContainer.focus();this._shadesCloseHandler=closeLightnessShades.bind(this,colorElement);this._shadesContainer.ownerDocument.addEventListener('mousedown',this._shadesCloseHandler,true);} -_slotIndexForEvent(e){var localX=e.pageX-this._paletteContainer.totalOffsetLeft();var localY=e.pageY-this._paletteContainer.totalOffsetTop();var col=Math.min(localX/ColorPicker.Spectrum._colorChipSize|0,ColorPicker.Spectrum._itemsPerPaletteRow-1);var row=(localY/ColorPicker.Spectrum._colorChipSize)|0;return Math.min(row*ColorPicker.Spectrum._itemsPerPaletteRow+col,this._customPaletteSetting.get().colors.length-1);} -_isDraggingToBin(e){return e.pageX>this._deleteIconToolbar.element.totalOffsetLeft();} -_paletteDragStart(e){var element=e.deepElementFromPoint();if(!element||!element.__mutable) -return false;var index=this._slotIndexForEvent(e);this._dragElement=element;this._dragHotSpotX=e.pageX-(index%ColorPicker.Spectrum._itemsPerPaletteRow)*ColorPicker.Spectrum._colorChipSize;this._dragHotSpotY=e.pageY-(index/ColorPicker.Spectrum._itemsPerPaletteRow|0)*ColorPicker.Spectrum._colorChipSize;return true;} -_paletteDrag(e){if(e.pageX<this._paletteContainer.totalOffsetLeft()||e.pageY<this._paletteContainer.totalOffsetTop()) -return;var newIndex=this._slotIndexForEvent(e);var offsetX=e.pageX-(newIndex%ColorPicker.Spectrum._itemsPerPaletteRow)*ColorPicker.Spectrum._colorChipSize;var offsetY=e.pageY-(newIndex/ColorPicker.Spectrum._itemsPerPaletteRow|0)*ColorPicker.Spectrum._colorChipSize;var isDeleting=this._isDraggingToBin(e);this._deleteIconToolbar.element.classList.add('dragging');this._deleteIconToolbar.element.classList.toggle('delete-color-toolbar-active',isDeleting);var dragElementTransform='translateX('+(offsetX-this._dragHotSpotX)+'px) translateY('+(offsetY-this._dragHotSpotY)+'px)';this._dragElement.style.transform=isDeleting?dragElementTransform+' scale(0.8)':dragElementTransform;var children=Array.prototype.slice.call(this._paletteContainer.children);var index=children.indexOf(this._dragElement);var swatchOffsets=new Map();for(var swatch of children) -swatchOffsets.set(swatch,swatch.totalOffset());if(index!==newIndex) -this._paletteContainer.insertBefore(this._dragElement,children[newIndex>index?newIndex+1:newIndex]);for(var swatch of children){if(swatch===this._dragElement) -continue;var before=swatchOffsets.get(swatch);var after=swatch.totalOffset();if(before.left!==after.left||before.top!==after.top){swatch.animate([{transform:'translateX('+(before.left-after.left)+'px) translateY('+(before.top-after.top)+'px)'},{transform:'none'}],{duration:100,easing:'cubic-bezier(0, 0, 0.2, 1)'});}}} -_paletteDragEnd(e){if(this._isDraggingToBin(e)) -this._dragElement.remove();this._dragElement.style.removeProperty('transform');var children=this._paletteContainer.children;var colors=[];for(var i=0;i<children.length;++i){if(children[i].__color) -colors.push(children[i].__color);} -var palette=this._customPaletteSetting.get();palette.colors=colors;this._customPaletteSetting.set(palette);this._showPalette(this._customPaletteSetting.get(),false);this._deleteIconToolbar.element.classList.remove('dragging');this._deleteIconToolbar.element.classList.remove('delete-color-toolbar-active');} -_loadPalettes(){this._palettes.set(ColorPicker.Spectrum.MaterialPalette.title,ColorPicker.Spectrum.MaterialPalette);var defaultCustomPalette={title:'Custom',colors:[],mutable:true};this._customPaletteSetting=Common.settings.createSetting('customColorPalette',defaultCustomPalette);this._palettes.set(this._customPaletteSetting.get().title,this._customPaletteSetting.get());this._selectedColorPalette=Common.settings.createSetting('selectedColorPalette',ColorPicker.Spectrum.GeneratedPaletteTitle);var palette=this._palettes.get(this._selectedColorPalette.get());if(palette) -this._showPalette(palette,true);} -_generatedPaletteLoaded(generatedPalette){if(generatedPalette.colors.length) -this._palettes.set(generatedPalette.title,generatedPalette);if(this._selectedColorPalette.get()!==generatedPalette.title){return;}else if(!generatedPalette.colors.length){this._paletteSelected(ColorPicker.Spectrum.MaterialPalette);return;} -this._showPalette(generatedPalette,true);} -_createPreviewPaletteElement(palette){var colorsPerPreviewRow=5;var previewElement=createElementWithClass('div','palette-preview');var titleElement=previewElement.createChild('div','palette-preview-title');titleElement.textContent=palette.title;for(var i=0;i<colorsPerPreviewRow&&i<palette.colors.length;i++) -previewElement.appendChild(this._createPaletteColor(palette.colors[i]));for(;i<colorsPerPreviewRow;i++) -previewElement.createChild('div','spectrum-palette-color empty-color');previewElement.addEventListener('click',this._paletteSelected.bind(this,palette));return previewElement;} -_paletteSelected(palette){this._selectedColorPalette.set(palette.title);this._showPalette(palette,true);} -_resizeForSelectedPalette(){var palette=this._palettes.get(this._selectedColorPalette.get());if(!palette) -return;var numColors=palette.colors.length;if(palette===this._customPaletteSetting.get()) -numColors++;var rowsNeeded=Math.max(1,Math.ceil(numColors/ColorPicker.Spectrum._itemsPerPaletteRow));if(this._numPaletteRowsShown===rowsNeeded) -return;this._numPaletteRowsShown=rowsNeeded;var paletteColorHeight=12;var paletteMargin=12;var paletteTop=235;this.element.style.height=(paletteTop+paletteMargin+(paletteColorHeight+paletteMargin)*rowsNeeded)+'px';this.dispatchEventToListeners(ColorPicker.Spectrum.Events.SizeChanged);} -_paletteColorSelected(colorText,matchUserFormat){var color=Common.Color.parse(colorText);if(!color) -return;this._innerSetColor(color.hsva(),colorText,matchUserFormat?this._colorFormat:color.format(),ColorPicker.Spectrum._ChangeSource.Other);} -_addColorToCustomPalette(event){var palette=this._customPaletteSetting.get();palette.colors.push(this.colorString());this._customPaletteSetting.set(palette);this._showPalette(this._customPaletteSetting.get(),false);} -_showPaletteColorContextMenu(colorIndex,event){if(!this._paletteContainerMutable) -return;var contextMenu=new UI.ContextMenu(event);if(colorIndex!==-1){contextMenu.defaultSection().appendItem(Common.UIString('Remove color'),this._deletePaletteColors.bind(this,colorIndex,false));contextMenu.defaultSection().appendItem(Common.UIString('Remove all to the right'),this._deletePaletteColors.bind(this,colorIndex,true));} -contextMenu.defaultSection().appendItem(Common.UIString('Clear palette'),this._deletePaletteColors.bind(this,-1,true));contextMenu.show();} -_deletePaletteColors(colorIndex,toRight){var palette=this._customPaletteSetting.get();if(toRight) -palette.colors.splice(colorIndex+1,palette.colors.length-colorIndex-1);else -palette.colors.splice(colorIndex,1);this._customPaletteSetting.set(palette);this._showPalette(this._customPaletteSetting.get(),false);} -setColor(color,colorFormat){this._originalFormat=colorFormat;this._innerSetColor(color.hsva(),'',colorFormat,ColorPicker.Spectrum._ChangeSource.Model);} -setContrastInfo(contrastInfo){if(this._contrastOverlay) -this._contrastOverlay.setContrastInfo(contrastInfo);} -_innerSetColor(hsva,colorString,colorFormat,changeSource){if(hsva!==undefined) -this._hsv=hsva;if(colorString!==undefined) -this._colorString=colorString;if(colorFormat!==undefined){var cf=Common.Color.Format;console.assert(colorFormat!==cf.Original,'Spectrum\'s color format cannot be Original');if(colorFormat===cf.RGBA) -colorFormat=cf.RGB;else if(colorFormat===cf.HSLA) -colorFormat=cf.HSL;else if(colorFormat===cf.HEXA) -colorFormat=cf.HEX;else if(colorFormat===cf.ShortHEXA) -colorFormat=cf.ShortHEX;this._colorFormat=colorFormat;} -if(hsva&&this._contrastOverlay) -this._contrastOverlay.setColor(hsva,this.colorString());this._updateHelperLocations();this._updateUI();if(changeSource!==ColorPicker.Spectrum._ChangeSource.Input) -this._updateInput();if(changeSource!==ColorPicker.Spectrum._ChangeSource.Model) -this.dispatchEventToListeners(ColorPicker.Spectrum.Events.ColorChanged,this.colorString());} -_color(){return Common.Color.fromHSVA(this._hsv);} -colorString(){if(this._colorString) -return this._colorString;var cf=Common.Color.Format;var color=this._color();var colorString=color.asString(this._colorFormat);if(colorString) -return colorString;if(this._colorFormat===cf.Nickname) -colorString=color.asString(color.hasAlpha()?cf.HEXA:cf.HEX);else if(this._colorFormat===cf.ShortHEX) -colorString=color.asString(color.detectHEXFormat());else if(this._colorFormat===cf.HEX) -colorString=color.asString(cf.HEXA);else if(this._colorFormat===cf.HSL) -colorString=color.asString(cf.HSLA);else -colorString=color.asString(cf.RGBA);console.assert(colorString);return colorString||'';} -_updateHelperLocations(){var h=this._hsv[0];var s=this._hsv[1];var v=this._hsv[2];var alpha=this._hsv[3];this._dragX=s*this.dragWidth;this._dragY=this.dragHeight-(v*this.dragHeight);var dragX=Math.max(-this._colorDragElementHeight,Math.min(this.dragWidth-this._colorDragElementHeight,this._dragX-this._colorDragElementHeight));var dragY=Math.max(-this._colorDragElementHeight,Math.min(this.dragHeight-this._colorDragElementHeight,this._dragY-this._colorDragElementHeight));this._colorDragElement.positionAt(dragX,dragY);var hueSlideX=(1-h)*this._hueAlphaWidth-this.slideHelperWidth;this._hueSlider.style.left=hueSlideX+'px';var alphaSlideX=alpha*this._hueAlphaWidth-this.slideHelperWidth;this._alphaSlider.style.left=alphaSlideX+'px';} -_updateInput(){var cf=Common.Color.Format;if(this._colorFormat===cf.HEX||this._colorFormat===cf.ShortHEX||this._colorFormat===cf.Nickname){this._hexContainer.hidden=false;this._displayContainer.hidden=true;if(this._colorFormat===cf.ShortHEX){this._hexValue.value=this._color().asString(this._color().detectHEXFormat());}else{this._hexValue.value=this._color().asString(this._color().hasAlpha()?cf.HEXA:cf.HEX);}}else{this._hexContainer.hidden=true;this._displayContainer.hidden=false;var isRgb=this._colorFormat===cf.RGB;this._textLabels.textContent=isRgb?'RGBA':'HSLA';var colorValues=isRgb?this._color().canonicalRGBA():this._color().canonicalHSLA();for(var i=0;i<3;++i){this._textValues[i].value=colorValues[i];if(!isRgb&&(i===1||i===2)) -this._textValues[i].value+='%';} -this._textValues[3].value=Math.round(colorValues[3]*100)/100;}} -_updateUI(){var h=Common.Color.fromHSVA([this._hsv[0],1,1,1]);this._colorElement.style.backgroundColor=(h.asString(Common.Color.Format.RGB));if(this._contrastOverlay){if(this.dragWidth) -this._contrastOverlay.show(this.dragWidth,this.dragHeight,this._dragX,this._dragY);else -this._contrastOverlay.hide();} -this._swatch.setColor(this._color(),this.colorString());this._colorDragElement.style.backgroundColor=(this._color().asString(Common.Color.Format.RGBA));var noAlpha=Common.Color.fromHSVA(this._hsv.slice(0,3).concat(1));this._alphaElementBackground.style.backgroundImage=String.sprintf('linear-gradient(to right, rgba(0,0,0,0), %s)',noAlpha.asString(Common.Color.Format.RGB));} -_formatViewSwitch(){var cf=Common.Color.Format;var format=cf.RGB;if(this._colorFormat===cf.RGB) -format=cf.HSL;else if(this._colorFormat===cf.HSL) -format=(this._originalFormat===cf.ShortHEX||this._originalFormat===cf.ShortHEXA)?cf.ShortHEX:cf.HEX;this._innerSetColor(undefined,'',format,ColorPicker.Spectrum._ChangeSource.Other);} -_inputChanged(event){function elementValue(element){return element.value;} -var inputElement=(event.currentTarget);var newValue=UI.createReplacementString(inputElement.value,event);if(newValue){inputElement.value=newValue;inputElement.selectionStart=0;inputElement.selectionEnd=newValue.length;event.consume(true);} -const cf=Common.Color.Format;var colorString;if(this._colorFormat===cf.Nickname||this._colorFormat===cf.HEX||this._colorFormat===cf.ShortHEX){colorString=this._hexValue.value;}else{var format=this._colorFormat===cf.RGB?'rgba':'hsla';var values=this._textValues.map(elementValue).join(', ');colorString=String.sprintf('%s(%s)',format,values);} -var color=Common.Color.parse(colorString);if(!color) -return;var colorFormat=undefined;if(this._colorFormat===cf.HEX||this._colorFormat===cf.ShortHEX) -colorFormat=color.detectHEXFormat();this._innerSetColor(color.hsva(),colorString,colorFormat,ColorPicker.Spectrum._ChangeSource.Input);} -wasShown(){this._hueAlphaWidth=this._hueElement.offsetWidth;this.slideHelperWidth=this._hueSlider.offsetWidth/2;this.dragWidth=this._colorElement.offsetWidth;this.dragHeight=this._colorElement.offsetHeight;this._colorDragElementHeight=this._colorDragElement.offsetHeight/2;this._innerSetColor(undefined,undefined,undefined,ColorPicker.Spectrum._ChangeSource.Model);this._toggleColorPicker(true);} -willHide(){this._toggleColorPicker(false);} -_toggleColorPicker(enabled,event){if(enabled===undefined) -enabled=!this._colorPickerButton.toggled();this._colorPickerButton.setToggled(enabled);InspectorFrontendHost.setEyeDropperActive(enabled);if(enabled){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._colorPickedBound);}else{InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._colorPickedBound);}} -_colorPicked(event){var rgbColor=(event.data);var rgba=[rgbColor.r,rgbColor.g,rgbColor.b,(rgbColor.a/2.55|0)/100];var color=Common.Color.fromRGBA(rgba);this._innerSetColor(color.hsva(),'',undefined,ColorPicker.Spectrum._ChangeSource.Other);InspectorFrontendHost.bringToFront();}};ColorPicker.Spectrum._ChangeSource={Input:'Input',Model:'Model',Other:'Other'};ColorPicker.Spectrum.Events={ColorChanged:Symbol('ColorChanged'),SizeChanged:Symbol('SizeChanged')};ColorPicker.Spectrum._colorChipSize=24;ColorPicker.Spectrum._itemsPerPaletteRow=8;ColorPicker.Spectrum.Palette;ColorPicker.Spectrum.GeneratedPaletteTitle='Page colors';ColorPicker.Spectrum.PaletteGenerator=class{constructor(callback){this._callback=callback;this._frequencyMap=new Map();var stylesheetPromises=[];for(var cssModel of SDK.targetManager.models(SDK.CSSModel)){for(var stylesheet of cssModel.allStyleSheets()) -stylesheetPromises.push(this._processStylesheet(stylesheet));} -Promise.all(stylesheetPromises).catchException(null).then(this._finish.bind(this));} -_frequencyComparator(a,b){return this._frequencyMap.get(b)-this._frequencyMap.get(a);} -_finish(){function hueComparator(a,b){var hsva=paletteColors.get(a).hsva();var hsvb=paletteColors.get(b).hsva();if(hsvb[1]<0.12&&hsva[1]<0.12) -return hsvb[2]*hsvb[3]-hsva[2]*hsva[3];if(hsvb[1]<0.12) -return-1;if(hsva[1]<0.12) -return 1;if(hsvb[0]===hsva[0]) -return hsvb[1]*hsvb[3]-hsva[1]*hsva[3];return(hsvb[0]+0.94)%1-(hsva[0]+0.94)%1;} -var colors=this._frequencyMap.keysArray();colors=colors.sort(this._frequencyComparator.bind(this));var paletteColors=new Map();var colorsPerRow=24;while(paletteColors.size<colorsPerRow&&colors.length){var colorText=colors.shift();var color=Common.Color.parse(colorText);if(!color||color.nickname()==='white'||color.nickname()==='black') -continue;paletteColors.set(colorText,color);} -this._callback({title:ColorPicker.Spectrum.GeneratedPaletteTitle,colors:paletteColors.keysArray().sort(hueComparator),mutable:false});} -async _processStylesheet(stylesheet){var text=await stylesheet.requestContent()||'';text=text.toLowerCase();var regexResult=text.match(/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-f]{6}|#[0-9a-f]{3})/g)||[];for(var c of regexResult){var frequency=this._frequencyMap.get(c)||0;this._frequencyMap.set(c,++frequency);}}};ColorPicker.Spectrum.MaterialPaletteShades={'#F44336':['#FFEBEE','#FFCDD2','#EF9A9A','#E57373','#EF5350','#F44336','#E53935','#D32F2F','#C62828','#B71C1C'],'#E91E63':['#FCE4EC','#F8BBD0','#F48FB1','#F06292','#EC407A','#E91E63','#D81B60','#C2185B','#AD1457','#880E4F'],'#9C27B0':['#F3E5F5','#E1BEE7','#CE93D8','#BA68C8','#AB47BC','#9C27B0','#8E24AA','#7B1FA2','#6A1B9A','#4A148C'],'#673AB7':['#EDE7F6','#D1C4E9','#B39DDB','#9575CD','#7E57C2','#673AB7','#5E35B1','#512DA8','#4527A0','#311B92'],'#3F51B5':['#E8EAF6','#C5CAE9','#9FA8DA','#7986CB','#5C6BC0','#3F51B5','#3949AB','#303F9F','#283593','#1A237E'],'#2196F3':['#E3F2FD','#BBDEFB','#90CAF9','#64B5F6','#42A5F5','#2196F3','#1E88E5','#1976D2','#1565C0','#0D47A1'],'#03A9F4':['#E1F5FE','#B3E5FC','#81D4FA','#4FC3F7','#29B6F6','#03A9F4','#039BE5','#0288D1','#0277BD','#01579B'],'#00BCD4':['#E0F7FA','#B2EBF2','#80DEEA','#4DD0E1','#26C6DA','#00BCD4','#00ACC1','#0097A7','#00838F','#006064'],'#009688':['#E0F2F1','#B2DFDB','#80CBC4','#4DB6AC','#26A69A','#009688','#00897B','#00796B','#00695C','#004D40'],'#4CAF50':['#E8F5E9','#C8E6C9','#A5D6A7','#81C784','#66BB6A','#4CAF50','#43A047','#388E3C','#2E7D32','#1B5E20'],'#8BC34A':['#F1F8E9','#DCEDC8','#C5E1A5','#AED581','#9CCC65','#8BC34A','#7CB342','#689F38','#558B2F','#33691E'],'#CDDC39':['#F9FBE7','#F0F4C3','#E6EE9C','#DCE775','#D4E157','#CDDC39','#C0CA33','#AFB42B','#9E9D24','#827717'],'#FFEB3B':['#FFFDE7','#FFF9C4','#FFF59D','#FFF176','#FFEE58','#FFEB3B','#FDD835','#FBC02D','#F9A825','#F57F17'],'#FFC107':['#FFF8E1','#FFECB3','#FFE082','#FFD54F','#FFCA28','#FFC107','#FFB300','#FFA000','#FF8F00','#FF6F00'],'#FF9800':['#FFF3E0','#FFE0B2','#FFCC80','#FFB74D','#FFA726','#FF9800','#FB8C00','#F57C00','#EF6C00','#E65100'],'#FF5722':['#FBE9E7','#FFCCBC','#FFAB91','#FF8A65','#FF7043','#FF5722','#F4511E','#E64A19','#D84315','#BF360C'],'#795548':['#EFEBE9','#D7CCC8','#BCAAA4','#A1887F','#8D6E63','#795548','#6D4C41','#5D4037','#4E342E','#3E2723'],'#9E9E9E':['#FAFAFA','#F5F5F5','#EEEEEE','#E0E0E0','#BDBDBD','#9E9E9E','#757575','#616161','#424242','#212121'],'#607D8B':['#ECEFF1','#CFD8DC','#B0BEC5','#90A4AE','#78909C','#607D8B','#546E7A','#455A64','#37474F','#263238']};ColorPicker.Spectrum.MaterialPalette={title:'Material',mutable:false,matchUserFormat:true,colors:Object.keys(ColorPicker.Spectrum.MaterialPaletteShades)};ColorPicker.Spectrum.Swatch=class{constructor(parentElement){this._colorString;var swatchElement=parentElement.createChild('span','swatch');this._swatchInnerElement=swatchElement.createChild('span','swatch-inner');this._swatchOverlayElement=swatchElement.createChild('span','swatch-overlay');this._swatchOverlayElement.addEventListener('click',this._onCopyIconClick.bind(this));this._swatchOverlayElement.addEventListener('mouseout',this._onCopyIconMouseout.bind(this));this._swatchCopyIcon=UI.Icon.create('largeicon-copy','copy-color-icon');this._swatchCopyIcon.title=Common.UIString('Copy color to clipboard');this._swatchOverlayElement.appendChild(this._swatchCopyIcon);} -setColor(color,colorString){this._swatchInnerElement.style.backgroundColor=(color.asString(Common.Color.Format.RGBA));this._swatchInnerElement.classList.toggle('swatch-inner-white',color.hsla()[2]>0.9);this._colorString=colorString||null;if(colorString) -this._swatchOverlayElement.hidden=false;else -this._swatchOverlayElement.hidden=true;} -_onCopyIconClick(){this._swatchCopyIcon.setIconType('largeicon-checkmark');InspectorFrontendHost.copyText(this._colorString);} -_onCopyIconMouseout(){this._swatchCopyIcon.setIconType('largeicon-copy');}};;Runtime.cachedResources["color_picker/spectrum.css"]="/* https://github.com/bgrins/spectrum */\n:host {\n width: 232px;\n height: 240px;\n -webkit-user-select: none;\n overflow: hidden;\n}\n\n:host-context(.palettes-enabled) {\n height: 319px;\n}\n\n.spectrum-color {\n position: relative;\n width: 232px;\n height: 124px;\n border-radius: 2px 2px 0 0;\n overflow: hidden;\n}\n\n.spectrum-display-value {\n -webkit-user-select: text;\n display: inline-block;\n padding-left: 2px;\n}\n\n.spectrum-hue {\n top: 140px;\n}\n\n.spectrum-alpha {\n top: 159px;\n background-image: url(Images/checker.png);\n background-size: 12px 11px;\n}\n\n.spectrum-alpha-background {\n height: 100%;\n border-radius: 2px;\n}\n\n.spectrum-hue, .spectrum-alpha {\n position: absolute;\n left: 86px;\n width: 130px;\n height: 11px;\n border-radius: 2px;\n}\n\n.spectrum-dragger,\n.spectrum-slider {\n -webkit-user-select: none;\n}\n\n.spectrum-sat,\n.-theme-preserve {\n background-image: linear-gradient(to right, white, rgba(204, 154, 129, 0));\n}\n\n.spectrum-val,\n.-theme-preserve {\n background-image: linear-gradient(to top, black, rgba(204, 154, 129, 0));\n}\n\n.spectrum-hue {\n background: linear-gradient(to left, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);\n}\n\n.spectrum-dragger {\n border-radius: 12px;\n height: 12px;\n width: 12px;\n border: 1px solid white;\n cursor: pointer;\n position: absolute;\n top: 0;\n left: 0;\n background: black;\n box-shadow: 0 0 2px 0px rgba(0, 0, 0, 0.24);\n}\n\n.spectrum-slider {\n position: absolute;\n top: -1px;\n cursor: pointer;\n width: 13px;\n height: 13px;\n border-radius: 13px;\n background-color: rgb(248, 248, 248);\n box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.37);\n}\n\n.spectrum-contrast-info {\n position: absolute;\n right: 10px;\n left: auto;\n bottom: 10px;\n color: white;\n border-radius: 2px;\n border: 0;\n padding: 3px 3px 2px;\n background-color: rgba(255, 255, 255, 0.2);\n align-items: center;\n transition: right .05s ease-out, left .05s ease-out, bottom .05s ease-out, top .05s ease-out;\n cursor: pointer;\n}\n\n.spectrum-contrast-info.contrast-unknown .value {\n display: none;\n}\n\n.spectrum-contrast-info .low-contrast {\n display: none;\n margin-right: 3px;\n}\n\n.spectrum-contrast-info.contrast-fail .low-contrast {\n display: initial;\n}\n\n.spectrum-contrast-info.contrast-info-left {\n left: 10px;\n right: auto;\n}\n\n.spectrum-contrast-info.contrast-info-top {\n top: 10px;\n bottom: auto;\n background-color: rgba(0, 0, 0, 0.2);\n}\n\n.spectrum-contrast-info.contrast-fail {\n background-color: #b40202;\n}\n\n.spectrum-contrast-info .value {\n margin-right: 4px;\n}\n\n.spectrum-contrast-details {\n position: absolute;\n background-color: white;\n width: 100%;\n height: 111px;\n top: 124px;\n z-index: 13;\n font-size: 13px;\n color: #333;\n display: none;\n line-height: initial;\n}\n\n.spectrum-contrast-details div.toolbar {\n position: absolute;\n right: 6px;\n top: 6px;\n margin: 0;\n}\n\n.spectrum-contrast-details div.toolbar [is=ui-icon] {\n position: absolute;\n right: 6px;\n top: 6px;\n margin: 0;\n background: transparent;\n}\n\n.spectrum-contrast-details.visible {\n display: initial;\n}\n\n.spectrum-contrast-details div {\n margin: 12px;\n}\n\n.contrast-pass-fail {\n margin-left: 0.5em;\n}\n\n.contrast-threshold .smallicon-checkmark-square,\n.contrast-threshold .smallicon-no{\n display: none;\n}\n\n.contrast-threshold.pass .smallicon-checkmark-square {\n display: inline-block;\n background-color: #00b06f;\n}\n\n.contrast-threshold.fail .smallicon-no {\n display: inline-block;\n background-color: #b40202;\n}\n\n.contrast-threshold-value {\n font-weight: bold;\n}\n.spectrum-contrast-details .contrast-thresholds div {\n margin: 0;\n}\n\n.contrast-link {\n margin-left: 0.5em;\n}\n\n.contrast-link .mediumicon-info {\n margin-top: -3px;\n background-color: #333;\n}\n\n.contrast-details-value {\n color: white;\n border-radius: 2px;\n margin-left: 0.5em;\n padding: 1px 3px;\n align-items: baseline;\n position: absolute;\n margin-top: -2px;\n border: 1px solid transparent;\n}\n\n.contrast-details-value.contrast-unknown {\n background-color: white;\n color: #333;\n border: 1px solid #ddd;\n width: 3em;\n text-align: center;\n}\n\n.contrast-details-value.contrast-color-white {\n border-color: #ddd;\n}\n\n.contrast-details-value.contrast-fail.hover {\n color: #333 !important;\n background-color: white !important;\n}\n\n.contrast-details-value.contrast-fail.hover [is=ui-icon] {\n background-color: black !important;\n}\n\n.contrast-details-value [is=ui-icon] {\n display: none;\n margin-left: 0.5em;\n}\n\n.contrast-details-value .smallicon-checkmark-behind {\n margin-left: -6px;\n}\n\n.contrast-details-value.contrast-fail .smallicon-no {\n display: inline-block;\n}\n\n.contrast-details-value.contrast-fail .smallicon-no {\n display: inline-block;\n}\n\n.contrast-details-value.contrast-aa .smallicon-checkmark-square {\n display: inline-block;\n}\n\n.contrast-details-value.contrast-aaa .smallicon-checkmark-behind {\n display: inline-block;\n}\n\n.swatch {\n width: 32px;\n height: 32px;\n margin: 0;\n position: absolute;\n top: 139px;\n left: 44px;\n background-image: url(Images/checker.png);\n border-radius: 16px;\n}\n\n.swatch-inner,\n.swatch-overlay {\n position: absolute;\n width: 100%;\n height: 100%;\n display: inline-block;\n border-radius: 16px;\n}\n\n.swatch-inner-white {\n border: 1px solid #ddd;\n}\n\n.swatch-overlay {\n cursor: pointer;\n opacity: 0;\n padding: 4px;\n}\n\n.swatch-overlay:hover {\n background-color: rgba(0, 0, 0, .3);\n opacity: 1;\n}\n\n.swatch-overlay:active {\n background-color: rgba(0, 0, 0, .5);\n}\n\n.copy-color-icon {\n background-color: white;\n}\n\n.spectrum-text {\n position: absolute;\n top: 184px;\n left: 16px;\n}\n\n.spectrum-text-value {\n display: inline-block;\n width: 40px;\n overflow: hidden;\n text-align: center;\n border: 1px solid #dadada;\n border-radius: 2px;\n margin-right: 6px;\n line-height: 20px;\n padding: 0;\n color: #333;\n white-space: nowrap;\n}\n\n.spectrum-text-label {\n letter-spacing: 39.5px;\n margin-top: 8px;\n display: block;\n color: #969696;\n margin-left: 16px;\n width: 174px;\n}\n\n.spectrum-text-hex > .spectrum-text-value {\n width: 178px;\n}\n\n.spectrum-text-hex > .spectrum-text-label {\n letter-spacing: normal;\n margin-left: 0px;\n text-align: center;\n}\n\n.spectrum-palette-value {\n background-color: rgb(65, 75, 217);\n border-radius: 2px;\n margin-top: 12px;\n margin-left: 12px;\n width: 12px;\n height: 12px;\n display: inline-block;\n}\n\n.spectrum-switcher {\n border-radius: 2px;\n height: 20px;\n width: 20px;\n padding: 2px;\n}\n\n:host-context(.-theme-with-dark-background) .spectrum-switcher {\n -webkit-filter: invert(60%);\n}\n\n.spectrum-display-switcher {\n top: 196px;\n position: absolute;\n right: 10px;\n}\n\n.spectrum-switcher:hover {\n background-color: #EEEEEE;\n}\n\n.spectrum-eye-dropper {\n width: 32px;\n height: 24px;\n position: absolute;\n left: 8px;\n top: 141px;\n cursor: pointer;\n}\n\n.spectrum-palette {\n border-top: 1px solid #dadada;\n position: absolute;\n top: 235px;\n width: 100%;\n padding: 6px 24px 6px 6px;\n display: flex;\n flex-wrap: wrap;\n}\n\n.spectrum-palette-color {\n width: 12px;\n height: 12px;\n flex: 0 0 12px;\n border-radius: 2px;\n margin: 6px;\n cursor: pointer;\n position: relative;\n border: 1px solid rgba(0, 0, 0, 0.1);\n background-position: -1px !important;\n}\n\n.spectrum-palette-color:hover:not(.spectrum-shades-shown) > .spectrum-palette-color-shadow {\n opacity: 0.2;\n}\n\n.spectrum-palette-color:hover:not(.spectrum-shades-shown) > .spectrum-palette-color-shadow:first-child {\n opacity: 0.6;\n top: -3px;\n left: 1px;\n}\n\n.spectrum-palette-color-shadow {\n position: absolute;\n opacity: 0;\n margin: 0;\n top: -5px;\n left: 3px;\n}\n\n.palette-color-shades {\n position: absolute;\n background-color: white;\n height: 228px;\n width: 28px;\n box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 1px 10px 0 rgba(0, 0, 0, 0.12), 0 2px 4px -1px rgba(0, 0, 0, 0.4);\n z-index: 14;\n border-radius: 2px;\n transform-origin: 0px 228px;\n margin-top: -208px;\n margin-left: -8px;\n}\n\n.spectrum-palette > .spectrum-palette-color.spectrum-shades-shown {\n z-index: 15;\n}\n\n.palette-color-shades > .spectrum-palette-color {\n margin: 8px 0 0 0;\n margin-left: 8px;\n width: 12px;\n}\n\n.spectrum-palette > .spectrum-palette-color {\n transition: transform 100ms cubic-bezier(0, 0, 0.2, 1);\n will-change: transform;\n z-index: 13;\n}\n\n.spectrum-palette > .spectrum-palette-color.empty-color {\n border-color: transparent;\n}\n\n.spectrum-palette > .spectrum-palette-color:not(.empty-color):not(.has-material-shades):hover,\n.palette-color-shades > .spectrum-palette-color:not(.empty-color):hover {\n transform: scale(1.15);\n}\n\n.add-color-toolbar {\n margin-left: -3px;\n margin-top: -1px;\n}\n\n.spectrum-palette-switcher {\n right: 10px;\n top: 235px;\n margin-top: 9px;\n position: absolute;\n}\n\n.palette-panel {\n width: 100%;\n height: 100%;\n position: absolute;\n top: 100%;\n display: flex;\n flex-direction: column;\n background-color: white;\n z-index: 14;\n transition: transform 200ms cubic-bezier(0, 0, 0.2, 1), visibility 0s 200ms;\n border-top: 1px solid #dadada;\n visibility: hidden;\n}\n\n.palette-panel-showing > .palette-panel {\n transform: translateY(calc(-100% + 117px));\n transition-delay: 0s;\n visibility: visible;\n}\n\n.palette-panel > div.toolbar {\n position: absolute;\n right: 6px;\n top: 6px;\n}\n\n.palette-panel > div:not(.toolbar) {\n flex: 0 0 38px;\n border-bottom: 1px solid #dadada;\n padding: 12px;\n line-height: 14px;\n color: #333;\n}\n\n.palette-panel > div.palette-title {\n font-size: 14px;\n line-height: 16px;\n color: #333;\n flex-basis: 40px;\n}\n\ndiv.palette-preview {\n display: flex;\n cursor: pointer;\n}\n\n.palette-preview-title {\n flex: 0 0 84px;\n}\n\n.palette-preview > .spectrum-palette-color {\n margin-top: 1px;\n}\n\n.palette-preview:hover {\n background-color: #eee;\n}\n\n.spectrum-overlay {\n z-index: 13;\n visibility: hidden;\n background-color: hsla(0, 0%, 0%, 0.5);\n opacity: 0;\n transition: opacity 100ms cubic-bezier(0, 0, 0.2, 1), visibility 0s 100ms;\n}\n\n.palette-panel-showing > .spectrum-overlay {\n transition-delay: 0s;\n visibility: visible;\n opacity: 1;\n}\n\n.spectrum-contrast-container {\n width: 100%;\n height: 100%;\n}\n\n.spectrum-contrast-line {\n fill: none;\n stroke: white;\n opacity: 0.7;\n stroke-width: 1.5px;\n}\n\n.delete-color-toolbar {\n position: absolute;\n right: 0;\n top: 0;\n background-color: #EFEFEF;\n visibility: hidden;\n z-index: 3;\n width: 36px;\n display: flex;\n align-items: center;\n padding-left: 4px;\n bottom: 2px;\n border-bottom-right-radius: 2px;\n}\n\n@keyframes showDeleteToolbar {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n.delete-color-toolbar.dragging {\n visibility: visible;\n animation: showDeleteToolbar 100ms 150ms cubic-bezier(0, 0, 0.2, 1) backwards;\n}\n\n.delete-color-toolbar-active {\n background-color: #ddd;\n color: white;\n}\n\n.swatch.contrast {\n width: 20px;\n height: 20px;\n margin: -10px;\n position: relative;\n top: -5px;\n left: 17px;\n background-image: url(Images/checker.png);\n border-radius: 10px;\n display: inline-block;\n}\n\n.swatch.contrast .swatch-overlay {\n padding: 0;\n}\n\n.swatch.contrast [is=ui-icon] {\n margin: -2px;\n}\n\nbutton.background-color-picker {\n border: 0;\n padding: 0;\n background: none;\n position: relative;\n margin-top: -12px;\n left: 26px;\n top: 7px;\n}\n\nbutton.background-color-picker.active [is=ui-icon].largeicon-eyedropper.icon-mask{\n background-color: hsl(218, 81%, 59%);\n}\n\n/*# sourceURL=color_picker/spectrum.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/console/console_module.js b/src/cobalt/debug/content/devtools/console/console_module.js deleted file mode 100644 index 9205ad8..0000000 --- a/src/cobalt/debug/content/devtools/console/console_module.js +++ /dev/null
@@ -1,639 +0,0 @@ -Console.ConsoleContextSelector=class{constructor(){this._items=new UI.ListModel();this._dropDown=new UI.SoftDropDown(this._items,this);this._dropDown.setRowHeight(36);this._toolbarItem=new UI.ToolbarItem(this._dropDown.element);this._badgePoolForExecutionContext=new Map();this._toolbarItem.element.classList.add('toolbar-has-dropdown');SDK.targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextCreated,this._onExecutionContextCreated,this);SDK.targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextChanged,this._onExecutionContextChanged,this);SDK.targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextDestroyed,this._onExecutionContextDestroyed,this);SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.FrameNavigated,this._frameNavigated,this);UI.context.addFlavorChangeListener(SDK.ExecutionContext,this._executionContextChangedExternally,this);UI.context.addFlavorChangeListener(SDK.DebuggerModel.CallFrame,this._callFrameSelectedInUI,this);SDK.targetManager.observeModels(SDK.RuntimeModel,this);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.CallFrameSelected,this._callFrameSelectedInModel,this);} -toolbarItem(){return this._toolbarItem;} -highlightedItemChanged(from,to,fromElement,toElement){SDK.OverlayModel.hideDOMNodeHighlight();if(to&&to.frameId){var overlayModel=to.target().model(SDK.OverlayModel);if(overlayModel) -overlayModel.highlightFrame(to.frameId);} -if(fromElement) -fromElement.classList.remove('highlighted');if(toElement) -toElement.classList.add('highlighted');} -titleFor(executionContext){var target=executionContext.target();var label=executionContext.label()?target.decorateLabel(executionContext.label()):'';if(executionContext.frameId){var resourceTreeModel=target.model(SDK.ResourceTreeModel);var frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);if(frame) -label=label||frame.displayName();} -label=label||executionContext.origin;return label;} -_depthFor(executionContext){var target=executionContext.target();var depth=0;if(!executionContext.isDefault) -depth++;if(executionContext.frameId){var resourceTreeModel=target.model(SDK.ResourceTreeModel);var frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);while(frame&&frame.parentFrame){depth++;frame=frame.parentFrame;}} -var targetDepth=0;while(target.parentTarget()){if(target.parentTarget().hasJSCapability()){targetDepth++;}else{targetDepth=0;break;} -target=target.parentTarget();} -depth+=targetDepth;return depth;} -_badgeFor(executionContext){if(!executionContext.frameId||!executionContext.isDefault) -return null;var resourceTreeModel=executionContext.target().model(SDK.ResourceTreeModel);var frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);if(!frame) -return null;var badgePool=new ProductRegistry.BadgePool();this._badgePoolForExecutionContext.set(executionContext,badgePool);return badgePool.badgeForFrame(frame);} -_disposeExecutionContextBadge(executionContext){var badgePool=this._badgePoolForExecutionContext.get(executionContext);if(!badgePool) -return;badgePool.reset();this._badgePoolForExecutionContext.delete(executionContext);} -_executionContextCreated(executionContext){if(!executionContext.target().hasJSCapability()) -return;this._items.insertWithComparator(executionContext,executionContext.runtimeModel.executionContextComparator());if(executionContext===UI.context.flavor(SDK.ExecutionContext)) -this._dropDown.selectItem(executionContext);} -_onExecutionContextCreated(event){var executionContext=(event.data);this._executionContextCreated(executionContext);} -_onExecutionContextChanged(event){var executionContext=(event.data);if(this._items.indexOf(executionContext)===-1) -return;this._executionContextDestroyed(executionContext);this._executionContextCreated(executionContext);} -_executionContextDestroyed(executionContext){var index=this._items.indexOf(executionContext);if(index===-1) -return;this._disposeExecutionContextBadge(executionContext);this._items.remove(index);} -_onExecutionContextDestroyed(event){var executionContext=(event.data);this._executionContextDestroyed(executionContext);} -_executionContextChangedExternally(event){var executionContext=(event.data);this._dropDown.selectItem(executionContext);} -_isTopContext(executionContext){if(!executionContext||!executionContext.isDefault) -return false;var resourceTreeModel=executionContext.target().model(SDK.ResourceTreeModel);var frame=executionContext.frameId&&resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);if(!frame) -return false;return frame.isMainFrame();} -_hasTopContext(){return this._items.some(executionContext=>this._isTopContext(executionContext));} -modelAdded(runtimeModel){runtimeModel.executionContexts().forEach(this._executionContextCreated,this);} -modelRemoved(runtimeModel){for(var i=0;i<this._items.length;i++){if(this._items.at(i).runtimeModel===runtimeModel) -this._executionContextDestroyed(this._items.at(i));}} -createElementForItem(item){var element=createElementWithClass('div');var shadowRoot=UI.createShadowRootWithCoreStyles(element,'console/consoleContextSelector.css');var title=shadowRoot.createChild('div','title');title.createTextChild(this.titleFor(item).trimEnd(100));var subTitle=shadowRoot.createChild('div','subtitle');var badgeElement=this._badgeFor(item);if(badgeElement){badgeElement.classList.add('badge');subTitle.appendChild(badgeElement);} -subTitle.createTextChild(this._subtitleFor(item));element.style.paddingLeft=(8+this._depthFor(item)*15)+'px';return element;} -_subtitleFor(executionContext){var target=executionContext.target();if(executionContext.frameId){var resourceTreeModel=target.model(SDK.ResourceTreeModel);var frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);} -if(!frame||!frame.parentFrame||frame.parentFrame.securityOrigin!==executionContext.origin){var url=executionContext&&executionContext.origin&&executionContext.origin.asParsedURL();if(url) -return url.domain();} -if(frame){var callFrame=frame.findCreationCallFrame(callFrame=>!!callFrame.url);if(callFrame) -return new Common.ParsedURL(callFrame.url).domain();return Common.UIString('IFrame');} -return'';} -isItemSelectable(item){var callFrame=item.debuggerModel.selectedCallFrame();var callFrameContext=callFrame&&callFrame.script.executionContext();return!callFrameContext||item===callFrameContext;} -itemSelected(item){this._toolbarItem.element.classList.toggle('warning',!this._isTopContext(item)&&this._hasTopContext());UI.context.setFlavor(SDK.ExecutionContext,item);} -_callFrameSelectedInUI(){var callFrame=UI.context.flavor(SDK.DebuggerModel.CallFrame);var callFrameContext=callFrame&&callFrame.script.executionContext();if(callFrameContext) -UI.context.setFlavor(SDK.ExecutionContext,callFrameContext);} -_callFrameSelectedInModel(event){var debuggerModel=(event.data);for(var executionContext of this._items){if(executionContext.debuggerModel===debuggerModel){this._disposeExecutionContextBadge(executionContext);this._dropDown.refreshItem(executionContext);}}} -_frameNavigated(event){var frame=(event.data);var runtimeModel=frame.resourceTreeModel().target().model(SDK.RuntimeModel);if(!runtimeModel) -return;for(var executionContext of runtimeModel.executionContexts()){if(frame.id===executionContext.frameId){this._disposeExecutionContextBadge(executionContext);this._dropDown.refreshItem(executionContext);}}}};;Console.ConsoleFilter=class{constructor(name,parsedFilters,executionContext,levelsMask){this.name=name;this.parsedFilters=parsedFilters;this.executionContext=executionContext;this.levelsMask=levelsMask||Console.ConsoleFilter.defaultLevelsFilterValue();} -static allLevelsFilterValue(){var result={};for(var name of Object.values(ConsoleModel.ConsoleMessage.MessageLevel)) -result[name]=true;return result;} -static defaultLevelsFilterValue(){var result=Console.ConsoleFilter.allLevelsFilterValue();result[ConsoleModel.ConsoleMessage.MessageLevel.Verbose]=false;return result;} -static singleLevelMask(level){var result={};result[level]=true;return result;} -clone(){var parsedFilters=this.parsedFilters.map(TextUtils.FilterParser.cloneFilter);var levelsMask=Object.assign({},this.levelsMask);return new Console.ConsoleFilter(this.name,parsedFilters,this.executionContext,levelsMask);} -shouldBeVisible(viewMessage){var message=viewMessage.consoleMessage();if(this.executionContext&&(this.executionContext.runtimeModel!==message.runtimeModel()||this.executionContext.id!==message.executionContextId)) -return false;if(message.type===ConsoleModel.ConsoleMessage.MessageType.Command||message.type===ConsoleModel.ConsoleMessage.MessageType.Result||message.isGroupMessage()) -return true;if(message.level&&!this.levelsMask[(message.level)]) -return false;for(var filter of this.parsedFilters){if(!filter.key){if(filter.regex&&viewMessage.matchesFilterRegex(filter.regex)===filter.negative) -return false;if(filter.text&&viewMessage.matchesFilterText(filter.text)===filter.negative) -return false;}else{switch(filter.key){case Console.ConsoleFilter.FilterType.Context:if(!passesFilter(filter,message.context,false)) -return false;break;case Console.ConsoleFilter.FilterType.Source:var sourceNameForMessage=message.source?ConsoleModel.ConsoleMessage.MessageSourceDisplayName.get((message.source)):message.source;if(!passesFilter(filter,sourceNameForMessage,true)) -return false;break;case Console.ConsoleFilter.FilterType.Url:if(!passesFilter(filter,message.url,false)) -return false;break;}}} -return true;function passesFilter(filter,value,exactMatch){if(!filter.text) -return!!value===filter.negative;if(!value) -return!filter.text===!filter.negative;var filterText=(filter.text).toLowerCase();var lowerCaseValue=value.toLowerCase();if(exactMatch&&(lowerCaseValue===filterText)===filter.negative) -return false;if(!exactMatch&&lowerCaseValue.includes(filterText)===filter.negative) -return false;return true;}}};Console.ConsoleFilter.FilterType={Context:'context',Source:'source',Url:'url'};;Console.ConsoleSidebar=class extends UI.VBox{constructor(badgePool){super(true);this.setMinimumSize(125,0);this._enabled=Runtime.experiments.isEnabled('logManagement');this._tree=new UI.TreeOutlineInShadow();this._tree.registerRequiredCSS('console/consoleSidebar.css');this._tree.addEventListener(UI.TreeOutline.Events.ElementSelected,this._selectionChanged.bind(this));this.contentElement.appendChild(this._tree.element);this._selectedTreeElement=null;this._treeElements=[];var Levels=ConsoleModel.ConsoleMessage.MessageLevel;var consoleAPIParsedFilters=[{key:Console.ConsoleFilter.FilterType.Source,text:ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI,negative:false}];this._appendGroup(Console.ConsoleSidebar._groupSingularName.All,[],Console.ConsoleFilter.allLevelsFilterValue(),UI.Icon.create('mediumicon-list'),badgePool);this._appendGroup(Console.ConsoleSidebar._groupSingularName.ConsoleAPI,consoleAPIParsedFilters,Console.ConsoleFilter.allLevelsFilterValue(),UI.Icon.create('mediumicon-account-circle'),badgePool);this._appendGroup(Console.ConsoleSidebar._groupSingularName.Error,[],Console.ConsoleFilter.singleLevelMask(Levels.Error),UI.Icon.create('mediumicon-error-circle'),badgePool);this._appendGroup(Console.ConsoleSidebar._groupSingularName.Warning,[],Console.ConsoleFilter.singleLevelMask(Levels.Warning),UI.Icon.create('mediumicon-warning-triangle'),badgePool);this._appendGroup(Console.ConsoleSidebar._groupSingularName.Info,[],Console.ConsoleFilter.singleLevelMask(Levels.Info),UI.Icon.create('mediumicon-info-circle'),badgePool);this._appendGroup(Console.ConsoleSidebar._groupSingularName.Verbose,[],Console.ConsoleFilter.singleLevelMask(Levels.Verbose),UI.Icon.create('mediumicon-bug'),badgePool);this._treeElements[0].select();} -_appendGroup(name,parsedFilters,levelsMask,icon,badgePool){var filter=new Console.ConsoleFilter(name,parsedFilters,null,levelsMask);var treeElement=new Console.ConsoleSidebar.FilterTreeElement(filter,icon,badgePool);this._tree.appendChild(treeElement);this._treeElements.push(treeElement);} -clear(){if(!this._enabled) -return;for(var treeElement of this._treeElements) -treeElement.clear();} -onMessageAdded(viewMessage){if(!this._enabled) -return;for(var treeElement of this._treeElements) -treeElement.onMessageAdded(viewMessage);} -shouldBeVisible(viewMessage){if(!this._enabled||!this._selectedTreeElement) -return true;return this._selectedTreeElement._filter.shouldBeVisible(viewMessage);} -_selectionChanged(event){this._selectedTreeElement=(event.data);this.dispatchEventToListeners(Console.ConsoleSidebar.Events.FilterSelected);}};Console.ConsoleSidebar.Events={FilterSelected:Symbol('FilterSelected')};Console.ConsoleSidebar.URLGroupTreeElement=class extends UI.TreeElement{constructor(filter,badge){super(filter.name);this._filter=filter;this._countElement=this.listItemElement.createChild('span','count');var leadingIcons=[UI.Icon.create('largeicon-navigator-file')];if(badge) -leadingIcons.push(badge);this.setLeadingIcons(leadingIcons);this._messageCount=0;} -incrementAndUpdateCounter(){this._messageCount++;this._countElement.textContent=this._messageCount;}};Console.ConsoleSidebar.FilterTreeElement=class extends UI.TreeElement{constructor(filter,icon,badgePool){super(filter.name,true);this._filter=filter;this._badgePool=badgePool;this._urlTreeElements=new Map();this.setLeadingIcons([icon]);this._messageCount=0;this._updateCounter();} -clear(){this._urlTreeElements.clear();this.removeChildren();this._messageCount=0;this._updateCounter();} -_updateCounter(){var prefix=this._messageCount?this._messageCount:Common.UIString('No');var pluralizedName=this._messageCount===1?this._filter.name:Console.ConsoleSidebar._groupPluralNameMap.get(this._filter.name);this.title=`${prefix} ${pluralizedName}`;} -onMessageAdded(viewMessage){var message=viewMessage.consoleMessage();var shouldIncrementCounter=message.type!==ConsoleModel.ConsoleMessage.MessageType.Command&&message.type!==ConsoleModel.ConsoleMessage.MessageType.Result&&!message.isGroupMessage();if(!this._filter.shouldBeVisible(viewMessage)||!shouldIncrementCounter) -return;var child=this._childElement(message.url);child.incrementAndUpdateCounter();this._messageCount++;this._updateCounter();} -_childElement(url){var urlValue=url||null;var child=this._urlTreeElements.get(urlValue);if(child) -return child;var filter=this._filter.clone();var parsedURL=urlValue?urlValue.asParsedURL():null;if(urlValue) -filter.name=parsedURL?parsedURL.displayName:urlValue;else -filter.name=Common.UIString('<other>');filter.parsedFilters.push({key:Console.ConsoleFilter.FilterType.Url,text:urlValue,negative:false});var badge=parsedURL?this._badgePool.badgeForURL(parsedURL):null;child=new Console.ConsoleSidebar.URLGroupTreeElement(filter,badge);if(urlValue) -child.tooltip=urlValue;this._urlTreeElements.set(urlValue,child);this.appendChild(child);return child;}};Console.ConsoleSidebar._groupSingularName={ConsoleAPI:Common.UIString('user message'),All:Common.UIString('message'),Error:Common.UIString('error'),Warning:Common.UIString('warning'),Info:Common.UIString('info'),Verbose:Common.UIString('verbose')};Console.ConsoleSidebar._groupPluralNameMap=new Map([[Console.ConsoleSidebar._groupSingularName.ConsoleAPI,Common.UIString('user messages')],[Console.ConsoleSidebar._groupSingularName.All,Common.UIString('messages')],[Console.ConsoleSidebar._groupSingularName.Error,Common.UIString('errors')],[Console.ConsoleSidebar._groupSingularName.Warning,Common.UIString('warnings')],[Console.ConsoleSidebar._groupSingularName.Info,Common.UIString('info')],[Console.ConsoleSidebar._groupSingularName.Verbose,Common.UIString('verbose')]]);;Console.ConsoleViewport=class{constructor(provider){this.element=createElement('div');this.element.style.overflow='auto';this._topGapElement=this.element.createChild('div');this._topGapElement.style.height='0px';this._topGapElement.style.color='transparent';this._contentElement=this.element.createChild('div');this._bottomGapElement=this.element.createChild('div');this._bottomGapElement.style.height='0px';this._bottomGapElement.style.color='transparent';this._topGapElement.textContent='\uFEFF';this._bottomGapElement.textContent='\uFEFF';this._provider=provider;this.element.addEventListener('scroll',this._onScroll.bind(this),false);this.element.addEventListener('copy',this._onCopy.bind(this),false);this.element.addEventListener('dragstart',this._onDragStart.bind(this),false);this._firstActiveIndex=0;this._lastActiveIndex=-1;this._renderedItems=[];this._anchorSelection=null;this._headSelection=null;this._itemCount=0;this._cumulativeHeights=new Int32Array(0);this._observer=new MutationObserver(this.refresh.bind(this));this._observerConfig={childList:true,subtree:true};} -stickToBottom(){return this._stickToBottom;} -setStickToBottom(value){this._stickToBottom=value;if(this._stickToBottom) -this._observer.observe(this._contentElement,this._observerConfig);else -this._observer.disconnect();} -_onCopy(event){var text=this._selectedText();if(!text) -return;event.preventDefault();event.clipboardData.setData('text/plain',text);} -_onDragStart(event){var text=this._selectedText();if(!text) -return false;event.dataTransfer.clearData();event.dataTransfer.setData('text/plain',text);event.dataTransfer.effectAllowed='copy';return true;} -contentElement(){return this._contentElement;} -invalidate(){delete this._cachedProviderElements;this._itemCount=this._provider.itemCount();this._rebuildCumulativeHeights();this.refresh();} -_providerElement(index){if(!this._cachedProviderElements) -this._cachedProviderElements=new Array(this._itemCount);var element=this._cachedProviderElements[index];if(!element){element=this._provider.itemElement(index);this._cachedProviderElements[index]=element;} -return element;} -_rebuildCumulativeHeights(){var firstActiveIndex=this._firstActiveIndex;var lastActiveIndex=this._lastActiveIndex;var height=0;this._cumulativeHeights=new Int32Array(this._itemCount);for(var i=0;i<this._itemCount;++i){if(firstActiveIndex<=i&&i-firstActiveIndex<this._renderedItems.length&&i<=lastActiveIndex) -height+=this._renderedItems[i-firstActiveIndex].element().offsetHeight;else -height+=this._provider.fastHeight(i);this._cumulativeHeights[i]=height;}} -_cachedItemHeight(index){return index===0?this._cumulativeHeights[0]:this._cumulativeHeights[index]-this._cumulativeHeights[index-1];} -_isSelectionBackwards(selection){if(!selection||!selection.rangeCount) -return false;var range=document.createRange();range.setStart(selection.anchorNode,selection.anchorOffset);range.setEnd(selection.focusNode,selection.focusOffset);return range.collapsed;} -_createSelectionModel(itemIndex,node,offset){return{item:itemIndex,node:node,offset:offset};} -_updateSelectionModel(selection){var range=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!range||selection.isCollapsed||!this.element.hasSelection()){this._headSelection=null;this._anchorSelection=null;return false;} -var firstSelected=Number.MAX_VALUE;var lastSelected=-1;var hasVisibleSelection=false;for(var i=0;i<this._renderedItems.length;++i){if(range.intersectsNode(this._renderedItems[i].element())){var index=i+this._firstActiveIndex;firstSelected=Math.min(firstSelected,index);lastSelected=Math.max(lastSelected,index);hasVisibleSelection=true;}} -if(hasVisibleSelection){firstSelected=this._createSelectionModel(firstSelected,(range.startContainer),range.startOffset);lastSelected=this._createSelectionModel(lastSelected,(range.endContainer),range.endOffset);} -var topOverlap=range.intersectsNode(this._topGapElement)&&this._topGapElement._active;var bottomOverlap=range.intersectsNode(this._bottomGapElement)&&this._bottomGapElement._active;if(!topOverlap&&!bottomOverlap&&!hasVisibleSelection){this._headSelection=null;this._anchorSelection=null;return false;} -if(!this._anchorSelection||!this._headSelection){this._anchorSelection=this._createSelectionModel(0,this.element,0);this._headSelection=this._createSelectionModel(this._itemCount-1,this.element,this.element.children.length);this._selectionIsBackward=false;} -var isBackward=this._isSelectionBackwards(selection);var startSelection=this._selectionIsBackward?this._headSelection:this._anchorSelection;var endSelection=this._selectionIsBackward?this._anchorSelection:this._headSelection;if(topOverlap&&bottomOverlap&&hasVisibleSelection){firstSelected=firstSelected.item<startSelection.item?firstSelected:startSelection;lastSelected=lastSelected.item>endSelection.item?lastSelected:endSelection;}else if(!hasVisibleSelection){firstSelected=startSelection;lastSelected=endSelection;}else if(topOverlap){firstSelected=isBackward?this._headSelection:this._anchorSelection;}else if(bottomOverlap){lastSelected=isBackward?this._anchorSelection:this._headSelection;} -if(isBackward){this._anchorSelection=lastSelected;this._headSelection=firstSelected;}else{this._anchorSelection=firstSelected;this._headSelection=lastSelected;} -this._selectionIsBackward=isBackward;return true;} -_restoreSelection(selection){var anchorElement=null;var anchorOffset;if(this._firstActiveIndex<=this._anchorSelection.item&&this._anchorSelection.item<=this._lastActiveIndex){anchorElement=this._anchorSelection.node;anchorOffset=this._anchorSelection.offset;}else{if(this._anchorSelection.item<this._firstActiveIndex) -anchorElement=this._topGapElement;else if(this._anchorSelection.item>this._lastActiveIndex) -anchorElement=this._bottomGapElement;anchorOffset=this._selectionIsBackward?1:0;} -var headElement=null;var headOffset;if(this._firstActiveIndex<=this._headSelection.item&&this._headSelection.item<=this._lastActiveIndex){headElement=this._headSelection.node;headOffset=this._headSelection.offset;}else{if(this._headSelection.item<this._firstActiveIndex) -headElement=this._topGapElement;else if(this._headSelection.item>this._lastActiveIndex) -headElement=this._bottomGapElement;headOffset=this._selectionIsBackward?0:1;} -selection.setBaseAndExtent(anchorElement,anchorOffset,headElement,headOffset);} -refresh(){this._observer.disconnect();this._innerRefresh();if(this._stickToBottom) -this._observer.observe(this._contentElement,this._observerConfig);} -_innerRefresh(){if(!this._visibleHeight()) -return;if(!this._itemCount){for(var i=0;i<this._renderedItems.length;++i) -this._renderedItems[i].willHide();this._renderedItems=[];this._contentElement.removeChildren();this._topGapElement.style.height='0px';this._bottomGapElement.style.height='0px';this._firstActiveIndex=-1;this._lastActiveIndex=-1;return;} -var selection=this.element.getComponentSelection();var shouldRestoreSelection=this._updateSelectionModel(selection);var visibleFrom=this.element.scrollTop;var visibleHeight=this._visibleHeight();for(var i=0;i<this._renderedItems.length;++i){var cachedItemHeight=this._cachedItemHeight(this._firstActiveIndex+i);if(Math.abs(cachedItemHeight-this._renderedItems[i].element().offsetHeight)>1){this._rebuildCumulativeHeights();break;}} -var activeHeight=visibleHeight*2;if(this._stickToBottom){this._firstActiveIndex=Math.max(this._itemCount-Math.ceil(activeHeight/this._provider.minimumRowHeight()),0);this._lastActiveIndex=this._itemCount-1;}else{this._firstActiveIndex=Math.max(Int32Array.prototype.lowerBound.call(this._cumulativeHeights,visibleFrom+1-(activeHeight-visibleHeight)/2),0);this._lastActiveIndex=this._firstActiveIndex+Math.ceil(activeHeight/this._provider.minimumRowHeight())-1;this._lastActiveIndex=Math.min(this._lastActiveIndex,this._itemCount-1);} -var topGapHeight=this._cumulativeHeights[this._firstActiveIndex-1]||0;var bottomGapHeight=this._cumulativeHeights[this._cumulativeHeights.length-1]-this._cumulativeHeights[this._lastActiveIndex];function prepare(){this._topGapElement.style.height=topGapHeight+'px';this._bottomGapElement.style.height=bottomGapHeight+'px';this._topGapElement._active=!!topGapHeight;this._bottomGapElement._active=!!bottomGapHeight;this._contentElement.style.setProperty('height','10000000px');} -this._partialViewportUpdate(prepare.bind(this));this._contentElement.style.removeProperty('height');if(shouldRestoreSelection) -this._restoreSelection(selection);if(this._stickToBottom) -this.element.scrollTop=10000000;} -_partialViewportUpdate(prepare){var itemsToRender=new Set();for(var i=this._firstActiveIndex;i<=this._lastActiveIndex;++i) -itemsToRender.add(this._providerElement(i));var willBeHidden=this._renderedItems.filter(item=>!itemsToRender.has(item));for(var i=0;i<willBeHidden.length;++i) -willBeHidden[i].willHide();prepare();for(var i=0;i<willBeHidden.length;++i) -willBeHidden[i].element().remove();var wasShown=[];var anchor=this._contentElement.firstChild;for(var viewportElement of itemsToRender){var element=viewportElement.element();if(element!==anchor){var shouldCallWasShown=!element.parentElement;if(shouldCallWasShown) -wasShown.push(viewportElement);this._contentElement.insertBefore(element,anchor);}else{anchor=anchor.nextSibling;}} -for(var i=0;i<wasShown.length;++i) -wasShown[i].wasShown();this._renderedItems=Array.from(itemsToRender);} -_selectedText(){this._updateSelectionModel(this.element.getComponentSelection());if(!this._headSelection||!this._anchorSelection) -return null;var startSelection=null;var endSelection=null;if(this._selectionIsBackward){startSelection=this._headSelection;endSelection=this._anchorSelection;}else{startSelection=this._anchorSelection;endSelection=this._headSelection;} -var textLines=[];for(var i=startSelection.item;i<=endSelection.item;++i){var element=this._providerElement(i).element();var lineContent=element.childTextNodes().map(Components.Linkifier.untruncatedNodeText).join('');textLines.push(lineContent);} -var endSelectionElement=this._providerElement(endSelection.item).element();if(endSelection.node&&endSelection.node.isSelfOrDescendant(endSelectionElement)){var itemTextOffset=this._textOffsetInNode(endSelectionElement,endSelection.node,endSelection.offset);textLines[textLines.length-1]=textLines.peekLast().substring(0,itemTextOffset);} -var startSelectionElement=this._providerElement(startSelection.item).element();if(startSelection.node&&startSelection.node.isSelfOrDescendant(startSelectionElement)){var itemTextOffset=this._textOffsetInNode(startSelectionElement,startSelection.node,startSelection.offset);textLines[0]=textLines[0].substring(itemTextOffset);} -return textLines.join('\n');} -_textOffsetInNode(itemElement,selectionNode,offset){if(selectionNode.nodeType!==Node.TEXT_NODE){if(offset<selectionNode.childNodes.length){selectionNode=(selectionNode.childNodes.item(offset));offset=0;}else{offset=selectionNode.textContent.length;}} -var chars=0;var node=itemElement;while((node=node.traverseNextNode(itemElement))&&node!==selectionNode){if(node.nodeType!==Node.TEXT_NODE||node.parentElement.nodeName==='STYLE'||node.parentElement.nodeName==='SCRIPT') -continue;chars+=Components.Linkifier.untruncatedNodeText(node).length;} -var untruncatedContainerLength=Components.Linkifier.untruncatedNodeText(selectionNode).length;if(offset>0&&untruncatedContainerLength!==selectionNode.textContent.length) -offset=untruncatedContainerLength;return chars+offset;} -_onScroll(event){this.refresh();} -firstVisibleIndex(){var firstVisibleIndex=Math.max(Int32Array.prototype.lowerBound.call(this._cumulativeHeights,this.element.scrollTop+1),0);return Math.max(firstVisibleIndex,this._firstActiveIndex);} -lastVisibleIndex(){var lastVisibleIndex;if(this._stickToBottom){lastVisibleIndex=this._itemCount-1;}else{lastVisibleIndex=this.firstVisibleIndex()+Math.ceil(this._visibleHeight()/this._provider.minimumRowHeight())-1;} -return Math.min(lastVisibleIndex,this._lastActiveIndex);} -renderedElementAt(index){if(index<this._firstActiveIndex) -return null;if(index>this._lastActiveIndex) -return null;return this._renderedItems[index-this._firstActiveIndex].element();} -scrollItemIntoView(index,makeLast){var firstVisibleIndex=this.firstVisibleIndex();var lastVisibleIndex=this.lastVisibleIndex();if(index>firstVisibleIndex&&index<lastVisibleIndex) -return;if(makeLast) -this.forceScrollItemToBeLast(index);else if(index<=firstVisibleIndex) -this.forceScrollItemToBeFirst(index);else if(index>=lastVisibleIndex) -this.forceScrollItemToBeLast(index);} -forceScrollItemToBeFirst(index){this.setStickToBottom(false);this.element.scrollTop=index>0?this._cumulativeHeights[index-1]:0;if(this.element.isScrolledToBottom()) -this.setStickToBottom(true);this.refresh();} -forceScrollItemToBeLast(index){this.setStickToBottom(false);this.element.scrollTop=this._cumulativeHeights[index]-this._visibleHeight();if(this.element.isScrolledToBottom()) -this.setStickToBottom(true);this.refresh();} -_visibleHeight(){return this.element.offsetHeight;}};Console.ConsoleViewportProvider=function(){};Console.ConsoleViewportProvider.prototype={fastHeight(index){return 0;},itemCount(){return 0;},minimumRowHeight(){return 0;},itemElement(index){return null;}};Console.ConsoleViewportElement=function(){};Console.ConsoleViewportElement.prototype={willHide(){},wasShown(){},element(){},};;Console.ConsoleViewMessage=class{constructor(consoleMessage,linkifier,badgePool,nestingLevel){this._message=consoleMessage;this._linkifier=linkifier;this._badgePool=badgePool;this._repeatCount=1;this._closeGroupDecorationCount=0;this._nestingLevel=nestingLevel;this._dataGrid=null;this._previewFormatter=new ObjectUI.RemoteObjectPreviewFormatter();this._searchRegex=null;this._messageLevelIcon=null;} -element(){return this.toMessageElement();} -wasShown(){if(this._dataGrid) -this._dataGrid.updateWidths();this._isVisible=true;} -onResize(){if(!this._isVisible) -return;if(this._dataGrid) -this._dataGrid.onResize();} -willHide(){this._isVisible=false;this._cachedHeight=this.contentElement().offsetHeight;} -fastHeight(){if(this._cachedHeight) -return this._cachedHeight;const defaultConsoleRowHeight=19;if(this._message.type===ConsoleModel.ConsoleMessage.MessageType.Table){var table=this._message.parameters[0];if(table&&table.preview) -return defaultConsoleRowHeight*table.preview.properties.length;} -return defaultConsoleRowHeight;} -consoleMessage(){return this._message;} -_buildTableMessage(){var formattedMessage=createElement('span');UI.appendStyle(formattedMessage,'object_ui/objectValue.css');formattedMessage.className='source-code';var anchorElement=this._buildMessageAnchor();if(anchorElement) -formattedMessage.appendChild(anchorElement);var badgeElement=this._buildMessageBadge();if(badgeElement) -formattedMessage.appendChild(badgeElement);var table=this._message.parameters&&this._message.parameters.length?this._message.parameters[0]:null;if(table) -table=this._parameterToRemoteObject(table);if(!table||!table.preview) -return formattedMessage;var rawValueColumnSymbol=Symbol('rawValueColumn');var columnNames=[];var preview=table.preview;var rows=[];for(var i=0;i<preview.properties.length;++i){var rowProperty=preview.properties[i];var rowSubProperties;if(rowProperty.valuePreview) -rowSubProperties=rowProperty.valuePreview.properties;else if(rowProperty.value) -rowSubProperties=[{name:rawValueColumnSymbol,type:rowProperty.type,value:rowProperty.value}];else -continue;var rowValue={};const maxColumnsToRender=20;for(var j=0;j<rowSubProperties.length;++j){var cellProperty=rowSubProperties[j];var columnRendered=columnNames.indexOf(cellProperty.name)!==-1;if(!columnRendered){if(columnNames.length===maxColumnsToRender) -continue;columnRendered=true;columnNames.push(cellProperty.name);} -if(columnRendered){var cellElement=this._renderPropertyPreviewOrAccessor(table,[rowProperty,cellProperty]);cellElement.classList.add('console-message-nowrap-below');rowValue[cellProperty.name]=cellElement;}} -rows.push([rowProperty.name,rowValue]);} -var flatValues=[];for(var i=0;i<rows.length;++i){var rowName=rows[i][0];var rowValue=rows[i][1];flatValues.push(rowName);for(var j=0;j<columnNames.length;++j) -flatValues.push(rowValue[columnNames[j]]);} -columnNames.unshift(Common.UIString('(index)'));var columnDisplayNames=columnNames.map(name=>name===rawValueColumnSymbol?Common.UIString('Value'):name);if(flatValues.length){this._dataGrid=DataGrid.SortableDataGrid.create(columnDisplayNames,flatValues);this._dataGrid.setStriped(true);var formattedResult=createElementWithClass('span','console-message-text');var tableElement=formattedResult.createChild('div','console-message-formatted-table');var dataGridContainer=tableElement.createChild('span');tableElement.appendChild(this._formatParameter(table,true,false));dataGridContainer.appendChild(this._dataGrid.element);formattedMessage.appendChild(formattedResult);this._dataGrid.renderInline();} -return formattedMessage;} -_buildMessage(){var messageElement;var messageText=this._message.messageText;if(this._message.source===ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI){switch(this._message.type){case ConsoleModel.ConsoleMessage.MessageType.Trace:messageElement=this._format(this._message.parameters||['console.trace']);break;case ConsoleModel.ConsoleMessage.MessageType.Clear:messageElement=createElementWithClass('span','console-info');if(Common.moduleSetting('preserveConsoleLog').get()) -messageElement.textContent=Common.UIString('console.clear() was prevented due to \'Preserve log\'');else -messageElement.textContent=Common.UIString('Console was cleared');messageElement.title=Common.UIString('Clear all messages with '+UI.shortcutRegistry.shortcutTitleForAction('console.clear'));break;case ConsoleModel.ConsoleMessage.MessageType.Assert:var args=[Common.UIString('Assertion failed:')];if(this._message.parameters) -args=args.concat(this._message.parameters);messageElement=this._format(args);break;case ConsoleModel.ConsoleMessage.MessageType.Dir:var obj=this._message.parameters?this._message.parameters[0]:undefined;var args=['%O',obj];messageElement=this._format(args);break;case ConsoleModel.ConsoleMessage.MessageType.Profile:case ConsoleModel.ConsoleMessage.MessageType.ProfileEnd:messageElement=this._format([messageText]);break;default:if(this._message.parameters&&this._message.parameters.length===1&&this._message.parameters[0].type==='string') -messageElement=this._tryFormatAsError((this._message.parameters[0].value));var args=this._message.parameters||[messageText];messageElement=messageElement||this._format(args);}}else if(this._message.source===ConsoleModel.ConsoleMessage.MessageSource.Network){var request=this._message.request;if(request){messageElement=createElement('span');if(this._message.level===ConsoleModel.ConsoleMessage.MessageLevel.Error){messageElement.createTextChild(request.requestMethod+' ');messageElement.appendChild(Components.Linkifier.linkifyRevealable(request,request.url(),request.url()));if(request.failed) -messageElement.createTextChildren(' ',request.localizedFailDescription);else -messageElement.createTextChildren(' ',String(request.statusCode),' (',request.statusText,')');}else{var fragment=Console.ConsoleViewMessage._linkifyWithCustomLinkifier(messageText,title=>Components.Linkifier.linkifyRevealable((request),title,request.url()));messageElement.appendChild(fragment);}}else{messageElement=this._format([messageText]);}}else{var messageInParameters=this._message.parameters&&messageText===(this._message.parameters[0]);if(this._message.source===ConsoleModel.ConsoleMessage.MessageSource.Violation) -messageText=Common.UIString('[Violation] %s',messageText);else if(this._message.source===ConsoleModel.ConsoleMessage.MessageSource.Intervention) -messageText=Common.UIString('[Intervention] %s',messageText);else if(this._message.source===ConsoleModel.ConsoleMessage.MessageSource.Deprecation) -messageText=Common.UIString('[Deprecation] %s',messageText);var args=this._message.parameters||[messageText];if(messageInParameters) -args[0]=messageText;messageElement=this._format(args);} -messageElement.classList.add('console-message-text');var formattedMessage=createElement('span');UI.appendStyle(formattedMessage,'object_ui/objectValue.css');formattedMessage.className='source-code';var anchorElement=this._buildMessageAnchor();if(anchorElement) -formattedMessage.appendChild(anchorElement);var badgeElement=this._buildMessageBadge();if(badgeElement) -formattedMessage.appendChild(badgeElement);formattedMessage.appendChild(messageElement);return formattedMessage;} -_buildMessageAnchor(){var anchorElement=null;if(this._message.source!==ConsoleModel.ConsoleMessage.MessageSource.Network||this._message.request){if(this._message.scriptId){anchorElement=this._linkifyScriptId(this._message.scriptId,this._message.url||'',this._message.line,this._message.column);}else if(this._message.stackTrace&&this._message.stackTrace.callFrames.length){anchorElement=this._linkifyStackTraceTopFrame(this._message.stackTrace);}else if(this._message.url&&this._message.url!=='undefined'){anchorElement=this._linkifyLocation(this._message.url,this._message.line,this._message.column);}}else if(this._message.url){anchorElement=Components.Linkifier.linkifyURL(this._message.url,{maxLength:Console.ConsoleViewMessage.MaxLengthForLinks});} -if(anchorElement){var anchorWrapperElement=createElementWithClass('span','console-message-anchor');anchorWrapperElement.appendChild(anchorElement);anchorWrapperElement.createTextChild(' ');return anchorWrapperElement;} -return null;} -_buildMessageBadge(){var badgeElement=this._badgeElement();if(!badgeElement) -return null;badgeElement.classList.add('console-message-badge');return badgeElement;} -_badgeElement(){if(this._message._url) -return this._badgePool.badgeForURL(new Common.ParsedURL(this._message._url));if(this._message.stackTrace){var stackTrace=this._message.stackTrace;while(stackTrace){for(var callFrame of this._message.stackTrace.callFrames){if(callFrame.url) -return this._badgePool.badgeForURL(new Common.ParsedURL(callFrame.url));} -stackTrace=stackTrace.parent;}} -if(!this._message.executionContextId) -return null;var runtimeModel=this._message.runtimeModel();if(!runtimeModel) -return null;var executionContext=runtimeModel.executionContext(this._message.executionContextId);if(!executionContext||!executionContext.frameId) -return null;var resourceTreeModel=executionContext.target().model(SDK.ResourceTreeModel);if(!resourceTreeModel) -return null;var frame=resourceTreeModel.frameForId(executionContext.frameId);if(!frame||!frame.parentFrame) -return null;return this._badgePool.badgeForFrame(frame);} -_buildMessageWithStackTrace(){var toggleElement=createElementWithClass('div','console-message-stack-trace-toggle');var contentElement=toggleElement.createChild('div','console-message-stack-trace-wrapper');var messageElement=this._buildMessage();var icon=UI.Icon.create('smallicon-triangle-right','console-message-expand-icon');var clickableElement=contentElement.createChild('div');clickableElement.appendChild(icon);clickableElement.appendChild(messageElement);var stackTraceElement=contentElement.createChild('div');var stackTracePreview=Components.DOMPresentationUtils.buildStackTracePreviewContents(this._message.runtimeModel().target(),this._linkifier,this._message.stackTrace);stackTraceElement.appendChild(stackTracePreview);stackTraceElement.classList.add('hidden');function expandStackTrace(expand){icon.setIconType(expand?'smallicon-triangle-down':'smallicon-triangle-right');stackTraceElement.classList.toggle('hidden',!expand);} -function toggleStackTrace(event){if(event.target.hasSelection()) -return;expandStackTrace(stackTraceElement.classList.contains('hidden'));event.consume();} -clickableElement.addEventListener('click',toggleStackTrace,false);if(this._message.type===ConsoleModel.ConsoleMessage.MessageType.Trace) -expandStackTrace(true);toggleElement._expandStackTraceForTest=expandStackTrace.bind(null,true);return toggleElement;} -_linkifyLocation(url,lineNumber,columnNumber){if(!this._message.runtimeModel()) -return null;return this._linkifier.linkifyScriptLocation(this._message.runtimeModel().target(),null,url,lineNumber,columnNumber);} -_linkifyStackTraceTopFrame(stackTrace){if(!this._message.runtimeModel()) -return null;return this._linkifier.linkifyStackTraceTopFrame(this._message.runtimeModel().target(),stackTrace);} -_linkifyScriptId(scriptId,url,lineNumber,columnNumber){if(!this._message.runtimeModel()) -return null;return this._linkifier.linkifyScriptLocation(this._message.runtimeModel().target(),scriptId,url,lineNumber,columnNumber);} -_parameterToRemoteObject(parameter){if(parameter instanceof SDK.RemoteObject) -return parameter;var runtimeModel=this._message.runtimeModel();if(!runtimeModel) -return SDK.RemoteObject.fromLocalObject(parameter);if(typeof parameter==='object') -return runtimeModel.createRemoteObject(parameter);return runtimeModel.createRemoteObjectFromPrimitiveValue(parameter);} -_format(rawParameters){var formattedResult=createElement('span');if(!rawParameters.length) -return formattedResult;var parameters=[];for(var i=0;i<rawParameters.length;++i) -parameters[i]=this._parameterToRemoteObject(rawParameters[i]);var shouldFormatMessage=SDK.RemoteObject.type(((parameters))[0])==='string'&&(this._message.type!==ConsoleModel.ConsoleMessage.MessageType.Result||this._message.level===ConsoleModel.ConsoleMessage.MessageLevel.Error);if(shouldFormatMessage){var result=this._formatWithSubstitutionString((parameters[0].description),parameters.slice(1),formattedResult);parameters=result.unusedSubstitutions;if(parameters.length) -formattedResult.createTextChild(' ');} -for(var i=0;i<parameters.length;++i){if(shouldFormatMessage&¶meters[i].type==='string') -formattedResult.appendChild(Console.ConsoleViewMessage._linkifyStringAsFragment(parameters[i].description));else -formattedResult.appendChild(this._formatParameter(parameters[i],false,true));if(i<parameters.length-1) -formattedResult.createTextChild(' ');} -return formattedResult;} -_formatParameter(output,forceObjectFormat,includePreview){if(output.customPreview()) -return(new ObjectUI.CustomPreviewComponent(output)).element;var type=forceObjectFormat?'object':(output.subtype||output.type);var element;switch(type){case'error':element=this._formatParameterAsError(output);break;case'function':element=this._formatParameterAsFunction(output,includePreview);break;case'array':case'arraybuffer':case'blob':case'dataview':case'generator':case'iterator':case'map':case'object':case'promise':case'proxy':case'set':case'typedarray':case'weakmap':case'weakset':element=this._formatParameterAsObject(output,includePreview);break;case'node':element=output.isNode()?this._formatParameterAsNode(output):this._formatParameterAsObject(output,false);break;case'string':element=this._formatParameterAsString(output);break;case'boolean':case'date':case'null':case'number':case'regexp':case'symbol':case'undefined':element=this._formatParameterAsValue(output);break;default:element=this._formatParameterAsValue(output);console.error('Tried to format remote object of unknown type.');} -element.classList.add('object-value-'+type);element.classList.add('source-code');return element;} -_formatParameterAsValue(obj){var result=createElement('span');result.createTextChild(obj.description||'');if(obj.objectId) -result.addEventListener('contextmenu',this._contextMenuEventFired.bind(this,obj),false);return result;} -_formatParameterAsObject(obj,includePreview){var titleElement=createElement('span');if(includePreview&&obj.preview){titleElement.classList.add('console-object-preview');this._previewFormatter.appendObjectPreview(titleElement,obj.preview,false);}else if(obj.type==='function'){ObjectUI.ObjectPropertiesSection.formatObjectAsFunction(obj,titleElement,false);titleElement.classList.add('object-value-function');}else{titleElement.createTextChild(obj.description||'');} -if(!obj.hasChildren||obj.customPreview()) -return titleElement;var note=titleElement.createChild('span','object-state-note');note.classList.add('info-note');note.title=Common.UIString('Value below was evaluated just now.');var section=new ObjectUI.ObjectPropertiesSection(obj,titleElement,this._linkifier);section.element.classList.add('console-view-object-properties-section');section.enableContextMenu();return section.element;} -_formatParameterAsFunction(func,includePreview){var result=createElement('span');SDK.RemoteFunction.objectAsFunction(func).targetFunction().then(formatTargetFunction.bind(this));return result;function formatTargetFunction(targetFunction){var functionElement=createElement('span');ObjectUI.ObjectPropertiesSection.formatObjectAsFunction(targetFunction,functionElement,true,includePreview);result.appendChild(functionElement);if(targetFunction!==func){var note=result.createChild('span','object-info-state-note');note.title=Common.UIString('Function was resolved from bound function.');} -result.addEventListener('contextmenu',this._contextMenuEventFired.bind(this,targetFunction),false);}} -_contextMenuEventFired(obj,event){var contextMenu=new UI.ContextMenu(event);contextMenu.appendApplicableItems(obj);contextMenu.show();} -_renderPropertyPreviewOrAccessor(object,propertyPath){var property=propertyPath.peekLast();if(property.type==='accessor') -return this._formatAsAccessorProperty(object,propertyPath.map(property=>property.name),false);return this._previewFormatter.renderPropertyPreview(property.type,(property.subtype),property.value);} -_formatParameterAsNode(remoteObject){var result=createElement('span');var domModel=remoteObject.runtimeModel().target().model(SDK.DOMModel);if(!domModel) -return result;domModel.pushObjectAsNodeToFrontend(remoteObject).then(node=>{if(!node){result.appendChild(this._formatParameterAsObject(remoteObject,false));return;} -Common.Renderer.renderPromise(node).then(rendererElement=>{result.appendChild(rendererElement);this._formattedParameterAsNodeForTest();});});return result;} -_formattedParameterAsNodeForTest(){} -_formatParameterAsString(output){var span=createElement('span');span.appendChild(Console.ConsoleViewMessage._linkifyStringAsFragment(output.description||''));var result=createElement('span');result.createChild('span','object-value-string-quote').textContent='"';result.appendChild(span);result.createChild('span','object-value-string-quote').textContent='"';return result;} -_formatParameterAsError(output){var result=createElement('span');var errorSpan=this._tryFormatAsError(output.description||'');result.appendChild(errorSpan?errorSpan:Console.ConsoleViewMessage._linkifyStringAsFragment(output.description||''));return result;} -_formatAsArrayEntry(output){return this._previewFormatter.renderPropertyPreview(output.type,output.subtype,output.description);} -_formatAsAccessorProperty(object,propertyPath,isArrayEntry){var rootElement=ObjectUI.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan(object,propertyPath,onInvokeGetterClick.bind(this));function onInvokeGetterClick(result,wasThrown){if(!result) -return;rootElement.removeChildren();if(wasThrown){var element=rootElement.createChild('span');element.textContent=Common.UIString('<exception>');element.title=(result.description);}else if(isArrayEntry){rootElement.appendChild(this._formatAsArrayEntry(result));}else{const maxLength=100;var type=result.type;var subtype=result.subtype;var description='';if(type!=='function'&&result.description){if(type==='string'||subtype==='regexp') -description=result.description.trimMiddle(maxLength);else -description=result.description.trimEnd(maxLength);} -rootElement.appendChild(this._previewFormatter.renderPropertyPreview(type,subtype,description));}} -return rootElement;} -_formatWithSubstitutionString(format,parameters,formattedResult){var formatters={};function parameterFormatter(force,includePreview,obj){return this._formatParameter(obj,force,includePreview);} -function stringFormatter(obj){return obj.description;} -function floatFormatter(obj){if(typeof obj.value!=='number') -return'NaN';return obj.value;} -function integerFormatter(obj){if(typeof obj.value!=='number') -return'NaN';return Math.floor(obj.value);} -function bypassFormatter(obj){return(obj instanceof Node)?obj:'';} -var currentStyle=null;function styleFormatter(obj){currentStyle={};var buffer=createElement('span');buffer.setAttribute('style',obj.description);for(var i=0;i<buffer.style.length;i++){var property=buffer.style[i];if(isWhitelistedProperty(property)) -currentStyle[property]=buffer.style[property];}} -function isWhitelistedProperty(property){var prefixes=['background','border','color','font','line','margin','padding','text','-webkit-background','-webkit-border','-webkit-font','-webkit-margin','-webkit-padding','-webkit-text'];for(var i=0;i<prefixes.length;i++){if(property.startsWith(prefixes[i])) -return true;} -return false;} -formatters.o=parameterFormatter.bind(this,false,true);formatters.s=stringFormatter;formatters.f=floatFormatter;formatters.i=integerFormatter;formatters.d=integerFormatter;formatters.c=styleFormatter;formatters.O=parameterFormatter.bind(this,true,false);formatters._=bypassFormatter;function append(a,b){if(b instanceof Node){a.appendChild(b);}else if(typeof b!=='undefined'){var toAppend=Console.ConsoleViewMessage._linkifyStringAsFragment(String(b));if(currentStyle){var wrapper=createElement('span');wrapper.appendChild(toAppend);applyCurrentStyle(wrapper);for(var i=0;i<wrapper.children.length;++i) -applyCurrentStyle(wrapper.children[i]);toAppend=wrapper;} -a.appendChild(toAppend);} -return a;} -function applyCurrentStyle(element){for(var key in currentStyle) -element.style[key]=currentStyle[key];} -return String.format(format,parameters,formatters,formattedResult,append);} -matchesFilterRegex(regexObject){regexObject.lastIndex=0;var text=this.contentElement().deepTextContent();return regexObject.test(text);} -matchesFilterText(filter){var text=this.contentElement().deepTextContent();return text.toLowerCase().includes(filter.toLowerCase());} -updateTimestamp(){if(!this._contentElement) -return;if(Common.moduleSetting('consoleTimestampsEnabled').get()){if(!this._timestampElement) -this._timestampElement=createElementWithClass('span','console-timestamp');this._timestampElement.textContent=formatTimestamp(this._message.timestamp,false)+' ';this._timestampElement.title=formatTimestamp(this._message.timestamp,true);this._contentElement.insertBefore(this._timestampElement,this._contentElement.firstChild);}else if(this._timestampElement){this._timestampElement.remove();delete this._timestampElement;} -function formatTimestamp(timestamp,full){var date=new Date(timestamp);var yymmdd=date.getFullYear()+'-'+leadZero(date.getMonth()+1,2)+'-'+leadZero(date.getDate(),2);var hhmmssfff=leadZero(date.getHours(),2)+':'+leadZero(date.getMinutes(),2)+':'+ -leadZero(date.getSeconds(),2)+'.'+leadZero(date.getMilliseconds(),3);return full?(yymmdd+' '+hhmmssfff):hhmmssfff;function leadZero(value,length){var valueString=value.toString();var padding=length-valueString.length;return padding<=0?valueString:'0'.repeat(padding)+valueString;}}} -nestingLevel(){return this._nestingLevel;} -setInSimilarGroup(inSimilarGroup,isLast){this._inSimilarGroup=inSimilarGroup;this._lastInSimilarGroup=inSimilarGroup&&!!isLast;if(this._similarGroupMarker&&!inSimilarGroup){this._similarGroupMarker.remove();this._similarGroupMarker=null;}else if(this._element&&!this._similarGroupMarker&&inSimilarGroup){this._similarGroupMarker=createElementWithClass('div','nesting-level-marker');this._element.insertBefore(this._similarGroupMarker,this._element.firstChild);this._similarGroupMarker.classList.toggle('group-closed',this._lastInSimilarGroup);}} -isLastInSimilarGroup(){return this._inSimilarGroup&&this._lastInSimilarGroup;} -resetCloseGroupDecorationCount(){if(!this._closeGroupDecorationCount) -return;this._closeGroupDecorationCount=0;this._updateCloseGroupDecorations();} -incrementCloseGroupDecorationCount(){++this._closeGroupDecorationCount;this._updateCloseGroupDecorations();} -_updateCloseGroupDecorations(){if(!this._nestingLevelMarkers) -return;for(var i=0,n=this._nestingLevelMarkers.length;i<n;++i){var marker=this._nestingLevelMarkers[i];marker.classList.toggle('group-closed',n-i<=this._closeGroupDecorationCount);}} -contentElement(){if(this._contentElement) -return this._contentElement;var contentElement=createElementWithClass('div','console-message');if(this._messageLevelIcon) -contentElement.appendChild(this._messageLevelIcon);this._contentElement=contentElement;var formattedMessage;var shouldIncludeTrace=!!this._message.stackTrace&&(this._message.source===ConsoleModel.ConsoleMessage.MessageSource.Network||this._message.source===ConsoleModel.ConsoleMessage.MessageSource.Violation||this._message.level===ConsoleModel.ConsoleMessage.MessageLevel.Error||this._message.level===ConsoleModel.ConsoleMessage.MessageLevel.Warning||this._message.type===ConsoleModel.ConsoleMessage.MessageType.Trace);if(this._message.runtimeModel()&&shouldIncludeTrace) -formattedMessage=this._buildMessageWithStackTrace();else if(this._message.type===ConsoleModel.ConsoleMessage.MessageType.Table) -formattedMessage=this._buildTableMessage();else -formattedMessage=this._buildMessage();contentElement.appendChild(formattedMessage);this.updateTimestamp();return this._contentElement;} -toMessageElement(){if(this._element) -return this._element;this._element=createElement('div');this.updateMessageElement();return this._element;} -updateMessageElement(){if(!this._element) -return;this._element.className='console-message-wrapper';this._element.removeChildren();if(this._message.isGroupStartMessage()) -this._element.classList.add('console-group-title');if(this._message.source===ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI) -this._element.classList.add('console-from-api');if(this._inSimilarGroup){this._similarGroupMarker=this._element.createChild('div','nesting-level-marker');this._similarGroupMarker.classList.toggle('group-closed',this._lastInSimilarGroup);} -this._nestingLevelMarkers=[];for(var i=0;i<this._nestingLevel;++i) -this._nestingLevelMarkers.push(this._element.createChild('div','nesting-level-marker'));this._updateCloseGroupDecorations();this._element.message=this;switch(this._message.level){case ConsoleModel.ConsoleMessage.MessageLevel.Verbose:this._element.classList.add('console-verbose-level');this._updateMessageLevelIcon('');break;case ConsoleModel.ConsoleMessage.MessageLevel.Info:this._element.classList.add('console-info-level');break;case ConsoleModel.ConsoleMessage.MessageLevel.Warning:this._element.classList.add('console-warning-level');this._updateMessageLevelIcon('smallicon-warning');break;case ConsoleModel.ConsoleMessage.MessageLevel.Error:this._element.classList.add('console-error-level');this._updateMessageLevelIcon('smallicon-error');break;} -if(this._shouldRenderAsWarning()) -this._element.classList.add('console-warning-level');this._element.appendChild(this.contentElement());if(this._repeatCount>1) -this._showRepeatCountElement();} -_shouldRenderAsWarning(){return(this._message.level===ConsoleModel.ConsoleMessage.MessageLevel.Verbose||this._message.level===ConsoleModel.ConsoleMessage.MessageLevel.Info)&&(this._message.source===ConsoleModel.ConsoleMessage.MessageSource.Violation||this._message.source===ConsoleModel.ConsoleMessage.MessageSource.Deprecation||this._message.source===ConsoleModel.ConsoleMessage.MessageSource.Intervention||this._message.source===ConsoleModel.ConsoleMessage.MessageSource.Recommendation);} -_updateMessageLevelIcon(iconType){if(!iconType&&!this._messageLevelIcon) -return;if(iconType&&!this._messageLevelIcon){this._messageLevelIcon=UI.Icon.create('','message-level-icon');if(this._contentElement) -this._contentElement.insertBefore(this._messageLevelIcon,this._contentElement.firstChild);} -this._messageLevelIcon.setIconType(iconType);} -repeatCount(){return this._repeatCount||1;} -resetIncrementRepeatCount(){this._repeatCount=1;if(!this._repeatCountElement) -return;this._repeatCountElement.remove();if(this._contentElement) -this._contentElement.classList.remove('repeated-message');delete this._repeatCountElement;} -incrementRepeatCount(){this._repeatCount++;this._showRepeatCountElement();} -setRepeatCount(repeatCount){this._repeatCount=repeatCount;this._showRepeatCountElement();} -_showRepeatCountElement(){if(!this._element) -return;if(!this._repeatCountElement){this._repeatCountElement=createElementWithClass('label','console-message-repeat-count','dt-small-bubble');switch(this._message.level){case ConsoleModel.ConsoleMessage.MessageLevel.Warning:this._repeatCountElement.type='warning';break;case ConsoleModel.ConsoleMessage.MessageLevel.Error:this._repeatCountElement.type='error';break;case ConsoleModel.ConsoleMessage.MessageLevel.Verbose:this._repeatCountElement.type='verbose';break;default:this._repeatCountElement.type='info';} -if(this._shouldRenderAsWarning()) -this._repeatCountElement.type='warning';this._element.insertBefore(this._repeatCountElement,this._contentElement);this._contentElement.classList.add('repeated-message');} -this._repeatCountElement.textContent=this._repeatCount;} -get text(){return this._message.messageText;} -toExportString(){var lines=[];var nodes=this.contentElement().childTextNodes();var messageContent=nodes.map(Components.Linkifier.untruncatedNodeText).join('');for(var i=0;i<this.repeatCount();++i) -lines.push(messageContent);return lines.join('\n');} -setSearchRegex(regex){if(this._searchHiglightNodeChanges&&this._searchHiglightNodeChanges.length) -UI.revertDomChanges(this._searchHiglightNodeChanges);this._searchRegex=regex;this._searchHighlightNodes=[];this._searchHiglightNodeChanges=[];if(!this._searchRegex) -return;var text=this.contentElement().deepTextContent();var match;this._searchRegex.lastIndex=0;var sourceRanges=[];while((match=this._searchRegex.exec(text))&&match[0]) -sourceRanges.push(new TextUtils.SourceRange(match.index,match[0].length));if(sourceRanges.length){this._searchHighlightNodes=UI.highlightSearchResults(this.contentElement(),sourceRanges,this._searchHiglightNodeChanges);}} -searchRegex(){return this._searchRegex;} -searchCount(){return this._searchHighlightNodes.length;} -searchHighlightNode(index){return this._searchHighlightNodes[index];} -_tryFormatAsError(string){function startsWith(prefix){return string.startsWith(prefix);} -var errorPrefixes=['EvalError','ReferenceError','SyntaxError','TypeError','RangeError','Error','URIError'];if(!this._message.runtimeModel()||!errorPrefixes.some(startsWith)) -return null;var debuggerModel=this._message.runtimeModel().debuggerModel();var lines=string.split('\n');var links=[];var position=0;for(var i=0;i<lines.length;++i){position+=i>0?lines[i-1].length+1:0;var isCallFrameLine=/^\s*at\s/.test(lines[i]);if(!isCallFrameLine&&links.length) -return null;if(!isCallFrameLine) -continue;var openBracketIndex=-1;var closeBracketIndex=-1;var match=/\([^\)\(]+\)/.exec(lines[i]);if(match){openBracketIndex=match.index;closeBracketIndex=match.index+match[0].length-1;} -var hasOpenBracket=openBracketIndex!==-1;var left=hasOpenBracket?openBracketIndex+1:lines[i].indexOf('at')+3;var right=hasOpenBracket?closeBracketIndex:lines[i].length;var linkCandidate=lines[i].substring(left,right);var splitResult=Common.ParsedURL.splitLineAndColumn(linkCandidate);if(!splitResult) -return null;var parsed=splitResult.url.asParsedURL();var url;if(parsed) -url=parsed.url;else if(debuggerModel.scriptsForSourceURL(splitResult.url).length) -url=splitResult.url;else if(splitResult.url==='<anonymous>') -continue;else -return null;links.push({url:url,positionLeft:position+left,positionRight:position+right,lineNumber:splitResult.lineNumber,columnNumber:splitResult.columnNumber});} -if(!links.length) -return null;var formattedResult=createElement('span');var start=0;for(var i=0;i<links.length;++i){formattedResult.appendChild(Console.ConsoleViewMessage._linkifyStringAsFragment(string.substring(start,links[i].positionLeft)));formattedResult.appendChild(this._linkifier.linkifyScriptLocation(debuggerModel.target(),null,links[i].url,links[i].lineNumber,links[i].columnNumber));start=links[i].positionRight;} -if(start!==string.length) -formattedResult.appendChild(Console.ConsoleViewMessage._linkifyStringAsFragment(string.substring(start)));return formattedResult;} -static _linkifyWithCustomLinkifier(string,linkifier){var container=createDocumentFragment();var tokens=this._tokenizeMessageText(string);for(var token of tokens){switch(token.type){case'url':{var realURL=(token.text.startsWith('www.')?'http://'+token.text:token.text);var splitResult=Common.ParsedURL.splitLineAndColumn(realURL);var linkNode;if(splitResult) -linkNode=linkifier(token.text,splitResult.url,splitResult.lineNumber,splitResult.columnNumber);else -linkNode=linkifier(token.text,token.value);container.appendChild(linkNode);break;} -default:container.appendChild(createTextNode(token.text));break;}} -return container;} -static _linkifyStringAsFragment(string){return Console.ConsoleViewMessage._linkifyWithCustomLinkifier(string,(text,url,lineNumber,columnNumber)=>{return Components.Linkifier.linkifyURL(url,{text,lineNumber,columnNumber});});} -static _tokenizeMessageText(string){if(!Console.ConsoleViewMessage._tokenizerRegexes){var linkStringRegex=/(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|data:|www\.)[\w$\-_+*'=\|\/\\(){}[\]^%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({^%@&#~]/;var pathLineRegex=/(?:\/[\w\.-]*)+\:[\d]+/;var timeRegex=/took [\d]+ms/;var eventRegex=/'\w+' event/;var milestoneRegex=/\sM[6-7]\d/;var autofillRegex=/\(suggested: \"[\w-]+\"\)/;var handlers=new Map();handlers.set(linkStringRegex,'url');handlers.set(pathLineRegex,'url');handlers.set(timeRegex,'time');handlers.set(eventRegex,'event');handlers.set(milestoneRegex,'milestone');handlers.set(autofillRegex,'autofill');Console.ConsoleViewMessage._tokenizerRegexes=Array.from(handlers.keys());Console.ConsoleViewMessage._tokenizerTypes=Array.from(handlers.values());} -var results=TextUtils.TextUtils.splitStringByRegexes(string,Console.ConsoleViewMessage._tokenizerRegexes);return results.map(result=>({text:result.value,type:Console.ConsoleViewMessage._tokenizerTypes[result.regexIndex]}));} -groupKey(){if(!this._groupKey) -this._groupKey=this._message.groupCategoryKey()+':'+this.groupTitle();return this._groupKey;} -groupTitle(){var tokens=Console.ConsoleViewMessage._tokenizeMessageText(this._message.messageText);var result=tokens.reduce((acc,token)=>{var text=token.text;if(token.type==='url') -text=Common.UIString('<URL>');else if(token.type==='time') -text=Common.UIString('took <N>ms');else if(token.type==='event') -text=Common.UIString('<some> event');else if(token.type==='milestone') -text=Common.UIString('M<XX>');else if(token.type==='autofill') -text=Common.UIString('<attribute>');return acc+text;},'');return result.replace(/[%]o/g,'');}};Console.ConsoleGroupViewMessage=class extends Console.ConsoleViewMessage{constructor(consoleMessage,linkifier,badgePool,nestingLevel){console.assert(consoleMessage.isGroupStartMessage());super(consoleMessage,linkifier,badgePool,nestingLevel);this._collapsed=consoleMessage.type===ConsoleModel.ConsoleMessage.MessageType.StartGroupCollapsed;this._expandGroupIcon=null;} -setCollapsed(collapsed){this._collapsed=collapsed;if(this._expandGroupIcon) -this._expandGroupIcon.setIconType(this._collapsed?'smallicon-triangle-right':'smallicon-triangle-down');} -collapsed(){return this._collapsed;} -toMessageElement(){if(!this._element){super.toMessageElement();this._expandGroupIcon=UI.Icon.create('','expand-group-icon');if(this._repeatCountElement) -this._repeatCountElement.insertBefore(this._expandGroupIcon,this._repeatCountElement.firstChild);else -this._element.insertBefore(this._expandGroupIcon,this._contentElement);this.setCollapsed(this._collapsed);} -return this._element;} -_showRepeatCountElement(){super._showRepeatCountElement();if(this._repeatCountElement&&this._expandGroupIcon) -this._repeatCountElement.insertBefore(this._expandGroupIcon,this._repeatCountElement.firstChild);}};Console.ConsoleViewMessage.MaxLengthForLinks=40;;Console.ConsolePrompt=class extends UI.Widget{constructor(){super();this._addCompletionsFromHistory=true;this._history=new Console.ConsoleHistoryManager();this._initialText='';this._editor=null;this.element.tabIndex=0;self.runtime.extension(UI.TextEditorFactory).instance().then(gotFactory.bind(this));function gotFactory(factory){this._editor=factory.createEditor({lineNumbers:false,lineWrapping:true,mimeType:'javascript',autoHeight:true});this._editor.configureAutocomplete({substituteRangeCallback:this._substituteRange.bind(this),suggestionsCallback:this._wordsWithQuery.bind(this),captureEnter:true});this._editor.widget().element.addEventListener('keydown',this._editorKeyDown.bind(this),true);this._editor.widget().show(this.element);this._editor.addEventListener(UI.TextEditor.Events.TextChanged,this._onTextChanged,this);this.setText(this._initialText);delete this._initialText;if(this.hasFocus()) -this.focus();this.element.tabIndex=-1;this._editorSetForTest();}} -_onTextChanged(){this.dispatchEventToListeners(Console.ConsolePrompt.Events.TextChanged);} -history(){return this._history;} -clearAutocomplete(){if(this._editor) -this._editor.clearAutocomplete();} -_isCaretAtEndOfPrompt(){return!!this._editor&&this._editor.selection().collapseToEnd().equal(this._editor.fullRange().collapseToEnd());} -moveCaretToEndOfPrompt(){if(this._editor) -this._editor.setSelection(TextUtils.TextRange.createFromLocation(Infinity,Infinity));} -setText(text){if(this._editor) -this._editor.setText(text);else -this._initialText=text;this.dispatchEventToListeners(Console.ConsolePrompt.Events.TextChanged);} -text(){return this._editor?this._editor.text():this._initialText;} -setAddCompletionsFromHistory(value){this._addCompletionsFromHistory=value;} -_editorKeyDown(event){var keyboardEvent=(event);var newText;var isPrevious;switch(keyboardEvent.keyCode){case UI.KeyboardShortcut.Keys.Up.code:if(keyboardEvent.shiftKey||this._editor.selection().endLine>0) -break;newText=this._history.previous(this.text());isPrevious=true;break;case UI.KeyboardShortcut.Keys.Down.code:if(keyboardEvent.shiftKey||this._editor.selection().endLine<this._editor.fullRange().endLine) -break;newText=this._history.next();break;case UI.KeyboardShortcut.Keys.P.code:if(Host.isMac()&&keyboardEvent.ctrlKey&&!keyboardEvent.metaKey&&!keyboardEvent.altKey&&!keyboardEvent.shiftKey){newText=this._history.previous(this.text());isPrevious=true;} -break;case UI.KeyboardShortcut.Keys.N.code:if(Host.isMac()&&keyboardEvent.ctrlKey&&!keyboardEvent.metaKey&&!keyboardEvent.altKey&&!keyboardEvent.shiftKey) -newText=this._history.next();break;case UI.KeyboardShortcut.Keys.Enter.code:this._enterKeyPressed(keyboardEvent);break;case UI.KeyboardShortcut.Keys.Tab.code:if(!this.text()) -keyboardEvent.consume();break;} -if(newText===undefined) -return;keyboardEvent.consume(true);this.setText(newText);if(isPrevious) -this._editor.setSelection(TextUtils.TextRange.createFromLocation(0,Infinity));else -this.moveCaretToEndOfPrompt();} -async _enterKeyPressed(event){if(event.altKey||event.ctrlKey||event.shiftKey) -return;event.consume(true);this.clearAutocomplete();var str=this.text();if(!str.length) -return;var currentExecutionContext=UI.context.flavor(SDK.ExecutionContext);if(!this._isCaretAtEndOfPrompt()||!currentExecutionContext){this._appendCommand(str,true);return;} -var result=await currentExecutionContext.runtimeModel.compileScript(str,'',false,currentExecutionContext.id);if(str!==this.text()) -return;var exceptionDetails=result && result.exceptionDetails;if(exceptionDetails&&(exceptionDetails.exception.description.startsWith('SyntaxError: Unexpected end of input')||exceptionDetails.exception.description.startsWith('SyntaxError: Unterminated template literal'))){this._editor.newlineAndIndent();this._enterProcessedForTest();return;} -await this._appendCommand(str,true);this._enterProcessedForTest();} -async _appendCommand(text,useCommandLineAPI){this.setText('');var currentExecutionContext=UI.context.flavor(SDK.ExecutionContext);if(currentExecutionContext){var executionContext=currentExecutionContext;var message=ConsoleModel.consoleModel.addCommandMessage(executionContext,text);text=SDK.RuntimeModel.wrapObjectLiteralExpressionIfNeeded(text);var preprocessed=false;if(text.indexOf('await')!==-1){var preprocessedText=await Formatter.formatterWorkerPool().preprocessTopLevelAwaitExpressions(text);preprocessed=!!preprocessedText;text=preprocessedText||text;} -ConsoleModel.consoleModel.evaluateCommandInConsole(executionContext,message,text,useCommandLineAPI,preprocessed);if(Console.ConsolePanel.instance().isShowing()) -Host.userMetrics.actionTaken(Host.UserMetrics.Action.CommandEvaluatedInConsolePanel);}} -_enterProcessedForTest(){} -_historyCompletions(prefix,force){if(!this._addCompletionsFromHistory||!this._isCaretAtEndOfPrompt()||(!prefix&&!force)) -return[];var result=[];var text=this.text();var set=new Set();var data=this._history.historyData();for(var i=data.length-1;i>=0&&result.length<50;--i){var item=data[i];if(!item.startsWith(text)) -continue;if(set.has(item)) -continue;set.add(item);result.push({text:item.substring(text.length-prefix.length),iconType:'smallicon-text-prompt',isSecondary:true});} -return result;} -focus(){if(this._editor) -this._editor.widget().focus();else -this.element.focus();} -_substituteRange(lineNumber,columnNumber){var token=this._editor.tokenAtTextPosition(lineNumber,columnNumber);if(token&&token.type==='js-string') -return new TextUtils.TextRange(lineNumber,token.startColumn,lineNumber,columnNumber);var lineText=this._editor.line(lineNumber);var index;for(index=columnNumber-1;index>=0;index--){if(' =:[({;,!+-*/&|^<>.\t\r\n'.indexOf(lineText.charAt(index))!==-1) -break;} -return new TextUtils.TextRange(lineNumber,index+1,lineNumber,columnNumber);} -_wordsWithQuery(queryRange,substituteRange,force){var query=this._editor.text(queryRange);var before=this._editor.text(new TextUtils.TextRange(0,0,queryRange.startLine,queryRange.startColumn));var historyWords=this._historyCompletions(query,force);var token=this._editor.tokenAtTextPosition(substituteRange.startLine,substituteRange.startColumn);if(token){var excludedTokens=new Set(['js-comment','js-string-2','js-def']);var trimmedBefore=before.trim();if(!trimmedBefore.endsWith('[')&&!trimmedBefore.match(/\.\s*(get|set|delete)\s*\(\s*$/)) -excludedTokens.add('js-string');if(!trimmedBefore.endsWith('.')) -excludedTokens.add('js-property');if(excludedTokens.has(token.type)) -return Promise.resolve(historyWords);} -return ObjectUI.JavaScriptAutocomplete.completionsForTextInCurrentContext(before,query,force).then(words=>words.concat(historyWords));} -_editorSetForTest(){}};Console.ConsoleHistoryManager=class{constructor(){this._data=[];this._historyOffset=1;} -historyData(){return this._data;} -setHistoryData(data){this._data=data.slice();this._historyOffset=1;} -pushHistoryItem(text){if(this._uncommittedIsTop){this._data.pop();delete this._uncommittedIsTop;} -this._historyOffset=1;if(text===this._currentHistoryItem()) -return;this._data.push(text);} -_pushCurrentText(currentText){if(this._uncommittedIsTop) -this._data.pop();this._uncommittedIsTop=true;this._data.push(currentText);} -previous(currentText){if(this._historyOffset>this._data.length) -return undefined;if(this._historyOffset===1) -this._pushCurrentText(currentText);++this._historyOffset;return this._currentHistoryItem();} -next(){if(this._historyOffset===1) -return undefined;--this._historyOffset;return this._currentHistoryItem();} -_currentHistoryItem(){return this._data[this._data.length-this._historyOffset];}};Console.ConsolePrompt.Events={TextChanged:Symbol('TextChanged')};;Console.ConsoleView=class extends UI.VBox{constructor(){super();this.setMinimumSize(0,35);this.registerRequiredCSS('console/consoleView.css');this._searchableView=new UI.SearchableView(this);this._searchableView.setPlaceholder(Common.UIString('Find string in logs'));this._searchableView.setMinimalSearchQuerySize(0);this._badgePool=new ProductRegistry.BadgePool();this._sidebar=new Console.ConsoleSidebar(this._badgePool);this._sidebar.addEventListener(Console.ConsoleSidebar.Events.FilterSelected,this._updateMessageList.bind(this));this._isSidebarOpen=false;var toolbar=new UI.Toolbar('',this.element);var isLogManagementEnabled=Runtime.experiments.isEnabled('logManagement');if(isLogManagementEnabled){this._splitWidget=new UI.SplitWidget(true,false,'console.sidebar.width',100);this._splitWidget.setMainWidget(this._searchableView);this._splitWidget.setSidebarWidget(this._sidebar);this._splitWidget.hideSidebar();this._splitWidget.show(this.element);toolbar.appendToolbarItem(this._splitWidget.createShowHideSidebarButton('console sidebar'));this._splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged,event=>{this._isSidebarOpen=event.data===UI.SplitWidget.ShowMode.Both;this._filter._levelMenuButton.setEnabled(!this._isSidebarOpen);this._onFilterChanged();});}else{this._searchableView.show(this.element);} -this._contentsElement=this._searchableView.element;this.element.classList.add('console-view');this._visibleViewMessages=[];this._urlToMessageCount={};this._hiddenByFilterCount=0;this._groupableMessages=new Map();this._groupableMessageTitle=new Map();this._regexMatchRanges=[];this._filter=new Console.ConsoleViewFilter(this._onFilterChanged.bind(this));this._consoleContextSelector=new Console.ConsoleContextSelector();this._filterStatusText=new UI.ToolbarText();this._filterStatusText.element.classList.add('dimmed');this._showSettingsPaneSetting=Common.settings.createSetting('consoleShowSettingsToolbar',false);this._showSettingsPaneButton=new UI.ToolbarSettingToggle(this._showSettingsPaneSetting,'largeicon-settings-gear',Common.UIString('Console settings'));this._progressToolbarItem=new UI.ToolbarItem(createElement('div'));this._groupSimilarSetting=Common.settings.moduleSetting('consoleGroupSimilar');this._groupSimilarSetting.addChangeListener(()=>this._updateMessageList());var groupSimilarToggle=new UI.ToolbarSettingCheckbox(this._groupSimilarSetting,Common.UIString('Group similar'));toolbar.appendToolbarItem(UI.Toolbar.createActionButton((UI.actionRegistry.action('console.clear'))));toolbar.appendSeparator();toolbar.appendToolbarItem(this._consoleContextSelector.toolbarItem());toolbar.appendSeparator();toolbar.appendToolbarItem(this._filter._textFilterUI);toolbar.appendToolbarItem(this._filter._levelMenuButton);toolbar.appendToolbarItem(groupSimilarToggle);toolbar.appendToolbarItem(this._progressToolbarItem);toolbar.appendSpacer();toolbar.appendToolbarItem(this._filterStatusText);toolbar.appendSeparator();toolbar.appendToolbarItem(this._showSettingsPaneButton);this._preserveLogCheckbox=new UI.ToolbarSettingCheckbox(Common.moduleSetting('preserveConsoleLog'),Common.UIString('Do not clear log on page reload / navigation'),Common.UIString('Preserve log'));this._hideNetworkMessagesCheckbox=new UI.ToolbarSettingCheckbox(this._filter._hideNetworkMessagesSetting,this._filter._hideNetworkMessagesSetting.title(),Common.UIString('Hide network'));var filterByExecutionContextCheckbox=new UI.ToolbarSettingCheckbox(this._filter._filterByExecutionContextSetting,Common.UIString('Only show messages from the current context (top, iframe, worker, extension)'),Common.UIString('Selected context only'));var filterConsoleAPICheckbox=new UI.ToolbarSettingCheckbox(Common.moduleSetting('consoleAPIFilterEnabled'),Common.UIString('Only show messages from console API methods'),Common.UIString('User messages only'));var monitoringXHREnabledSetting=Common.moduleSetting('monitoringXHREnabled');this._timestampsSetting=Common.moduleSetting('consoleTimestampsEnabled');this._consoleHistoryAutocompleteSetting=Common.moduleSetting('consoleHistoryAutocomplete');var settingsPane=new UI.HBox();settingsPane.show(this._contentsElement);settingsPane.element.classList.add('console-settings-pane');var settingsToolbarLeft=new UI.Toolbar('',settingsPane.element);settingsToolbarLeft.makeVertical();settingsToolbarLeft.appendToolbarItem(this._hideNetworkMessagesCheckbox);settingsToolbarLeft.appendToolbarItem(this._preserveLogCheckbox);settingsToolbarLeft.appendToolbarItem(filterByExecutionContextCheckbox);if(!isLogManagementEnabled) -settingsToolbarLeft.appendToolbarItem(filterConsoleAPICheckbox);var settingsToolbarRight=new UI.Toolbar('',settingsPane.element);settingsToolbarRight.makeVertical();settingsToolbarRight.appendToolbarItem(new UI.ToolbarSettingCheckbox(monitoringXHREnabledSetting));settingsToolbarRight.appendToolbarItem(new UI.ToolbarSettingCheckbox(this._timestampsSetting));settingsToolbarRight.appendToolbarItem(new UI.ToolbarSettingCheckbox(this._consoleHistoryAutocompleteSetting));if(!this._showSettingsPaneSetting.get()) -settingsPane.element.classList.add('hidden');this._showSettingsPaneSetting.addChangeListener(()=>settingsPane.element.classList.toggle('hidden',!this._showSettingsPaneSetting.get()));this._viewport=new Console.ConsoleViewport(this);this._viewport.setStickToBottom(true);this._viewport.contentElement().classList.add('console-group','console-group-messages');this._contentsElement.appendChild(this._viewport.element);this._messagesElement=this._viewport.element;this._messagesElement.id='console-messages';this._messagesElement.classList.add('monospace');this._messagesElement.addEventListener('click',this._messagesClicked.bind(this),true);this._viewportThrottler=new Common.Throttler(50);this._topGroup=Console.ConsoleGroup.createTopGroup();this._currentGroup=this._topGroup;this._promptElement=this._messagesElement.createChild('div','source-code');var promptIcon=UI.Icon.create('smallicon-text-prompt','console-prompt-icon');this._promptElement.appendChild(promptIcon);this._promptElement.id='console-prompt';var selectAllFixer=this._messagesElement.createChild('div','console-view-fix-select-all');selectAllFixer.textContent='.';this._registerShortcuts();this._messagesElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),false);this._linkifier=new Components.Linkifier(Console.ConsoleViewMessage.MaxLengthForLinks);this._consoleMessages=[];this._viewMessageSymbol=Symbol('viewMessage');this._consoleHistorySetting=Common.settings.createLocalSetting('consoleHistory',[]);this._prompt=new Console.ConsolePrompt();this._prompt.show(this._promptElement);this._prompt.element.addEventListener('keydown',this._promptKeyDown.bind(this),true);this._prompt.addEventListener(Console.ConsolePrompt.Events.TextChanged,this._promptTextChanged,this);this._consoleHistoryAutocompleteSetting.addChangeListener(this._consoleHistoryAutocompleteChanged,this);var historyData=this._consoleHistorySetting.get();this._prompt.history().setHistoryData(historyData);this._consoleHistoryAutocompleteChanged();this._updateFilterStatus();this._timestampsSetting.addChangeListener(this._consoleTimestampsSettingChanged,this);this._registerWithMessageSink();UI.context.addFlavorChangeListener(SDK.ExecutionContext,this._executionContextChanged,this);this._messagesElement.addEventListener('mousedown',this._updateStickToBottomOnMouseDown.bind(this),false);this._messagesElement.addEventListener('mouseup',this._updateStickToBottomOnMouseUp.bind(this),false);this._messagesElement.addEventListener('mouseleave',this._updateStickToBottomOnMouseUp.bind(this),false);this._messagesElement.addEventListener('wheel',this._updateStickToBottomOnWheel.bind(this),false);ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.ConsoleCleared,this._consoleCleared,this);ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.MessageAdded,this._onConsoleMessageAdded,this);ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.MessageUpdated,this._onConsoleMessageUpdated,this);ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.CommandEvaluated,this._commandEvaluated,this);ConsoleModel.consoleModel.messages().forEach(this._addConsoleMessage,this);} -static instance(){if(!Console.ConsoleView._instance) -Console.ConsoleView._instance=new Console.ConsoleView();return Console.ConsoleView._instance;} -static clearConsole(){ConsoleModel.consoleModel.requestClearMessages();} -_onFilterChanged(){this._filter._currentFilter.levelsMask=this._isSidebarOpen?Console.ConsoleFilter.allLevelsFilterValue():this._filter._messageLevelFiltersSetting.get();this._updateMessageList();} -searchableView(){return this._searchableView;} -_clearHistory(){this._consoleHistorySetting.set([]);this._prompt.history().setHistoryData([]);} -_consoleHistoryAutocompleteChanged(){this._prompt.setAddCompletionsFromHistory(this._consoleHistoryAutocompleteSetting.get());} -itemCount(){return this._visibleViewMessages.length;} -itemElement(index){return this._visibleViewMessages[index];} -fastHeight(index){return this._visibleViewMessages[index].fastHeight();} -minimumRowHeight(){return 16;} -_registerWithMessageSink(){Common.console.messages().forEach(this._addSinkMessage,this);Common.console.addEventListener(Common.Console.Events.MessageAdded,messageAdded,this);function messageAdded(event){this._addSinkMessage((event.data));}} -_addSinkMessage(message){var level=ConsoleModel.ConsoleMessage.MessageLevel.Verbose;switch(message.level){case Common.Console.MessageLevel.Info:level=ConsoleModel.ConsoleMessage.MessageLevel.Info;break;case Common.Console.MessageLevel.Error:level=ConsoleModel.ConsoleMessage.MessageLevel.Error;break;case Common.Console.MessageLevel.Warning:level=ConsoleModel.ConsoleMessage.MessageLevel.Warning;break;} -var consoleMessage=new ConsoleModel.ConsoleMessage(null,ConsoleModel.ConsoleMessage.MessageSource.Other,level,message.text,ConsoleModel.ConsoleMessage.MessageType.System,undefined,undefined,undefined,undefined,undefined,undefined,message.timestamp);this._addConsoleMessage(consoleMessage);} -_consoleTimestampsSettingChanged(){this._updateMessageList();this._consoleMessages.forEach(viewMessage=>viewMessage.updateTimestamp());this._groupableMessageTitle.forEach(viewMessage=>viewMessage.updateTimestamp());} -_executionContextChanged(){this._prompt.clearAutocomplete();} -willHide(){this._hidePromptSuggestBox();} -wasShown(){this._viewport.refresh();} -focus(){if(!this._prompt.hasFocus()) -this._prompt.focus();} -restoreScrollPositions(){if(this._viewport.stickToBottom()) -this._immediatelyScrollToBottom();else -super.restoreScrollPositions();} -onResize(){this._scheduleViewportRefresh();this._hidePromptSuggestBox();if(this._viewport.stickToBottom()) -this._immediatelyScrollToBottom();for(var i=0;i<this._visibleViewMessages.length;++i) -this._visibleViewMessages[i].onResize();} -_hidePromptSuggestBox(){this._prompt.clearAutocomplete();} -_invalidateViewport(){if(this._muteViewportUpdates){this._maybeDirtyWhileMuted=true;return Promise.resolve();} -if(this._needsFullUpdate){this._updateMessageList();delete this._needsFullUpdate;}else{this._viewport.invalidate();} -return Promise.resolve();} -_scheduleViewportRefresh(){if(this._muteViewportUpdates){this._maybeDirtyWhileMuted=true;this._scheduleViewportRefreshForTest(true);return;}else{this._scheduleViewportRefreshForTest(false);} -this._viewportThrottler.schedule(this._invalidateViewport.bind(this));} -_scheduleViewportRefreshForTest(muted){} -_immediatelyScrollToBottom(){this._viewport.setStickToBottom(true);this._promptElement.scrollIntoView(true);} -_updateFilterStatus(){if(this._hiddenByFilterCount===this._lastShownHiddenByFilterCount) -return;this._filterStatusText.setText(Common.UIString(this._hiddenByFilterCount+' hidden'));this._filterStatusText.setVisible(!!this._hiddenByFilterCount);this._lastShownHiddenByFilterCount=this._hiddenByFilterCount;} -_onConsoleMessageAdded(event){var message=(event.data);this._addConsoleMessage(message);} -_addConsoleMessage(message){var viewMessage=this._createViewMessage(message);message[this._viewMessageSymbol]=viewMessage;if(message.type===ConsoleModel.ConsoleMessage.MessageType.Command||message.type===ConsoleModel.ConsoleMessage.MessageType.Result){var lastMessage=this._consoleMessages.peekLast();viewMessage[Console.ConsoleView._messageSortingTimeSymbol]=lastMessage?lastMessage[Console.ConsoleView._messageSortingTimeSymbol]:0;}else{viewMessage[Console.ConsoleView._messageSortingTimeSymbol]=viewMessage.consoleMessage().timestamp;} -var insertAt;if(!this._consoleMessages.length||timeComparator(viewMessage,this._consoleMessages[this._consoleMessages.length-1])>0) -insertAt=this._consoleMessages.length;else -insertAt=this._consoleMessages.upperBound(viewMessage,timeComparator);var insertedInMiddle=insertAt<this._consoleMessages.length;this._consoleMessages.splice(insertAt,0,viewMessage);if(this._urlToMessageCount[message.url]) -++this._urlToMessageCount[message.url];else -this._urlToMessageCount[message.url]=1;this._filter.onMessageAdded(message);this._sidebar.onMessageAdded(viewMessage);var shouldGoIntoGroup=false;if(message.isGroupable()){var groupKey=viewMessage.groupKey();shouldGoIntoGroup=this._groupSimilarSetting.get()&&this._groupableMessages.has(groupKey);var list=this._groupableMessages.get(groupKey);if(!list){list=[];this._groupableMessages.set(groupKey,list);} -list.push(viewMessage);} -if(!shouldGoIntoGroup&&!insertedInMiddle){this._appendMessageToEnd(viewMessage);this._updateFilterStatus();this._searchableView.updateSearchMatchesCount(this._regexMatchRanges.length);}else{this._needsFullUpdate=true;} -this._scheduleViewportRefresh();this._consoleMessageAddedForTest(viewMessage);function timeComparator(viewMessage1,viewMessage2){return viewMessage1[Console.ConsoleView._messageSortingTimeSymbol]- -viewMessage2[Console.ConsoleView._messageSortingTimeSymbol];}} -_onConsoleMessageUpdated(event){var message=(event.data);var viewMessage=message[this._viewMessageSymbol];if(viewMessage){viewMessage.updateMessageElement();this._updateMessageList();}} -_consoleMessageAddedForTest(viewMessage){} -_shouldMessageBeVisible(viewMessage){return this._filter.shouldBeVisible(viewMessage)&&(!this._isSidebarOpen||this._sidebar.shouldBeVisible(viewMessage));} -_appendMessageToEnd(viewMessage,preventCollapse){if(!this._shouldMessageBeVisible(viewMessage)){this._hiddenByFilterCount++;return;} -if(!preventCollapse&&this._tryToCollapseMessages(viewMessage,this._visibleViewMessages.peekLast())) -return;var lastMessage=this._visibleViewMessages.peekLast();if(viewMessage.consoleMessage().type===ConsoleModel.ConsoleMessage.MessageType.EndGroup){if(lastMessage&&!this._currentGroup.messagesHidden()) -lastMessage.incrementCloseGroupDecorationCount();this._currentGroup=this._currentGroup.parentGroup()||this._currentGroup;return;} -if(!this._currentGroup.messagesHidden()){var originatingMessage=viewMessage.consoleMessage().originatingMessage();if(lastMessage&&originatingMessage&&lastMessage.consoleMessage()===originatingMessage) -lastMessage.toMessageElement().classList.add('console-adjacent-user-command-result');this._visibleViewMessages.push(viewMessage);this._searchMessage(this._visibleViewMessages.length-1);} -if(viewMessage.consoleMessage().isGroupStartMessage()) -this._currentGroup=new Console.ConsoleGroup(this._currentGroup,viewMessage);this._messageAppendedForTests();} -_messageAppendedForTests(){} -_createViewMessage(message){var nestingLevel=this._currentGroup.nestingLevel();switch(message.type){case ConsoleModel.ConsoleMessage.MessageType.Command:return new Console.ConsoleCommand(message,this._linkifier,this._badgePool,nestingLevel);case ConsoleModel.ConsoleMessage.MessageType.Result:return new Console.ConsoleCommandResult(message,this._linkifier,this._badgePool,nestingLevel);case ConsoleModel.ConsoleMessage.MessageType.StartGroupCollapsed:case ConsoleModel.ConsoleMessage.MessageType.StartGroup:return new Console.ConsoleGroupViewMessage(message,this._linkifier,this._badgePool,nestingLevel);default:return new Console.ConsoleViewMessage(message,this._linkifier,this._badgePool,nestingLevel);}} -_consoleCleared(){this._currentMatchRangeIndex=-1;this._consoleMessages=[];this._groupableMessages.clear();this._groupableMessageTitle.clear();this._sidebar.clear();this._updateMessageList();this._hidePromptSuggestBox();this._viewport.setStickToBottom(true);this._linkifier.reset();this._badgePool.reset();this._filter.clear();} -_handleContextMenuEvent(event){var contextMenu=new UI.ContextMenu(event);if(event.target.isSelfOrDescendant(this._promptElement)){contextMenu.show();return;} -var sourceElement=event.target.enclosingNodeOrSelfWithClass('console-message-wrapper');var consoleMessage=sourceElement?sourceElement.message.consoleMessage():null;var filterSubMenu=contextMenu.headerSection().appendSubMenuItem(Common.UIString('Filter'));if(consoleMessage&&consoleMessage.url){var menuTitle=Common.UIString('Hide messages from %s',new Common.ParsedURL(consoleMessage.url).displayName);filterSubMenu.headerSection().appendItem(menuTitle,this._filter.addMessageURLFilter.bind(this._filter,consoleMessage.url));} -var unhideAll=filterSubMenu.footerSection().appendItem(Common.UIString('Unhide all'),this._filter.removeMessageURLFilter.bind(this._filter));var hasFilters=false;for(var url in this._filter.messageURLFilters()){filterSubMenu.defaultSection().appendCheckboxItem(String.sprintf('%s (%d)',new Common.ParsedURL(url).displayName,this._urlToMessageCount[url]),this._filter.removeMessageURLFilter.bind(this._filter,url),true);hasFilters=true;} -filterSubMenu.setEnabled(hasFilters||(consoleMessage&&consoleMessage.url));unhideAll.setEnabled(hasFilters);contextMenu.defaultSection().appendAction('console.clear');contextMenu.defaultSection().appendAction('console.clear.history');contextMenu.saveSection().appendItem(Common.UIString('Save as...'),this._saveConsole.bind(this));var request=consoleMessage?consoleMessage.request:null;if(request&&SDK.NetworkManager.canReplayRequest(request)){contextMenu.debugSection().appendItem(Common.UIString('Replay XHR'),SDK.NetworkManager.replayRequest.bind(null,request));} -contextMenu.show();} -async _saveConsole(){var url=SDK.targetManager.mainTarget().inspectedURL();var parsedURL=url.asParsedURL();var filename=String.sprintf('%s-%d.log',parsedURL?parsedURL.host:'console',Date.now());var stream=new Bindings.FileOutputStream();var progressIndicator=new UI.ProgressIndicator();progressIndicator.setTitle(Common.UIString('Writing file…'));progressIndicator.setTotalWork(this.itemCount());var chunkSize=350;if(!await stream.open(filename)) -return;this._progressToolbarItem.element.appendChild(progressIndicator.element);var messageIndex=0;while(messageIndex<this.itemCount()&&!progressIndicator.isCanceled()){var messageContents=[];for(var i=0;i<chunkSize&&i+messageIndex<this.itemCount();++i){var message=this.itemElement(messageIndex+i);messageContents.push(message.toExportString());} -messageIndex+=i;await stream.write(messageContents.join('\n')+'\n');progressIndicator.setWorked(messageIndex);} -stream.close();progressIndicator.done();} -_tryToCollapseMessages(viewMessage,lastMessage){var timestampsShown=this._timestampsSetting.get();if(!timestampsShown&&lastMessage&&!viewMessage.consoleMessage().isGroupMessage()&&viewMessage.consoleMessage().isEqual(lastMessage.consoleMessage())){lastMessage.incrementRepeatCount();if(viewMessage.isLastInSimilarGroup()) -lastMessage.setInSimilarGroup(true,true);return true;} -return false;} -_updateMessageList(){this._topGroup=Console.ConsoleGroup.createTopGroup();this._currentGroup=this._topGroup;this._regexMatchRanges=[];this._hiddenByFilterCount=0;for(var i=0;i<this._visibleViewMessages.length;++i){this._visibleViewMessages[i].resetCloseGroupDecorationCount();this._visibleViewMessages[i].resetIncrementRepeatCount();} -this._visibleViewMessages=[];if(this._groupSimilarSetting.get()){this._addGroupableMessagesToEnd();}else{for(var i=0;i<this._consoleMessages.length;++i){this._consoleMessages[i].setInSimilarGroup(false);this._appendMessageToEnd(this._consoleMessages[i]);}} -this._updateFilterStatus();this._searchableView.updateSearchMatchesCount(this._regexMatchRanges.length);this._viewport.invalidate();} -_addGroupableMessagesToEnd(){var alreadyAdded=new Set();for(var i=0;i<this._consoleMessages.length;++i){var viewMessage=this._consoleMessages[i];var message=viewMessage.consoleMessage();if(alreadyAdded.has(message)) -continue;if(!message.isGroupable()){this._appendMessageToEnd(viewMessage);alreadyAdded.add(message);continue;} -var key=viewMessage.groupKey();var viewMessagesInGroup=this._groupableMessages.get(key);if(!viewMessagesInGroup||viewMessagesInGroup.length<5){viewMessage.setInSimilarGroup(false);this._appendMessageToEnd(viewMessage);alreadyAdded.add(message);continue;} -if(!viewMessagesInGroup.find(x=>this._shouldMessageBeVisible(x))){alreadyAdded.addAll(viewMessagesInGroup);continue;} -var startGroupViewMessage=this._groupableMessageTitle.get(key);if(!startGroupViewMessage){var startGroupMessage=new ConsoleModel.ConsoleMessage(null,message.source,message.level,viewMessage.groupTitle(),ConsoleModel.ConsoleMessage.MessageType.StartGroupCollapsed);startGroupViewMessage=this._createViewMessage(startGroupMessage);this._groupableMessageTitle.set(key,startGroupViewMessage);} -startGroupViewMessage.setRepeatCount(viewMessagesInGroup.length);this._appendMessageToEnd(startGroupViewMessage);for(var viewMessageInGroup of viewMessagesInGroup){viewMessageInGroup.setInSimilarGroup(true,viewMessagesInGroup.peekLast()===viewMessageInGroup);this._appendMessageToEnd(viewMessageInGroup,true);alreadyAdded.add(viewMessageInGroup.consoleMessage());} -var endGroupMessage=new ConsoleModel.ConsoleMessage(null,message.source,message.level,message.messageText,ConsoleModel.ConsoleMessage.MessageType.EndGroup);this._appendMessageToEnd(this._createViewMessage(endGroupMessage));}} -_messagesClicked(event){if(!this._messagesElement.hasSelection()){var clickedOutsideMessageList=event.target===this._messagesElement;if(clickedOutsideMessageList) -this._prompt.moveCaretToEndOfPrompt();var oldScrollTop=this._viewport.element.scrollTop;this.focus();this._viewport.element.scrollTop=oldScrollTop;} -var groupMessage=event.target.enclosingNodeOrSelfWithClass('console-group-title');if(!groupMessage) -return;var consoleGroupViewMessage=groupMessage.message;consoleGroupViewMessage.setCollapsed(!consoleGroupViewMessage.collapsed());this._updateMessageList();} -_registerShortcuts(){this._shortcuts={};var shortcut=UI.KeyboardShortcut;var section=UI.shortcutsScreen.section(Common.UIString('Console'));var shortcutL=shortcut.makeDescriptor('l',UI.KeyboardShortcut.Modifiers.Ctrl);var keys=[shortcutL];if(Host.isMac()){var shortcutK=shortcut.makeDescriptor('k',UI.KeyboardShortcut.Modifiers.Meta);keys.unshift(shortcutK);} -section.addAlternateKeys(keys,Common.UIString('Clear console'));keys=[shortcut.makeDescriptor(shortcut.Keys.Tab),shortcut.makeDescriptor(shortcut.Keys.Right)];section.addRelatedKeys(keys,Common.UIString('Accept suggestion'));var shortcutU=shortcut.makeDescriptor('u',UI.KeyboardShortcut.Modifiers.Ctrl);this._shortcuts[shortcutU.key]=this._clearPromptBackwards.bind(this);section.addAlternateKeys([shortcutU],Common.UIString('Clear console prompt'));keys=[shortcut.makeDescriptor(shortcut.Keys.Down),shortcut.makeDescriptor(shortcut.Keys.Up)];section.addRelatedKeys(keys,Common.UIString('Next/previous line'));if(Host.isMac()){keys=[shortcut.makeDescriptor('N',shortcut.Modifiers.Alt),shortcut.makeDescriptor('P',shortcut.Modifiers.Alt)];section.addRelatedKeys(keys,Common.UIString('Next/previous command'));} -section.addKey(shortcut.makeDescriptor(shortcut.Keys.Enter),Common.UIString('Execute command'));} -_clearPromptBackwards(){this._prompt.setText('');} -_promptKeyDown(event){var keyboardEvent=(event);if(keyboardEvent.key==='PageUp'){this._updateStickToBottomOnWheel();return;} -var shortcut=UI.KeyboardShortcut.makeKeyFromEvent(keyboardEvent);var handler=this._shortcuts[shortcut];if(handler){handler();keyboardEvent.preventDefault();}} -_printResult(result,originatingConsoleMessage,exceptionDetails){if(!result) -return;var level=!!exceptionDetails?ConsoleModel.ConsoleMessage.MessageLevel.Error:ConsoleModel.ConsoleMessage.MessageLevel.Info;var message;if(!exceptionDetails){message=new ConsoleModel.ConsoleMessage(result.runtimeModel(),ConsoleModel.ConsoleMessage.MessageSource.JS,level,'',ConsoleModel.ConsoleMessage.MessageType.Result,undefined,undefined,undefined,undefined,[result]);}else{message=ConsoleModel.ConsoleMessage.fromException(result.runtimeModel(),exceptionDetails,ConsoleModel.ConsoleMessage.MessageType.Result,undefined,undefined);} -message.setOriginatingMessage(originatingConsoleMessage);ConsoleModel.consoleModel.addMessage(message);} -_commandEvaluated(event){var data=(event.data);this._prompt.history().pushHistoryItem(data.commandMessage.messageText);this._consoleHistorySetting.set(this._prompt.history().historyData().slice(-Console.ConsoleView.persistedHistorySize));this._printResult(data.result,data.commandMessage,data.exceptionDetails);} -elementsToRestoreScrollPositionsFor(){return[this._messagesElement];} -searchCanceled(){this._cleanupAfterSearch();for(var i=0;i<this._visibleViewMessages.length;++i){var message=this._visibleViewMessages[i];message.setSearchRegex(null);} -this._currentMatchRangeIndex=-1;this._regexMatchRanges=[];delete this._searchRegex;this._viewport.refresh();} -performSearch(searchConfig,shouldJump,jumpBackwards){this.searchCanceled();this._searchableView.updateSearchMatchesCount(0);this._searchRegex=searchConfig.toSearchRegex(true);this._regexMatchRanges=[];this._currentMatchRangeIndex=-1;if(shouldJump) -this._searchShouldJumpBackwards=!!jumpBackwards;this._searchProgressIndicator=new UI.ProgressIndicator();this._searchProgressIndicator.setTitle(Common.UIString('Searching…'));this._searchProgressIndicator.setTotalWork(this._visibleViewMessages.length);this._progressToolbarItem.element.appendChild(this._searchProgressIndicator.element);this._innerSearch(0);} -_cleanupAfterSearch(){delete this._searchShouldJumpBackwards;if(this._innerSearchTimeoutId){clearTimeout(this._innerSearchTimeoutId);delete this._innerSearchTimeoutId;} -if(this._searchProgressIndicator){this._searchProgressIndicator.done();delete this._searchProgressIndicator;}} -_searchFinishedForTests(){} -_innerSearch(index){delete this._innerSearchTimeoutId;if(this._searchProgressIndicator.isCanceled()){this._cleanupAfterSearch();return;} -var startTime=Date.now();for(;index<this._visibleViewMessages.length&&Date.now()-startTime<100;++index) -this._searchMessage(index);this._searchableView.updateSearchMatchesCount(this._regexMatchRanges.length);if(typeof this._searchShouldJumpBackwards!=='undefined'&&this._regexMatchRanges.length){this._jumpToMatch(this._searchShouldJumpBackwards?-1:0);delete this._searchShouldJumpBackwards;} -if(index===this._visibleViewMessages.length){this._cleanupAfterSearch();setTimeout(this._searchFinishedForTests.bind(this),0);return;} -this._innerSearchTimeoutId=setTimeout(this._innerSearch.bind(this,index),100);this._searchProgressIndicator.setWorked(index);} -_searchMessage(index){var message=this._visibleViewMessages[index];message.setSearchRegex(this._searchRegex);for(var i=0;i<message.searchCount();++i) -this._regexMatchRanges.push({messageIndex:index,matchIndex:i});} -jumpToNextSearchResult(){this._jumpToMatch(this._currentMatchRangeIndex+1);} -jumpToPreviousSearchResult(){this._jumpToMatch(this._currentMatchRangeIndex-1);} -supportsCaseSensitiveSearch(){return true;} -supportsRegexSearch(){return true;} -_jumpToMatch(index){if(!this._regexMatchRanges.length) -return;var matchRange;if(this._currentMatchRangeIndex>=0){matchRange=this._regexMatchRanges[this._currentMatchRangeIndex];var message=this._visibleViewMessages[matchRange.messageIndex];message.searchHighlightNode(matchRange.matchIndex).classList.remove(UI.highlightedCurrentSearchResultClassName);} -index=mod(index,this._regexMatchRanges.length);this._currentMatchRangeIndex=index;this._searchableView.updateCurrentMatchIndex(index);matchRange=this._regexMatchRanges[index];var message=this._visibleViewMessages[matchRange.messageIndex];var highlightNode=message.searchHighlightNode(matchRange.matchIndex);highlightNode.classList.add(UI.highlightedCurrentSearchResultClassName);this._viewport.scrollItemIntoView(matchRange.messageIndex);highlightNode.scrollIntoViewIfNeeded();} -_updateStickToBottomOnMouseDown(){this._muteViewportUpdates=true;this._viewport.setStickToBottom(false);if(this._waitForScrollTimeout){clearTimeout(this._waitForScrollTimeout);delete this._waitForScrollTimeout;}} -_updateStickToBottomOnMouseUp(){if(!this._muteViewportUpdates) -return;this._waitForScrollTimeout=setTimeout(updateViewportState.bind(this),200);function updateViewportState(){this._muteViewportUpdates=false;this._viewport.setStickToBottom(this._messagesElement.isScrolledToBottom());if(this._maybeDirtyWhileMuted){this._scheduleViewportRefresh();delete this._maybeDirtyWhileMuted;} -delete this._waitForScrollTimeout;this._updateViewportStickinessForTest();}} -_updateViewportStickinessForTest(){} -_updateStickToBottomOnWheel(){this._updateStickToBottomOnMouseDown();this._updateStickToBottomOnMouseUp();} -_promptTextChanged(){if(this.itemCount()!==0&&this._viewport.firstVisibleIndex()!==this.itemCount()) -this._immediatelyScrollToBottom();this._promptTextChangedForTest();} -_promptTextChangedForTest(){}};Console.ConsoleView.persistedHistorySize=300;Console.ConsoleViewFilter=class{constructor(filterChangedCallback){this._filterChanged=filterChangedCallback;this._messageURLFiltersSetting=Common.settings.createSetting('messageURLFilters',{});this._messageLevelFiltersSetting=Console.ConsoleViewFilter.levelFilterSetting();this._hideNetworkMessagesSetting=Common.moduleSetting('hideNetworkMessages');this._filterByExecutionContextSetting=Common.moduleSetting('selectedContextFilterEnabled');this._filterByConsoleAPISetting=Common.moduleSetting('consoleAPIFilterEnabled');this._messageURLFiltersSetting.addChangeListener(this._onFilterChanged.bind(this));this._messageLevelFiltersSetting.addChangeListener(this._onFilterChanged.bind(this));this._hideNetworkMessagesSetting.addChangeListener(this._onFilterChanged.bind(this));this._filterByExecutionContextSetting.addChangeListener(this._onFilterChanged.bind(this));this._filterByConsoleAPISetting.addChangeListener(this._onFilterChanged.bind(this));UI.context.addFlavorChangeListener(SDK.ExecutionContext,this._onFilterChanged,this);var filterKeys=Object.values(Console.ConsoleFilter.FilterType);this._suggestionBuilder=new UI.FilterSuggestionBuilder(filterKeys);this._textFilterUI=new UI.ToolbarInput(Common.UIString('Filter'),0.2,1,Common.UIString('e.g. /event\\d/ -cdn url:a.com'),this._suggestionBuilder.completions.bind(this._suggestionBuilder));this._textFilterUI.addEventListener(UI.ToolbarInput.Event.TextChanged,this._onFilterChanged,this);this._filterParser=new TextUtils.FilterParser(filterKeys);this._currentFilter=new Console.ConsoleFilter('',[],null,this._messageLevelFiltersSetting.get());this._updateCurrentFilter();this._levelLabels={};this._levelLabels[ConsoleModel.ConsoleMessage.MessageLevel.Verbose]=Common.UIString('Verbose');this._levelLabels[ConsoleModel.ConsoleMessage.MessageLevel.Info]=Common.UIString('Info');this._levelLabels[ConsoleModel.ConsoleMessage.MessageLevel.Warning]=Common.UIString('Warnings');this._levelLabels[ConsoleModel.ConsoleMessage.MessageLevel.Error]=Common.UIString('Errors');this._levelMenuButton=new UI.ToolbarButton('');this._levelMenuButton.turnIntoSelect();this._levelMenuButton.addEventListener(UI.ToolbarButton.Events.Click,this._showLevelContextMenu.bind(this));this._updateLevelMenuButtonText();this._messageLevelFiltersSetting.addChangeListener(this._updateLevelMenuButtonText.bind(this));} -onMessageAdded(message){if(message.type===ConsoleModel.ConsoleMessage.MessageType.Command||message.type===ConsoleModel.ConsoleMessage.MessageType.Result||message.isGroupMessage()) -return;if(message.context) -this._suggestionBuilder.addItem(Console.ConsoleFilter.FilterType.Context,message.context);if(message.source) -this._suggestionBuilder.addItem(Console.ConsoleFilter.FilterType.Source,message.source);if(message.url) -this._suggestionBuilder.addItem(Console.ConsoleFilter.FilterType.Url,message.url);} -static levelFilterSetting(){return Common.settings.createSetting('messageLevelFilters',Console.ConsoleFilter.defaultLevelsFilterValue());} -_updateCurrentFilter(){var parsedFilters=this._filterParser.parse(this._textFilterUI.value());if(this._hideNetworkMessagesSetting.get()){parsedFilters.push({key:Console.ConsoleFilter.FilterType.Source,text:ConsoleModel.ConsoleMessage.MessageSource.Network,negative:true});} -if(this._filterByConsoleAPISetting.get()){parsedFilters.push({key:Console.ConsoleFilter.FilterType.Source,text:ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI,negative:false});} -var blockedURLs=Object.keys(this._messageURLFiltersSetting.get());var urlFilters=blockedURLs.map(url=>({key:Console.ConsoleFilter.FilterType.Url,text:url,negative:true}));parsedFilters=parsedFilters.concat(urlFilters);this._currentFilter.executionContext=this._filterByExecutionContextSetting.get()?UI.context.flavor(SDK.ExecutionContext):null;this._currentFilter.parsedFilters=parsedFilters;this._currentFilter.levelsMask=this._messageLevelFiltersSetting.get();} -_onFilterChanged(){this._updateCurrentFilter();this._filterChanged();} -_updateLevelMenuButtonText(){var isAll=true;var isDefault=true;var allValue=Console.ConsoleFilter.allLevelsFilterValue();var defaultValue=Console.ConsoleFilter.defaultLevelsFilterValue();var text=null;var levels=this._messageLevelFiltersSetting.get();for(var name of Object.values(ConsoleModel.ConsoleMessage.MessageLevel)){isAll=isAll&&levels[name]===allValue[name];isDefault=isDefault&&levels[name]===defaultValue[name];if(levels[name]) -text=text?Common.UIString('Custom levels'):Common.UIString('%s only',this._levelLabels[name]);} -if(isAll) -text=Common.UIString('All levels');else if(isDefault) -text=Common.UIString('Default levels');else -text=text||Common.UIString('Hide all');this._levelMenuButton.setText(text);} -_showLevelContextMenu(event){var mouseEvent=(event.data);var setting=this._messageLevelFiltersSetting;var levels=setting.get();var contextMenu=new UI.ContextMenu(mouseEvent,true);contextMenu.headerSection().appendItem(Common.UIString('Default'),()=>setting.set(Console.ConsoleFilter.defaultLevelsFilterValue()));for(var level in this._levelLabels){contextMenu.defaultSection().appendCheckboxItem(this._levelLabels[level],toggleShowLevel.bind(null,level),levels[level]);} -contextMenu.show();function toggleShowLevel(level){levels[level]=!levels[level];setting.set(levels);}} -addMessageURLFilter(url){var value=this._messageURLFiltersSetting.get();value[url]=true;this._messageURLFiltersSetting.set(value);} -removeMessageURLFilter(url){var value;if(url){value=this._messageURLFiltersSetting.get();delete value[url];}else{value={};} -this._messageURLFiltersSetting.set(value);} -messageURLFilters(){return this._messageURLFiltersSetting.get();} -shouldBeVisible(viewMessage){return this._currentFilter.shouldBeVisible(viewMessage);} -clear(){this._suggestionBuilder.clear();} -reset(){this._messageURLFiltersSetting.set({});this._messageLevelFiltersSetting.set(Console.ConsoleFilter.defaultLevelsFilterValue());this._filterByExecutionContextSetting.set(false);this._filterByConsoleAPISetting.set(false);this._hideNetworkMessagesSetting.set(false);this._textFilterUI.setValue('');this._onFilterChanged();}};Console.ConsoleCommand=class extends Console.ConsoleViewMessage{constructor(message,linkifier,badgePool,nestingLevel){super(message,linkifier,badgePool,nestingLevel);} -contentElement(){if(!this._contentElement){this._contentElement=createElementWithClass('div','console-user-command');var icon=UI.Icon.create('smallicon-user-command','command-result-icon');this._contentElement.appendChild(icon);this._contentElement.message=this;this._formattedCommand=createElementWithClass('span','source-code');this._formattedCommand.textContent=this.text.replaceControlCharacters();this._contentElement.appendChild(this._formattedCommand);if(this._formattedCommand.textContent.length<Console.ConsoleCommand.MaxLengthToIgnoreHighlighter){var javascriptSyntaxHighlighter=new UI.SyntaxHighlighter('text/javascript',true);javascriptSyntaxHighlighter.syntaxHighlightNode(this._formattedCommand).then(this._updateSearch.bind(this));}else{this._updateSearch();} -this.updateTimestamp();} -return this._contentElement;} -_updateSearch(){this.setSearchRegex(this.searchRegex());}};Console.ConsoleCommand.MaxLengthToIgnoreHighlighter=10000;Console.ConsoleCommandResult=class extends Console.ConsoleViewMessage{constructor(message,linkifier,badgePool,nestingLevel){super(message,linkifier,badgePool,nestingLevel);} -contentElement(){var element=super.contentElement();if(!element.classList.contains('console-user-command-result')){element.classList.add('console-user-command-result');if(this.consoleMessage().level===ConsoleModel.ConsoleMessage.MessageLevel.Info){var icon=UI.Icon.create('smallicon-command-result','command-result-icon');element.insertBefore(icon,element.firstChild);}} -return element;}};Console.ConsoleGroup=class{constructor(parentGroup,groupMessage){this._parentGroup=parentGroup;this._nestingLevel=parentGroup?parentGroup.nestingLevel()+1:0;this._messagesHidden=groupMessage&&groupMessage.collapsed()||this._parentGroup&&this._parentGroup.messagesHidden();} -static createTopGroup(){return new Console.ConsoleGroup(null,null);} -messagesHidden(){return this._messagesHidden;} -nestingLevel(){return this._nestingLevel;} -parentGroup(){return this._parentGroup;}};Console.ConsoleView.ActionDelegate=class{handleAction(context,actionId){switch(actionId){case'console.show':InspectorFrontendHost.bringToFront();Common.console.show();return true;case'console.clear':Console.ConsoleView.clearConsole();return true;case'console.clear.history':Console.ConsoleView.instance()._clearHistory();return true;} -return false;}};Console.ConsoleView.RegexMatchRange;Console.ConsoleView._messageSortingTimeSymbol=Symbol('messageSortingTime');;Console.ConsolePanel=class extends UI.Panel{constructor(){super('console');this._view=Console.ConsoleView.instance();} -static instance(){return(self.runtime.sharedInstance(Console.ConsolePanel));} -wasShown(){super.wasShown();var wrapper=Console.ConsolePanel.WrapperView._instance;if(wrapper&&wrapper.isShowing()) -UI.inspectorView.setDrawerMinimized(true);this._view.show(this.element);} -willHide(){super.willHide();if(Console.ConsolePanel.WrapperView._instance) -Console.ConsolePanel.WrapperView._instance._showViewInWrapper();UI.inspectorView.setDrawerMinimized(false);} -searchableView(){return Console.ConsoleView.instance().searchableView();}};Console.ConsolePanel.WrapperView=class extends UI.VBox{constructor(){super();this.element.classList.add('console-view-wrapper');Console.ConsolePanel.WrapperView._instance=this;this._view=Console.ConsoleView.instance();} -wasShown(){if(!Console.ConsolePanel.instance().isShowing()) -this._showViewInWrapper();else -UI.inspectorView.setDrawerMinimized(true);} -willHide(){UI.inspectorView.setDrawerMinimized(false);} -_showViewInWrapper(){this._view.show(this.element);}};Console.ConsolePanel.ConsoleRevealer=class{reveal(object){var consoleView=Console.ConsoleView.instance();if(consoleView.isShowing()){consoleView.focus();return Promise.resolve();} -UI.viewManager.showView('console-view');return Promise.resolve();}};;Runtime.cachedResources["console/consoleContextSelector.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n padding: 2px 1px 2px 2px;\n white-space: nowrap;\n display: flex;\n flex-direction: column;\n height: 36px;\n justify-content: center;\n}\n\n.title {\n overflow: hidden;\n text-overflow: ellipsis;\n flex-grow: 0;\n}\n\n.badge {\n pointer-events: none;\n margin-right: 4px;\n display: inline-block;\n height: 15px;\n}\n\n.subtitle {\n color: #999;\n margin-right: 3px;\n overflow: hidden;\n text-overflow: ellipsis;\n flex-grow: 0;\n}\n\n:host(.highlighted) .subtitle {\n color: inherit;\n}\n\n/*# sourceURL=console/consoleContextSelector.css */";Runtime.cachedResources["console/consoleSidebar.css"]="/*\n * Copyright (c) 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow: auto;\n}\n\n.tree-outline-disclosure {\n max-width: 100%;\n padding-left: 6px;\n}\n\n.count {\n flex: none;\n margin: 0 8px;\n}\n\n[is=ui-icon] {\n margin: 0 5px;\n}\n\n[is=ui-icon].icon-warning {\n background: linear-gradient(45deg, hsla(48, 100%, 50%, 1), hsla(48, 70%, 50%, 1));\n}\n\nli {\n height: 24px;\n}\n\nli .largeicon-navigator-file {\n background: linear-gradient(45deg, hsl(48, 70%, 50%), hsl(48, 70%, 70%));\n margin: 0;\n}\n\nli .largeicon-navigator-folder {\n background: linear-gradient(45deg, hsl(210, 82%, 65%), hsl(210, 82%, 80%));\n margin: -3px -3px 0 -5px;\n}\n\n.tree-element-title {\n flex-shrink: 100;\n flex-grow: 1;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n/*# sourceURL=console/consoleSidebar.css */";Runtime.cachedResources["console/consoleView.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.console-view {\n background-color: white;\n overflow: hidden;\n}\n\n.console-view > .toolbar {\n border-bottom: 1px solid #dadada;\n}\n\n.console-view-wrapper {\n background-color: #eee;\n}\n\n.console-view-fix-select-all {\n height: 0;\n overflow: hidden;\n}\n\n.console-settings-pane {\n flex: none;\n border-bottom: 1px solid #dadada;\n}\n\n.console-settings-pane .toolbar {\n flex: 1 1;\n}\n\n#console-messages {\n flex: 1 1;\n padding: 2px 0;\n overflow-y: auto;\n word-wrap: break-word;\n -webkit-user-select: text;\n transform: translateZ(0);\n}\n\n#console-prompt {\n clear: right;\n position: relative;\n margin: 0 22px 0 20px;\n min-height: 18px; /* Sync with ConsoleViewMessage.js */\n}\n\n#console-prompt .CodeMirror {\n padding: 3px 0 1px 0;\n}\n\n#console-prompt .CodeMirror-line {\n padding-top: 0;\n}\n\n#console-prompt .CodeMirror-lines {\n padding-top: 0;\n}\n\n#console-prompt .console-prompt-icon {\n position: absolute;\n left: -13px;\n top: 5px;\n -webkit-user-select: none;\n}\n\n.console-message,\n.console-user-command {\n clear: right;\n position: relative;\n padding: 3px 22px 1px 0;\n margin-left: 24px;\n min-height: 18px; /* Sync with ConsoleViewMessage.js */\n flex: auto;\n display: flex;\n}\n\n.console-message > * {\n flex: auto;\n}\n\n.console-timestamp {\n color: gray;\n -webkit-user-select: none;\n flex: none;\n margin-right: 5px;\n}\n\n.message-level-icon, .command-result-icon {\n position: absolute;\n left: -17px;\n top: 4px;\n -webkit-user-select: none;\n}\n\n.console-message-repeat-count {\n margin: 2px 0 0 10px;\n flex: none;\n}\n\n.repeated-message {\n margin-left: 4px;\n}\n\n.repeated-message .message-level-icon {\n display: none;\n}\n\n.repeated-message .console-message-stack-trace-toggle,\n.repeated-message > .console-message-text {\n flex: 1;\n}\n\n.console-error-level .repeated-message,\n.console-warning-level .repeated-message,\n.console-verbose-level .repeated-message,\n.console-info-level .repeated-message {\n display: flex;\n}\n\n.console-info {\n color: rgb(128, 128, 128);\n font-style: italic;\n padding-bottom: 2px;\n}\n\n.console-group .console-group > .console-group-messages {\n margin-left: 16px;\n}\n\n.console-group-title.console-from-api {\n font-weight: bold;\n}\n\n.console-group-title .console-message {\n margin-left: 12px;\n}\n\n.expand-group-icon {\n -webkit-user-select: none;\n flex: none;\n background-color: rgb(110, 110, 110);\n position: relative;\n left: 10px;\n top: 5px;\n margin-right: 2px;\n}\n\n.console-group-title .message-level-icon {\n display: none;\n}\n\n.console-message-repeat-count .expand-group-icon {\n left: 2px;\n top: 2px;\n background-color: #fff;\n margin-right: 4px;\n}\n\n.console-group {\n position: relative;\n}\n\n.console-message-wrapper {\n display: flex;\n border-bottom: 1px solid rgb(240, 240, 240);\n}\n\n.console-message-wrapper.console-adjacent-user-command-result {\n border-bottom: none;\n}\n\n.console-message-wrapper.console-error-level {\n border-top: 1px solid hsl(0, 100%, 92%);\n border-bottom: 1px solid hsl(0, 100%, 92%);\n margin-top: -1px;\n}\n\n.console-message-wrapper.console-warning-level {\n border-top: 1px solid hsl(50, 100%, 88%);\n border-bottom: 1px solid hsl(50, 100%, 88%);\n margin-top: -1px;\n}\n\n.console-message-wrapper .nesting-level-marker {\n width: 14px;\n flex: 0 0 auto;\n border-right: 1px solid #a5a5a5;\n position: relative;\n margin-bottom: -1px;\n}\n\n.console-message-wrapper:last-child .nesting-level-marker::before,\n.console-message-wrapper .nesting-level-marker.group-closed::before {\n content: \"\";\n}\n\n.console-message-wrapper .nesting-level-marker::before {\n border-bottom: 1px solid #a5a5a5;\n position: absolute;\n top: 0;\n left: 0;\n margin-left: 100%;\n width: 3px;\n height: 100%;\n box-sizing: border-box;\n}\n\n.console-error-level {\n background-color: hsl(0, 100%, 97%);\n}\n\n.-theme-with-dark-background .console-error-level {\n background-color: hsl(0, 100%, 8%);\n}\n\n.console-warning-level {\n background-color: hsl(50, 100%, 95%);\n}\n\n.-theme-with-dark-background .console-warning-level {\n background-color: hsl(50, 100%, 10%);\n}\n\n.console-warning-level .console-message-text {\n color: hsl(39, 100%, 18%);\n}\n\n.console-error-level .console-message-text,\n.console-error-level .console-view-object-properties-section {\n color: red !important;\n}\n\n.-theme-with-dark-background .console-error-level .console-message-text,\n.-theme-with-dark-background .console-error-level .console-view-object-properties-section {\n color: hsl(0, 100%, 75%) !important;\n}\n\n.-theme-with-dark-background .console-verbose-level .console-message-text {\n color: hsl(220, 100%, 65%) !important;\n}\n\n.console-message.console-warning-level {\n background-color: rgb(255, 250, 224);\n}\n\n#console-messages .link {\n text-decoration: underline;\n}\n\n#console-messages .link,\n#console-messages .devtools-link {\n color: rgb(33%, 33%, 33%);\n cursor: pointer;\n word-break: break-all;\n}\n\n#console-messages .link:hover,\n#console-messages .devtools-link:hover {\n color: rgb(15%, 15%, 15%);\n}\n\n.console-group-messages .section {\n margin: 0 0 0 12px !important;\n}\n\n.console-group-messages .section > .header {\n padding: 0 8px 0 0;\n background-image: none;\n border: none;\n min-height: 0;\n}\n\n.console-group-messages .section > .header::before {\n margin-left: -12px;\n}\n\n.console-group-messages .section > .header .title {\n color: #222;\n font-weight: normal;\n line-height: 13px;\n}\n\n.console-group-messages .section .properties li .info {\n padding-top: 0;\n padding-bottom: 0;\n color: rgb(60%, 60%, 60%);\n}\n\n.console-object-preview {\n white-space: normal;\n word-wrap: break-word;\n font-style: italic;\n}\n\n.console-object-preview .name {\n /* Follows .section .properties .name, .event-properties .name */\n color: rgb(136, 19, 145);\n flex-shrink: 0;\n}\n\n.console-message-text .object-value-string {\n white-space: pre-wrap;\n}\n\n.console-message-formatted-table {\n clear: both;\n}\n\n.console-message-anchor {\n float: right;\n text-align: right;\n max-width: 100%;\n margin-left: 4px;\n}\n\n.console-message-badge {\n float: right;\n margin-left: 4px;\n}\n\n.console-message-nowrap-below,\n.console-message-nowrap-below div,\n.console-message-nowrap-below span {\n white-space: nowrap !important;\n}\n\n.object-state-note {\n display: inline-block;\n width: 11px;\n height: 11px;\n color: white;\n text-align: center;\n border-radius: 3px;\n line-height: 13px;\n margin: 0 6px;\n font-size: 9px;\n}\n\n.-theme-with-dark-background .object-state-note {\n background-color: hsl(230, 100%, 80%);\n}\n\n.info-note {\n background-color: rgb(179, 203, 247);\n}\n\n.info-note::before {\n content: \"i\";\n}\n\n.console-view-object-properties-section:not(.expanded) .info-note {\n display: none;\n}\n\n.console-view-object-properties-section {\n padding: 0px;\n position: relative;\n vertical-align: baseline;\n color: inherit;\n display: inline-block;\n}\n\n.console-message-stack-trace-toggle {\n display: flex;\n flex-direction: row;\n align-items: flex-start;\n}\n\n.console-message-stack-trace-wrapper {\n flex: 1 1 auto;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n}\n\n.console-message-stack-trace-wrapper > * {\n flex: none;\n}\n\n.console-message-expand-icon {\n margin-bottom: -2px;\n}\n/*# sourceURL=console/consoleView.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/cookie_table/cookie_table_module.js b/src/cobalt/debug/content/devtools/cookie_table/cookie_table_module.js deleted file mode 100644 index d4ff8c0..0000000 --- a/src/cobalt/debug/content/devtools/cookie_table/cookie_table_module.js +++ /dev/null
@@ -1,68 +0,0 @@ -CookieTable.CookiesTable=class extends UI.VBox{constructor(saveCallback,refreshCallback,selectedCallback,deleteCallback){super();this._saveCallback=saveCallback;this._refreshCallback=refreshCallback;this._deleteCallback=deleteCallback;var editable=!!saveCallback;var columns=([{id:'name',title:Common.UIString('Name'),sortable:true,disclosure:editable,sort:DataGrid.DataGrid.Order.Ascending,longText:true,weight:24,editable:editable},{id:'value',title:Common.UIString('Value'),sortable:true,longText:true,weight:34,editable:editable},{id:'domain',title:Common.UIString('Domain'),sortable:true,weight:7,editable:editable},{id:'path',title:Common.UIString('Path'),sortable:true,weight:7,editable:editable},{id:'expires',title:Common.UIString('Expires / Max-Age'),sortable:true,weight:7,editable:editable},{id:'size',title:Common.UIString('Size'),sortable:true,align:DataGrid.DataGrid.Align.Right,weight:7},{id:'httpOnly',title:Common.UIString('HTTP'),sortable:true,align:DataGrid.DataGrid.Align.Center,weight:7},{id:'secure',title:Common.UIString('Secure'),sortable:true,align:DataGrid.DataGrid.Align.Center,weight:7},{id:'sameSite',title:Common.UIString('SameSite'),sortable:true,align:DataGrid.DataGrid.Align.Center,weight:7}]);if(editable){this._dataGrid=new DataGrid.DataGrid(columns,this._onUpdateCookie.bind(this),this._onDeleteCookie.bind(this),refreshCallback);}else{this._dataGrid=new DataGrid.DataGrid(columns);} -this._dataGrid.setStriped(true);this._dataGrid.setName('cookiesTable');this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._rebuildTable,this);if(selectedCallback) -this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,selectedCallback,this);this._lastEditedColumnId=null;this._dataGrid.asWidget().show(this.element);this._data=[];this._cookieDomain='';} -setCookies(cookies){this.setCookieFolders([{cookies:cookies}]);} -setCookieFolders(cookieFolders){this._data=cookieFolders;this._rebuildTable();} -setCookieDomain(cookieDomain){this._cookieDomain=cookieDomain;} -selectedCookie(){var node=this._dataGrid.selectedNode;return node?node.cookie:null;} -_getSelectionCookies(){var node=this._dataGrid.selectedNode;var nextNeighbor=node&&node.traverseNextNode(true);var previousNeighbor=node&&node.traversePreviousNode(true);return{current:node&&node.cookie,neighbor:(nextNeighbor&&nextNeighbor.cookie)||(previousNeighbor&&previousNeighbor.cookie)};} -willHide(){this._lastEditedColumnId=null;} -_findSelectedCookie(selectionCookies,cookies){if(!cookies) -return null;var current=selectionCookies.current;var foundCurrent=cookies.find(cookie=>this._isSameCookie(cookie,current));if(foundCurrent) -return foundCurrent;var neighbor=selectionCookies.neighbor;var foundNeighbor=cookies.find(cookie=>this._isSameCookie(cookie,neighbor));if(foundNeighbor) -return foundNeighbor;return null;} -_isSameCookie(cookieA,cookieB){return!!cookieB&&cookieB.name()===cookieA.name()&&cookieB.domain()===cookieA.domain()&&cookieB.path()===cookieA.path();} -_rebuildTable(){var selectionCookies=this._getSelectionCookies();var lastEditedColumnId=this._lastEditedColumnId;this._lastEditedColumnId=null;this._dataGrid.rootNode().removeChildren();for(var i=0;i<this._data.length;++i){var item=this._data[i];var selectedCookie=this._findSelectedCookie(selectionCookies,item.cookies);if(item.folderName){var groupData={name:item.folderName,value:'',domain:'',path:'',expires:'',size:this._totalSize(item.cookies),httpOnly:'',secure:'',sameSite:''};var groupNode=new DataGrid.DataGridNode(groupData);groupNode.selectable=true;this._dataGrid.rootNode().appendChild(groupNode);groupNode.element().classList.add('row-group');this._populateNode(groupNode,item.cookies,selectedCookie,lastEditedColumnId);groupNode.expand();}else{this._populateNode(this._dataGrid.rootNode(),item.cookies,selectedCookie,lastEditedColumnId);}} -if(selectionCookies.current&&lastEditedColumnId&&!this._dataGrid.selectedNode) -this._addInactiveNode(this._dataGrid.rootNode(),selectionCookies.current,lastEditedColumnId);if(this._saveCallback) -this._dataGrid.addCreationNode(false);} -_populateNode(parentNode,cookies,selectedCookie,lastEditedColumnId){parentNode.removeChildren();if(!cookies) -return;this._sortCookies(cookies);for(var i=0;i<cookies.length;++i){var cookie=cookies[i];var cookieNode=this._createGridNode(cookie);parentNode.appendChild(cookieNode);if(this._isSameCookie(cookie,selectedCookie)){cookieNode.select();if(lastEditedColumnId!==null) -this._dataGrid.startEditingNextEditableColumnOfDataGridNode(cookieNode,lastEditedColumnId);}}} -_addInactiveNode(parentNode,cookie,editedColumnId){const cookieNode=this._createGridNode(cookie);parentNode.appendChild(cookieNode);cookieNode.select();cookieNode.setInactive(true);if(editedColumnId!==null) -this._dataGrid.startEditingNextEditableColumnOfDataGridNode(cookieNode,editedColumnId);} -_totalSize(cookies){var totalSize=0;for(var i=0;cookies&&i<cookies.length;++i) -totalSize+=cookies[i].size();return totalSize;} -_sortCookies(cookies){var sortDirection=this._dataGrid.isSortOrderAscending()?1:-1;function getValue(cookie,property){return typeof cookie[property]==='function'?String(cookie[property]()):String(cookie.name());} -function compareTo(property,cookie1,cookie2){return sortDirection*getValue(cookie1,property).compareTo(getValue(cookie2,property));} -function numberCompare(cookie1,cookie2){return sortDirection*(cookie1.size()-cookie2.size());} -function expiresCompare(cookie1,cookie2){if(cookie1.session()!==cookie2.session()) -return sortDirection*(cookie1.session()?1:-1);if(cookie1.session()) -return 0;if(cookie1.maxAge()&&cookie2.maxAge()) -return sortDirection*(cookie1.maxAge()-cookie2.maxAge());if(cookie1.expires()&&cookie2.expires()) -return sortDirection*(cookie1.expires()-cookie2.expires());return sortDirection*(cookie1.expires()?1:-1);} -var comparator;var columnId=this._dataGrid.sortColumnId()||'name';if(columnId==='expires') -comparator=expiresCompare;else if(columnId==='size') -comparator=numberCompare;else -comparator=compareTo.bind(null,columnId);cookies.sort(comparator);} -_createGridNode(cookie){var data={};data.name=cookie.name();data.value=cookie.value();if(cookie.type()===SDK.Cookie.Type.Request){data.domain=Common.UIString('N/A');data.path=Common.UIString('N/A');data.expires=Common.UIString('N/A');}else{data.domain=cookie.domain()||'';data.path=cookie.path()||'';if(cookie.maxAge()) -data.expires=Number.secondsToString(parseInt(cookie.maxAge(),10));else if(cookie.expires()) -data.expires=new Date(cookie.expires()).toISOString();else -data.expires=CookieTable.CookiesTable._expiresSessionValue;} -data.size=cookie.size();const checkmark='\u2713';data.httpOnly=(cookie.httpOnly()?checkmark:'');data.secure=(cookie.secure()?checkmark:'');data.sameSite=cookie.sameSite()||'';var node=new DataGrid.DataGridNode(data);node.cookie=cookie;node.selectable=true;return node;} -_onDeleteCookie(node){if(node.cookie&&this._deleteCallback) -this._deleteCallback(node.cookie,()=>this._refresh());} -_onUpdateCookie(editingNode,columnIdentifier,oldText,newText){this._lastEditedColumnId=columnIdentifier;this._setDefaults(editingNode);if(this._isValidCookieData(editingNode.data)) -this._saveNode(editingNode);else -editingNode.setDirty(true);} -_setDefaults(node){if(node.data.name===null) -node.data.name='';if(node.data.value===null) -node.data.value='';if(node.data.domain===null) -node.data.domain=this._cookieDomain;if(node.data.path===null) -node.data.path='/';if(node.data.expires===null) -node.data.expires=CookieTable.CookiesTable._expiresSessionValue;} -_saveNode(node){var oldCookie=node.cookie;var newCookie=this._createCookieFromData(node.data);node.cookie=newCookie;this._saveCallback(newCookie,oldCookie).then(success=>{if(success) -this._refresh();else -node.setDirty(true);});} -_createCookieFromData(data){var cookie=new SDK.Cookie(data.name,data.value,null);cookie.addAttribute('domain',data.domain);cookie.addAttribute('path',data.path);if(data.expires&&data.expires!==CookieTable.CookiesTable._expiresSessionValue) -cookie.addAttribute('expires',(new Date(data.expires)).toUTCString());if(data.httpOnly) -cookie.addAttribute('httpOnly');if(data.secure) -cookie.addAttribute('secure');if(data.sameSite) -cookie.addAttribute('sameSite',data.sameSite);cookie.setSize(data.name.length+data.value.length);return cookie;} -_isValidCookieData(data){return(data.name||data.value)&&this._isValidDomain(data.domain)&&this._isValidPath(data.path)&&this._isValidDate(data.expires);} -_isValidDomain(domain){if(!domain) -return true;var parsedURL=('http://'+domain).asParsedURL();return!!parsedURL&&parsedURL.domain()===domain;} -_isValidPath(path){var parsedURL=('http://example.com'+path).asParsedURL();return!!parsedURL&&parsedURL.path===path;} -_isValidDate(date){return date===''||date===CookieTable.CookiesTable._expiresSessionValue||!isNaN(Date.parse(date));} -_refresh(){if(this._refreshCallback) -this._refreshCallback();}};CookieTable.CookiesTable._expiresSessionValue=Common.UIString('Session');; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/coverage/coverage_module.js b/src/cobalt/debug/content/devtools/coverage/coverage_module.js deleted file mode 100644 index 731922e..0000000 --- a/src/cobalt/debug/content/devtools/coverage/coverage_module.js +++ /dev/null
@@ -1,182 +0,0 @@ -Coverage.RangeUseCount;Coverage.CoverageSegment;Coverage.CoverageType={CSS:(1<<0),JavaScript:(1<<1),JavaScriptCoarse:(1<<2),};Coverage.CoverageModel=class extends SDK.SDKModel{constructor(target){super(target);this._cpuProfilerModel=target.model(SDK.CPUProfilerModel);this._cssModel=target.model(SDK.CSSModel);this._debuggerModel=target.model(SDK.DebuggerModel);this._coverageByURL=new Map();this._coverageByContentProvider=new Map();this._bestEffortCoveragePromise=null;} -start(){if(this._cssModel){this._clearCSS();this._cssModel.startCoverage();} -if(this._cpuProfilerModel){this._bestEffortCoveragePromise=this._cpuProfilerModel.bestEffortCoverage();this._cpuProfilerModel.startPreciseCoverage();} -return!!(this._cssModel||this._cpuProfilerModel);} -stop(){var pollPromise=this.poll();if(this._cpuProfilerModel) -this._cpuProfilerModel.stopPreciseCoverage();if(this._cssModel) -this._cssModel.stopCoverage();return pollPromise;} -reset(){this._coverageByURL=new Map();this._coverageByContentProvider=new Map();} -async poll(){var updates=await Promise.all([this._takeCSSCoverage(),this._takeJSCoverage()]);return updates[0].concat(updates[1]);} -entries(){return Array.from(this._coverageByURL.values());} -usageForRange(contentProvider,startOffset,endOffset){var coverageInfo=this._coverageByContentProvider.get(contentProvider);return coverageInfo&&coverageInfo.usageForRange(startOffset,endOffset);} -_clearCSS(){for(var entry of this._coverageByContentProvider.values()){if(entry.type()!==Coverage.CoverageType.CSS) -continue;var contentProvider=(entry.contentProvider());this._coverageByContentProvider.delete(contentProvider);var key=`${contentProvider.startLine}:${contentProvider.startColumn}`;var urlEntry=this._coverageByURL.get(entry.url());if(!urlEntry||!urlEntry._coverageInfoByLocation.delete(key)) -continue;urlEntry._size-=entry._size;urlEntry._usedSize-=entry._usedSize;if(!urlEntry._coverageInfoByLocation.size) -this._coverageByURL.delete(entry.url());}} -async _takeJSCoverage(){if(!this._cpuProfilerModel) -return[];var rawCoverageData=await this._cpuProfilerModel.takePreciseCoverage();if(this._bestEffortCoveragePromise){var bestEffortCoverage=await this._bestEffortCoveragePromise;this._bestEffortCoveragePromise=null;rawCoverageData=bestEffortCoverage.concat(rawCoverageData);} -return this._processJSCoverage(rawCoverageData);} -_processJSCoverage(scriptsCoverage){var updatedEntries=[];for(var entry of scriptsCoverage){var script=this._debuggerModel.scriptForId(entry.scriptId);if(!script) -continue;var ranges=[];var type=Coverage.CoverageType.JavaScript;for(var func of entry.functions){if(func.isBlockCoverage===false&&!(func.ranges.length===1&&!func.ranges[0].count)) -type|=Coverage.CoverageType.JavaScriptCoarse;for(var range of func.ranges) -ranges.push(range);} -var entry=this._addCoverage(script,script.contentLength,script.lineOffset,script.columnOffset,ranges,type);if(entry) -updatedEntries.push(entry);} -return updatedEntries;} -async _takeCSSCoverage(){if(!this._cssModel) -return[];var rawCoverageData=await this._cssModel.takeCoverageDelta();return this._processCSSCoverage(rawCoverageData);} -_processCSSCoverage(ruleUsageList){var updatedEntries=[];var rulesByStyleSheet=new Map();for(var rule of ruleUsageList){var styleSheetHeader=this._cssModel.styleSheetHeaderForId(rule.styleSheetId);if(!styleSheetHeader) -continue;var ranges=rulesByStyleSheet.get(styleSheetHeader);if(!ranges){ranges=[];rulesByStyleSheet.set(styleSheetHeader,ranges);} -ranges.push({startOffset:rule.startOffset,endOffset:rule.endOffset,count:Number(rule.used)});} -for(var entry of rulesByStyleSheet){var styleSheetHeader=(entry[0]);var ranges=(entry[1]);var entry=this._addCoverage(styleSheetHeader,styleSheetHeader.contentLength,styleSheetHeader.startLine,styleSheetHeader.startColumn,ranges,Coverage.CoverageType.CSS);if(entry) -updatedEntries.push(entry);} -return updatedEntries;} -static _convertToDisjointSegments(ranges){ranges.sort((a,b)=>a.startOffset-b.startOffset);var result=[];var stack=[];for(var entry of ranges){var top=stack.peekLast();while(top&&top.endOffset<=entry.startOffset){append(top.endOffset,top.count);stack.pop();top=stack.peekLast();} -append(entry.startOffset,top?top.count:undefined);stack.push(entry);} -while(stack.length){var top=stack.pop();append(top.endOffset,top.count);} -function append(end,count){var last=result.peekLast();if(last){if(last.end===end) -return;if(last.count===count){last.end=end;return;}} -result.push({end:end,count:count});} -return result;} -_addCoverage(contentProvider,contentLength,startLine,startColumn,ranges,type){var url=contentProvider.contentURL();if(!url) -return null;var urlCoverage=this._coverageByURL.get(url);if(!urlCoverage){urlCoverage=new Coverage.URLCoverageInfo(url);this._coverageByURL.set(url,urlCoverage);} -var coverageInfo=urlCoverage._ensureEntry(contentProvider,contentLength,startLine,startColumn,type);this._coverageByContentProvider.set(contentProvider,coverageInfo);var segments=Coverage.CoverageModel._convertToDisjointSegments(ranges);if(segments.length&&segments.peekLast().end<contentLength) -segments.push({end:contentLength});var oldUsedSize=coverageInfo._usedSize;coverageInfo.mergeCoverage(segments);if(coverageInfo._usedSize===oldUsedSize) -return null;urlCoverage._usedSize+=coverageInfo._usedSize-oldUsedSize;return coverageInfo;}};Coverage.URLCoverageInfo=class{constructor(url){this._url=url;this._coverageInfoByLocation=new Map();this._size=0;this._usedSize=0;this._type;this._isContentScript=false;} -url(){return this._url;} -type(){return this._type;} -size(){return this._size;} -usedSize(){return this._usedSize;} -unusedSize(){return this._size-this._usedSize;} -isContentScript(){return this._isContentScript;} -_ensureEntry(contentProvider,contentLength,lineOffset,columnOffset,type){var key=`${lineOffset}:${columnOffset}`;var entry=this._coverageInfoByLocation.get(key);if((type&Coverage.CoverageType.JavaScript)&&!this._coverageInfoByLocation.size) -this._isContentScript=(contentProvider).isContentScript();this._type|=type;if(entry){entry._coverageType|=type;return entry;} -if((type&Coverage.CoverageType.JavaScript)&&!this._coverageInfoByLocation.size) -this._isContentScript=(contentProvider).isContentScript();entry=new Coverage.CoverageInfo(contentProvider,contentLength,type);this._coverageInfoByLocation.set(key,entry);this._size+=contentLength;return entry;}};Coverage.CoverageInfo=class{constructor(contentProvider,size,type){this._contentProvider=contentProvider;this._size=size;this._usedSize=0;this._coverageType=type;this._segments=[];} -contentProvider(){return this._contentProvider;} -url(){return this._contentProvider.contentURL();} -type(){return this._coverageType;} -mergeCoverage(segments){this._segments=Coverage.CoverageInfo._mergeCoverage(this._segments,segments);this._updateStats();} -usageForRange(start,end){var index=this._segments.upperBound(start,(position,segment)=>position-segment.end);for(;index<this._segments.length&&this._segments[index].end<end;++index){if(this._segments[index].count) -return true;} -return index<this._segments.length&&!!this._segments[index].count;} -static _mergeCoverage(segmentsA,segmentsB){var result=[];var indexA=0;var indexB=0;while(indexA<segmentsA.length&&indexB<segmentsB.length){var a=segmentsA[indexA];var b=segmentsB[indexB];var count=typeof a.count==='number'||typeof b.count==='number'?(a.count||0)+(b.count||0):undefined;var end=Math.min(a.end,b.end);var last=result.peekLast();if(!last||last.count!==count) -result.push({end:end,count:count});else -last.end=end;if(a.end<=b.end) -indexA++;if(a.end>=b.end) -indexB++;} -for(;indexA<segmentsA.length;indexA++) -result.push(segmentsA[indexA]);for(;indexB<segmentsB.length;indexB++) -result.push(segmentsB[indexB]);return result;} -_updateStats(){this._usedSize=0;var last=0;for(var segment of this._segments){if(segment.count) -this._usedSize+=segment.end-last;last=segment.end;}}};;Coverage.CoverageListView=class extends UI.VBox{constructor(filterCallback){super(true);this._nodeForCoverageInfo=new Map();this._filterCallback=filterCallback;this._highlightRegExp=null;this.registerRequiredCSS('coverage/coverageListView.css');var columns=[{id:'url',title:Common.UIString('URL'),width:'250px',fixedWidth:false,sortable:true},{id:'type',title:Common.UIString('Type'),width:'45px',fixedWidth:true,sortable:true},{id:'size',title:Common.UIString('Total Bytes'),width:'60px',fixedWidth:true,sortable:true,align:DataGrid.DataGrid.Align.Right},{id:'unusedSize',title:Common.UIString('Unused Bytes'),width:'100px',fixedWidth:true,sortable:true,align:DataGrid.DataGrid.Align.Right,sort:DataGrid.DataGrid.Order.Descending},{id:'bars',title:'',width:'250px',fixedWidth:false,sortable:true}];this._dataGrid=new DataGrid.SortableDataGrid(columns);this._dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last);this._dataGrid.element.classList.add('flex-auto');this._dataGrid.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.OpenedNode,this._onOpenedNode,this);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortingChanged,this);var dataGridWidget=this._dataGrid.asWidget();dataGridWidget.show(this.contentElement);} -update(coverageInfo){var hadUpdates=false;var maxSize=coverageInfo.reduce((acc,entry)=>Math.max(acc,entry.size()),0);var rootNode=this._dataGrid.rootNode();for(var entry of coverageInfo){var node=this._nodeForCoverageInfo.get(entry);if(node){if(this._filterCallback(node._coverageInfo)) -hadUpdates=node._refreshIfNeeded(maxSize)||hadUpdates;continue;} -node=new Coverage.CoverageListView.GridNode(entry,maxSize);this._nodeForCoverageInfo.set(entry,node);if(this._filterCallback(node._coverageInfo)){rootNode.appendChild(node);hadUpdates=true;}} -if(hadUpdates) -this._sortingChanged();} -reset(){this._nodeForCoverageInfo.clear();this._dataGrid.rootNode().removeChildren();} -updateFilterAndHighlight(highlightRegExp){this._highlightRegExp=highlightRegExp;var hadTreeUpdates=false;for(var node of this._nodeForCoverageInfo.values()){var shouldBeVisible=this._filterCallback(node._coverageInfo);var isVisible=!!node.parent;if(shouldBeVisible) -node._setHighlight(this._highlightRegExp);if(shouldBeVisible===isVisible) -continue;hadTreeUpdates=true;if(!shouldBeVisible) -node.remove();else -this._dataGrid.rootNode().appendChild(node);} -if(hadTreeUpdates) -this._sortingChanged();} -_onOpenedNode(){this._revealSourceForSelectedNode();} -_onKeyDown(event){if(!isEnterKey(event)) -return;event.consume(true);this._revealSourceForSelectedNode();} -async _revealSourceForSelectedNode(){var node=this._dataGrid.selectedNode;if(!node) -return;var coverageInfo=(node)._coverageInfo;var sourceCode=Workspace.workspace.uiSourceCodeForURL(coverageInfo.url());if(!sourceCode) -return;var content=await sourceCode.requestContent();if(TextUtils.isMinified(content)){var formatData=await Sources.sourceFormatter.format(sourceCode);sourceCode=formatData.formattedSourceCode;} -if(this._dataGrid.selectedNode!==node) -return;Common.Revealer.reveal(sourceCode);} -_sortingChanged(){var columnId=this._dataGrid.sortColumnId();if(!columnId) -return;var sortFunction;switch(columnId){case'url':sortFunction=compareURL;break;case'type':sortFunction=compareType;break;case'size':sortFunction=compareNumericField.bind(null,'size');break;case'bars':case'unusedSize':sortFunction=compareNumericField.bind(null,'unusedSize');break;default:console.assert(false,'Unknown sort field: '+columnId);return;} -this._dataGrid.sortNodes(sortFunction,!this._dataGrid.isSortOrderAscending());function compareURL(a,b){var nodeA=(a);var nodeB=(b);return nodeA._url.localeCompare(nodeB._url);} -function compareNumericField(fieldName,a,b){var nodeA=(a);var nodeB=(b);return nodeA._coverageInfo[fieldName]()-nodeB._coverageInfo[fieldName]()||compareURL(a,b);} -function compareType(a,b){var nodeA=(a);var nodeB=(b);var typeA=Coverage.CoverageListView._typeToString(nodeA._coverageInfo.type());var typeB=Coverage.CoverageListView._typeToString(nodeB._coverageInfo.type());return typeA.localeCompare(typeB)||compareURL(a,b);}} -static _typeToString(type){var types=[];if(type&Coverage.CoverageType.CSS) -types.push(Common.UIString('CSS'));if(type&Coverage.CoverageType.JavaScriptCoarse) -types.push(Common.UIString('JS (coarse)'));else if(type&Coverage.CoverageType.JavaScript) -types.push(Common.UIString('JS'));return types.join('+');}};Coverage.CoverageListView.GridNode=class extends DataGrid.SortableDataGridNode{constructor(coverageInfo,maxSize){super();this._coverageInfo=coverageInfo;this._lastUsedSize;this._url=coverageInfo.url();this._maxSize=maxSize;this._highlightDOMChanges=[];this._highlightRegExp=null;} -_setHighlight(highlightRegExp){if(this._highlightRegExp===highlightRegExp) -return;this._highlightRegExp=highlightRegExp;this.refresh();} -_refreshIfNeeded(maxSize){if(this._lastUsedSize===this._coverageInfo.usedSize()&&maxSize===this._maxSize) -return false;this._lastUsedSize=this._coverageInfo.usedSize();this._maxSize=maxSize;this.refresh();return true;} -createCell(columnId){var cell=this.createTD(columnId);switch(columnId){case'url':cell.title=this._url;var outer=cell.createChild('div','url-outer');var prefix=outer.createChild('div','url-prefix');var suffix=outer.createChild('div','url-suffix');var splitURL=/^(.*)(\/[^/]*)$/.exec(this._url);prefix.textContent=splitURL?splitURL[1]:this._url;suffix.textContent=splitURL?splitURL[2]:'';if(this._highlightRegExp) -this._highlight(outer,this._url);break;case'type':cell.textContent=Coverage.CoverageListView._typeToString(this._coverageInfo.type());if(this._coverageInfo.type()&Coverage.CoverageType.JavaScriptCoarse) -cell.title=Common.UIString('JS coverage is function-level only. Reload the page for block-level coverage.');break;case'size':cell.textContent=Number.withThousandsSeparator(this._coverageInfo.size()||0);break;case'unusedSize':var unusedSize=this._coverageInfo.unusedSize()||0;var unusedSizeSpan=cell.createChild('span');var unusedPercentsSpan=cell.createChild('span','percent-value');unusedSizeSpan.textContent=Number.withThousandsSeparator(unusedSize);unusedPercentsSpan.textContent=Common.UIString('%.1f\xa0%%',unusedSize/this._coverageInfo.size()*100);break;case'bars':var barContainer=cell.createChild('div','bar-container');var unusedSizeBar=barContainer.createChild('div','bar bar-unused-size');unusedSizeBar.style.width=(100*this._coverageInfo.unusedSize()/this._maxSize).toFixed(4)+'%';var usedSizeBar=barContainer.createChild('div','bar bar-used-size');usedSizeBar.style.width=(100*this._coverageInfo.usedSize()/this._maxSize).toFixed(4)+'%';} -return cell;} -_highlight(element,textContent){var matches=this._highlightRegExp.exec(textContent);if(!matches||!matches.length) -return;var range=new TextUtils.SourceRange(matches.index,matches[0].length);UI.highlightRangesWithStyleClass(element,[range],'filter-highlight');}};;Coverage.CoverageView=class extends UI.VBox{constructor(){super(true);this._model=null;this._pollTimer;this._decorationManager=null;this._resourceTreeModel=null;this.registerRequiredCSS('coverage/coverageView.css');var toolbarContainer=this.contentElement.createChild('div','coverage-toolbar-container');var toolbar=new UI.Toolbar('coverage-toolbar',toolbarContainer);this._toggleRecordAction=(UI.actionRegistry.action('coverage.toggle-recording'));this._toggleRecordButton=UI.Toolbar.createActionButton(this._toggleRecordAction);toolbar.appendToolbarItem(this._toggleRecordButton);var startWithReloadAction=(UI.actionRegistry.action('coverage.start-with-reload'));this._startWithReloadButton=UI.Toolbar.createActionButton(startWithReloadAction);toolbar.appendToolbarItem(this._startWithReloadButton);this._clearButton=new UI.ToolbarButton(Common.UIString('Clear all'),'largeicon-clear');this._clearButton.addEventListener(UI.ToolbarButton.Events.Click,this._clear.bind(this));toolbar.appendToolbarItem(this._clearButton);this._textFilterRegExp=null;toolbar.appendSeparator();this._filterInput=new UI.ToolbarInput(Common.UIString('URL filter'),0.4,1);this._filterInput.setEnabled(false);this._filterInput.addEventListener(UI.ToolbarInput.Event.TextChanged,this._onFilterChanged,this);toolbar.appendToolbarItem(this._filterInput);toolbar.appendSeparator();this._showContentScriptsSetting=Common.settings.createSetting('showContentScripts',false);this._showContentScriptsSetting.addChangeListener(this._onFilterChanged,this);var contentScriptsCheckbox=new UI.ToolbarSettingCheckbox(this._showContentScriptsSetting,Common.UIString('Include extension content scripts'),Common.UIString('Content scripts'));toolbar.appendToolbarItem(contentScriptsCheckbox);this._coverageResultsElement=this.contentElement.createChild('div','coverage-results');this._landingPage=this._buildLandingPage();this._listView=new Coverage.CoverageListView(this._isVisible.bind(this,false));this._statusToolbarElement=this.contentElement.createChild('div','coverage-toolbar-summary');this._statusMessageElement=this._statusToolbarElement.createChild('div','coverage-message');this._landingPage.show(this._coverageResultsElement);} -_buildLandingPage(){var recordButton=UI.createInlineButton(UI.Toolbar.createActionButton(this._toggleRecordAction));var reloadButton=UI.createInlineButton(UI.Toolbar.createActionButtonForId('coverage.start-with-reload'));var widget=new UI.VBox();var message=UI.formatLocalized('Click the record button %s to start capturing coverage.\n'+'Click the reload button %s to reload and start capturing coverage.',[recordButton,reloadButton]);message.classList.add('message');widget.contentElement.appendChild(message);widget.element.classList.add('landing-page');return widget;} -_clear(){this._model=null;this._reset();} -_reset(){if(this._decorationManager){this._decorationManager.dispose();this._decorationManager=null;} -this._listView.reset();this._listView.detach();this._landingPage.show(this._coverageResultsElement);this._statusMessageElement.textContent='';this._filterInput.setEnabled(false);} -_toggleRecording(){var enable=!this._toggleRecordAction.toggled();if(enable) -this._startRecording(false);else -this._stopRecording();} -_startRecording(reload){this._reset();var mainTarget=SDK.targetManager.mainTarget();if(!mainTarget) -return;this._resourceTreeModel=(mainTarget.model(SDK.ResourceTreeModel));if(!this._resourceTreeModel) -return;if(!this._model||reload) -this._model=new Coverage.CoverageModel(mainTarget);Host.userMetrics.actionTaken(Host.UserMetrics.Action.CoverageStarted);if(!this._model.start()) -return;this._resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this);this._decorationManager=new Coverage.CoverageDecorationManager(this._model);this._toggleRecordAction.setToggled(true);this._clearButton.setEnabled(false);this._startWithReloadButton.setEnabled(false);this._filterInput.setEnabled(true);if(this._landingPage.isShowing()) -this._landingPage.detach();this._listView.show(this._coverageResultsElement);if(reload) -this._resourceTreeModel.reloadPage();else -this._poll();} -async _poll(){delete this._pollTimer;var updates=await this._model.poll();this._updateViews(updates);this._pollTimer=setTimeout(()=>this._poll(),700);} -async _stopRecording(){if(this._pollTimer){clearTimeout(this._pollTimer);delete this._pollTimer;} -this._resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this);this._resourceTreeModel=null;var updatedEntries=await this._model.stop();this._updateViews(updatedEntries);this._toggleRecordAction.setToggled(false);this._startWithReloadButton.setEnabled(true);this._clearButton.setEnabled(true);} -_onMainFrameNavigated(){this._model.reset();this._decorationManager.reset();this._listView.reset();this._poll();} -async _updateViews(updatedEntries){this._updateStats();this._listView.update(this._model.entries());this._decorationManager.update(updatedEntries);} -_updateStats(){var total=0;var unused=0;for(var info of this._model.entries()){if(!this._isVisible(true,info)) -continue;total+=info.size();unused+=info.unusedSize();} -var percentUnused=total?Math.round(100*unused/total):0;this._statusMessageElement.textContent=Common.UIString('%s of %s bytes are not used. (%d%%)',Number.bytesToString(unused),Number.bytesToString(total),percentUnused);} -_onFilterChanged(){if(!this._listView) -return;var text=this._filterInput.value();this._textFilterRegExp=text?createPlainTextSearchRegex(text,'i'):null;this._listView.updateFilterAndHighlight(this._textFilterRegExp);this._updateStats();} -_isVisible(ignoreTextFilter,coverageInfo){var url=coverageInfo.url();if(url.startsWith(Coverage.CoverageView._extensionBindingsURLPrefix)) -return false;if(coverageInfo.isContentScript()&&!this._showContentScriptsSetting.get()) -return false;return ignoreTextFilter||!this._textFilterRegExp||this._textFilterRegExp.test(url);}};Coverage.CoverageView._extensionBindingsURLPrefix='extensions::';Coverage.CoverageView.ActionDelegate=class{handleAction(context,actionId){var coverageViewId='coverage';UI.viewManager.showView(coverageViewId).then(()=>UI.viewManager.view(coverageViewId).widget()).then(widget=>this._innerHandleAction((widget),actionId));return true;} -_innerHandleAction(coverageView,actionId){switch(actionId){case'coverage.toggle-recording':coverageView._toggleRecording();break;case'coverage.start-with-reload':coverageView._startRecording(true);break;default:console.assert(false,`Unknown action: ${actionId}`);}}};;Coverage.RawLocation;Coverage.CoverageDecorationManager=class{constructor(coverageModel){this._coverageModel=coverageModel;this._textByProvider=new Map();this._uiSourceCodeByContentProvider=new Multimap();this._documentUISouceCodeToStylesheets=new WeakMap();for(var uiSourceCode of Workspace.workspace.uiSourceCodes()) -uiSourceCode.addLineDecoration(0,Coverage.CoverageDecorationManager._decoratorType,this);Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._onUISourceCodeAdded,this);} -reset(){for(var uiSourceCode of Workspace.workspace.uiSourceCodes()) -uiSourceCode.removeDecorationsForType(Coverage.CoverageDecorationManager._decoratorType);} -dispose(){this.reset();Workspace.workspace.removeEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._onUISourceCodeAdded,this);} -update(updatedEntries){for(var entry of updatedEntries){for(var uiSourceCode of this._uiSourceCodeByContentProvider.get(entry.contentProvider())){uiSourceCode.removeDecorationsForType(Coverage.CoverageDecorationManager._decoratorType);uiSourceCode.addLineDecoration(0,Coverage.CoverageDecorationManager._decoratorType,this);}}} -async usageByLine(uiSourceCode){var result=[];var sourceText=new TextUtils.Text(uiSourceCode.content()||'');await this._updateTexts(uiSourceCode,sourceText);var lineEndings=sourceText.lineEndings();for(var line=0;line<sourceText.lineCount();++line){var lineLength=lineEndings[line]-(line?lineEndings[line-1]:0)-1;if(!lineLength){result.push(undefined);continue;} -var startLocations=this._rawLocationsForSourceLocation(uiSourceCode,line,0);var endLocations=this._rawLocationsForSourceLocation(uiSourceCode,line,lineLength);var used=undefined;for(var startIndex=0,endIndex=0;startIndex<startLocations.length;++startIndex){var start=startLocations[startIndex];while(endIndex<endLocations.length&&Coverage.CoverageDecorationManager._compareLocations(start,endLocations[endIndex])>=0) -++endIndex;if(endIndex>=endLocations.length||endLocations[endIndex].id!==start.id) -continue;var end=endLocations[endIndex++];var text=this._textByProvider.get(end.contentProvider);if(!text) -continue;var textValue=text.value();var startOffset=Math.min(text.offsetFromPosition(start.line,start.column),textValue.length-1);var endOffset=Math.min(text.offsetFromPosition(end.line,end.column),textValue.length-1);while(startOffset<=endOffset&&/\s/.test(textValue[startOffset])) -++startOffset;while(startOffset<=endOffset&&/\s/.test(textValue[endOffset])) ---endOffset;if(startOffset<=endOffset) -used=this._coverageModel.usageForRange(end.contentProvider,startOffset,endOffset);if(used) -break;} -result.push(used);} -return result;} -_updateTexts(uiSourceCode,text){var promises=[];for(var line=0;line<text.lineCount();++line){for(var entry of this._rawLocationsForSourceLocation(uiSourceCode,line,0)){if(this._textByProvider.has(entry.contentProvider)) -continue;this._textByProvider.set(entry.contentProvider,null);this._uiSourceCodeByContentProvider.set(entry.contentProvider,uiSourceCode);promises.push(this._updateTextForProvider(entry.contentProvider));}} -return Promise.all(promises);} -async _updateTextForProvider(contentProvider){var content=await contentProvider.requestContent();this._textByProvider.set(contentProvider,new TextUtils.Text(content));} -_rawLocationsForSourceLocation(uiSourceCode,line,column){var result=[];var contentType=uiSourceCode.contentType();if(contentType.hasScripts()){var location=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(uiSourceCode,line,column);if(location&&location.script()){var script=location.script();if(script.isInlineScript()&&contentType.isDocument()){if(comparePositions(script.lineOffset,script.columnOffset,location.lineNumber,location.columnNumber)>0||comparePositions(script.endLine,script.endColumn,location.lineNumber,location.columnNumber)<=0){location=null;}else{location.lineNumber-=script.lineOffset;if(!location.lineNumber) -location.columnNumber-=script.columnOffset;}} -if(location){result.push({id:`js:${location.scriptId}`,contentProvider:location.script(),line:location.lineNumber,column:location.columnNumber});}}} -if(contentType.isStyleSheet()||contentType.isDocument()){var rawStyleLocations=contentType.isDocument()?this._documentUILocationToCSSRawLocations(uiSourceCode,line,column):Bindings.cssWorkspaceBinding.uiLocationToRawLocations(new Workspace.UILocation(uiSourceCode,line,column));for(var location of rawStyleLocations){var header=location.header();if(!header) -continue;if(header.isInline&&contentType.isDocument()){location.lineNumber-=header.startLine;if(!location.lineNumber) -location.columnNumber-=header.startColumn;} -result.push({id:`css:${location.styleSheetId}`,contentProvider:location.header(),line:location.lineNumber,column:location.columnNumber});}} -result.sort(Coverage.CoverageDecorationManager._compareLocations);function comparePositions(aLine,aColumn,bLine,bColumn){return aLine-bLine||aColumn-bColumn;} -return result;} -_documentUILocationToCSSRawLocations(uiSourceCode,line,column){var stylesheets=this._documentUISouceCodeToStylesheets.get(uiSourceCode);if(!stylesheets){stylesheets=[];var cssModel=this._coverageModel.target().model(SDK.CSSModel);if(!cssModel) -return[];for(var headerId of cssModel.styleSheetIdsForURL(uiSourceCode.url())){var header=cssModel.styleSheetHeaderForId(headerId);if(header) -stylesheets.push(header);} -stylesheets.sort(stylesheetComparator);this._documentUISouceCodeToStylesheets.set(uiSourceCode,stylesheets);} -var endIndex=stylesheets.upperBound(undefined,(unused,header)=>line-header.startLine||column-header.startColumn);if(!endIndex) -return[];var locations=[];var last=stylesheets[endIndex-1];for(var index=endIndex-1;index>=0&&stylesheets[index].startLine===last.startLine&&stylesheets[index].startColumn===last.startColumn;--index) -locations.push(new SDK.CSSLocation(stylesheets[index],line,column));return locations;function stylesheetComparator(a,b){return a.startLine-b.startLine||a.startColumn-b.startColumn||a.id.localeCompare(b.id);}} -static _compareLocations(a,b){return a.id.localeCompare(b.id)||a.line-b.line||a.column-b.column;} -_onUISourceCodeAdded(event){var uiSourceCode=(event.data);uiSourceCode.addLineDecoration(0,Coverage.CoverageDecorationManager._decoratorType,this);}};Coverage.CoverageDecorationManager._decoratorType='coverage';Coverage.CoverageView.LineDecorator=class{decorate(uiSourceCode,textEditor){var decorations=uiSourceCode.decorationsForType(Coverage.CoverageDecorationManager._decoratorType);if(!decorations||!decorations.size){textEditor.uninstallGutter(Coverage.CoverageView.LineDecorator._gutterType);return;} -var decorationManager=(decorations.values().next().value.data());decorationManager.usageByLine(uiSourceCode).then(lineUsage=>{textEditor.operation(()=>this._innerDecorate(textEditor,lineUsage));});} -_innerDecorate(textEditor,lineUsage){var gutterType=Coverage.CoverageView.LineDecorator._gutterType;textEditor.uninstallGutter(gutterType);textEditor.installGutter(gutterType,false);for(var line=0;line<lineUsage.length;++line){if(typeof lineUsage[line]!=='boolean') -continue;var className=lineUsage[line]?'text-editor-coverage-used-marker':'text-editor-coverage-unused-marker';textEditor.setGutterDecoration(line,gutterType,createElementWithClass('div',className));}}};Coverage.CoverageView.LineDecorator._gutterType='CodeMirror-gutter-coverage';;Runtime.cachedResources["coverage/coverageListView.css"]=".data-grid {\n border: none;\n}\n\n.data-grid td .url-outer {\n width: 100%;\n display: inline-flex;\n justify-content: flex-start;\n}\n\n.data-grid td .url-outer .filter-highlight {\n font-weight: bold;\n}\n\n.data-grid td .url-prefix {\n overflow-x: hidden;\n text-overflow: ellipsis;\n}\n\n.data-grid td .url-suffix {\n flex: none;\n}\n\n.data-grid td .bar {\n display: inline-block;\n height: 8px;\n}\n\n.data-grid .selected td .bar {\n border-top: 1px white solid;\n border-bottom: 1px white solid;\n}\n\n.data-grid .selected td .bar:last-child {\n border-right: 1px white solid;\n}\n\n.data-grid .selected td .bar:first-child {\n border-left: 1px white solid;\n}\n\n.data-grid td .bar-container {\n}\n\n.data-grid td .bar-unused-size {\n background-color: #E57373;\n}\n\n.data-grid td .bar-used-size {\n background-color: #81C784;\n}\n\n.data-grid td .percent-value {\n color: #888;\n width: 45px;\n display: inline-block;\n}\n\n.data-grid:focus tr.selected span.percent-value {\n color: #eee;\n}\n\n/*# sourceURL=coverage/coverageListView.css */";Runtime.cachedResources["coverage/coverageView.css"]="/*\n * Copyright (c) 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow: hidden;\n}\n\n.coverage-toolbar-container {\n display: flex;\n border-bottom: 1px solid #ccc;\n flex: 0 0;\n}\n\n.coverage-toolbar {\n display: inline-block;\n}\n\n.coverage-toolbar-summary {\n background-color: #eee;\n border-top: 1px solid #ccc;\n padding-left: 5px;\n flex: 0 0 19px;\n display: flex;\n padding-right: 5px;\n}\n\n.coverage-toolbar-summary .coverage-message {\n padding-top: 2px;\n padding-left: 1ex;\n text-overflow: ellipsis;\n white-space: nowrap;\n overflow: hidden;\n}\n\n.coverage-results {\n overflow-y: auto;\n display: flex;\n flex: auto;\n}\n\n.landing-page {\n justify-content: center;\n align-items: center;\n padding: 20px;\n}\n\n.landing-page .message {\n white-space: pre-line;\n}\n\n/*# sourceURL=coverage/coverageView.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/data_grid/data_grid_module.js b/src/cobalt/debug/content/devtools/data_grid/data_grid_module.js deleted file mode 100644 index 0c70c7f..0000000 --- a/src/cobalt/debug/content/devtools/data_grid/data_grid_module.js +++ /dev/null
@@ -1,455 +0,0 @@ -DataGrid.DataGrid=class extends Common.Object{constructor(columnsArray,editCallback,deleteCallback,refreshCallback){super();this.element=createElementWithClass('div','data-grid');UI.appendStyle(this.element,'data_grid/dataGrid.css');this.element.tabIndex=0;this.element.addEventListener('keydown',this._keyDown.bind(this),false);this.element.addEventListener('contextmenu',this._contextMenu.bind(this),true);this._editCallback=editCallback;this._deleteCallback=deleteCallback;this._refreshCallback=refreshCallback;var headerContainer=this.element.createChild('div','header-container');this._headerTable=headerContainer.createChild('table','header');this._headerTableHeaders={};this._scrollContainer=this.element.createChild('div','data-container');this._dataTable=this._scrollContainer.createChild('table','data');if(editCallback) -this._dataTable.addEventListener('dblclick',this._ondblclick.bind(this),false);this._dataTable.addEventListener('mousedown',this._mouseDownInDataTable.bind(this));this._dataTable.addEventListener('click',this._clickInDataTable.bind(this),true);this._inline=false;this._columnsArray=[];this._columns={};this._visibleColumnsArray=columnsArray;columnsArray.forEach(column=>this._innerAddColumn(column));this._cellClass=null;this._headerTableColumnGroup=this._headerTable.createChild('colgroup');this._headerTableBody=this._headerTable.createChild('tbody');this._headerRow=this._headerTableBody.createChild('tr');this._dataTableColumnGroup=this._dataTable.createChild('colgroup');this.dataTableBody=this._dataTable.createChild('tbody');this._topFillerRow=this.dataTableBody.createChild('tr','data-grid-filler-row revealed');this._bottomFillerRow=this.dataTableBody.createChild('tr','data-grid-filler-row revealed');this.setVerticalPadding(0,0);this._refreshHeader();this._editing=false;this.selectedNode=null;this.expandNodesWhenArrowing=false;this.setRootNode((new DataGrid.DataGridNode()));this.indentWidth=15;this._resizers=[];this._columnWidthsInitialized=false;this._cornerWidth=DataGrid.DataGrid.CornerWidth;this._resizeMethod=DataGrid.DataGrid.ResizeMethod.Nearest;this._headerContextMenuCallback=null;this._rowContextMenuCallback=null;} -static setElementText(element,newText,longText){if(longText&&newText.length>1000){element.textContent=newText.trimEnd(1000);element.title=newText;element[DataGrid.DataGrid._longTextSymbol]=newText;}else{element.textContent=newText;element.title='';element[DataGrid.DataGrid._longTextSymbol]=undefined;}} -setStriped(isStriped){this.element.classList.toggle('striped-data-grid',isStriped);} -headerTableBody(){return this._headerTableBody;} -_innerAddColumn(column,position){var columnId=column.id;if(columnId in this._columns) -this._innerRemoveColumn(columnId);if(position===undefined) -position=this._columnsArray.length;this._columnsArray.splice(position,0,column);this._columns[columnId]=column;if(column.disclosure) -this.disclosureColumnId=columnId;var cell=createElement('th');cell.className=columnId+'-column';cell[DataGrid.DataGrid._columnIdSymbol]=columnId;this._headerTableHeaders[columnId]=cell;var div=createElement('div');if(column.titleDOMFragment) -div.appendChild(column.titleDOMFragment);else -div.textContent=column.title;cell.appendChild(div);if(column.sort){cell.classList.add(column.sort);this._sortColumnCell=cell;} -if(column.sortable){cell.addEventListener('click',this._clickInHeaderCell.bind(this),false);cell.classList.add('sortable');var icon=UI.Icon.create('','sort-order-icon');cell.createChild('div','sort-order-icon-container').appendChild(icon);cell[DataGrid.DataGrid._sortIconSymbol]=icon;}} -addColumn(column,position){this._innerAddColumn(column,position);} -_innerRemoveColumn(columnId){var column=this._columns[columnId];if(!column) -return;delete this._columns[columnId];var index=this._columnsArray.findIndex(columnConfig=>columnConfig.id===columnId);this._columnsArray.splice(index,1);var cell=this._headerTableHeaders[columnId];if(cell.parentElement) -cell.parentElement.removeChild(cell);delete this._headerTableHeaders[columnId];} -removeColumn(columnId){this._innerRemoveColumn(columnId);} -setCellClass(cellClass){this._cellClass=cellClass;} -_refreshHeader(){this._headerTableColumnGroup.removeChildren();this._dataTableColumnGroup.removeChildren();this._headerRow.removeChildren();this._topFillerRow.removeChildren();this._bottomFillerRow.removeChildren();for(var i=0;i<this._visibleColumnsArray.length;++i){var column=this._visibleColumnsArray[i];var columnId=column.id;var headerColumn=this._headerTableColumnGroup.createChild('col');var dataColumn=this._dataTableColumnGroup.createChild('col');if(column.width){headerColumn.style.width=column.width;dataColumn.style.width=column.width;} -this._headerRow.appendChild(this._headerTableHeaders[columnId]);this._topFillerRow.createChild('td','top-filler-td');this._bottomFillerRow.createChild('td','bottom-filler-td')[DataGrid.DataGrid._columnIdSymbol]=columnId;} -this._headerRow.createChild('th','corner');this._topFillerRow.createChild('td','corner').classList.add('top-filler-td');this._bottomFillerRow.createChild('td','corner').classList.add('bottom-filler-td');this._headerTableColumnGroup.createChild('col','corner');this._dataTableColumnGroup.createChild('col','corner');} -setVerticalPadding(top,bottom){var topPx=top+'px';var bottomPx=(top||bottom)?bottom+'px':'auto';if(this._topFillerRow.style.height===topPx&&this._bottomFillerRow.style.height===bottomPx) -return;this._topFillerRow.style.height=topPx;this._bottomFillerRow.style.height=bottomPx;this.dispatchEventToListeners(DataGrid.DataGrid.Events.PaddingChanged);} -setRootNode(rootNode){if(this._rootNode){this._rootNode.removeChildren();this._rootNode.dataGrid=null;this._rootNode._isRoot=false;} -this._rootNode=rootNode;rootNode._isRoot=true;rootNode.setHasChildren(false);rootNode._expanded=true;rootNode._revealed=true;rootNode.selectable=false;rootNode.dataGrid=this;} -rootNode(){return this._rootNode;} -_ondblclick(event){if(this._editing||this._editingNode) -return;var columnId=this.columnIdFromNode((event.target));if(!columnId||!this._columns[columnId].editable) -return;this._startEditing((event.target));} -_startEditingColumnOfDataGridNode(node,cellIndex){this._editing=true;this._editingNode=node;this._editingNode.select();var element=this._editingNode._element.children[cellIndex];UI.InplaceEditor.startEditing(element,this._startEditingConfig(element));element.getComponentSelection().selectAllChildren(element);} -startEditingNextEditableColumnOfDataGridNode(node,columnIdentifier){const column=this._columns[columnIdentifier];const cellIndex=this._visibleColumnsArray.indexOf(column);const nextEditableColumn=this._nextEditableColumn(cellIndex);if(nextEditableColumn!==-1) -this._startEditingColumnOfDataGridNode(node,nextEditableColumn);} -_startEditing(target){var element=(target.enclosingNodeOrSelfWithNodeName('td'));if(!element) -return;this._editingNode=this.dataGridNodeFromNode(target);if(!this._editingNode){if(!this.creationNode) -return;this._editingNode=this.creationNode;} -if(this._editingNode.isCreationNode){this._startEditingColumnOfDataGridNode(this._editingNode,this._nextEditableColumn(-1));return;} -this._editing=true;if(element[DataGrid.DataGrid._longTextSymbol]) -element.textContent=element[DataGrid.DataGrid._longTextSymbol];UI.InplaceEditor.startEditing(element,this._startEditingConfig(element));element.getComponentSelection().selectAllChildren(element);} -renderInline(){this.element.classList.add('inline');this._cornerWidth=0;this._inline=true;this.updateWidths();} -_startEditingConfig(element){return new UI.InplaceEditor.Config(this._editingCommitted.bind(this),this._editingCancelled.bind(this));} -_editingCommitted(element,newText,oldText,context,moveDirection){var columnId=this.columnIdFromNode(element);if(!columnId){this._editingCancelled(element);return;} -var column=this._columns[columnId];var cellIndex=this._visibleColumnsArray.indexOf(column);var textBeforeEditing=(this._editingNode.data[columnId]||'');var currentEditingNode=this._editingNode;function moveToNextIfNeeded(wasChange){if(!moveDirection) -return;if(moveDirection==='forward'){var firstEditableColumn=this._nextEditableColumn(-1);if(currentEditingNode.isCreationNode&&cellIndex===firstEditableColumn&&!wasChange) -return;var nextEditableColumn=this._nextEditableColumn(cellIndex);if(nextEditableColumn!==-1){this._startEditingColumnOfDataGridNode(currentEditingNode,nextEditableColumn);return;} -var nextDataGridNode=currentEditingNode.traverseNextNode(true,null,true);if(nextDataGridNode){this._startEditingColumnOfDataGridNode(nextDataGridNode,firstEditableColumn);return;} -if(currentEditingNode.isCreationNode&&wasChange){this.addCreationNode(false);this._startEditingColumnOfDataGridNode(this.creationNode,firstEditableColumn);return;} -return;} -if(moveDirection==='backward'){var prevEditableColumn=this._nextEditableColumn(cellIndex,true);if(prevEditableColumn!==-1){this._startEditingColumnOfDataGridNode(currentEditingNode,prevEditableColumn);return;} -var lastEditableColumn=this._nextEditableColumn(this._visibleColumnsArray.length,true);var nextDataGridNode=currentEditingNode.traversePreviousNode(true,true);if(nextDataGridNode) -this._startEditingColumnOfDataGridNode(nextDataGridNode,lastEditableColumn);return;}} -DataGrid.DataGrid.setElementText(element,newText,!!column.longText);if(textBeforeEditing===newText){this._editingCancelled(element);moveToNextIfNeeded.call(this,false);return;} -this._editingNode.data[columnId]=newText;this._editCallback(this._editingNode,columnId,textBeforeEditing,newText);if(this._editingNode.isCreationNode) -this.addCreationNode(false);this._editingCancelled(element);moveToNextIfNeeded.call(this,true);} -_editingCancelled(element){this._editing=false;this._editingNode=null;} -_nextEditableColumn(cellIndex,moveBackward){var increment=moveBackward?-1:1;var columns=this._visibleColumnsArray;for(var i=cellIndex+increment;(i>=0)&&(i<columns.length);i+=increment){if(columns[i].editable) -return i;} -return-1;} -sortColumnId(){if(!this._sortColumnCell) -return null;return this._sortColumnCell[DataGrid.DataGrid._columnIdSymbol];} -sortOrder(){if(!this._sortColumnCell||this._sortColumnCell.classList.contains(DataGrid.DataGrid.Order.Ascending)) -return DataGrid.DataGrid.Order.Ascending;if(this._sortColumnCell.classList.contains(DataGrid.DataGrid.Order.Descending)) -return DataGrid.DataGrid.Order.Descending;return null;} -isSortOrderAscending(){return!this._sortColumnCell||this._sortColumnCell.classList.contains(DataGrid.DataGrid.Order.Ascending);} -_autoSizeWidths(widths,minPercent,maxPercent){if(minPercent) -minPercent=Math.min(minPercent,Math.floor(100/widths.length));var totalWidth=0;for(var i=0;i<widths.length;++i) -totalWidth+=widths[i];var totalPercentWidth=0;for(var i=0;i<widths.length;++i){var width=Math.round(100*widths[i]/totalWidth);if(minPercent&&width<minPercent) -width=minPercent;else if(maxPercent&&width>maxPercent) -width=maxPercent;totalPercentWidth+=width;widths[i]=width;} -var recoupPercent=totalPercentWidth-100;while(minPercent&&recoupPercent>0){for(var i=0;i<widths.length;++i){if(widths[i]>minPercent){--widths[i];--recoupPercent;if(!recoupPercent) -break;}}} -while(maxPercent&&recoupPercent<0){for(var i=0;i<widths.length;++i){if(widths[i]<maxPercent){++widths[i];++recoupPercent;if(!recoupPercent) -break;}}} -return widths;} -autoSizeColumns(minPercent,maxPercent,maxDescentLevel){var widths=[];for(var i=0;i<this._columnsArray.length;++i) -widths.push((this._columnsArray[i].title||'').length);maxDescentLevel=maxDescentLevel||0;var children=this._enumerateChildren(this._rootNode,[],maxDescentLevel+1);for(var i=0;i<children.length;++i){var node=children[i];for(var j=0;j<this._columnsArray.length;++j){var text=node.data[this._columnsArray[j].id];if(text.length>widths[j]) -widths[j]=text.length;}} -widths=this._autoSizeWidths(widths,minPercent,maxPercent);for(var i=0;i<this._columnsArray.length;++i) -this._columnsArray[i].weight=widths[i];this._columnWidthsInitialized=false;this.updateWidths();} -_enumerateChildren(rootNode,result,maxLevel){if(!rootNode._isRoot) -result.push(rootNode);if(!maxLevel) -return[];for(var i=0;i<rootNode.children.length;++i) -this._enumerateChildren(rootNode.children[i],result,maxLevel-1);return result;} -onResize(){this.updateWidths();} -updateWidths(){if(!this._columnWidthsInitialized&&this.element.offsetWidth){var tableWidth=this.element.offsetWidth-this._cornerWidth;var cells=this._headerTableBody.rows[0].cells;var numColumns=cells.length-1;for(var i=0;i<numColumns;i++){var column=this._visibleColumnsArray[i];if(!column.weight) -column.weight=100*cells[i].offsetWidth/tableWidth||10;} -this._columnWidthsInitialized=true;} -this._applyColumnWeights();} -setName(name){this._columnWeightsSetting=Common.settings.createSetting('dataGrid-'+name+'-columnWeights',{});this._loadColumnWeights();} -_loadColumnWeights(){if(!this._columnWeightsSetting) -return;var weights=this._columnWeightsSetting.get();for(var i=0;i<this._columnsArray.length;++i){var column=this._columnsArray[i];var weight=weights[column.id];if(weight) -column.weight=weight;} -this._applyColumnWeights();} -_saveColumnWeights(){if(!this._columnWeightsSetting) -return;var weights={};for(var i=0;i<this._columnsArray.length;++i){var column=this._columnsArray[i];weights[column.id]=column.weight;} -this._columnWeightsSetting.set(weights);} -wasShown(){this._loadColumnWeights();} -willHide(){} -_applyColumnWeights(){var tableWidth=this.element.offsetWidth-this._cornerWidth;if(tableWidth<=0) -return;var sumOfWeights=0.0;var fixedColumnWidths=[];for(var i=0;i<this._visibleColumnsArray.length;++i){var column=this._visibleColumnsArray[i];if(column.fixedWidth){var width=this._headerTableColumnGroup.children[i][DataGrid.DataGrid._preferredWidthSymbol]||this._headerTableBody.rows[0].cells[i].offsetWidth;fixedColumnWidths[i]=width;tableWidth-=width;}else{sumOfWeights+=this._visibleColumnsArray[i].weight;}} -var sum=0;var lastOffset=0;for(var i=0;i<this._visibleColumnsArray.length;++i){var column=this._visibleColumnsArray[i];var width;if(column.fixedWidth){width=fixedColumnWidths[i];}else{sum+=column.weight;var offset=(sum*tableWidth/sumOfWeights)|0;width=offset-lastOffset;lastOffset=offset;} -this._setPreferredWidth(i,width);} -this._positionResizers();} -setColumnsVisiblity(columnsVisibility){this._visibleColumnsArray=[];for(var i=0;i<this._columnsArray.length;++i){var column=this._columnsArray[i];if(columnsVisibility[column.id]) -this._visibleColumnsArray.push(column);} -this._refreshHeader();this._applyColumnWeights();var nodes=this._enumerateChildren(this.rootNode(),[],-1);for(var i=0;i<nodes.length;++i) -nodes[i].refresh();} -get scrollContainer(){return this._scrollContainer;} -_positionResizers(){var headerTableColumns=this._headerTableColumnGroup.children;var numColumns=headerTableColumns.length-1;var left=[];var resizers=this._resizers;while(resizers.length>numColumns-1) -resizers.pop().remove();for(var i=0;i<numColumns-1;i++){left[i]=(left[i-1]||0)+this._headerTableBody.rows[0].cells[i].offsetWidth;} -for(var i=0;i<numColumns-1;i++){var resizer=resizers[i];if(!resizer){resizer=createElement('div');resizer.__index=i;resizer.classList.add('data-grid-resizer');UI.installDragHandle(resizer,this._startResizerDragging.bind(this),this._resizerDragging.bind(this),this._endResizerDragging.bind(this),'col-resize');this.element.appendChild(resizer);resizers.push(resizer);} -if(resizer.__position!==left[i]){resizer.__position=left[i];resizer.style.left=left[i]+'px';}}} -addCreationNode(hasChildren){if(this.creationNode) -this.creationNode.makeNormal();var emptyData={};for(var column in this._columns) -emptyData[column]=null;this.creationNode=new DataGrid.CreationDataGridNode(emptyData,hasChildren);this.rootNode().appendChild(this.creationNode);} -_keyDown(event){if(!this.selectedNode||event.shiftKey||event.metaKey||event.ctrlKey||this._editing) -return;var handled=false;var nextSelectedNode;if(event.key==='ArrowUp'&&!event.altKey){nextSelectedNode=this.selectedNode.traversePreviousNode(true);while(nextSelectedNode&&!nextSelectedNode.selectable) -nextSelectedNode=nextSelectedNode.traversePreviousNode(true);handled=nextSelectedNode?true:false;}else if(event.key==='ArrowDown'&&!event.altKey){nextSelectedNode=this.selectedNode.traverseNextNode(true);while(nextSelectedNode&&!nextSelectedNode.selectable) -nextSelectedNode=nextSelectedNode.traverseNextNode(true);handled=nextSelectedNode?true:false;}else if(event.key==='ArrowLeft'){if(this.selectedNode.expanded){if(event.altKey) -this.selectedNode.collapseRecursively();else -this.selectedNode.collapse();handled=true;}else if(this.selectedNode.parent&&!this.selectedNode.parent._isRoot){handled=true;if(this.selectedNode.parent.selectable){nextSelectedNode=this.selectedNode.parent;handled=nextSelectedNode?true:false;}else if(this.selectedNode.parent){this.selectedNode.parent.collapse();}}}else if(event.key==='ArrowRight'){if(!this.selectedNode.revealed){this.selectedNode.reveal();handled=true;}else if(this.selectedNode.hasChildren()){handled=true;if(this.selectedNode.expanded){nextSelectedNode=this.selectedNode.children[0];handled=nextSelectedNode?true:false;}else{if(event.altKey) -this.selectedNode.expandRecursively();else -this.selectedNode.expand();}}}else if(event.keyCode===8||event.keyCode===46){if(this._deleteCallback){handled=true;this._deleteCallback(this.selectedNode);}}else if(isEnterKey(event)){if(this._editCallback){handled=true;this._startEditing(this.selectedNode._element.children[this._nextEditableColumn(-1)]);}else{this.dispatchEventToListeners(DataGrid.DataGrid.Events.OpenedNode,this.selectedNode);}} -if(nextSelectedNode){nextSelectedNode.reveal();nextSelectedNode.select();} -if(handled) -event.consume(true);} -updateSelectionBeforeRemoval(root,onlyAffectsSubtree){var ancestor=this.selectedNode;while(ancestor&&ancestor!==root) -ancestor=ancestor.parent;if(!ancestor) -return;var nextSelectedNode;for(ancestor=root;ancestor&&!ancestor.nextSibling;ancestor=ancestor.parent){} -if(ancestor) -nextSelectedNode=ancestor.nextSibling;while(nextSelectedNode&&!nextSelectedNode.selectable) -nextSelectedNode=nextSelectedNode.traverseNextNode(true);if(!nextSelectedNode||nextSelectedNode.isCreationNode){nextSelectedNode=root.traversePreviousNode(true);while(nextSelectedNode&&!nextSelectedNode.selectable) -nextSelectedNode=nextSelectedNode.traversePreviousNode(true);} -if(nextSelectedNode){nextSelectedNode.reveal();nextSelectedNode.select();}else{this.selectedNode.deselect();}} -dataGridNodeFromNode(target){var rowElement=target.enclosingNodeOrSelfWithNodeName('tr');return rowElement&&rowElement._dataGridNode;} -columnIdFromNode(target){var cellElement=target.enclosingNodeOrSelfWithNodeName('td');return cellElement&&cellElement[DataGrid.DataGrid._columnIdSymbol];} -_clickInHeaderCell(event){var cell=event.target.enclosingNodeOrSelfWithNodeName('th');if(!cell||(cell[DataGrid.DataGrid._columnIdSymbol]===undefined)||!cell.classList.contains('sortable')) -return;var sortOrder=DataGrid.DataGrid.Order.Ascending;if((cell===this._sortColumnCell)&&this.isSortOrderAscending()) -sortOrder=DataGrid.DataGrid.Order.Descending;if(this._sortColumnCell) -this._sortColumnCell.classList.remove(DataGrid.DataGrid.Order.Ascending,DataGrid.DataGrid.Order.Descending);this._sortColumnCell=cell;cell.classList.add(sortOrder);var icon=cell[DataGrid.DataGrid._sortIconSymbol];icon.setIconType(sortOrder===DataGrid.DataGrid.Order.Ascending?'smallicon-triangle-up':'smallicon-triangle-down');this.dispatchEventToListeners(DataGrid.DataGrid.Events.SortingChanged);} -markColumnAsSortedBy(columnId,sortOrder){if(this._sortColumnCell) -this._sortColumnCell.classList.remove(DataGrid.DataGrid.Order.Ascending,DataGrid.DataGrid.Order.Descending);this._sortColumnCell=this._headerTableHeaders[columnId];this._sortColumnCell.classList.add(sortOrder);} -headerTableHeader(columnId){return this._headerTableHeaders[columnId];} -_mouseDownInDataTable(event){var target=(event.target);var gridNode=this.dataGridNodeFromNode(target);if(!gridNode||!gridNode.selectable||gridNode.isEventWithinDisclosureTriangle(event)) -return;var columnId=this.columnIdFromNode(target);if(columnId&&this._columns[columnId].nonSelectable) -return;if(event.metaKey){if(gridNode.selected) -gridNode.deselect();else -gridNode.select();}else{gridNode.select();this.dispatchEventToListeners(DataGrid.DataGrid.Events.OpenedNode,gridNode);}} -setHeaderContextMenuCallback(callback){this._headerContextMenuCallback=callback;} -setRowContextMenuCallback(callback){this._rowContextMenuCallback=callback;} -_contextMenu(event){var contextMenu=new UI.ContextMenu(event);var target=(event.target);if(target.isSelfOrDescendant(this._headerTableBody)){if(this._headerContextMenuCallback) -this._headerContextMenuCallback(contextMenu);return;} -var gridNode=this.dataGridNodeFromNode(target);if(this._refreshCallback&&(!gridNode||gridNode!==this.creationNode)) -contextMenu.defaultSection().appendItem(Common.UIString('Refresh'),this._refreshCallback.bind(this));if(gridNode&&gridNode.selectable&&!gridNode.isEventWithinDisclosureTriangle(event)){if(this._editCallback){if(gridNode===this.creationNode){contextMenu.defaultSection().appendItem(Common.UIString('Add new'),this._startEditing.bind(this,target));}else{var columnId=this.columnIdFromNode(target);if(columnId&&this._columns[columnId].editable){contextMenu.defaultSection().appendItem(Common.UIString('Edit "%s"',this._columns[columnId].title),this._startEditing.bind(this,target));}}} -if(this._deleteCallback&&gridNode!==this.creationNode) -contextMenu.defaultSection().appendItem(Common.UIString('Delete'),this._deleteCallback.bind(this,gridNode));if(this._rowContextMenuCallback) -this._rowContextMenuCallback(contextMenu,gridNode);} -contextMenu.show();} -_clickInDataTable(event){var gridNode=this.dataGridNodeFromNode((event.target));if(!gridNode||!gridNode.hasChildren()||!gridNode.isEventWithinDisclosureTriangle(event)) -return;if(gridNode.expanded){if(event.altKey) -gridNode.collapseRecursively();else -gridNode.collapse();}else{if(event.altKey) -gridNode.expandRecursively();else -gridNode.expand();}} -setResizeMethod(method){this._resizeMethod=method;} -_startResizerDragging(event){this._currentResizer=event.target;return true;} -_endResizerDragging(){this._currentResizer=null;this._saveColumnWeights();} -_resizerDragging(event){var resizer=this._currentResizer;if(!resizer) -return;var dragPoint=event.clientX-this.element.totalOffsetLeft();var firstRowCells=this._headerTableBody.rows[0].cells;var leftEdgeOfPreviousColumn=0;var leftCellIndex=resizer.__index;var rightCellIndex=leftCellIndex+1;for(var i=0;i<leftCellIndex;i++) -leftEdgeOfPreviousColumn+=firstRowCells[i].offsetWidth;if(this._resizeMethod===DataGrid.DataGrid.ResizeMethod.Last){rightCellIndex=this._resizers.length;}else if(this._resizeMethod===DataGrid.DataGrid.ResizeMethod.First){leftEdgeOfPreviousColumn+=firstRowCells[leftCellIndex].offsetWidth-firstRowCells[0].offsetWidth;leftCellIndex=0;} -var rightEdgeOfNextColumn=leftEdgeOfPreviousColumn+firstRowCells[leftCellIndex].offsetWidth+firstRowCells[rightCellIndex].offsetWidth;var leftMinimum=leftEdgeOfPreviousColumn+DataGrid.DataGrid.ColumnResizePadding;var rightMaximum=rightEdgeOfNextColumn-DataGrid.DataGrid.ColumnResizePadding;if(leftMinimum>rightMaximum) -return;dragPoint=Number.constrain(dragPoint,leftMinimum,rightMaximum);var position=(dragPoint-DataGrid.DataGrid.CenterResizerOverBorderAdjustment);resizer.__position=position;resizer.style.left=position+'px';this._setPreferredWidth(leftCellIndex,dragPoint-leftEdgeOfPreviousColumn);this._setPreferredWidth(rightCellIndex,rightEdgeOfNextColumn-dragPoint);var leftColumn=this._visibleColumnsArray[leftCellIndex];var rightColumn=this._visibleColumnsArray[rightCellIndex];if(leftColumn.weight||rightColumn.weight){var sumOfWeights=leftColumn.weight+rightColumn.weight;var delta=rightEdgeOfNextColumn-leftEdgeOfPreviousColumn;leftColumn.weight=(dragPoint-leftEdgeOfPreviousColumn)*sumOfWeights/delta;rightColumn.weight=(rightEdgeOfNextColumn-dragPoint)*sumOfWeights/delta;} -this._positionResizers();event.preventDefault();} -_setPreferredWidth(columnIndex,width){var pxWidth=width+'px';this._headerTableColumnGroup.children[columnIndex][DataGrid.DataGrid._preferredWidthSymbol]=width;this._headerTableColumnGroup.children[columnIndex].style.width=pxWidth;this._dataTableColumnGroup.children[columnIndex].style.width=pxWidth;} -columnOffset(columnId){if(!this.element.offsetWidth) -return 0;for(var i=1;i<this._visibleColumnsArray.length;++i){if(columnId===this._visibleColumnsArray[i].id){if(this._resizers[i-1]) -return this._resizers[i-1].__position;}} -return 0;} -asWidget(){if(!this._dataGridWidget) -this._dataGridWidget=new DataGrid.DataGridWidget(this);return this._dataGridWidget;} -topFillerRowElement(){return this._topFillerRow;}};DataGrid.DataGrid.CornerWidth=14;DataGrid.DataGrid.ColumnDescriptor;DataGrid.DataGrid.Events={SelectedNode:Symbol('SelectedNode'),DeselectedNode:Symbol('DeselectedNode'),OpenedNode:Symbol('OpenedNode'),SortingChanged:Symbol('SortingChanged'),PaddingChanged:Symbol('PaddingChanged'),};DataGrid.DataGrid.Order={Ascending:'sort-ascending',Descending:'sort-descending'};DataGrid.DataGrid.Align={Center:'center',Right:'right'};DataGrid.DataGrid._preferredWidthSymbol=Symbol('preferredWidth');DataGrid.DataGrid._columnIdSymbol=Symbol('columnId');DataGrid.DataGrid._sortIconSymbol=Symbol('sortIcon');DataGrid.DataGrid._longTextSymbol=Symbol('longText');DataGrid.DataGrid.ColumnResizePadding=24;DataGrid.DataGrid.CenterResizerOverBorderAdjustment=3;DataGrid.DataGrid.ResizeMethod={Nearest:'nearest',First:'first',Last:'last'};DataGrid.DataGridNode=class extends Common.Object{constructor(data,hasChildren){super();this._element=null;this._expanded=false;this._selected=false;this._dirty=false;this._inactive=false;this._depth;this._revealed;this._attached=false;this._savedPosition=null;this._shouldRefreshChildren=true;this._data=data||{};this._hasChildren=hasChildren||false;this.children=[];this.dataGrid=null;this.parent=null;this.previousSibling=null;this.nextSibling=null;this.disclosureToggleWidth=10;this.selectable=true;this._isRoot=false;} -element(){if(!this._element){var element=this.createElement();this.createCells(element);} -return(this._element);} -createElement(){this._element=createElementWithClass('tr','data-grid-data-grid-node');this._element._dataGridNode=this;if(this._hasChildren) -this._element.classList.add('parent');if(this.expanded) -this._element.classList.add('expanded');if(this.selected) -this._element.classList.add('selected');if(this.revealed) -this._element.classList.add('revealed');if(this.dirty) -this._element.classList.add('dirty');if(this.inactive) -this._element.classList.add('inactive');return this._element;} -existingElement(){return this._element||null;} -resetElement(){this._element=null;} -createCells(element){element.removeChildren();var columnsArray=this.dataGrid._visibleColumnsArray;for(var i=0;i<columnsArray.length;++i) -element.appendChild(this.createCell(columnsArray[i].id));element.appendChild(this._createTDWithClass('corner'));} -get data(){return this._data;} -set data(x){this._data=x||{};this.refresh();} -get revealed(){if(this._revealed!==undefined) -return this._revealed;var currentAncestor=this.parent;while(currentAncestor&&!currentAncestor._isRoot){if(!currentAncestor.expanded){this._revealed=false;return false;} -currentAncestor=currentAncestor.parent;} -this.revealed=true;return true;} -set revealed(x){if(this._revealed===x) -return;this._revealed=x;if(this._element) -this._element.classList.toggle('revealed',this._revealed);for(var i=0;i<this.children.length;++i) -this.children[i].revealed=x&&this.expanded;} -isDirty(){return this._dirty;} -setDirty(dirty){if(this._dirty===dirty) -return;this._dirty=dirty;if(!this._element) -return;if(dirty) -this._element.classList.add('dirty');else -this._element.classList.remove('dirty');} -isInactive(){return this._inactive;} -setInactive(inactive){if(this._inactive===inactive) -return;this._inactive=inactive;if(!this._element) -return;if(inactive) -this._element.classList.add('inactive');else -this._element.classList.remove('inactive');} -hasChildren(){return this._hasChildren;} -setHasChildren(x){if(this._hasChildren===x) -return;this._hasChildren=x;if(!this._element) -return;this._element.classList.toggle('parent',this._hasChildren);this._element.classList.toggle('expanded',this._hasChildren&&this.expanded);} -get depth(){if(this._depth!==undefined) -return this._depth;if(this.parent&&!this.parent._isRoot) -this._depth=this.parent.depth+1;else -this._depth=0;return this._depth;} -get leftPadding(){return this.depth*this.dataGrid.indentWidth;} -get shouldRefreshChildren(){return this._shouldRefreshChildren;} -set shouldRefreshChildren(x){this._shouldRefreshChildren=x;if(x&&this.expanded) -this.expand();} -get selected(){return this._selected;} -set selected(x){if(x) -this.select();else -this.deselect();} -get expanded(){return this._expanded;} -set expanded(x){if(x) -this.expand();else -this.collapse();} -refresh(){if(!this.dataGrid) -this._element=null;if(!this._element) -return;this.createCells(this._element);} -_createTDWithClass(className){var cell=createElementWithClass('td',className);var cellClass=this.dataGrid._cellClass;if(cellClass) -cell.classList.add(cellClass);return cell;} -createTD(columnId){var cell=this._createTDWithClass(columnId+'-column');cell[DataGrid.DataGrid._columnIdSymbol]=columnId;var alignment=this.dataGrid._columns[columnId].align;if(alignment) -cell.classList.add(alignment);if(columnId===this.dataGrid.disclosureColumnId){cell.classList.add('disclosure');if(this.leftPadding) -cell.style.setProperty('padding-left',this.leftPadding+'px');} -return cell;} -createCell(columnId){var cell=this.createTD(columnId);var data=this.data[columnId];if(data instanceof Node) -cell.appendChild(data);else if(data!==null) -DataGrid.DataGrid.setElementText(cell,(data),!!this.dataGrid._columns[columnId].longText);return cell;} -nodeSelfHeight(){return 20;} -appendChild(child){this.insertChild(child,this.children.length);} -resetNode(onlyCaches){delete this._depth;delete this._revealed;if(onlyCaches) -return;if(this.previousSibling) -this.previousSibling.nextSibling=this.nextSibling;if(this.nextSibling) -this.nextSibling.previousSibling=this.previousSibling;this.dataGrid=null;this.parent=null;this.nextSibling=null;this.previousSibling=null;this._attached=false;} -insertChild(child,index){if(!child) -throw'insertChild: Node can\'t be undefined or null.';if(child.parent===this){var currentIndex=this.children.indexOf(child);if(currentIndex<0) -console.assert(false,'Inconsistent DataGrid state');if(currentIndex===index) -return;if(currentIndex<index) ---index;} -child.remove();this.children.splice(index,0,child);this.setHasChildren(true);child.parent=this;child.dataGrid=this.dataGrid;child.recalculateSiblings(index);child._shouldRefreshChildren=true;var current=child.children[0];while(current){current.resetNode(true);current.dataGrid=this.dataGrid;current._attached=false;current._shouldRefreshChildren=true;current=current.traverseNextNode(false,child,true);} -if(this.expanded) -child._attach();if(!this.revealed) -child.revealed=false;} -remove(){if(this.parent) -this.parent.removeChild(this);} -removeChild(child){if(!child) -throw'removeChild: Node can\'t be undefined or null.';if(child.parent!==this) -throw'removeChild: Node is not a child of this node.';if(this.dataGrid) -this.dataGrid.updateSelectionBeforeRemoval(child,false);child._detach();child.resetNode();this.children.remove(child,true);if(this.children.length<=0) -this.setHasChildren(false);} -removeChildren(){if(this.dataGrid) -this.dataGrid.updateSelectionBeforeRemoval(this,true);for(var i=0;i<this.children.length;++i){var child=this.children[i];child._detach();child.resetNode();} -this.children=[];this.setHasChildren(false);} -recalculateSiblings(myIndex){if(!this.parent) -return;var previousChild=this.parent.children[myIndex-1]||null;if(previousChild) -previousChild.nextSibling=this;this.previousSibling=previousChild;var nextChild=this.parent.children[myIndex+1]||null;if(nextChild) -nextChild.previousSibling=this;this.nextSibling=nextChild;} -collapse(){if(this._isRoot) -return;if(this._element) -this._element.classList.remove('expanded');this._expanded=false;for(var i=0;i<this.children.length;++i) -this.children[i].revealed=false;} -collapseRecursively(){var item=this;while(item){if(item.expanded) -item.collapse();item=item.traverseNextNode(false,this,true);}} -populate(){} -expand(){if(!this._hasChildren||this.expanded) -return;if(this._isRoot) -return;if(this.revealed&&!this._shouldRefreshChildren){for(var i=0;i<this.children.length;++i) -this.children[i].revealed=true;} -if(this._shouldRefreshChildren){for(var i=0;i<this.children.length;++i) -this.children[i]._detach();this.populate();if(this._attached){for(var i=0;i<this.children.length;++i){var child=this.children[i];if(this.revealed) -child.revealed=true;child._attach();}} -this._shouldRefreshChildren=false;} -if(this._element) -this._element.classList.add('expanded');this._expanded=true;} -expandRecursively(){var item=this;while(item){item.expand();item=item.traverseNextNode(false,this);}} -reveal(){if(this._isRoot) -return;var currentAncestor=this.parent;while(currentAncestor&&!currentAncestor._isRoot){if(!currentAncestor.expanded) -currentAncestor.expand();currentAncestor=currentAncestor.parent;} -this.element().scrollIntoViewIfNeeded(false);} -select(supressSelectedEvent){if(!this.dataGrid||!this.selectable||this.selected) -return;if(this.dataGrid.selectedNode) -this.dataGrid.selectedNode.deselect();this._selected=true;this.dataGrid.selectedNode=this;if(this._element) -this._element.classList.add('selected');if(!supressSelectedEvent) -this.dataGrid.dispatchEventToListeners(DataGrid.DataGrid.Events.SelectedNode,this);} -revealAndSelect(){if(this._isRoot) -return;this.reveal();this.select();} -deselect(supressDeselectedEvent){if(!this.dataGrid||this.dataGrid.selectedNode!==this||!this.selected) -return;this._selected=false;this.dataGrid.selectedNode=null;if(this._element) -this._element.classList.remove('selected');if(!supressDeselectedEvent) -this.dataGrid.dispatchEventToListeners(DataGrid.DataGrid.Events.DeselectedNode);} -traverseNextNode(skipHidden,stayWithin,dontPopulate,info){if(!dontPopulate&&this._hasChildren) -this.populate();if(info) -info.depthChange=0;var node=(!skipHidden||this.revealed)?this.children[0]:null;if(node&&(!skipHidden||this.expanded)){if(info) -info.depthChange=1;return node;} -if(this===stayWithin) -return null;node=(!skipHidden||this.revealed)?this.nextSibling:null;if(node) -return node;node=this;while(node&&!node._isRoot&&!((!skipHidden||node.revealed)?node.nextSibling:null)&&node.parent!==stayWithin){if(info) -info.depthChange-=1;node=node.parent;} -if(!node) -return null;return(!skipHidden||node.revealed)?node.nextSibling:null;} -traversePreviousNode(skipHidden,dontPopulate){var node=(!skipHidden||this.revealed)?this.previousSibling:null;if(!dontPopulate&&node&&node._hasChildren) -node.populate();while(node&&((!skipHidden||(node.revealed&&node.expanded))?node.children[node.children.length-1]:null)){if(!dontPopulate&&node._hasChildren) -node.populate();node=((!skipHidden||(node.revealed&&node.expanded))?node.children[node.children.length-1]:null);} -if(node) -return node;if(!this.parent||this.parent._isRoot) -return null;return this.parent;} -isEventWithinDisclosureTriangle(event){if(!this._hasChildren) -return false;var cell=event.target.enclosingNodeOrSelfWithNodeName('td');if(!cell||!cell.classList.contains('disclosure')) -return false;var left=cell.totalOffsetLeft()+this.leftPadding;return event.pageX>=left&&event.pageX<=left+this.disclosureToggleWidth;} -_attach(){if(!this.dataGrid||this._attached) -return;this._attached=true;var previousNode=this.traversePreviousNode(true,true);var previousElement=previousNode?previousNode.element():this.dataGrid._topFillerRow;this.dataGrid.dataTableBody.insertBefore(this.element(),previousElement.nextSibling);if(this.expanded){for(var i=0;i<this.children.length;++i) -this.children[i]._attach();}} -_detach(){if(!this._attached) -return;this._attached=false;if(this._element) -this._element.remove();for(var i=0;i<this.children.length;++i) -this.children[i]._detach();} -savePosition(){if(this._savedPosition) -return;if(!this.parent) -throw'savePosition: Node must have a parent.';this._savedPosition={parent:this.parent,index:this.parent.children.indexOf(this)};} -restorePosition(){if(!this._savedPosition) -return;if(this.parent!==this._savedPosition.parent) -this._savedPosition.parent.insertChild(this,this._savedPosition.index);this._savedPosition=null;}};DataGrid.CreationDataGridNode=class extends DataGrid.DataGridNode{constructor(data,hasChildren){super(data,hasChildren);this.isCreationNode=true;} -makeNormal(){this.isCreationNode=false;}};DataGrid.DataGridWidget=class extends UI.VBox{constructor(dataGrid){super();this._dataGrid=dataGrid;this.element.appendChild(dataGrid.element);} -wasShown(){this._dataGrid.wasShown();} -willHide(){this._dataGrid.willHide();} -onResize(){this._dataGrid.onResize();} -elementsToRestoreScrollPositionsFor(){return[this._dataGrid._scrollContainer];} -detachChildWidgets(){super.detachChildWidgets();for(var dataGrid of this._dataGrids) -this.element.removeChild(dataGrid.element);this._dataGrids=[];}};;DataGrid.ViewportDataGrid=class extends DataGrid.DataGrid{constructor(columnsArray,editCallback,deleteCallback,refreshCallback){super(columnsArray,editCallback,deleteCallback,refreshCallback);this._onScrollBound=this._onScroll.bind(this);this._scrollContainer.addEventListener('scroll',this._onScrollBound,true);this._visibleNodes=[];this._inline=false;this._stickToBottom=false;this._updateIsFromUser=false;this._lastScrollTop=0;this._firstVisibleIsStriped=false;this._isStriped=false;this.setRootNode(new DataGrid.ViewportDataGridNode());} -setStriped(striped){this._isStriped=striped;var startsWithOdd=true;if(this._visibleNodes.length){var allChildren=this.rootNode().flatChildren();startsWithOdd=!!(allChildren.indexOf(this._visibleNodes[0]));} -this._updateStripesClass(startsWithOdd);} -_updateStripesClass(startsWithOdd){this.element.classList.toggle('striped-data-grid',!startsWithOdd&&this._isStriped);this.element.classList.toggle('striped-data-grid-starts-with-odd',startsWithOdd&&this._isStriped);} -setScrollContainer(scrollContainer){this._scrollContainer.removeEventListener('scroll',this._onScrollBound,true);this._scrollContainer=scrollContainer;this._scrollContainer.addEventListener('scroll',this._onScrollBound,true);} -onResize(){if(this._stickToBottom) -this._scrollContainer.scrollTop=this._scrollContainer.scrollHeight-this._scrollContainer.clientHeight;this.scheduleUpdate();super.onResize();} -setStickToBottom(stick){this._stickToBottom=stick;} -_onScroll(event){this._stickToBottom=this._scrollContainer.isScrolledToBottom();if(this._lastScrollTop!==this._scrollContainer.scrollTop) -this.scheduleUpdate(true);} -scheduleUpdateStructure(){this.scheduleUpdate();} -scheduleUpdate(isFromUser){if(this._stickToBottom&&isFromUser) -this._stickToBottom=this._scrollContainer.isScrolledToBottom();this._updateIsFromUser=this._updateIsFromUser||isFromUser;if(this._updateAnimationFrameId) -return;this._updateAnimationFrameId=this.element.window().requestAnimationFrame(this._update.bind(this));} -updateInstantly(){this._update();} -renderInline(){this._inline=true;super.renderInline();this._update();} -_calculateVisibleNodes(clientHeight,scrollTop){var nodes=this.rootNode().flatChildren();if(this._inline) -return{topPadding:0,bottomPadding:0,contentHeight:0,visibleNodes:nodes,offset:0};var size=nodes.length;var i=0;var y=0;for(;i<size&&y+nodes[i].nodeSelfHeight()<scrollTop;++i) -y+=nodes[i].nodeSelfHeight();var start=i;var topPadding=y;for(;i<size&&y<scrollTop+clientHeight;++i) -y+=nodes[i].nodeSelfHeight();var end=i;var bottomPadding=0;for(;i<size;++i) -bottomPadding+=nodes[i].nodeSelfHeight();return{topPadding:topPadding,bottomPadding:bottomPadding,contentHeight:y-topPadding,visibleNodes:nodes.slice(start,end),offset:start};} -_contentHeight(){var nodes=this.rootNode().flatChildren();var result=0;for(var i=0,size=nodes.length;i<size;++i) -result+=nodes[i].nodeSelfHeight();return result;} -_update(){if(this._updateAnimationFrameId){this.element.window().cancelAnimationFrame(this._updateAnimationFrameId);delete this._updateAnimationFrameId;} -var clientHeight=this._scrollContainer.clientHeight;var scrollTop=this._scrollContainer.scrollTop;var currentScrollTop=scrollTop;var maxScrollTop=Math.max(0,this._contentHeight()-clientHeight);if(!this._updateIsFromUser&&this._stickToBottom) -scrollTop=maxScrollTop;this._updateIsFromUser=false;scrollTop=Math.min(maxScrollTop,scrollTop);var viewportState=this._calculateVisibleNodes(clientHeight,scrollTop);var visibleNodes=viewportState.visibleNodes;var visibleNodesSet=new Set(visibleNodes);for(var i=0;i<this._visibleNodes.length;++i){var oldNode=this._visibleNodes[i];if(!visibleNodesSet.has(oldNode)&&oldNode.attached()){var element=oldNode.existingElement();element.remove();}} -var previousElement=this.topFillerRowElement();var tBody=this.dataTableBody;var offset=viewportState.offset;if(visibleNodes.length){var nodes=this.rootNode().flatChildren();var index=nodes.indexOf(visibleNodes[0]);this._updateStripesClass(!!(index%2));if(index!==-1&&!!(index%2)!==this._firstVisibleIsStriped) -offset+=1;} -this._firstVisibleIsStriped=!!(offset%2);for(var i=0;i<visibleNodes.length;++i){var node=visibleNodes[i];var element=node.element();node.setStriped((offset+i)%2===0);if(element!==previousElement.nextSibling) -tBody.insertBefore(element,previousElement.nextSibling);node.revealed=true;previousElement=element;} -this.setVerticalPadding(viewportState.topPadding,viewportState.bottomPadding);this._lastScrollTop=scrollTop;if(scrollTop!==currentScrollTop) -this._scrollContainer.scrollTop=scrollTop;var contentFits=viewportState.contentHeight<=clientHeight&&viewportState.topPadding+viewportState.bottomPadding===0;if(contentFits!==this.element.classList.contains('data-grid-fits-viewport')){this.element.classList.toggle('data-grid-fits-viewport',contentFits);this.updateWidths();} -this._visibleNodes=visibleNodes;this.dispatchEventToListeners(DataGrid.ViewportDataGrid.Events.ViewportCalculated);} -_revealViewportNode(node){var nodes=this.rootNode().flatChildren();var index=nodes.indexOf(node);if(index===-1) -return;var fromY=0;for(var i=0;i<index;++i) -fromY+=nodes[i].nodeSelfHeight();var toY=fromY+node.nodeSelfHeight();var scrollTop=this._scrollContainer.scrollTop;if(scrollTop>fromY){scrollTop=fromY;this._stickToBottom=false;}else if(scrollTop+this._scrollContainer.offsetHeight<toY){scrollTop=toY-this._scrollContainer.offsetHeight;} -this._scrollContainer.scrollTop=scrollTop;}};DataGrid.ViewportDataGrid.Events={ViewportCalculated:Symbol('ViewportCalculated')};DataGrid.ViewportDataGridNode=class extends DataGrid.DataGridNode{constructor(data,hasChildren){super(data,hasChildren);this._stale=false;this._flatNodes=null;this._isStriped=false;} -element(){var existingElement=this.existingElement();var element=existingElement||this.createElement();if(!existingElement||this._stale){this.createCells(element);this._stale=false;} -return element;} -setStriped(isStriped){this._isStriped=isStriped;this.element().classList.toggle('odd',isStriped);} -isStriped(){return this._isStriped;} -clearFlatNodes(){this._flatNodes=null;var parent=(this.parent);if(parent) -parent.clearFlatNodes();} -flatChildren(){if(this._flatNodes) -return this._flatNodes;var flatNodes=[];var children=[this.children];var counters=[0];var depth=0;while(depth>=0){if(children[depth].length<=counters[depth]){depth--;continue;} -var node=children[depth][counters[depth]++];flatNodes.push(node);if(node._expanded&&node.children.length){depth++;children[depth]=node.children;counters[depth]=0;}} -this._flatNodes=flatNodes;return flatNodes;} -insertChild(child,index){this.clearFlatNodes();if(child.parent===this){var currentIndex=this.children.indexOf(child);if(currentIndex<0) -console.assert(false,'Inconsistent DataGrid state');if(currentIndex===index) -return;if(currentIndex<index) ---index;} -child.remove();child.parent=this;child.dataGrid=this.dataGrid;if(!this.children.length) -this.setHasChildren(true);this.children.splice(index,0,child);child.recalculateSiblings(index);if(this._expanded) -this.dataGrid.scheduleUpdateStructure();} -removeChild(child){this.clearFlatNodes();if(this.dataGrid) -this.dataGrid.updateSelectionBeforeRemoval(child,false);if(child.previousSibling) -child.previousSibling.nextSibling=child.nextSibling;if(child.nextSibling) -child.nextSibling.previousSibling=child.previousSibling;if(child.parent!==this) -throw'removeChild: Node is not a child of this node.';this.children.remove(child,true);child._unlink();if(!this.children.length) -this.setHasChildren(false);if(this._expanded) -this.dataGrid.scheduleUpdateStructure();} -removeChildren(){this.clearFlatNodes();if(this.dataGrid) -this.dataGrid.updateSelectionBeforeRemoval(this,true);for(var i=0;i<this.children.length;++i) -this.children[i]._unlink();this.children=[];if(this._expanded) -this.dataGrid.scheduleUpdateStructure();} -_unlink(){if(this.attached()) -this.existingElement().remove();this.resetNode();} -collapse(){if(!this._expanded) -return;this.clearFlatNodes();this._expanded=false;if(this.existingElement()) -this.existingElement().classList.remove('expanded');this.dataGrid.scheduleUpdateStructure();} -expand(){if(this._expanded) -return;this.dataGrid._stickToBottom=false;this.clearFlatNodes();super.expand();this.dataGrid.scheduleUpdateStructure();} -attached(){return!!(this.dataGrid&&this.existingElement()&&this.existingElement().parentElement);} -refresh(){if(this.attached()){this._stale=true;this.dataGrid.scheduleUpdate();}else{this.resetElement();}} -reveal(){this.dataGrid._revealViewportNode(this);} -recalculateSiblings(index){this.clearFlatNodes();super.recalculateSiblings(index);}};;DataGrid.SortableDataGrid=class extends DataGrid.ViewportDataGrid{constructor(columnsArray,editCallback,deleteCallback,refreshCallback){super(columnsArray,editCallback,deleteCallback,refreshCallback);this._sortingFunction=DataGrid.SortableDataGrid.TrivialComparator;this.setRootNode((new DataGrid.SortableDataGridNode()));} -static TrivialComparator(a,b){return 0;} -static NumericComparator(columnId,a,b){var aValue=a.data[columnId];var bValue=b.data[columnId];var aNumber=Number(aValue instanceof Node?aValue.textContent:aValue);var bNumber=Number(bValue instanceof Node?bValue.textContent:bValue);return aNumber<bNumber?-1:(aNumber>bNumber?1:0);} -static StringComparator(columnId,a,b){var aValue=a.data[columnId];var bValue=b.data[columnId];var aString=aValue instanceof Node?aValue.textContent:String(aValue);var bString=bValue instanceof Node?bValue.textContent:String(bValue);return aString<bString?-1:(aString>bString?1:0);} -static Comparator(comparator,reverseMode,a,b){return reverseMode?comparator(b,a):comparator(a,b);} -static create(columnNames,values){var numColumns=columnNames.length;if(!numColumns) -return null;var columns=([]);for(var i=0;i<columnNames.length;++i) -columns.push({id:String(i),title:columnNames[i],width:columnNames[i].length,sortable:true});var nodes=[];for(var i=0;i<values.length/numColumns;++i){var data={};for(var j=0;j<columnNames.length;++j) -data[j]=values[numColumns*i+j];var node=new DataGrid.SortableDataGridNode(data);node.selectable=false;nodes.push(node);} -var dataGrid=new DataGrid.SortableDataGrid(columns);var length=nodes.length;var rootNode=dataGrid.rootNode();for(var i=0;i<length;++i) -rootNode.appendChild(nodes[i]);dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,sortDataGrid);function sortDataGrid(){var nodes=dataGrid.rootNode().children;var sortColumnId=dataGrid.sortColumnId();if(!sortColumnId) -return;var columnIsNumeric=true;for(var i=0;i<nodes.length;i++){var value=nodes[i].data[sortColumnId];if(isNaN(value instanceof Node?value.textContent:value)){columnIsNumeric=false;break;}} -var comparator=columnIsNumeric?DataGrid.SortableDataGrid.NumericComparator:DataGrid.SortableDataGrid.StringComparator;dataGrid.sortNodes(comparator.bind(null,sortColumnId),!dataGrid.isSortOrderAscending());} -return dataGrid;} -insertChild(node){var root=(this.rootNode());root.insertChildOrdered(node);} -sortNodes(comparator,reverseMode){this._sortingFunction=DataGrid.SortableDataGrid.Comparator.bind(null,comparator,reverseMode);this.rootNode().recalculateSiblings(0);this.rootNode()._sortChildren(reverseMode);this.scheduleUpdateStructure();}};DataGrid.SortableDataGridNode=class extends DataGrid.ViewportDataGridNode{constructor(data,hasChildren){super(data,hasChildren);} -insertChildOrdered(node){this.insertChild(node,this.children.upperBound(node,this.dataGrid._sortingFunction));} -_sortChildren(){this.children.sort(this.dataGrid._sortingFunction);for(var i=0;i<this.children.length;++i) -this.children[i].recalculateSiblings(i);for(var child of this.children) -child._sortChildren();}};;DataGrid.ShowMoreDataGridNode=class extends DataGrid.DataGridNode{constructor(callback,startPosition,endPosition,chunkSize){super({summaryRow:true},false);this._callback=callback;this._startPosition=startPosition;this._endPosition=endPosition;this._chunkSize=chunkSize;this.showNext=createElement('button');this.showNext.setAttribute('type','button');this.showNext.addEventListener('click',this._showNextChunk.bind(this),false);this.showNext.textContent=Common.UIString('Show %d before',this._chunkSize);this.showAll=createElement('button');this.showAll.setAttribute('type','button');this.showAll.addEventListener('click',this._showAll.bind(this),false);this.showLast=createElement('button');this.showLast.setAttribute('type','button');this.showLast.addEventListener('click',this._showLastChunk.bind(this),false);this.showLast.textContent=Common.UIString('Show %d after',this._chunkSize);this._updateLabels();this.selectable=false;} -_showNextChunk(){this._callback(this._startPosition,this._startPosition+this._chunkSize);} -_showAll(){this._callback(this._startPosition,this._endPosition);} -_showLastChunk(){this._callback(this._endPosition-this._chunkSize,this._endPosition);} -_updateLabels(){var totalSize=this._endPosition-this._startPosition;if(totalSize>this._chunkSize){this.showNext.classList.remove('hidden');this.showLast.classList.remove('hidden');}else{this.showNext.classList.add('hidden');this.showLast.classList.add('hidden');} -this.showAll.textContent=Common.UIString('Show all %d',totalSize);} -createCells(element){this._hasCells=false;super.createCells(element);} -createCell(columnIdentifier){var cell=this.createTD(columnIdentifier);if(!this._hasCells){this._hasCells=true;if(this.depth) -cell.style.setProperty('padding-left',(this.depth*this.dataGrid.indentWidth)+'px');cell.appendChild(this.showNext);cell.appendChild(this.showAll);cell.appendChild(this.showLast);} -return cell;} -setStartPosition(from){this._startPosition=from;this._updateLabels();} -setEndPosition(to){this._endPosition=to;this._updateLabels();} -nodeSelfHeight(){return 40;} -dispose(){}};;Runtime.cachedResources["data_grid/dataGrid.css"]=".data-grid {\n position: relative;\n border: 1px solid #aaa;\n line-height: 120%;\n}\n\n.data-grid table {\n table-layout: fixed;\n border-spacing: 0;\n border-collapse: separate;\n height: 100%;\n width: 100%;\n}\n\n.data-grid .header-container,\n.data-grid .data-container {\n position: absolute;\n left: 0;\n right: 0;\n overflow-x: hidden;\n}\n\n.data-grid .header-container {\n top: 0;\n height: 21px;\n}\n\n.data-grid .data-container {\n top: 21px;\n bottom: 0;\n overflow-y: overlay;\n transform: translateZ(0);\n}\n\n.data-grid.inline .header-container,\n.data-grid.inline .data-container {\n position: static;\n}\n\n.data-grid.inline .corner {\n display: none;\n}\n\n.platform-mac .data-grid .corner,\n.data-grid.data-grid-fits-viewport .corner {\n display: none;\n}\n\n.data-grid .corner {\n width: 14px;\n padding-right: 0;\n padding-left: 0;\n border-left: 0 none transparent !important;\n}\n\n.data-grid .top-filler-td,\n.data-grid .bottom-filler-td {\n height: auto !important;\n padding: 0 !important;\n}\n\n.data-grid table.data {\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n border-top: 0 none transparent;\n table-layout: fixed;\n}\n\n.data-grid.inline table.data {\n position: static;\n}\n\n.data-grid table.data tr {\n display: none;\n}\n\n.data-grid table.data tr.revealed {\n display: table-row;\n}\n\n.striped-data-grid .revealed.data-grid-data-grid-node:nth-child(odd),\n.striped-data-grid-starts-with-odd .revealed.data-grid-data-grid-node:nth-child(even) {\n background-color: hsl(214, 70%, 97%);\n}\n\n.data-grid td,\n.data-grid th {\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n line-height: 18px;\n height: 18px;\n border-left: 1px solid #aaa;\n padding: 1px 4px;\n}\n\n.data-grid th:first-child,\n.data-grid td:first-child {\n border-left: none !important;\n}\n\n.data-grid td {\n vertical-align: top;\n -webkit-user-select: text;\n}\n\n.data-grid th {\n text-align: left;\n background-color: #f3f3f3;\n border-bottom: 1px solid #aaa;\n font-weight: normal;\n vertical-align: middle;\n}\n\n.data-grid td > div,\n.data-grid th > div {\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.data-grid td.editing > div {\n text-overflow: clip;\n}\n\n.data-grid .center {\n text-align: center;\n}\n\n.data-grid .right {\n text-align: right;\n}\n\n.data-grid th.sortable {\n position: relative;\n}\n\n.data-grid th.sortable:active::after {\n content: \"\";\n position: absolute;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.15);\n}\n\n.data-grid th .sort-order-icon-container {\n position: absolute;\n top: 1px;\n right: 0;\n bottom: 1px;\n display: flex;\n align-items: center;\n}\n\n.data-grid th .sort-order-icon {\n margin-right: 4px;\n margin-bottom: -2px;\n display: none;\n}\n\n.data-grid th.sort-ascending .sort-order-icon,\n.data-grid th.sort-descending .sort-order-icon {\n display: block;\n}\n\n.data-grid th.sortable:hover {\n background-color: hsla(0, 0%, 90%, 1);\n}\n\n.data-grid button {\n line-height: 18px;\n color: inherit;\n}\n\n.data-grid td.disclosure::before {\n -webkit-user-select: none;\n -webkit-mask-image: url(Images/treeoutlineTriangles.png);\n -webkit-mask-position: 0 0;\n -webkit-mask-size: 32px 24px;\n float: left;\n width: 8px;\n height: 12px;\n margin-right: 2px;\n content: \"\";\n position: relative;\n top: 3px;\n background-color: rgb(110, 110, 110);\n}\n\n.data-grid tr:not(.parent) td.disclosure::before {\n background-color: transparent;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\n.data-grid tr.parent td.disclosure::before {\n -webkit-mask-image: url(Images/treeoutlineTriangles_2x.png);\n}\n} /* media */\n\n.data-grid tr.expanded td.disclosure::before {\n -webkit-mask-position: -16px 0;\n}\n\n.data-grid table.data tr.revealed.selected {\n background-color: rgb(212, 212, 212);\n color: inherit;\n}\n\n.data-grid:focus table.data tr.selected {\n background-color: rgb(56, 121, 217);\n color: white;\n}\n\n.data-grid:focus tr.selected .devtools-link {\n color: white;\n}\n\n.data-grid:focus tr.parent.selected td.disclosure::before {\n background-color: white;\n -webkit-mask-position: 0 0;\n}\n\n.data-grid:focus tr.expanded.selected td.disclosure::before {\n background-color: white;\n -webkit-mask-position: -16px 0;\n}\n\n.data-grid tr.inactive {\n color: rgb(128, 128, 128);\n font-style: italic;\n}\n\n.data-grid tr.dirty {\n background-color: hsl(0, 100%, 92%);\n color: red;\n font-style: normal;\n}\n\n.data-grid:focus tr.selected.dirty {\n background-color: hsl(0, 100%, 70%);\n}\n\n.data-grid-resizer {\n position: absolute;\n top: 0;\n bottom: 0;\n width: 5px;\n z-index: 500;\n}\n\n/*# sourceURL=data_grid/dataGrid.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/devices/devices_module.js b/src/cobalt/debug/content/devtools/devices/devices_module.js deleted file mode 100644 index da33090..0000000 --- a/src/cobalt/debug/content/devtools/devices/devices_module.js +++ /dev/null
@@ -1,96 +0,0 @@ -Devices.DevicesView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('devices/devicesView.css');this.contentElement.classList.add('devices-view');var hbox=this.contentElement.createChild('div','hbox devices-container');var sidebar=hbox.createChild('div','devices-sidebar');sidebar.createChild('div','devices-view-title').createTextChild(Common.UIString('Devices'));this._sidebarList=sidebar.createChild('div','devices-sidebar-list');this._discoveryView=new Devices.DevicesView.DiscoveryView();this._sidebarListSpacer=this._sidebarList.createChild('div','devices-sidebar-spacer');this._discoveryListItem=this._sidebarList.createChild('div','devices-sidebar-item');this._discoveryListItem.textContent=Common.UIString('Settings');this._discoveryListItem.addEventListener('click',this._selectSidebarListItem.bind(this,this._discoveryListItem,this._discoveryView));this._viewById=new Map();this._devices=[];this._listItemById=new Map();this._selectedListItem=null;this._visibleView=null;this._viewContainer=hbox.createChild('div','flex-auto vbox');var discoveryFooter=this.contentElement.createChild('div','devices-footer');this._deviceCountSpan=discoveryFooter.createChild('span');discoveryFooter.createChild('span').textContent=Common.UIString(' Read ');discoveryFooter.appendChild(UI.createExternalLink('https://developers.google.com/chrome-developer-tools/docs/remote-debugging',Common.UIString('remote debugging documentation')));discoveryFooter.createChild('span').textContent=Common.UIString(' for more information.');this._updateFooter();this._selectSidebarListItem(this._discoveryListItem,this._discoveryView);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DevicesUpdated,this._devicesUpdated,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged,this._devicesDiscoveryConfigChanged,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DevicesPortForwardingStatusChanged,this._devicesPortForwardingStatusChanged,this);this.contentElement.tabIndex=0;this.setDefaultFocusedElement(this.contentElement);} -static _instance(){if(!Devices.DevicesView._instanceObject) -Devices.DevicesView._instanceObject=new Devices.DevicesView();return Devices.DevicesView._instanceObject;} -_selectSidebarListItem(listItem,view){if(this._selectedListItem===listItem) -return;if(this._selectedListItem){this._selectedListItem.classList.remove('selected');this._visibleView.detach();} -this._visibleView=view;this._selectedListItem=listItem;this._visibleView.show(this._viewContainer);this._selectedListItem.classList.add('selected');} -_devicesUpdated(event){this._devices=(event.data).slice().filter(d=>d.adbSerial.toUpperCase()!=='WEBRTC'&&d.adbSerial.toUpperCase()!=='LOCALHOST');for(var device of this._devices){if(!device.adbConnected) -device.adbModel=Common.UIString('Unknown');} -var ids=new Set();for(var device of this._devices) -ids.add(device.id);var selectedRemoved=false;for(var deviceId of this._viewById.keys()){if(!ids.has(deviceId)){var listItem=(this._listItemById.get(deviceId));this._listItemById.remove(deviceId);this._viewById.remove(deviceId);listItem.remove();if(listItem===this._selectedListItem) -selectedRemoved=true;}} -for(var device of this._devices){var view=this._viewById.get(device.id);var listItem=this._listItemById.get(device.id);if(!view){view=new Devices.DevicesView.DeviceView();this._viewById.set(device.id,view);listItem=this._createSidebarListItem(view);this._listItemById.set(device.id,listItem);this._sidebarList.insertBefore(listItem,this._sidebarListSpacer);} -listItem._title.textContent=device.adbModel;listItem._status.textContent=device.adbConnected?Common.UIString('Connected'):Common.UIString('Pending Authorization');listItem.classList.toggle('device-connected',device.adbConnected);view.update(device);} -if(selectedRemoved) -this._selectSidebarListItem(this._discoveryListItem,this._discoveryView);this._updateFooter();} -_createSidebarListItem(view){var listItem=createElementWithClass('div','devices-sidebar-item');listItem.addEventListener('click',this._selectSidebarListItem.bind(this,listItem,view));listItem._title=listItem.createChild('div','devices-sidebar-item-title');listItem._status=listItem.createChild('div','devices-sidebar-item-status');return listItem;} -_devicesDiscoveryConfigChanged(event){var config=(event.data);this._discoveryView.discoveryConfigChanged(config);} -_devicesPortForwardingStatusChanged(event){var status=(event.data);for(var deviceId in status){var view=this._viewById.get(deviceId);if(view) -view.portForwardingStatusChanged(status[deviceId]);} -for(var deviceId of this._viewById.keys()){var view=this._viewById.get(deviceId);if(view&&!(deviceId in status)) -view.portForwardingStatusChanged({ports:{},browserId:''});}} -_updateFooter(){this._deviceCountSpan.textContent=!this._devices.length?Common.UIString('No devices detected.'):this._devices.length===1?Common.UIString('1 device detected.'):Common.UIString('%d devices detected.',this._devices.length);} -wasShown(){super.wasShown();if(Runtime.queryParam('nodeFrontend')) -InspectorFrontendHost.setDevicesUpdatesEnabled(false);InspectorFrontendHost.setDevicesUpdatesEnabled(true);} -willHide(){super.wasShown();if(!Runtime.queryParam('nodeFrontend')) -InspectorFrontendHost.setDevicesUpdatesEnabled(false);}};Devices.DevicesView.DiscoveryView=class extends UI.VBox{constructor(){super();this.setMinimumSize(100,100);this.element.classList.add('discovery-view');this.contentElement.createChild('div','hbox device-text-row').createChild('div','view-title').textContent=Common.UIString('Settings');var discoverUsbDevicesCheckbox=UI.CheckboxLabel.create(Common.UIString('Discover USB devices'));discoverUsbDevicesCheckbox.classList.add('usb-checkbox');this.element.appendChild(discoverUsbDevicesCheckbox);this._discoverUsbDevicesCheckbox=discoverUsbDevicesCheckbox.checkboxElement;this._discoverUsbDevicesCheckbox.addEventListener('click',()=>{this._config.discoverUsbDevices=this._discoverUsbDevicesCheckbox.checked;InspectorFrontendHost.setDevicesDiscoveryConfig(this._config);},false);var help=this.element.createChild('div','discovery-help');help.createChild('span').textContent=Common.UIString('Need help? Read Chrome ');help.appendChild(UI.createExternalLink('https://developers.google.com/chrome-developer-tools/docs/remote-debugging',Common.UIString('remote debugging documentation.')));this._config;this._portForwardingView=new Devices.DevicesView.PortForwardingView((enabled,config)=>{this._config.portForwardingEnabled=enabled;this._config.portForwardingConfig={};for(var rule of config) -this._config.portForwardingConfig[rule.port]=rule.address;InspectorFrontendHost.setDevicesDiscoveryConfig(this._config);});this._portForwardingView.show(this.element);this._networkDiscoveryView=new Devices.DevicesView.NetworkDiscoveryView(false,(enabled,config)=>{this._config.networkDiscoveryEnabled=enabled;this._config.networkDiscoveryConfig=config;InspectorFrontendHost.setDevicesDiscoveryConfig(this._config);});this._networkDiscoveryView.show(this.element);} -discoveryConfigChanged(config){this._config=config;this._discoverUsbDevicesCheckbox.checked=config.discoverUsbDevices;this._portForwardingView.discoveryConfigChanged(config.portForwardingEnabled,config.portForwardingConfig);this._networkDiscoveryView.discoveryConfigChanged(config.networkDiscoveryEnabled,config.networkDiscoveryConfig);}};Devices.DevicesView.PortForwardingView=class extends UI.VBox{constructor(callback){super();this._callback=callback;this.element.classList.add('port-forwarding-view');var portForwardingHeader=this.element.createChild('div','port-forwarding-header');var portForwardingEnabledCheckbox=UI.CheckboxLabel.create(Common.UIString('Port forwarding'));portForwardingEnabledCheckbox.classList.add('port-forwarding-checkbox');portForwardingHeader.appendChild(portForwardingEnabledCheckbox);this._portForwardingEnabledCheckbox=portForwardingEnabledCheckbox.checkboxElement;this._portForwardingEnabledCheckbox.addEventListener('click',this._update.bind(this),false);var portForwardingFooter=this.element.createChild('div','port-forwarding-footer');portForwardingFooter.createChild('span').textContent=Common.UIString('Define the listening port on your device that maps to a port accessible from your development machine. ');portForwardingFooter.appendChild(UI.createExternalLink('https://developer.chrome.com/devtools/docs/remote-debugging#port-forwarding',Common.UIString('Learn more')));this._list=new UI.ListWidget(this);this._list.registerRequiredCSS('devices/devicesView.css');this._list.element.classList.add('port-forwarding-list');var placeholder=createElementWithClass('div','port-forwarding-list-empty');placeholder.textContent=Common.UIString('No rules');this._list.setEmptyPlaceholder(placeholder);this._list.show(this.element);this._editor=null;this.element.appendChild(UI.createTextButton(Common.UIString('Add rule'),this._addRuleButtonClicked.bind(this),'add-rule-button'));this._portForwardingConfig=[];} -_update(){this._callback.call(null,this._portForwardingEnabledCheckbox.checked,this._portForwardingConfig);} -_addRuleButtonClicked(){this._list.addNewItem(this._portForwardingConfig.length,{port:'',address:''});} -discoveryConfigChanged(portForwardingEnabled,portForwardingConfig){this._portForwardingEnabledCheckbox.checked=portForwardingEnabled;this._portForwardingConfig=[];this._list.clear();for(var key of Object.keys(portForwardingConfig)){var rule=({port:key,address:portForwardingConfig[key]});this._portForwardingConfig.push(rule);this._list.appendItem(rule,true);}} -renderItem(rule,editable){var element=createElementWithClass('div','port-forwarding-list-item');var port=element.createChild('div','port-forwarding-value port-forwarding-port');port.createChild('span','port-localhost').textContent=Common.UIString('localhost:');port.createTextChild(rule.port);element.createChild('div','port-forwarding-separator');element.createChild('div','port-forwarding-value').textContent=rule.address;return element;} -removeItemRequested(rule,index){this._portForwardingConfig.splice(index,1);this._list.removeItem(index);this._update();} -commitEdit(rule,editor,isNew){rule.port=editor.control('port').value.trim();rule.address=editor.control('address').value.trim();if(isNew) -this._portForwardingConfig.push(rule);this._update();} -beginEdit(rule){var editor=this._createEditor();editor.control('port').value=rule.port;editor.control('address').value=rule.address;return editor;} -_createEditor(){if(this._editor) -return this._editor;var editor=new UI.ListWidget.Editor();this._editor=editor;var content=editor.contentElement();var fields=content.createChild('div','port-forwarding-edit-row');fields.createChild('div','port-forwarding-value port-forwarding-port').appendChild(editor.createInput('port','text','Device port (3333)',portValidator.bind(this)));fields.createChild('div','port-forwarding-separator port-forwarding-separator-invisible');fields.createChild('div','port-forwarding-value').appendChild(editor.createInput('address','text','Local address (dev.example.corp:3333)',addressValidator));return editor;function portValidator(rule,index,input){var value=input.value.trim();var match=value.match(/^(\d+)$/);if(!match) -return false;var port=parseInt(match[1],10);if(port<1024||port>65535) -return false;for(var i=0;i<this._portForwardingConfig.length;++i){if(i!==index&&this._portForwardingConfig[i].port===value) -return false;} -return true;} -function addressValidator(rule,index,input){var match=input.value.trim().match(/^([a-zA-Z0-9\.\-_]+):(\d+)$/);if(!match) -return false;var port=parseInt(match[2],10);return port<=65535;}}};Devices.DevicesView.NetworkDiscoveryView=class extends UI.VBox{constructor(nodeFrontend,callback){super();this._nodeFrontend=nodeFrontend;this._callback=callback;this.element.classList.add('network-discovery-view');var networkDiscoveryHeader=this.element.createChild('div','network-discovery-header');var networkDiscoveryEnabledCheckbox=UI.CheckboxLabel.create(Common.UIString('Network targets'));networkDiscoveryEnabledCheckbox.classList.add('network-discovery-checkbox');networkDiscoveryHeader.appendChild(networkDiscoveryEnabledCheckbox);this._networkDiscoveryEnabledCheckbox=networkDiscoveryEnabledCheckbox.checkboxElement;this._networkDiscoveryEnabledCheckbox.disabled=!!Runtime.queryParam('nodeFrontend');this._networkDiscoveryEnabledCheckbox.checked=!!Runtime.queryParam('nodeFrontend');this._networkDiscoveryEnabledCheckbox.addEventListener('click',this._enabledCheckboxClicked.bind(this),false);var networkDiscoveryFooter=this.element.createChild('div','network-discovery-footer');if(nodeFrontend){networkDiscoveryFooter.createChild('span').textContent=Common.UIString('Specify network endpoint and DevTools will connect to it automatically. ');var link=networkDiscoveryFooter.createChild('span','link');link.textContent=Common.UIString('Learn more');link.addEventListener('click',()=>InspectorFrontendHost.openInNewTab('https://nodejs.org/en/docs/inspector/'));}else{networkDiscoveryFooter.createChild('span').textContent=Common.UIString('Define the target connection address');} -this._list=new UI.ListWidget(this);this._list.registerRequiredCSS('devices/devicesView.css');this._list.element.classList.add('network-discovery-list');var placeholder=createElementWithClass('div','network-discovery-list-empty');placeholder.textContent=nodeFrontend?Common.UIString('No connections specified'):Common.UIString('No addresses defined');this._list.setEmptyPlaceholder(placeholder);this._list.show(this.element);this._editor=null;var addButton=UI.createTextButton(nodeFrontend?Common.UIString('Add connection'):Common.UIString('Add address'),this._addNetworkTargetButtonClicked.bind(this),'add-network-target-button',true);this.element.appendChild(addButton);this._networkDiscoveryConfig=[];this._networkDiscoveryEnabled=false;if(nodeFrontend){this.element.classList.add('node-frontend');this._list.element.classList.add('node-frontend');}} -_update(){var config=this._networkDiscoveryConfig.map(item=>item.address);this._callback.call(null,this._networkDiscoveryEnabled,config);} -_addNetworkTargetButtonClicked(){this._list.addNewItem(this._networkDiscoveryConfig.length,{address:'',port:''});} -discoveryConfigChanged(networkDiscoveryEnabled,networkDiscoveryConfig){this._networkDiscoveryEnabled=networkDiscoveryEnabled;if(!Runtime.queryParam('nodeFrontend')) -this._networkDiscoveryEnabledCheckbox.checked=networkDiscoveryEnabled;this._networkDiscoveryConfig=[];this._list.clear();for(var address of networkDiscoveryConfig){var item={address:address,port:''};this._networkDiscoveryConfig.push(item);this._list.appendItem(item,true);}} -_enabledCheckboxClicked(){if(!Runtime.queryParam('nodeFrontend')){this._networkDiscoveryEnabled=this._networkDiscoveryEnabledCheckbox.checked;this._update();}} -renderItem(rule,editable){var element=createElementWithClass('div','network-discovery-list-item');element.createChild('div','network-discovery-value network-discovery-address').textContent=rule.address;return element;} -removeItemRequested(rule,index){this._networkDiscoveryConfig.splice(index,1);this._list.removeItem(index);this._update();} -commitEdit(rule,editor,isNew){rule.address=editor.control('address').value.trim();if(isNew) -this._networkDiscoveryConfig.push(rule);this._update();} -beginEdit(rule){var editor=this._createEditor();editor.control('address').value=rule.address;return editor;} -_createEditor(){if(this._editor) -return this._editor;var editor=new UI.ListWidget.Editor();this._editor=editor;var content=editor.contentElement();var fields=content.createChild('div','network-discovery-edit-row');var input=editor.createInput('address','text','Network address (e.g. localhost:9229)',addressValidator);fields.createChild('div','network-discovery-value network-discovery-address').appendChild(input);return editor;function addressValidator(rule,index,input){var match=input.value.trim().match(/^([a-zA-Z0-9\.\-_]+):(\d+)$/);if(!match) -return false;var port=parseInt(match[2],10);return port<=65535;}}};Devices.DevicesView.DeviceView=class extends UI.VBox{constructor(){super();this.setMinimumSize(100,100);this.contentElement.classList.add('device-view');var topRow=this.contentElement.createChild('div','hbox device-text-row');this._deviceTitle=topRow.createChild('div','view-title');this._deviceSerial=topRow.createChild('div','device-serial');this._portStatus=this.contentElement.createChild('div','device-port-status hidden');this._deviceOffline=this.contentElement.createChild('div');this._deviceOffline.textContent=Common.UIString('Pending authentication: please accept debugging session on the device.');this._noBrowsers=this.contentElement.createChild('div');this._noBrowsers.textContent=Common.UIString('No browsers detected.');this._browsers=this.contentElement.createChild('div','device-browser-list vbox');this._browserById=new Map();this._cachedPortStatus=null;this._device=null;} -update(device){if(!this._device||this._device.adbModel!==device.adbModel) -this._deviceTitle.textContent=device.adbModel;if(!this._device||this._device.adbSerial!==device.adbSerial) -this._deviceSerial.textContent='#'+device.adbSerial;this._deviceOffline.classList.toggle('hidden',device.adbConnected);this._noBrowsers.classList.toggle('hidden',!device.adbConnected||!!device.browsers.length);this._browsers.classList.toggle('hidden',!device.adbConnected||!device.browsers.length);var browserIds=new Set();for(var browser of device.browsers) -browserIds.add(browser.id);for(var browserId of this._browserById.keys()){if(!browserIds.has(browserId)){this._browserById.get(browserId).element.remove();this._browserById.remove(browserId);}} -for(var browser of device.browsers){var section=this._browserById.get(browser.id);if(!section){section=this._createBrowserSection();this._browserById.set(browser.id,section);this._browsers.appendChild(section.element);} -this._updateBrowserSection(section,browser);} -this._device=device;} -_createBrowserSection(){var element=createElementWithClass('div','vbox flex-none');var topRow=element.createChild('div','');var title=topRow.createChild('div','device-browser-title');var newTabRow=element.createChild('div','device-browser-new-tab');newTabRow.createChild('div','').textContent=Common.UIString('New tab:');var newTabInput=UI.createInput('','text');newTabRow.appendChild(newTabInput);newTabInput.placeholder=Common.UIString('Enter URL');newTabInput.addEventListener('keydown',newTabKeyDown,false);var newTabButton=UI.createTextButton(Common.UIString('Open'),openNewTab);newTabRow.appendChild(newTabButton);var pages=element.createChild('div','device-page-list vbox');var viewMore=element.createChild('div','device-view-more');viewMore.addEventListener('click',viewMoreClick,false);updateViewMoreTitle();var section={browser:null,element:element,title:title,pages:pages,viewMore:viewMore,newTab:newTabRow,pageSections:new Map()};return section;function viewMoreClick(){pages.classList.toggle('device-view-more-toggled');updateViewMoreTitle();} -function updateViewMoreTitle(){viewMore.textContent=pages.classList.contains('device-view-more-toggled')?Common.UIString('View less tabs\u2026'):Common.UIString('View more tabs\u2026');} -function newTabKeyDown(event){if(event.key==='Enter'){event.consume(true);openNewTab();}} -function openNewTab(){if(section.browser){InspectorFrontendHost.openRemotePage(section.browser.id,newTabInput.value.trim()||'about:blank');newTabInput.value='';}}} -_updateBrowserSection(section,browser){if(!section.browser||section.browser.adbBrowserName!==browser.adbBrowserName||section.browser.adbBrowserVersion!==browser.adbBrowserVersion){if(browser.adbBrowserVersion) -section.title.textContent=String.sprintf('%s (%s)',browser.adbBrowserName,browser.adbBrowserVersion);else -section.title.textContent=browser.adbBrowserName;} -var pageIds=new Set();for(var page of browser.pages) -pageIds.add(page.id);for(var pageId of section.pageSections.keys()){if(!pageIds.has(pageId)){section.pageSections.get(pageId).element.remove();section.pageSections.remove(pageId);}} -for(var index=0;index<browser.pages.length;++index){var page=browser.pages[index];var pageSection=section.pageSections.get(page.id);if(!pageSection){pageSection=this._createPageSection();section.pageSections.set(page.id,pageSection);section.pages.appendChild(pageSection.element);} -this._updatePageSection(pageSection,page);if(!index&§ion.pages.firstChild!==pageSection.element) -section.pages.insertBefore(pageSection.element,section.pages.firstChild);} -var kViewMoreCount=3;for(var index=0,element=section.pages.firstChild;element;element=element.nextSibling,++index) -element.classList.toggle('device-view-more-page',index>=kViewMoreCount);section.viewMore.classList.toggle('device-needs-view-more',browser.pages.length>kViewMoreCount);section.newTab.classList.toggle('hidden',!browser.adbBrowserChromeVersion);section.browser=browser;} -_createPageSection(){var element=createElementWithClass('div','vbox');var titleRow=element.createChild('div','device-page-title-row');var title=titleRow.createChild('div','device-page-title');var inspect=UI.createTextButton(Common.UIString('Inspect'),doAction.bind(null,'inspect'));titleRow.appendChild(inspect);var toolbar=new UI.Toolbar('');toolbar.appendToolbarItem(new UI.ToolbarMenuButton(appendActions));titleRow.appendChild(toolbar.element);var url=element.createChild('div','device-page-url');var section={page:null,element:element,title:title,url:url,inspect:inspect};return section;function appendActions(contextMenu){contextMenu.defaultSection().appendItem(Common.UIString('Reload'),doAction.bind(null,'reload'));contextMenu.defaultSection().appendItem(Common.UIString('Focus'),doAction.bind(null,'activate'));contextMenu.defaultSection().appendItem(Common.UIString('Close'),doAction.bind(null,'close'));} -function doAction(action){if(section.page) -InspectorFrontendHost.performActionOnRemotePage(section.page.id,action);}} -_updatePageSection(section,page){if(!section.page||section.page.name!==page.name){section.title.textContent=page.name;section.title.title=page.name;} -if(!section.page||section.page.url!==page.url){section.url.textContent='';section.url.appendChild(UI.createExternalLink(page.url));} -section.inspect.disabled=page.attached;section.page=page;} -portForwardingStatusChanged(status){var json=JSON.stringify(status);if(json===this._cachedPortStatus) -return;this._cachedPortStatus=json;this._portStatus.removeChildren();this._portStatus.createChild('div','device-port-status-text').textContent=Common.UIString('Port Forwarding:');var connected=[];var transient=[];var error=[];var empty=true;for(var port in status.ports){if(!status.ports.hasOwnProperty(port)) -continue;empty=false;var portStatus=status.ports[port];var portNumber=createElementWithClass('div','device-view-port-number monospace');portNumber.textContent=':'+port;if(portStatus>=0) -this._portStatus.appendChild(portNumber);else -this._portStatus.insertBefore(portNumber,this._portStatus.firstChild);var portIcon=createElementWithClass('div','device-view-port-icon');if(portStatus>=0){connected.push(port);}else if(portStatus===-1||portStatus===-2){portIcon.classList.add('device-view-port-icon-transient');transient.push(port);}else if(portStatus<0){portIcon.classList.add('device-view-port-icon-error');error.push(port);} -this._portStatus.insertBefore(portIcon,portNumber);} -var title=[];if(connected.length) -title.push(Common.UIString('Connected: %s',connected.join(', ')));if(transient.length) -title.push(Common.UIString('Transient: %s',transient.join(', ')));if(error.length) -title.push(Common.UIString('Error: %s',error.join(', ')));this._portStatus.title=title.join('; ');this._portStatus.classList.toggle('hidden',empty);}};Devices.DevicesView.BrowserSection;Devices.DevicesView.PageSection;Devices.DevicesView.Panel=class extends UI.Panel{constructor(){super('node-connection');this.registerRequiredCSS('devices/devicesView.css');this.contentElement.classList.add('devices-view-panel');var container=this.contentElement.createChild('div','devices-view-panel-center');var image=container.createChild('img','devices-view-panel-logo');image.src='https://nodejs.org/static/images/logos/nodejs-new-pantone-black.png';InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged,this._devicesDiscoveryConfigChanged,this);this._config;this.contentElement.tabIndex=0;this.setDefaultFocusedElement(this.contentElement);InspectorFrontendHost.setDevicesUpdatesEnabled(false);InspectorFrontendHost.setDevicesUpdatesEnabled(true);this._networkDiscoveryView=new Devices.DevicesView.NetworkDiscoveryView(true,(enabled,config)=>{this._config.networkDiscoveryEnabled=enabled;this._config.networkDiscoveryConfig=config;InspectorFrontendHost.setDevicesDiscoveryConfig(this._config);});this._networkDiscoveryView.show(container);} -_devicesDiscoveryConfigChanged(event){this._config=(event.data);this._networkDiscoveryView.discoveryConfigChanged(this._config.networkDiscoveryEnabled,this._config.networkDiscoveryConfig);}};;Runtime.cachedResources["devices/devicesView.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.devices-container {\n overflow: hidden;\n flex: auto;\n}\n\n.devices-sidebar {\n flex: 0 0 150px;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n padding-top: 15px;\n}\n\n.devices-sidebar-list {\n flex: none;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n}\n\n.devices-sidebar-item {\n color: #222 !important;\n padding: 6px 6px 6px 16px;\n flex: auto;\n display: flex;\n flex-direction: column;\n justify-content: center;\n font-size: 14px;\n}\n\n.devices-sidebar-item.selected {\n border-left: 6px solid #666 !important;\n padding-left: 10px;\n}\n\n.devices-sidebar-item-status:before {\n content: \"\\25cf\";\n font-size: 16px;\n color: red;\n position: relative;\n top: 1px;\n margin-right: 2px;\n}\n\n.devices-sidebar-item.device-connected .devices-sidebar-item-status:before {\n color: green;\n}\n\n.devices-sidebar-spacer {\n flex: none;\n}\n\n.devices-view-title {\n font-size: 16px;\n margin: 0 0 15px 15px;\n padding-top: 1px;\n}\n\n.view-title {\n font-size: 16px;\n flex: none;\n}\n\n.devices-footer {\n border-top: 1px solid #cdcdcd;\n background-color: #f3f3f3;\n flex: none;\n padding: 3px 10px;\n overflow: hidden;\n}\n\n.devices-footer > span {\n white-space: pre;\n}\n\n.discovery-view {\n overflow-x: hidden;\n overflow-y: auto;\n padding: 15px 15px 0px 0px;\n}\n\n.discovery-view > * {\n flex: none;\n}\n\n.usb-checkbox {\n padding-bottom: 8px;\n margin-top: 20px;\n}\n\n.port-forwarding-header {\n display: flex;\n align-items: center;\n flex-direction: row;\n margin-top: 5px;\n}\n\n.add-rule-button {\n margin: 10px 25px;\n align-self: flex-start;\n}\n\n.discovery-help {\n margin: 5px 0 25px 25px;\n}\n\n.discovery-help > span {\n white-space: pre;\n}\n\n.port-forwarding-list {\n margin: 10px 0 0 25px;\n max-width: 500px;\n flex: none;\n}\n\n.port-forwarding-list-empty {\n flex: auto;\n height: 30px;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.port-forwarding-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n position: relative;\n flex: auto 1 1;\n}\n\n.list-item .port-forwarding-value {\n white-space: nowrap;\n text-overflow: ellipsis;\n -webkit-user-select: none;\n color: #222;\n overflow: hidden;\n}\n\n.port-forwarding-value {\n flex: 3 1 0;\n}\n\n.port-forwarding-value.port-forwarding-port {\n flex: 1 1 0;\n}\n\n.port-localhost {\n color: #aaa;\n}\n\n.port-forwarding-separator {\n flex: 0 0 1px;\n background-color: rgb(231, 231, 231);\n height: 30px;\n margin: 0 4px;\n}\n\n.port-forwarding-separator-invisible {\n visibility: hidden;\n height: 100% !important;\n}\n\n.port-forwarding-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 6px 5px;\n align-items: center;\n}\n\n.port-forwarding-edit-row input {\n width: 100%;\n text-align: inherit;\n}\n\n.port-forwarding-footer {\n overflow: hidden;\n margin: 15px 0 0 25px;\n max-width: 500px;\n}\n\n.port-forwarding-footer > * {\n white-space: pre-wrap;\n}\n\n.network-discovery-header {\n display: flex;\n align-items: center;\n flex-direction: row;\n margin-top: 5px;\n}\n\n.add-network-target-button {\n margin: 10px 25px;\n align-self: flex-start;\n}\n\n.network-discovery-list {\n margin: 10px 0 0 25px;\n max-width: 500px;\n flex: none;\n}\n\n.network-discovery-list-empty {\n flex: auto;\n height: 30px;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.network-discovery-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n position: relative;\n flex: auto 1 1;\n}\n\n.list-item .network-discovery-value {\n white-space: nowrap;\n text-overflow: ellipsis;\n -webkit-user-select: none;\n color: #222;\n overflow: hidden;\n}\n\n.network-discovery-value {\n flex: 3 1 0;\n}\n\n.network-discovery-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 6px 5px;\n align-items: center;\n}\n\n.network-discovery-edit-row input {\n width: 100%;\n text-align: inherit;\n}\n\n.network-discovery-footer {\n overflow: hidden;\n margin: 15px 0 0 25px;\n max-width: 500px;\n}\n\n.network-discovery-footer > * {\n white-space: pre-wrap;\n}\n\n.device-view {\n overflow: auto;\n -webkit-user-select: text;\n flex: auto;\n}\n\n.device-text-row {\n align-items: baseline;\n margin-right: 25px;\n}\n\n.device-serial {\n color: #777;\n margin-left: 5px;\n flex: none;\n}\n\n.device-browser-list {\n flex: auto;\n overflow: auto;\n padding-right: 10px;\n margin-top: 30px;\n}\n\n.device-browser-list > div {\n margin-bottom: 15px;\n}\n\n.device-browser-title {\n font-size: 16px;\n}\n\n.device-browser-new-tab {\n display: flex;\n flex-direction: row;\n align-items: center;\n margin: 10px 0 0 10px;\n}\n\n.device-browser-new-tab > div {\n font-size: 13px;\n}\n\n.device-browser-new-tab > input {\n margin: 0 10px;\n}\n\n.device-page-list {\n margin: 10px 0 0 10px;\n overflow-x: auto;\n align-items: stretch;\n flex: none;\n}\n\n.device-page-list > div {\n flex: none;\n padding: 5px 0;\n}\n\n.device-page-list:not(.device-view-more-toggled) > div.device-view-more-page {\n display: none;\n}\n\n.device-page-title-row {\n display: flex;\n flex-direction: row;\n align-items: center;\n}\n\n.device-page-title {\n font-size: 15px;\n flex: auto;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.device-page-title-row .toolbar {\n margin-left: 3px;\n padding: 0;\n border-radius: 3px;\n}\n\n.device-page-title-row .toolbar:hover {\n background-color: hsl(0, 0%, 90%);\n}\n\n.device-page-url {\n margin: 3px 100px 3px 0;\n}\n\n.device-page-url a {\n color: #777;\n word-break: break-all;\n}\n\n.device-view-more {\n cursor: pointer;\n text-decoration: underline;\n color: rgb(17, 85, 204);\n margin: 5px 0 0 10px;\n display: none;\n}\n\n.device-view-more.device-needs-view-more {\n display: block;\n}\n\n.device-port-status {\n overflow: hidden;\n flex: none;\n display: flex;\n align-items: baseline;\n margin: 10px 0 0 10px;\n}\n\n.device-port-status-text {\n margin-right: 10px;\n}\n\n.device-view-port-icon {\n background-color: green;\n border: 0 solid transparent;\n border-radius: 6px;\n height: 12px;\n width: 12px;\n position: relative;\n top: 2px;\n flex: none;\n}\n\n.device-view-port-number {\n margin: 0 10px 0 2px;\n flex: none;\n}\n\n.device-view-port-icon.device-view-port-icon-error {\n background-color: red;\n}\n\n.device-view-port-icon.device-view-port-icon-transient {\n transform: scale(1.2);\n background-color: orange;\n}\n\n.node-frontend .network-discovery-header {\n display: none;\n}\n\n.devices-view-panel {\n align-items: center;\n justify-content: flex-start;\n}\n\n.node-frontend.network-discovery-view {\n min-width: 400px;\n flex: auto;\n}\n\n.node-frontend .add-network-target-button {\n align-self: center;\n}\n\n:host-context(.node-frontend) .network-discovery-list-empty {\n height: 40px;\n}\n\n:host-context(.node-frontend) .network-discovery-list-item {\n padding: 3px 15px;\n height: 40px;\n}\n\n.node-frontend .network-discovery-list {\n margin: 20px 0 5px 0;\n max-width: 600px;\n max-height: 202px;\n}\n\n.node-frontend .network-discovery-footer {\n margin: 0;\n}\n\n.devices-view-panel-center {\n display: flex;\n align-items: stretch;\n justify-content: center;\n max-width: 600px;\n flex-direction: column;\n padding-top: 50px;\n}\n\n.devices-view-panel-logo {\n align-self: center;\n width: 400px;\n margin-bottom: 50px;\n flex: none;\n}\n\n:host-context(.node-frontend) .network-discovery-edit-row input {\n height: 30px;\n padding-left: 5px;\n}\n\n:host-context(.node-frontend) .network-discovery-edit-row {\n margin: 6px 9px;\n}\n\n/*# sourceURL=devices/devicesView.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/devtools_compatibility.js b/src/cobalt/debug/content/devtools/devtools_compatibility.js deleted file mode 100644 index 4fe6045..0000000 --- a/src/cobalt/debug/content/devtools/devtools_compatibility.js +++ /dev/null
@@ -1,1283 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -/* eslint-disable indent */ -(function(window) { - - // DevToolsAPI ---------------------------------------------------------------- - - /** - * @unrestricted - */ - var DevToolsAPIImpl = class { - constructor() { - /** - * @type {number} - */ - this._lastCallId = 0; - - /** - * @type {!Object.<number, function(?Object)>} - */ - this._callbacks = {}; - } - - /** - * @param {number} id - * @param {?Object} arg - */ - embedderMessageAck(id, arg) { - var callback = this._callbacks[id]; - delete this._callbacks[id]; - if (callback) - callback(arg); - } - - /** - * @param {string} method - * @param {!Array.<*>} args - * @param {?function(?Object)} callback - */ - sendMessageToEmbedder(method, args, callback) { - var callId = ++this._lastCallId; - if (callback) - this._callbacks[callId] = callback; - var message = {'id': callId, 'method': method}; - if (args.length) - message.params = args; - DevToolsHost.sendMessageToEmbedder(JSON.stringify(message)); - } - - /** - * @param {string} method - * @param {!Array<*>} args - */ - _dispatchOnInspectorFrontendAPI(method, args) { - const inspectorFrontendAPI = /** @type {!Object<string, function()>} */ (window['InspectorFrontendAPI']); - inspectorFrontendAPI[method].apply(inspectorFrontendAPI, args); - } - - // API methods below this line -------------------------------------------- - - /** - * @param {!Array.<!ExtensionDescriptor>} extensions - */ - addExtensions(extensions) { - // Support for legacy front-ends (<M41). - if (window['WebInspector'] && window['WebInspector']['addExtensions']) { - window['WebInspector']['addExtensions'](extensions); - } else if (window['InspectorFrontendAPI']) { - // The addExtensions command is sent as the onload event happens for - // DevTools front-end. In case of hosted mode, this - // happens before the InspectorFrontendAPI is initialized. - this._dispatchOnInspectorFrontendAPI('addExtensions', [extensions]); - } - } - - /** - * @param {string} url - */ - appendedToURL(url) { - this._dispatchOnInspectorFrontendAPI('appendedToURL', [url]); - } - - /** - * @param {string} url - */ - canceledSaveURL(url) { - this._dispatchOnInspectorFrontendAPI('canceledSaveURL', [url]); - } - - contextMenuCleared() { - this._dispatchOnInspectorFrontendAPI('contextMenuCleared', []); - } - - /** - * @param {string} id - */ - contextMenuItemSelected(id) { - this._dispatchOnInspectorFrontendAPI('contextMenuItemSelected', [id]); - } - - /** - * @param {number} count - */ - deviceCountUpdated(count) { - this._dispatchOnInspectorFrontendAPI('deviceCountUpdated', [count]); - } - - /** - * @param {!Adb.Config} config - */ - devicesDiscoveryConfigChanged(config) { - this._dispatchOnInspectorFrontendAPI('devicesDiscoveryConfigChanged', [config]); - } - - /** - * @param {!Adb.PortForwardingStatus} status - */ - devicesPortForwardingStatusChanged(status) { - this._dispatchOnInspectorFrontendAPI('devicesPortForwardingStatusChanged', [status]); - } - - /** - * @param {!Array.<!Adb.Device>} devices - */ - devicesUpdated(devices) { - this._dispatchOnInspectorFrontendAPI('devicesUpdated', [devices]); - } - - /** - * @param {string} message - */ - dispatchMessage(message) { - this._dispatchOnInspectorFrontendAPI('dispatchMessage', [message]); - } - - /** - * @param {string} messageChunk - * @param {number} messageSize - */ - dispatchMessageChunk(messageChunk, messageSize) { - this._dispatchOnInspectorFrontendAPI('dispatchMessageChunk', [messageChunk, messageSize]); - } - - enterInspectElementMode() { - this._dispatchOnInspectorFrontendAPI('enterInspectElementMode', []); - } - - /** - * @param {number} callId - * @param {string} script - */ - evaluateForTestInFrontend(callId, script) { - this._dispatchOnInspectorFrontendAPI('evaluateForTestInFrontend', [callId, script]); - } - - /** - * @param {!{r: number, g: number, b: number, a: number}} color - */ - eyeDropperPickedColor(color) { - this._dispatchOnInspectorFrontendAPI('eyeDropperPickedColor', [color]); - } - - /** - * @param {!Array.<!{fileSystemName: string, rootURL: string, fileSystemPath: string}>} fileSystems - */ - fileSystemsLoaded(fileSystems) { - this._dispatchOnInspectorFrontendAPI('fileSystemsLoaded', [fileSystems]); - } - - /** - * @param {string} fileSystemPath - */ - fileSystemRemoved(fileSystemPath) { - this._dispatchOnInspectorFrontendAPI('fileSystemRemoved', [fileSystemPath]); - } - - /** - * @param {?string} error - * @param {?{type: string, fileSystemName: string, rootURL: string, fileSystemPath: string}} fileSystem - */ - fileSystemAdded(error, fileSystem) { - this._dispatchOnInspectorFrontendAPI('fileSystemAdded', [error, fileSystem]); - } - - /** - * @param {!Array<string>} changedPaths - * @param {!Array<string>} addedPaths - * @param {!Array<string>} removedPaths - */ - fileSystemFilesChangedAddedRemoved(changedPaths, addedPaths, removedPaths) { - // Support for legacy front-ends (<M58) - if (window['InspectorFrontendAPI'] && window['InspectorFrontendAPI']['fileSystemFilesChanged']) { - this._dispatchOnInspectorFrontendAPI( - 'fileSystemFilesChanged', [changedPaths.concat(addedPaths).concat(removedPaths)]); - } else { - this._dispatchOnInspectorFrontendAPI( - 'fileSystemFilesChangedAddedRemoved', [changedPaths, addedPaths, removedPaths]); - } - } - - /** - * @param {number} requestId - * @param {string} fileSystemPath - * @param {number} totalWork - */ - indexingTotalWorkCalculated(requestId, fileSystemPath, totalWork) { - this._dispatchOnInspectorFrontendAPI('indexingTotalWorkCalculated', [requestId, fileSystemPath, totalWork]); - } - - /** - * @param {number} requestId - * @param {string} fileSystemPath - * @param {number} worked - */ - indexingWorked(requestId, fileSystemPath, worked) { - this._dispatchOnInspectorFrontendAPI('indexingWorked', [requestId, fileSystemPath, worked]); - } - - /** - * @param {number} requestId - * @param {string} fileSystemPath - */ - indexingDone(requestId, fileSystemPath) { - this._dispatchOnInspectorFrontendAPI('indexingDone', [requestId, fileSystemPath]); - } - - /** - * @param {{type: string, key: string, code: string, keyCode: number, modifiers: number}} event - */ - keyEventUnhandled(event) { - event.key = keyCodeToKeyIdentifier(event.keyCode); - this._dispatchOnInspectorFrontendAPI('keyEventUnhandled', [event]); - } - - /** - * @param {boolean} hard - */ - reloadInspectedPage(hard) { - this._dispatchOnInspectorFrontendAPI('reloadInspectedPage', [hard]); - } - - /** - * @param {string} url - * @param {number} lineNumber - * @param {number} columnNumber - */ - revealSourceLine(url, lineNumber, columnNumber) { - this._dispatchOnInspectorFrontendAPI('revealSourceLine', [url, lineNumber, columnNumber]); - } - - /** - * @param {string} url - * @param {string=} fileSystemPath - */ - savedURL(url, fileSystemPath) { - this._dispatchOnInspectorFrontendAPI('savedURL', [url, fileSystemPath]); - } - - /** - * @param {number} requestId - * @param {string} fileSystemPath - * @param {!Array.<string>} files - */ - searchCompleted(requestId, fileSystemPath, files) { - this._dispatchOnInspectorFrontendAPI('searchCompleted', [requestId, fileSystemPath, files]); - } - - /** - * @param {string} tabId - */ - setInspectedTabId(tabId) { - // Support for legacy front-ends (<M41). - if (window['WebInspector'] && window['WebInspector']['setInspectedTabId']) - window['WebInspector']['setInspectedTabId'](tabId); - else - this._dispatchOnInspectorFrontendAPI('setInspectedTabId', [tabId]); - } - - /** - * @param {boolean} useSoftMenu - */ - setUseSoftMenu(useSoftMenu) { - this._dispatchOnInspectorFrontendAPI('setUseSoftMenu', [useSoftMenu]); - } - - /** - * @param {string} panelName - */ - showPanel(panelName) { - this._dispatchOnInspectorFrontendAPI('showPanel', [panelName]); - } - - /** - * @param {number} id - * @param {string} chunk - * @param {boolean} encoded - */ - streamWrite(id, chunk, encoded) { - this._dispatchOnInspectorFrontendAPI('streamWrite', [id, encoded ? this._decodeBase64(chunk) : chunk]); - } - - /** - * @param {string} chunk - * @return {string} - */ - _decodeBase64(chunk) { - var request = new XMLHttpRequest(); - request.open('GET', 'data:text/plain;base64,' + chunk, false); - request.send(null); - if (request.status === 200) { - return request.responseText; - } else { - console.error('Error while decoding chunk in streamWrite'); - return ''; - } - } - }; - - var DevToolsAPI = new DevToolsAPIImpl(); - window.DevToolsAPI = DevToolsAPI; - - // InspectorFrontendHostImpl -------------------------------------------------- - - /** - * @implements {InspectorFrontendHostAPI} - * @unrestricted - */ - var InspectorFrontendHostImpl = class { - /** - * @override - * @return {string} - */ - getSelectionBackgroundColor() { - return DevToolsHost.getSelectionBackgroundColor(); - } - - /** - * @override - * @return {string} - */ - getSelectionForegroundColor() { - return DevToolsHost.getSelectionForegroundColor(); - } - - /** - * @override - * @return {string} - */ - platform() { - return DevToolsHost.platform(); - } - - /** - * @override - */ - loadCompleted() { - DevToolsAPI.sendMessageToEmbedder('loadCompleted', [], null); - // Support for legacy (<57) frontends. - if (window.Runtime && window.Runtime.queryParam) { - var panelToOpen = window.Runtime.queryParam('panel'); - if (panelToOpen) - window.DevToolsAPI.showPanel(panelToOpen); - } - } - - /** - * @override - */ - bringToFront() { - DevToolsAPI.sendMessageToEmbedder('bringToFront', [], null); - } - - /** - * @override - */ - closeWindow() { - DevToolsAPI.sendMessageToEmbedder('closeWindow', [], null); - } - - /** - * @override - * @param {boolean} isDocked - * @param {function()} callback - */ - setIsDocked(isDocked, callback) { - DevToolsAPI.sendMessageToEmbedder('setIsDocked', [isDocked], callback); - } - - /** - * Requests inspected page to be placed atop of the inspector frontend with specified bounds. - * @override - * @param {{x: number, y: number, width: number, height: number}} bounds - */ - setInspectedPageBounds(bounds) { - DevToolsAPI.sendMessageToEmbedder('setInspectedPageBounds', [bounds], null); - } - - /** - * @override - */ - inspectElementCompleted() { - DevToolsAPI.sendMessageToEmbedder('inspectElementCompleted', [], null); - } - - /** - * @override - * @param {string} url - * @param {string} headers - * @param {number} streamId - * @param {function(!InspectorFrontendHostAPI.LoadNetworkResourceResult)} callback - */ - loadNetworkResource(url, headers, streamId, callback) { - DevToolsAPI.sendMessageToEmbedder( - 'loadNetworkResource', [url, headers, streamId], /** @type {function(?Object)} */ (callback)); - } - - /** - * @override - * @param {function(!Object<string, string>)} callback - */ - getPreferences(callback) { - DevToolsAPI.sendMessageToEmbedder('getPreferences', [], /** @type {function(?Object)} */ (callback)); - } - - /** - * @override - * @param {string} name - * @param {string} value - */ - setPreference(name, value) { - DevToolsAPI.sendMessageToEmbedder('setPreference', [name, value], null); - } - - /** - * @override - * @param {string} name - */ - removePreference(name) { - DevToolsAPI.sendMessageToEmbedder('removePreference', [name], null); - } - - /** - * @override - */ - clearPreferences() { - DevToolsAPI.sendMessageToEmbedder('clearPreferences', [], null); - } - - /** - * @override - * @param {string} origin - * @param {string} script - */ - setInjectedScriptForOrigin(origin, script) { - DevToolsAPI.sendMessageToEmbedder('registerExtensionsAPI', [origin, script], null); - } - - /** - * @override - * @param {string} url - */ - inspectedURLChanged(url) { - DevToolsAPI.sendMessageToEmbedder('inspectedURLChanged', [url], null); - } - - /** - * @override - * @param {string} text - */ - copyText(text) { - DevToolsHost.copyText(text); - } - - /** - * @override - * @param {string} url - */ - openInNewTab(url) { - DevToolsAPI.sendMessageToEmbedder('openInNewTab', [url], null); - } - - /** - * @override - * @param {string} url - * @param {string} content - * @param {boolean} forceSaveAs - */ - save(url, content, forceSaveAs) { - DevToolsAPI.sendMessageToEmbedder('save', [url, content, forceSaveAs], null); - } - - /** - * @override - * @param {string} url - * @param {string} content - */ - append(url, content) { - DevToolsAPI.sendMessageToEmbedder('append', [url, content], null); - } - - /** - * @override - * @param {string} message - */ - sendMessageToBackend(message) { - DevToolsAPI.sendMessageToEmbedder('dispatchProtocolMessage', [message], null); - } - - /** - * @override - * @param {string} actionName - * @param {number} actionCode - * @param {number} bucketSize - */ - recordEnumeratedHistogram(actionName, actionCode, bucketSize) { - // Support for M49 frontend. - if (actionName === 'DevTools.DrawerShown') - return; - DevToolsAPI.sendMessageToEmbedder('recordEnumeratedHistogram', [actionName, actionCode, bucketSize], null); - } - - /** - * @override - */ - requestFileSystems() { - DevToolsAPI.sendMessageToEmbedder('requestFileSystems', [], null); - } - - /** - * @override - * @param {string=} type - */ - addFileSystem(type) { - DevToolsAPI.sendMessageToEmbedder('addFileSystem', [type || ''], null); - } - - /** - * @override - * @param {string} fileSystemPath - */ - removeFileSystem(fileSystemPath) { - DevToolsAPI.sendMessageToEmbedder('removeFileSystem', [fileSystemPath], null); - } - - /** - * @override - * @param {string} fileSystemId - * @param {string} registeredName - * @return {?DOMFileSystem} - */ - isolatedFileSystem(fileSystemId, registeredName) { - return DevToolsHost.isolatedFileSystem(fileSystemId, registeredName); - } - - /** - * @override - * @param {!FileSystem} fileSystem - */ - upgradeDraggedFileSystemPermissions(fileSystem) { - DevToolsHost.upgradeDraggedFileSystemPermissions(fileSystem); - } - - /** - * @override - * @param {number} requestId - * @param {string} fileSystemPath - */ - indexPath(requestId, fileSystemPath) { - DevToolsAPI.sendMessageToEmbedder('indexPath', [requestId, fileSystemPath], null); - } - - /** - * @override - * @param {number} requestId - */ - stopIndexing(requestId) { - DevToolsAPI.sendMessageToEmbedder('stopIndexing', [requestId], null); - } - - /** - * @override - * @param {number} requestId - * @param {string} fileSystemPath - * @param {string} query - */ - searchInPath(requestId, fileSystemPath, query) { - DevToolsAPI.sendMessageToEmbedder('searchInPath', [requestId, fileSystemPath, query], null); - } - - /** - * @override - * @return {number} - */ - zoomFactor() { - return DevToolsHost.zoomFactor(); - } - - /** - * @override - */ - zoomIn() { - DevToolsAPI.sendMessageToEmbedder('zoomIn', [], null); - } - - /** - * @override - */ - zoomOut() { - DevToolsAPI.sendMessageToEmbedder('zoomOut', [], null); - } - - /** - * @override - */ - resetZoom() { - DevToolsAPI.sendMessageToEmbedder('resetZoom', [], null); - } - - /** - * @override - * @param {string} shortcuts - */ - setWhitelistedShortcuts(shortcuts) { - DevToolsAPI.sendMessageToEmbedder('setWhitelistedShortcuts', [shortcuts], null); - } - - /** - * @override - * @param {boolean} active - */ - setEyeDropperActive(active) { - DevToolsAPI.sendMessageToEmbedder('setEyeDropperActive', [active], null); - } - - /** - * @override - * @param {!Array<string>} certChain - */ - showCertificateViewer(certChain) { - DevToolsAPI.sendMessageToEmbedder('showCertificateViewer', [JSON.stringify(certChain)], null); - } - - /** - * @override - * @return {boolean} - */ - isUnderTest() { - return DevToolsHost.isUnderTest(); - } - - /** - * @override - * @param {function()} callback - */ - reattach(callback) { - DevToolsAPI.sendMessageToEmbedder('reattach', [], callback); - } - - /** - * @override - */ - readyForTest() { - DevToolsAPI.sendMessageToEmbedder('readyForTest', [], null); - } - - /** - * @override - * @param {!Adb.Config} config - */ - setDevicesDiscoveryConfig(config) { - DevToolsAPI.sendMessageToEmbedder( - 'setDevicesDiscoveryConfig', - [ - config.discoverUsbDevices, config.portForwardingEnabled, JSON.stringify(config.portForwardingConfig), - config.networkDiscoveryEnabled, JSON.stringify(config.networkDiscoveryConfig) - ], - null); - } - - /** - * @override - * @param {boolean} enabled - */ - setDevicesUpdatesEnabled(enabled) { - DevToolsAPI.sendMessageToEmbedder('setDevicesUpdatesEnabled', [enabled], null); - } - - /** - * @override - * @param {string} pageId - * @param {string} action - */ - performActionOnRemotePage(pageId, action) { - DevToolsAPI.sendMessageToEmbedder('performActionOnRemotePage', [pageId, action], null); - } - - /** - * @override - * @param {string} browserId - * @param {string} url - */ - openRemotePage(browserId, url) { - DevToolsAPI.sendMessageToEmbedder('openRemotePage', [browserId, url], null); - } - - /** - * @override - */ - openNodeFrontend() { - DevToolsAPI.sendMessageToEmbedder('openNodeFrontend', [], null); - } - - /** - * @override - * @param {number} x - * @param {number} y - * @param {!Array.<!InspectorFrontendHostAPI.ContextMenuDescriptor>} items - * @param {!Document} document - */ - showContextMenuAtPoint(x, y, items, document) { - DevToolsHost.showContextMenuAtPoint(x, y, items, document); - } - - /** - * @override - * @return {boolean} - */ - isHostedMode() { - return DevToolsHost.isHostedMode(); - } - - // Backward-compatible methods below this line -------------------------------------------- - - /** - * Support for legacy front-ends (<M50). - * @param {string} message - */ - sendFrontendAPINotification(message) { - } - - /** - * Support for legacy front-ends (<M41). - * @return {string} - */ - port() { - return 'unknown'; - } - - /** - * Support for legacy front-ends (<M38). - * @param {number} zoomFactor - */ - setZoomFactor(zoomFactor) { - } - - /** - * Support for legacy front-ends (<M34). - */ - sendMessageToEmbedder() { - } - - /** - * Support for legacy front-ends (<M34). - * @param {string} dockSide - */ - requestSetDockSide(dockSide) { - DevToolsAPI.sendMessageToEmbedder('setIsDocked', [dockSide !== 'undocked'], null); - } - - /** - * Support for legacy front-ends (<M34). - * @return {boolean} - */ - supportsFileSystems() { - return true; - } - - /** - * Support for legacy front-ends (<M28). - * @return {boolean} - */ - canInspectWorkers() { - return true; - } - - /** - * Support for legacy front-ends (<M28). - * @return {boolean} - */ - canSaveAs() { - return true; - } - - /** - * Support for legacy front-ends (<M28). - * @return {boolean} - */ - canSave() { - return true; - } - - /** - * Support for legacy front-ends (<M28). - */ - loaded() { - } - - /** - * Support for legacy front-ends (<M28). - * @return {string} - */ - hiddenPanels() { - return ''; - } - - /** - * Support for legacy front-ends (<M28). - * @return {string} - */ - localizedStringsURL() { - return ''; - } - - /** - * Support for legacy front-ends (<M28). - * @param {string} url - */ - close(url) { - } - - /** - * Support for legacy front-ends (<M44). - * @param {number} actionCode - */ - recordActionTaken(actionCode) { - this.recordEnumeratedHistogram('DevTools.ActionTaken', actionCode, 100); - } - - /** - * Support for legacy front-ends (<M44). - * @param {number} panelCode - */ - recordPanelShown(panelCode) { - this.recordEnumeratedHistogram('DevTools.PanelShown', panelCode, 20); - } - }; - - window.InspectorFrontendHost = new InspectorFrontendHostImpl(); - - // DevToolsApp --------------------------------------------------------------- - - function installObjectObserve() { - /** @type {!Array<string>} */ - var properties = [ - 'advancedSearchConfig', - 'auditsPanelSplitViewState', - 'auditsSidebarWidth', - 'blockedURLs', - 'breakpoints', - 'cacheDisabled', - 'colorFormat', - 'consoleHistory', - 'consoleTimestampsEnabled', - 'cpuProfilerView', - 'cssSourceMapsEnabled', - 'currentDockState', - 'customColorPalette', - 'customDevicePresets', - 'customEmulatedDeviceList', - 'customFormatters', - 'customUserAgent', - 'databaseTableViewVisibleColumns', - 'dataGrid-cookiesTable', - 'dataGrid-DOMStorageItemsView', - 'debuggerSidebarHidden', - 'disableDataSaverInfobar', - 'disablePausedStateOverlay', - 'domBreakpoints', - 'domWordWrap', - 'elementsPanelSplitViewState', - 'elementsSidebarWidth', - 'emulation.deviceHeight', - 'emulation.deviceModeValue', - 'emulation.deviceOrientationOverride', - 'emulation.deviceScale', - 'emulation.deviceScaleFactor', - 'emulation.deviceUA', - 'emulation.deviceWidth', - 'emulation.geolocationOverride', - 'emulation.showDeviceMode', - 'emulation.showRulers', - 'enableAsyncStackTraces', - 'eventListenerBreakpoints', - 'fileMappingEntries', - 'fileSystemMapping', - 'FileSystemViewSidebarWidth', - 'fileSystemViewSplitViewState', - 'filterBar-consoleView', - 'filterBar-networkPanel', - 'filterBar-promisePane', - 'filterBar-timelinePanel', - 'frameViewerHideChromeWindow', - 'heapSnapshotRetainersViewSize', - 'heapSnapshotSplitViewState', - 'hideCollectedPromises', - 'hideNetworkMessages', - 'highlightNodeOnHoverInOverlay', - 'highResolutionCpuProfiling', - 'inlineVariableValues', - 'Inspector.drawerSplitView', - 'Inspector.drawerSplitViewState', - 'InspectorView.panelOrder', - 'InspectorView.screencastSplitView', - 'InspectorView.screencastSplitViewState', - 'InspectorView.splitView', - 'InspectorView.splitViewState', - 'javaScriptDisabled', - 'jsSourceMapsEnabled', - 'lastActivePanel', - 'lastDockState', - 'lastSelectedSourcesSidebarPaneTab', - 'lastSnippetEvaluationIndex', - 'layerDetailsSplitView', - 'layerDetailsSplitViewState', - 'layersPanelSplitViewState', - 'layersShowInternalLayers', - 'layersSidebarWidth', - 'messageLevelFilters', - 'messageURLFilters', - 'monitoringXHREnabled', - 'navigatorGroupByFolder', - 'navigatorHidden', - 'networkColorCodeResourceTypes', - 'networkConditions', - 'networkConditionsCustomProfiles', - 'networkHideDataURL', - 'networkLogColumnsVisibility', - 'networkLogLargeRows', - 'networkLogShowOverview', - 'networkPanelSplitViewState', - 'networkRecordFilmStripSetting', - 'networkResourceTypeFilters', - 'networkShowPrimaryLoadWaterfall', - 'networkSidebarWidth', - 'openLinkHandler', - 'pauseOnCaughtException', - 'pauseOnExceptionEnabled', - 'preserveConsoleLog', - 'prettyPrintInfobarDisabled', - 'previouslyViewedFiles', - 'profilesPanelSplitViewState', - 'profilesSidebarWidth', - 'promiseStatusFilters', - 'recordAllocationStacks', - 'requestHeaderFilterSetting', - 'request-info-formData-category-expanded', - 'request-info-general-category-expanded', - 'request-info-queryString-category-expanded', - 'request-info-requestHeaders-category-expanded', - 'request-info-requestPayload-category-expanded', - 'request-info-responseHeaders-category-expanded', - 'resources', - 'resourcesLastSelectedItem', - 'resourcesPanelSplitViewState', - 'resourcesSidebarWidth', - 'resourceViewTab', - 'savedURLs', - 'screencastEnabled', - 'scriptsPanelNavigatorSidebarWidth', - 'searchInContentScripts', - 'selectedAuditCategories', - 'selectedColorPalette', - 'selectedProfileType', - 'shortcutPanelSwitch', - 'showAdvancedHeapSnapshotProperties', - 'showEventListenersForAncestors', - 'showFrameowkrListeners', - 'showHeaSnapshotObjectsHiddenProperties', - 'showInheritedComputedStyleProperties', - 'showMediaQueryInspector', - 'showNativeFunctionsInJSProfile', - 'showUAShadowDOM', - 'showWhitespacesInEditor', - 'sidebarPosition', - 'skipContentScripts', - 'skipStackFramesPattern', - 'sourceMapInfobarDisabled', - 'sourcesPanelDebuggerSidebarSplitViewState', - 'sourcesPanelNavigatorSplitViewState', - 'sourcesPanelSplitSidebarRatio', - 'sourcesPanelSplitViewState', - 'sourcesSidebarWidth', - 'standardEmulatedDeviceList', - 'StylesPaneSplitRatio', - 'stylesPaneSplitViewState', - 'textEditorAutocompletion', - 'textEditorAutoDetectIndent', - 'textEditorBracketMatching', - 'textEditorIndent', - 'timelineCaptureFilmStrip', - 'timelineCaptureLayersAndPictures', - 'timelineCaptureMemory', - 'timelineCaptureNetwork', - 'timeline-details', - 'timelineEnableJSSampling', - 'timelineOverviewMode', - 'timelinePanelDetailsSplitViewState', - 'timelinePanelRecorsSplitViewState', - 'timelinePanelTimelineStackSplitViewState', - 'timelinePerspective', - 'timeline-split', - 'timelineTreeGroupBy', - 'timeline-view', - 'timelineViewMode', - 'uiTheme', - 'watchExpressions', - 'WebInspector.Drawer.lastSelectedView', - 'WebInspector.Drawer.showOnLoad', - 'workspaceExcludedFolders', - 'workspaceFolderExcludePattern', - 'workspaceInfobarDisabled', - 'workspaceMappingInfobarDisabled', - 'xhrBreakpoints' - ]; - - /** - * @this {!{_storage: Object, _name: string}} - */ - function settingRemove() { - this._storage[this._name] = undefined; - } - - /** - * @param {!Object} object - * @param {function(!Array<!{name: string}>)} observer - */ - function objectObserve(object, observer) { - if (window['WebInspector']) { - var settingPrototype = /** @type {!Object} */ (window['WebInspector']['Setting']['prototype']); - if (typeof settingPrototype['remove'] === 'function') - settingPrototype['remove'] = settingRemove; - } - /** @type {!Set<string>} */ - var changedProperties = new Set(); - var scheduled = false; - - function scheduleObserver() { - if (scheduled) - return; - scheduled = true; - setImmediate(callObserver); - } - - function callObserver() { - scheduled = false; - var changes = /** @type {!Array<!{name: string}>} */ ([]); - changedProperties.forEach(function(name) { - changes.push({name: name}); - }); - changedProperties.clear(); - observer.call(null, changes); - } - - /** @type {!Map<string, *>} */ - var storage = new Map(); - - /** - * @param {string} property - */ - function defineProperty(property) { - if (property in object) { - storage.set(property, object[property]); - delete object[property]; - } - - Object.defineProperty(object, property, { - /** - * @return {*} - */ - get: function() { - return storage.get(property); - }, - - /** - * @param {*} value - */ - set: function(value) { - storage.set(property, value); - changedProperties.add(property); - scheduleObserver(); - } - }); - } - - for (var i = 0; i < properties.length; ++i) - defineProperty(properties[i]); - } - - window.Object.observe = objectObserve; - } - - /** @type {!Map<number, string>} */ - var staticKeyIdentifiers = new Map([ - [0x12, 'Alt'], - [0x11, 'Control'], - [0x10, 'Shift'], - [0x14, 'CapsLock'], - [0x5b, 'Win'], - [0x5c, 'Win'], - [0x0c, 'Clear'], - [0x28, 'Down'], - [0x23, 'End'], - [0x0a, 'Enter'], - [0x0d, 'Enter'], - [0x2b, 'Execute'], - [0x70, 'F1'], - [0x71, 'F2'], - [0x72, 'F3'], - [0x73, 'F4'], - [0x74, 'F5'], - [0x75, 'F6'], - [0x76, 'F7'], - [0x77, 'F8'], - [0x78, 'F9'], - [0x79, 'F10'], - [0x7a, 'F11'], - [0x7b, 'F12'], - [0x7c, 'F13'], - [0x7d, 'F14'], - [0x7e, 'F15'], - [0x7f, 'F16'], - [0x80, 'F17'], - [0x81, 'F18'], - [0x82, 'F19'], - [0x83, 'F20'], - [0x84, 'F21'], - [0x85, 'F22'], - [0x86, 'F23'], - [0x87, 'F24'], - [0x2f, 'Help'], - [0x24, 'Home'], - [0x2d, 'Insert'], - [0x25, 'Left'], - [0x22, 'PageDown'], - [0x21, 'PageUp'], - [0x13, 'Pause'], - [0x2c, 'PrintScreen'], - [0x27, 'Right'], - [0x91, 'Scroll'], - [0x29, 'Select'], - [0x26, 'Up'], - [0x2e, 'U+007F'], // Standard says that DEL becomes U+007F. - [0xb0, 'MediaNextTrack'], - [0xb1, 'MediaPreviousTrack'], - [0xb2, 'MediaStop'], - [0xb3, 'MediaPlayPause'], - [0xad, 'VolumeMute'], - [0xae, 'VolumeDown'], - [0xaf, 'VolumeUp'], - ]); - - /** - * @param {number} keyCode - * @return {string} - */ - function keyCodeToKeyIdentifier(keyCode) { - var result = staticKeyIdentifiers.get(keyCode); - if (result !== undefined) - return result; - result = 'U+'; - var hexString = keyCode.toString(16).toUpperCase(); - for (var i = hexString.length; i < 4; ++i) - result += '0'; - result += hexString; - return result; - } - - function installBackwardsCompatibility() { - if (window.location.search.indexOf('remoteFrontend') === -1) - return; - - // Support for legacy (<M53) frontends. - if (!window.KeyboardEvent.prototype.hasOwnProperty('key')) { - Object.defineProperty(window.KeyboardEvent.prototype, 'key', { - /** - * @return {string} - * @this {KeyboardEvent} - */ - get: function() { - return keyCodeToKeyIdentifier(this.keyCode); - } - }); - } - - // Support for legacy (<M50) frontends. - installObjectObserve(); - - /** - * @param {string} property - * @return {!CSSValue|null} - * @this {CSSStyleDeclaration} - */ - function getValue(property) { - // Note that |property| comes from another context, so we can't use === here. - // eslint-disable-next-line eqeqeq - if (property == 'padding-left') { - return /** @type {!CSSValue} */ ({ - /** - * @return {number} - * @this {!{__paddingLeft: number}} - */ - getFloatValue: function() { - return this.__paddingLeft; - }, - __paddingLeft: parseFloat(this.paddingLeft) - }); - } - throw new Error('getPropertyCSSValue is undefined'); - } - - // Support for legacy (<M41) frontends. - window.CSSStyleDeclaration.prototype.getPropertyCSSValue = getValue; - - function CSSPrimitiveValue() { - } - CSSPrimitiveValue.CSS_PX = 5; - window.CSSPrimitiveValue = CSSPrimitiveValue; - - // Support for legacy (<M44) frontends. - var styleElement = window.document.createElement('style'); - styleElement.type = 'text/css'; - styleElement.textContent = 'html /deep/ * { min-width: 0; min-height: 0; }'; - - // Support for quirky border-image behavior (<M51), see: - // https://bugs.chromium.org/p/chromium/issues/detail?id=559258 - styleElement.textContent += - '\nhtml /deep/ .cm-breakpoint .CodeMirror-linenumber { border-style: solid !important; }'; - styleElement.textContent += - '\nhtml /deep/ .cm-breakpoint.cm-breakpoint-conditional .CodeMirror-linenumber { border-style: solid !important; }'; - window.document.head.appendChild(styleElement); - - // Support for legacy (<M49) frontends. - Event.prototype.deepPath = undefined; - - // Support for legacy (<53) frontends. - window.FileError = /** @type {!function (new: FileError) : ?} */ ({ - NOT_FOUND_ERR: DOMException.NOT_FOUND_ERR, - ABORT_ERR: DOMException.ABORT_ERR, - INVALID_MODIFICATION_ERR: DOMException.INVALID_MODIFICATION_ERR, - NOT_READABLE_ERR: 0 // No matching DOMException, so code will be 0. - }); - } - - function windowLoaded() { - window.removeEventListener('DOMContentLoaded', windowLoaded, false); - installBackwardsCompatibility(); - } - - if (window.document.head && - (window.document.readyState === 'complete' || window.document.readyState === 'interactive')) - installBackwardsCompatibility(); - else - window.addEventListener('DOMContentLoaded', windowLoaded, false); - - /** @type {(!function(string, boolean=):boolean)|undefined} */ - DOMTokenList.prototype.__originalDOMTokenListToggle; - - if (!DOMTokenList.prototype.__originalDOMTokenListToggle) { - DOMTokenList.prototype.__originalDOMTokenListToggle = DOMTokenList.prototype.toggle; - /** - * @param {string} token - * @param {boolean=} force - * @return {boolean} - */ - DOMTokenList.prototype.toggle = function(token, force) { - if (arguments.length === 1) - force = !this.contains(token); - return this.__originalDOMTokenListToggle(token, !!force); - }; - } - -})(window);
diff --git a/src/cobalt/debug/content/devtools/devtools_extension_api.js b/src/cobalt/debug/content/devtools/devtools_extension_api.js deleted file mode 100644 index 635f1d2..0000000 --- a/src/cobalt/debug/content/devtools/devtools_extension_api.js +++ /dev/null
@@ -1,957 +0,0 @@ -(function() { - /* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* eslint-disable indent */ - -function defineCommonExtensionSymbols(apiPrivate) { - if (!apiPrivate.audits) - apiPrivate.audits = {}; - apiPrivate.audits.Severity = {Info: 'info', Warning: 'warning', Severe: 'severe'}; - - if (!apiPrivate.panels) - apiPrivate.panels = {}; - apiPrivate.panels.SearchAction = { - CancelSearch: 'cancelSearch', - PerformSearch: 'performSearch', - NextSearchResult: 'nextSearchResult', - PreviousSearchResult: 'previousSearchResult' - }; - - /** @enum {string} */ - apiPrivate.Events = { - AuditStarted: 'audit-started-', - ButtonClicked: 'button-clicked-', - PanelObjectSelected: 'panel-objectSelected-', - NetworkRequestFinished: 'network-request-finished', - OpenResource: 'open-resource', - PanelSearch: 'panel-search-', - RecordingStarted: 'trace-recording-started-', - RecordingStopped: 'trace-recording-stopped-', - ResourceAdded: 'resource-added', - ResourceContentCommitted: 'resource-content-committed', - ViewShown: 'view-shown-', - ViewHidden: 'view-hidden-' - }; - - /** @enum {string} */ - apiPrivate.Commands = { - AddAuditCategory: 'addAuditCategory', - AddAuditResult: 'addAuditResult', - AddRequestHeaders: 'addRequestHeaders', - AddTraceProvider: 'addTraceProvider', - ApplyStyleSheet: 'applyStyleSheet', - CompleteTraceSession: 'completeTraceSession', - CreatePanel: 'createPanel', - CreateSidebarPane: 'createSidebarPane', - CreateToolbarButton: 'createToolbarButton', - EvaluateOnInspectedPage: 'evaluateOnInspectedPage', - ForwardKeyboardEvent: '_forwardKeyboardEvent', - GetHAR: 'getHAR', - GetPageResources: 'getPageResources', - GetRequestContent: 'getRequestContent', - GetResourceContent: 'getResourceContent', - InspectedURLChanged: 'inspectedURLChanged', - OpenResource: 'openResource', - Reload: 'Reload', - Subscribe: 'subscribe', - SetOpenResourceHandler: 'setOpenResourceHandler', - SetResourceContent: 'setResourceContent', - SetSidebarContent: 'setSidebarContent', - SetSidebarHeight: 'setSidebarHeight', - SetSidebarPage: 'setSidebarPage', - ShowPanel: 'showPanel', - StopAuditCategoryRun: 'stopAuditCategoryRun', - Unsubscribe: 'unsubscribe', - UpdateAuditProgress: 'updateAuditProgress', - UpdateButton: 'updateButton' - }; -} - -/** - * @param {!ExtensionDescriptor} extensionInfo - * @param {string} inspectedTabId - * @param {string} themeName - * @param {number} injectedScriptId - * @param {function(!Object, !Object)} testHook - * @suppressGlobalPropertiesCheck - */ -function injectedExtensionAPI(extensionInfo, inspectedTabId, themeName, testHook, injectedScriptId) { - var apiPrivate = {}; - - defineCommonExtensionSymbols(apiPrivate); - - var commands = apiPrivate.Commands; - var events = apiPrivate.Events; - var userAction = false; - - // Here and below, all constructors are private to API implementation. - // For a public type Foo, if internal fields are present, these are on - // a private FooImpl type, an instance of FooImpl is used in a closure - // by Foo consutrctor to re-bind publicly exported members to an instance - // of Foo. - - /** - * @constructor - */ - function EventSinkImpl(type, customDispatch) { - this._type = type; - this._listeners = []; - this._customDispatch = customDispatch; - } - - EventSinkImpl.prototype = { - addListener: function(callback) { - if (typeof callback !== 'function') - throw 'addListener: callback is not a function'; - if (this._listeners.length === 0) - extensionServer.sendRequest({command: commands.Subscribe, type: this._type}); - this._listeners.push(callback); - extensionServer.registerHandler('notify-' + this._type, this._dispatch.bind(this)); - }, - - removeListener: function(callback) { - var listeners = this._listeners; - - for (var i = 0; i < listeners.length; ++i) { - if (listeners[i] === callback) { - listeners.splice(i, 1); - break; - } - } - if (this._listeners.length === 0) - extensionServer.sendRequest({command: commands.Unsubscribe, type: this._type}); - }, - - /** - * @param {...} vararg - */ - _fire: function(vararg) { - var listeners = this._listeners.slice(); - for (var i = 0; i < listeners.length; ++i) - listeners[i].apply(null, arguments); - }, - - _dispatch: function(request) { - if (this._customDispatch) - this._customDispatch.call(this, request); - else - this._fire.apply(this, request.arguments); - } - }; - - /** - * @constructor - */ - function InspectorExtensionAPI() { - this.audits = new Audits(); - this.inspectedWindow = new InspectedWindow(); - this.panels = new Panels(); - this.network = new Network(); - this.timeline = new Timeline(); - defineDeprecatedProperty(this, 'webInspector', 'resources', 'network'); - } - - /** - * @constructor - */ - function Network() { - /** - * @this {EventSinkImpl} - */ - function dispatchRequestEvent(message) { - var request = message.arguments[1]; - request.__proto__ = new Request(message.arguments[0]); - this._fire(request); - } - this.onRequestFinished = new EventSink(events.NetworkRequestFinished, dispatchRequestEvent); - defineDeprecatedProperty(this, 'network', 'onFinished', 'onRequestFinished'); - this.onNavigated = new EventSink(events.InspectedURLChanged); - } - - Network.prototype = { - getHAR: function(callback) { - function callbackWrapper(result) { - var entries = (result && result.entries) || []; - for (var i = 0; i < entries.length; ++i) { - entries[i].__proto__ = new Request(entries[i]._requestId); - delete entries[i]._requestId; - } - callback(result); - } - extensionServer.sendRequest({command: commands.GetHAR}, callback && callbackWrapper); - }, - - addRequestHeaders: function(headers) { - extensionServer.sendRequest( - {command: commands.AddRequestHeaders, headers: headers, extensionId: window.location.hostname}); - } - }; - - /** - * @constructor - */ - function RequestImpl(id) { - this._id = id; - } - - RequestImpl.prototype = { - getContent: function(callback) { - function callbackWrapper(response) { - callback(response.content, response.encoding); - } - extensionServer.sendRequest({command: commands.GetRequestContent, id: this._id}, callback && callbackWrapper); - } - }; - - /** - * @constructor - */ - function Panels() { - var panels = { - elements: new ElementsPanel(), - sources: new SourcesPanel(), - }; - - function panelGetter(name) { - return panels[name]; - } - for (var panel in panels) - this.__defineGetter__(panel, panelGetter.bind(null, panel)); - this.applyStyleSheet = function(styleSheet) { - extensionServer.sendRequest({command: commands.ApplyStyleSheet, styleSheet: styleSheet}); - }; - } - - Panels.prototype = { - create: function(title, icon, page, callback) { - var id = 'extension-panel-' + extensionServer.nextObjectId(); - var request = {command: commands.CreatePanel, id: id, title: title, icon: icon, page: page}; - extensionServer.sendRequest(request, callback && callback.bind(this, new ExtensionPanel(id))); - }, - - setOpenResourceHandler: function(callback) { - var hadHandler = extensionServer.hasHandler(events.OpenResource); - - function callbackWrapper(message) { - // Allow the panel to show itself when handling the event. - userAction = true; - try { - callback.call(null, new Resource(message.resource), message.lineNumber); - } finally { - userAction = false; - } - } - - if (!callback) - extensionServer.unregisterHandler(events.OpenResource); - else - extensionServer.registerHandler(events.OpenResource, callbackWrapper); - - // Only send command if we either removed an existing handler or added handler and had none before. - if (hadHandler === !callback) - extensionServer.sendRequest({command: commands.SetOpenResourceHandler, 'handlerPresent': !!callback}); - }, - - openResource: function(url, lineNumber, callback) { - extensionServer.sendRequest({command: commands.OpenResource, 'url': url, 'lineNumber': lineNumber}, callback); - }, - - get SearchAction() { - return apiPrivate.panels.SearchAction; - } - }; - - /** - * @constructor - */ - function ExtensionViewImpl(id) { - this._id = id; - - /** - * @this {EventSinkImpl} - */ - function dispatchShowEvent(message) { - var frameIndex = message.arguments[0]; - if (typeof frameIndex === 'number') - this._fire(window.parent.frames[frameIndex]); - else - this._fire(); - } - - if (id) { - this.onShown = new EventSink(events.ViewShown + id, dispatchShowEvent); - this.onHidden = new EventSink(events.ViewHidden + id); - } - } - - /** - * @constructor - * @extends {ExtensionViewImpl} - * @param {string} hostPanelName - */ - function PanelWithSidebarImpl(hostPanelName) { - ExtensionViewImpl.call(this, null); - this._hostPanelName = hostPanelName; - this.onSelectionChanged = new EventSink(events.PanelObjectSelected + hostPanelName); - } - - PanelWithSidebarImpl.prototype = { - createSidebarPane: function(title, callback) { - var id = 'extension-sidebar-' + extensionServer.nextObjectId(); - var request = {command: commands.CreateSidebarPane, panel: this._hostPanelName, id: id, title: title}; - function callbackWrapper() { - callback(new ExtensionSidebarPane(id)); - } - extensionServer.sendRequest(request, callback && callbackWrapper); - }, - - __proto__: ExtensionViewImpl.prototype - }; - - function declareInterfaceClass(implConstructor) { - return function() { - var impl = {__proto__: implConstructor.prototype}; - implConstructor.apply(impl, arguments); - populateInterfaceClass(this, impl); - }; - } - - function defineDeprecatedProperty(object, className, oldName, newName) { - var warningGiven = false; - function getter() { - if (!warningGiven) { - console.warn(className + '.' + oldName + ' is deprecated. Use ' + className + '.' + newName + ' instead'); - warningGiven = true; - } - return object[newName]; - } - object.__defineGetter__(oldName, getter); - } - - function extractCallbackArgument(args) { - var lastArgument = args[args.length - 1]; - return typeof lastArgument === 'function' ? lastArgument : undefined; - } - - var AuditCategory = declareInterfaceClass(AuditCategoryImpl); - var AuditResult = declareInterfaceClass(AuditResultImpl); - var Button = declareInterfaceClass(ButtonImpl); - var EventSink = declareInterfaceClass(EventSinkImpl); - var ExtensionPanel = declareInterfaceClass(ExtensionPanelImpl); - var ExtensionSidebarPane = declareInterfaceClass(ExtensionSidebarPaneImpl); - var PanelWithSidebar = declareInterfaceClass(PanelWithSidebarImpl); - var Request = declareInterfaceClass(RequestImpl); - var Resource = declareInterfaceClass(ResourceImpl); - var TraceSession = declareInterfaceClass(TraceSessionImpl); - - /** - * @constructor - * @extends {PanelWithSidebar} - */ - function ElementsPanel() { - PanelWithSidebar.call(this, 'elements'); - } - - ElementsPanel.prototype = {__proto__: PanelWithSidebar.prototype}; - - /** - * @constructor - * @extends {PanelWithSidebar} - */ - function SourcesPanel() { - PanelWithSidebar.call(this, 'sources'); - } - - SourcesPanel.prototype = {__proto__: PanelWithSidebar.prototype}; - - /** - * @constructor - * @extends {ExtensionViewImpl} - */ - function ExtensionPanelImpl(id) { - ExtensionViewImpl.call(this, id); - this.onSearch = new EventSink(events.PanelSearch + id); - } - - ExtensionPanelImpl.prototype = { - /** - * @return {!Object} - */ - createStatusBarButton: function(iconPath, tooltipText, disabled) { - var id = 'button-' + extensionServer.nextObjectId(); - var request = { - command: commands.CreateToolbarButton, - panel: this._id, - id: id, - icon: iconPath, - tooltip: tooltipText, - disabled: !!disabled - }; - extensionServer.sendRequest(request); - return new Button(id); - }, - - show: function() { - if (!userAction) - return; - - var request = {command: commands.ShowPanel, id: this._id}; - extensionServer.sendRequest(request); - }, - - __proto__: ExtensionViewImpl.prototype - }; - - /** - * @constructor - * @extends {ExtensionViewImpl} - */ - function ExtensionSidebarPaneImpl(id) { - ExtensionViewImpl.call(this, id); - } - - ExtensionSidebarPaneImpl.prototype = { - setHeight: function(height) { - extensionServer.sendRequest({command: commands.SetSidebarHeight, id: this._id, height: height}); - }, - - setExpression: function(expression, rootTitle, evaluateOptions) { - var request = { - command: commands.SetSidebarContent, - id: this._id, - expression: expression, - rootTitle: rootTitle, - evaluateOnPage: true, - }; - if (typeof evaluateOptions === 'object') - request.evaluateOptions = evaluateOptions; - extensionServer.sendRequest(request, extractCallbackArgument(arguments)); - }, - - setObject: function(jsonObject, rootTitle, callback) { - extensionServer.sendRequest( - {command: commands.SetSidebarContent, id: this._id, expression: jsonObject, rootTitle: rootTitle}, callback); - }, - - setPage: function(page) { - extensionServer.sendRequest({command: commands.SetSidebarPage, id: this._id, page: page}); - }, - - __proto__: ExtensionViewImpl.prototype - }; - - /** - * @constructor - */ - function ButtonImpl(id) { - this._id = id; - this.onClicked = new EventSink(events.ButtonClicked + id); - } - - ButtonImpl.prototype = { - update: function(iconPath, tooltipText, disabled) { - var request = - {command: commands.UpdateButton, id: this._id, icon: iconPath, tooltip: tooltipText, disabled: !!disabled}; - extensionServer.sendRequest(request); - } - }; - - /** - * @constructor - */ - function Timeline() { - } - - Timeline.prototype = { - /** - * @param {string} categoryName - * @param {string} categoryTooltip - * @return {!TraceProvider} - */ - addTraceProvider: function(categoryName, categoryTooltip) { - var id = 'extension-trace-provider-' + extensionServer.nextObjectId(); - extensionServer.sendRequest( - {command: commands.AddTraceProvider, id: id, categoryName: categoryName, categoryTooltip: categoryTooltip}); - return new TraceProvider(id); - } - }; - - /** - * @constructor - * @param {string} id - */ - function TraceSessionImpl(id) { - this._id = id; - } - - TraceSessionImpl.prototype = - { - /** - * @param {string=} url - * @param {number=} timeOffset - */ - complete: function(url, timeOffset) { - var request = {command: commands.CompleteTraceSession, id: this._id, url: url || '', timeOffset: timeOffset || 0}; - extensionServer.sendRequest(request); - } - }; - - /** - * @constructor - * @param {string} id - */ - function TraceProvider(id) { - /** - * @this {EventSinkImpl} - */ - function dispatchRecordingStarted(message) { - var sessionId = message.arguments[0]; - this._fire(new TraceSession(sessionId)); - } - - this.onRecordingStarted = new EventSink(events.RecordingStarted + id, dispatchRecordingStarted); - this.onRecordingStopped = new EventSink(events.RecordingStopped + id); - } - - /** - * @constructor - */ - function Audits() {} - - Audits.prototype = { - /** - * @return {!AuditCategory} - */ - addCategory: function(displayName, resultCount) { - var id = 'extension-audit-category-' + extensionServer.nextObjectId(); - if (typeof resultCount !== 'undefined') { - console.warn( - 'Passing resultCount to audits.addCategory() is deprecated. Use AuditResult.updateProgress() instead.'); - } - extensionServer.sendRequest( - {command: commands.AddAuditCategory, id: id, displayName: displayName, resultCount: resultCount}); - return new AuditCategory(id); - } - }; - - /** - * @constructor - */ - function AuditCategoryImpl(id) { - /** - * @this {EventSinkImpl} - */ - function dispatchAuditEvent(request) { - var auditResult = new AuditResult(request.arguments[0]); - try { - this._fire(auditResult); - } catch (e) { - console.error('Uncaught exception in extension audit event handler: ' + e); - auditResult.done(); - } - } - this._id = id; - this.onAuditStarted = new EventSink(events.AuditStarted + id, dispatchAuditEvent); - } - - /** - * @constructor - */ - function AuditResultImpl(id) { - this._id = id; - - this.createURL = this._nodeFactory.bind(this, 'url'); - this.createSnippet = this._nodeFactory.bind(this, 'snippet'); - this.createText = this._nodeFactory.bind(this, 'text'); - this.createObject = this._nodeFactory.bind(this, 'object'); - this.createNode = this._nodeFactory.bind(this, 'node'); - } - - AuditResultImpl.prototype = { - addResult: function(displayName, description, severity, details) { - // shorthand for specifying details directly in addResult(). - if (details && !(details instanceof AuditResultNode)) - details = new AuditResultNode(Array.isArray(details) ? details : [details]); - - var request = { - command: commands.AddAuditResult, - resultId: this._id, - displayName: displayName, - description: description, - severity: severity, - details: details - }; - extensionServer.sendRequest(request); - }, - - /** - * @return {!Object} - */ - createResult: function() { - return new AuditResultNode(Array.prototype.slice.call(arguments)); - }, - - updateProgress: function(worked, totalWork) { - extensionServer.sendRequest( - {command: commands.UpdateAuditProgress, resultId: this._id, progress: worked / totalWork}); - }, - - done: function() { - extensionServer.sendRequest({command: commands.StopAuditCategoryRun, resultId: this._id}); - }, - - /** - * @type {!Object.<string, string>} - */ - get Severity() { - return apiPrivate.audits.Severity; - }, - - /** - * @return {!{type: string, arguments: !Array.<string|number>}} - */ - createResourceLink: function(url, lineNumber) { - return {type: 'resourceLink', arguments: [url, lineNumber && lineNumber - 1]}; - }, - - /** - * @return {!{type: string, arguments: !Array.<string|number>}} - */ - _nodeFactory: function(type) { - return {type: type, arguments: Array.prototype.slice.call(arguments, 1)}; - } - }; - - /** - * @constructor - */ - function AuditResultNode(contents) { - this.contents = contents; - this.children = []; - this.expanded = false; - } - - AuditResultNode.prototype = { - /** - * @return {!Object} - */ - addChild: function() { - var node = new AuditResultNode(Array.prototype.slice.call(arguments)); - this.children.push(node); - return node; - } - }; - - /** - * @constructor - */ - function InspectedWindow() { - /** - * @this {EventSinkImpl} - */ - function dispatchResourceEvent(message) { - this._fire(new Resource(message.arguments[0])); - } - - /** - * @this {EventSinkImpl} - */ - function dispatchResourceContentEvent(message) { - this._fire(new Resource(message.arguments[0]), message.arguments[1]); - } - - this.onResourceAdded = new EventSink(events.ResourceAdded, dispatchResourceEvent); - this.onResourceContentCommitted = new EventSink(events.ResourceContentCommitted, dispatchResourceContentEvent); - } - - InspectedWindow.prototype = { - reload: function(optionsOrUserAgent) { - var options = null; - if (typeof optionsOrUserAgent === 'object') { - options = optionsOrUserAgent; - } else if (typeof optionsOrUserAgent === 'string') { - options = {userAgent: optionsOrUserAgent}; - console.warn( - 'Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. ' + - 'Use inspectedWindow.reload({ userAgent: value}) instead.'); - } - extensionServer.sendRequest({command: commands.Reload, options: options}); - }, - - /** - * @return {?Object} - */ - eval: function(expression, evaluateOptions) { - var callback = extractCallbackArgument(arguments); - function callbackWrapper(result) { - if (result.isError || result.isException) - callback(undefined, result); - else - callback(result.value); - } - var request = {command: commands.EvaluateOnInspectedPage, expression: expression}; - if (typeof evaluateOptions === 'object') - request.evaluateOptions = evaluateOptions; - extensionServer.sendRequest(request, callback && callbackWrapper); - return null; - }, - - getResources: function(callback) { - function wrapResource(resourceData) { - return new Resource(resourceData); - } - function callbackWrapper(resources) { - callback(resources.map(wrapResource)); - } - extensionServer.sendRequest({command: commands.GetPageResources}, callback && callbackWrapper); - } - }; - - /** - * @constructor - */ - function ResourceImpl(resourceData) { - this._url = resourceData.url; - this._type = resourceData.type; - } - - ResourceImpl.prototype = { - get url() { - return this._url; - }, - - get type() { - return this._type; - }, - - getContent: function(callback) { - function callbackWrapper(response) { - callback(response.content, response.encoding); - } - - extensionServer.sendRequest({command: commands.GetResourceContent, url: this._url}, callback && callbackWrapper); - }, - - setContent: function(content, commit, callback) { - extensionServer.sendRequest( - {command: commands.SetResourceContent, url: this._url, content: content, commit: commit}, callback); - } - }; - - function getTabId() { - return inspectedTabId; - } - - var keyboardEventRequestQueue = []; - var forwardTimer = null; - - function forwardKeyboardEvent(event) { - // We only care about global hotkeys, not about random text - if (!event.ctrlKey && !event.altKey && !event.metaKey && !/^F\d+$/.test(event.key) && event.key !== 'Escape') - return; - var requestPayload = { - eventType: event.type, - ctrlKey: event.ctrlKey, - altKey: event.altKey, - metaKey: event.metaKey, - key: event.key, - key: event.key, - code: event.code, - location: event.location, - keyCode: event.keyCode - }; - keyboardEventRequestQueue.push(requestPayload); - if (!forwardTimer) - forwardTimer = setTimeout(forwardEventQueue, 0); - } - - function forwardEventQueue() { - forwardTimer = null; - var request = {command: commands.ForwardKeyboardEvent, entries: keyboardEventRequestQueue}; - extensionServer.sendRequest(request); - keyboardEventRequestQueue = []; - } - - document.addEventListener('keydown', forwardKeyboardEvent, false); - document.addEventListener('keypress', forwardKeyboardEvent, false); - - /** - * @constructor - */ - function ExtensionServerClient() { - this._callbacks = {}; - this._handlers = {}; - this._lastRequestId = 0; - this._lastObjectId = 0; - - this.registerHandler('callback', this._onCallback.bind(this)); - - var channel = new MessageChannel(); - this._port = channel.port1; - this._port.addEventListener('message', this._onMessage.bind(this), false); - this._port.start(); - - window.parent.postMessage('registerExtension', '*', [channel.port2]); - } - - ExtensionServerClient.prototype = { - /** - * @param {!Object} message - * @param {function()=} callback - */ - sendRequest: function(message, callback) { - if (typeof callback === 'function') - message.requestId = this._registerCallback(callback); - this._port.postMessage(message); - }, - - /** - * @return {boolean} - */ - hasHandler: function(command) { - return !!this._handlers[command]; - }, - - registerHandler: function(command, handler) { - this._handlers[command] = handler; - }, - - unregisterHandler: function(command) { - delete this._handlers[command]; - }, - - /** - * @return {string} - */ - nextObjectId: function() { - return injectedScriptId.toString() + '_' + ++this._lastObjectId; - }, - - _registerCallback: function(callback) { - var id = ++this._lastRequestId; - this._callbacks[id] = callback; - return id; - }, - - _onCallback: function(request) { - if (request.requestId in this._callbacks) { - var callback = this._callbacks[request.requestId]; - delete this._callbacks[request.requestId]; - callback(request.result); - } - }, - - _onMessage: function(event) { - var request = event.data; - var handler = this._handlers[request.command]; - if (handler) - handler.call(this, request); - } - }; - - function populateInterfaceClass(interfaze, implementation) { - for (var member in implementation) { - if (member.charAt(0) === '_') - continue; - var descriptor = null; - // Traverse prototype chain until we find the owner. - for (var owner = implementation; owner && !descriptor; owner = owner.__proto__) - descriptor = Object.getOwnPropertyDescriptor(owner, member); - if (!descriptor) - continue; - if (typeof descriptor.value === 'function') - interfaze[member] = descriptor.value.bind(implementation); - else if (typeof descriptor.get === 'function') - interfaze.__defineGetter__(member, descriptor.get.bind(implementation)); - else - Object.defineProperty(interfaze, member, descriptor); - } - } - - var extensionServer = new ExtensionServerClient(); - var coreAPI = new InspectorExtensionAPI(); - - var chrome = window.chrome || {}; - // Override chrome.devtools as a workaround for a error-throwing getter being exposed - // in extension pages loaded into a non-extension process (only happens for remote client - // extensions) - var devtools_descriptor = Object.getOwnPropertyDescriptor(chrome, 'devtools'); - if (!devtools_descriptor || devtools_descriptor.get) - Object.defineProperty(chrome, 'devtools', {value: {}, enumerable: true}); - - // Only expose tabId on chrome.devtools.inspectedWindow, not webInspector.inspectedWindow. - chrome.devtools.inspectedWindow = {}; - chrome.devtools.inspectedWindow.__defineGetter__('tabId', getTabId); - chrome.devtools.inspectedWindow.__proto__ = coreAPI.inspectedWindow; - chrome.devtools.network = coreAPI.network; - chrome.devtools.panels = coreAPI.panels; - chrome.devtools.panels.themeName = themeName; - - // default to expose experimental APIs for now. - if (extensionInfo.exposeExperimentalAPIs !== false) { - chrome.experimental = chrome.experimental || {}; - chrome.experimental.devtools = chrome.experimental.devtools || {}; - - var properties = Object.getOwnPropertyNames(coreAPI); - for (var i = 0; i < properties.length; ++i) { - var descriptor = Object.getOwnPropertyDescriptor(coreAPI, properties[i]); - if (descriptor) - Object.defineProperty(chrome.experimental.devtools, properties[i], descriptor); - } - chrome.experimental.devtools.inspectedWindow = chrome.devtools.inspectedWindow; - } - - if (extensionInfo.exposeWebInspectorNamespace) - window.webInspector = coreAPI; - testHook(extensionServer, coreAPI); -} - -/** - * @param {!ExtensionDescriptor} extensionInfo - * @param {string} inspectedTabId - * @param {string} themeName - * @param {function(!Object, !Object)|undefined} testHook - * @return {string} - */ -function buildExtensionAPIInjectedScript(extensionInfo, inspectedTabId, themeName, testHook) { - var argumentsJSON = [extensionInfo, inspectedTabId || null, themeName].map(_ => JSON.stringify(_)).join(','); - if (!testHook) - testHook = () => {}; - return '(function(injectedScriptId){ ' + defineCommonExtensionSymbols.toString() + ';' + - '(' + injectedExtensionAPI.toString() + ')(' + argumentsJSON + ',' + testHook + ', injectedScriptId);' + - '})'; -} - - var tabId; - var extensionInfo = {}; - var extensionServer; - platformExtensionAPI(injectedExtensionAPI("remote-" + window.parent.frames.length)); - })(); \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/devtools_resources.grd b/src/cobalt/debug/content/devtools/devtools_resources.grd deleted file mode 100644 index 7a20027..0000000 --- a/src/cobalt/debug/content/devtools/devtools_resources.grd +++ /dev/null
@@ -1,128 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?><grit current_release="1" latest_public_release="0" output_all_resource_defines="false"> - <outputs> - <output filename="grit/devtools_resources.h" type="rc_header"> - <emit emit_type="prepend"/> - </output> - <output filename="grit/devtools_resources_map.cc" type="resource_file_map_source"/> - <output filename="grit/devtools_resources_map.h" type="resource_map_header"/> - - <output filename="devtools_resources.pak" type="data_package"/> - </outputs> - <release seq="1"> - <includes> - <include file="${compressed_protocol_file}" name="COMPRESSED_PROTOCOL_JSON" type="BINDATA" use_base_dir="false"/> - - <include file="inspector.html" name="INSPECTOR_HTML" type="BINDATA"/> - <include file="inspector.js" name="INSPECTOR_JS" type="BINDATA"/> - <include file="toolbox.html" name="TOOLBOX_HTML" type="BINDATA"/> - <include file="toolbox.js" name="TOOLBOX_JS" type="BINDATA"/> - <include file="audits2_worker.js" name="AUDITS2_WORKER_JS" type="BINDATA"/> - <include file="formatter_worker.js" name="FORMATTER_WORKER_JS" type="BINDATA"/> - <include file="heap_snapshot_worker.js" name="HEAP_SNAPSHOT_WORKER_JS" type="BINDATA"/> - <include file="animation/animation_module.js" name="ANIMATION_ANIMATION_MODULE_JS" type="BINDATA"/> - <include file="audits2/audits2_module.js" name="AUDITS2_AUDITS2_MODULE_JS" type="BINDATA"/> - <include file="changes/changes_module.js" name="CHANGES_CHANGES_MODULE_JS" type="BINDATA"/> - <include file="cm/cm_module.js" name="CM_CM_MODULE_JS" type="BINDATA"/> - <include file="color_picker/color_picker_module.js" name="COLOR_PICKER_COLOR_PICKER_MODULE_JS" type="BINDATA"/> - <include file="console/console_module.js" name="CONSOLE_CONSOLE_MODULE_JS" type="BINDATA"/> - <include file="cookie_table/cookie_table_module.js" name="COOKIE_TABLE_COOKIE_TABLE_MODULE_JS" type="BINDATA"/> - <include file="coverage/coverage_module.js" name="COVERAGE_COVERAGE_MODULE_JS" type="BINDATA"/> - <include file="data_grid/data_grid_module.js" name="DATA_GRID_DATA_GRID_MODULE_JS" type="BINDATA"/> - <include file="devices/devices_module.js" name="DEVICES_DEVICES_MODULE_JS" type="BINDATA"/> - <include file="diff/diff_module.js" name="DIFF_DIFF_MODULE_JS" type="BINDATA"/> - <include file="elements/elements_module.js" name="ELEMENTS_ELEMENTS_MODULE_JS" type="BINDATA"/> - <include file="event_listeners/event_listeners_module.js" name="EVENT_LISTENERS_EVENT_LISTENERS_MODULE_JS" type="BINDATA"/> - <include file="formatter/formatter_module.js" name="FORMATTER_FORMATTER_MODULE_JS" type="BINDATA"/> - <include file="har_importer/har_importer_module.js" name="HAR_IMPORTER_HAR_IMPORTER_MODULE_JS" type="BINDATA"/> - <include file="heap_snapshot_model/heap_snapshot_model_module.js" name="HEAP_SNAPSHOT_MODEL_HEAP_SNAPSHOT_MODEL_MODULE_JS" type="BINDATA"/> - <include file="inline_editor/inline_editor_module.js" name="INLINE_EDITOR_INLINE_EDITOR_MODULE_JS" type="BINDATA"/> - <include file="layer_viewer/layer_viewer_module.js" name="LAYER_VIEWER_LAYER_VIEWER_MODULE_JS" type="BINDATA"/> - <include file="layers/layers_module.js" name="LAYERS_LAYERS_MODULE_JS" type="BINDATA"/> - <include file="network/network_module.js" name="NETWORK_NETWORK_MODULE_JS" type="BINDATA"/> - <include file="network_priorities/network_priorities_module.js" name="NETWORK_PRIORITIES_NETWORK_PRIORITIES_MODULE_JS" type="BINDATA"/> - <include file="object_ui/object_ui_module.js" name="OBJECT_UI_OBJECT_UI_MODULE_JS" type="BINDATA"/> - <include file="perf_ui/perf_ui_module.js" name="PERF_UI_PERF_UI_MODULE_JS" type="BINDATA"/> - <include file="profiler/profiler_module.js" name="PROFILER_PROFILER_MODULE_JS" type="BINDATA"/> - <include file="quick_open/quick_open_module.js" name="QUICK_OPEN_QUICK_OPEN_MODULE_JS" type="BINDATA"/> - <include file="resources/resources_module.js" name="RESOURCES_RESOURCES_MODULE_JS" type="BINDATA"/> - <include file="sass/sass_module.js" name="SASS_SASS_MODULE_JS" type="BINDATA"/> - <include file="security/security_module.js" name="SECURITY_SECURITY_MODULE_JS" type="BINDATA"/> - <include file="settings/settings_module.js" name="SETTINGS_SETTINGS_MODULE_JS" type="BINDATA"/> - <include file="snippets/snippets_module.js" name="SNIPPETS_SNIPPETS_MODULE_JS" type="BINDATA"/> - <include file="source_frame/source_frame_module.js" name="SOURCE_FRAME_SOURCE_FRAME_MODULE_JS" type="BINDATA"/> - <include file="sources/sources_module.js" name="SOURCES_SOURCES_MODULE_JS" type="BINDATA"/> - <include file="text_editor/text_editor_module.js" name="TEXT_EDITOR_TEXT_EDITOR_MODULE_JS" type="BINDATA"/> - <include file="timeline_model/timeline_model_module.js" name="TIMELINE_MODEL_TIMELINE_MODEL_MODULE_JS" type="BINDATA"/> - <include file="timeline/timeline_module.js" name="TIMELINE_TIMELINE_MODULE_JS" type="BINDATA"/> - <include file="workspace_diff/workspace_diff_module.js" name="WORKSPACE_DIFF_WORKSPACE_DIFF_MODULE_JS" type="BINDATA"/> - <include file="devtools_extension_api.js" name="DEVTOOLS_EXTENSION_API_JS" type="BINDATA"/> - <include file="devtools_compatibility.js" name="DEVTOOLS_COMPATIBILITY_JS" type="BINDATA"/> - <include file="Tests.js" name="TESTS_JS" type="BINDATA"/> - <include file="Images/accelerometer-back.png" name="IMAGES_ACCELEROMETER_BACK_PNG" type="BINDATA"/> - <include file="Images/accelerometer-bottom.png" name="IMAGES_ACCELEROMETER_BOTTOM_PNG" type="BINDATA"/> - <include file="Images/accelerometer-front.png" name="IMAGES_ACCELEROMETER_FRONT_PNG" type="BINDATA"/> - <include file="Images/accelerometer-left.png" name="IMAGES_ACCELEROMETER_LEFT_PNG" type="BINDATA"/> - <include file="Images/accelerometer-right.png" name="IMAGES_ACCELEROMETER_RIGHT_PNG" type="BINDATA"/> - <include file="Images/accelerometer-top.png" name="IMAGES_ACCELEROMETER_TOP_PNG" type="BINDATA"/> - <include file="Images/audits_logo.svg" name="IMAGES_AUDITS_LOGO_SVG" type="BINDATA"/> - <include file="Images/breakpoint.png" name="IMAGES_BREAKPOINT_PNG" type="BINDATA"/> - <include file="Images/breakpointConditional.png" name="IMAGES_BREAKPOINTCONDITIONAL_PNG" type="BINDATA"/> - <include file="Images/breakpointConditional_2x.png" name="IMAGES_BREAKPOINTCONDITIONAL_2X_PNG" type="BINDATA"/> - <include file="Images/breakpoint_2x.png" name="IMAGES_BREAKPOINT_2X_PNG" type="BINDATA"/> - <include file="Images/checkboxCheckmark.png" name="IMAGES_CHECKBOXCHECKMARK_PNG" type="BINDATA"/> - <include file="Images/checkboxCheckmark_2x.png" name="IMAGES_CHECKBOXCHECKMARK_2X_PNG" type="BINDATA"/> - <include file="Images/checker.png" name="IMAGES_CHECKER_PNG" type="BINDATA"/> - <include file="Images/chevrons.png" name="IMAGES_CHEVRONS_PNG" type="BINDATA"/> - <include file="Images/chevrons_2x.png" name="IMAGES_CHEVRONS_2X_PNG" type="BINDATA"/> - <include file="Images/chromeDisabledSelect.png" name="IMAGES_CHROMEDISABLEDSELECT_PNG" type="BINDATA"/> - <include file="Images/chromeDisabledSelect_2x.png" name="IMAGES_CHROMEDISABLEDSELECT_2X_PNG" type="BINDATA"/> - <include file="Images/chromeLeft.png" name="IMAGES_CHROMELEFT_PNG" type="BINDATA"/> - <include file="Images/chromeMiddle.png" name="IMAGES_CHROMEMIDDLE_PNG" type="BINDATA"/> - <include file="Images/chromeRight.png" name="IMAGES_CHROMERIGHT_PNG" type="BINDATA"/> - <include file="Images/chromeSelect.png" name="IMAGES_CHROMESELECT_PNG" type="BINDATA"/> - <include file="Images/chromeSelect_2x.png" name="IMAGES_CHROMESELECT_2X_PNG" type="BINDATA"/> - <include file="Images/deleteIcon.png" name="IMAGES_DELETEICON_PNG" type="BINDATA"/> - <include file="Images/errorWave.png" name="IMAGES_ERRORWAVE_PNG" type="BINDATA"/> - <include file="Images/errorWave_2x.png" name="IMAGES_ERRORWAVE_2X_PNG" type="BINDATA"/> - <include file="Images/ic_info_black_18dp.svg" name="IMAGES_IC_INFO_BLACK_18DP_SVG" type="BINDATA"/> - <include file="Images/ic_warning_black_18dp.svg" name="IMAGES_IC_WARNING_BLACK_18DP_SVG" type="BINDATA"/> - <include file="Images/largeIcons.png" name="IMAGES_LARGEICONS_PNG" type="BINDATA"/> - <include file="Images/largeIcons_2x.png" name="IMAGES_LARGEICONS_2X_PNG" type="BINDATA"/> - <include file="Images/mediumIcons.png" name="IMAGES_MEDIUMICONS_PNG" type="BINDATA"/> - <include file="Images/mediumIcons_2x.png" name="IMAGES_MEDIUMICONS_2X_PNG" type="BINDATA"/> - <include file="Images/navigationControls.png" name="IMAGES_NAVIGATIONCONTROLS_PNG" type="BINDATA"/> - <include file="Images/navigationControls_2x.png" name="IMAGES_NAVIGATIONCONTROLS_2X_PNG" type="BINDATA"/> - <include file="Images/nodeIcon.png" name="IMAGES_NODEICON_PNG" type="BINDATA"/> - <include file="Images/popoverArrows.png" name="IMAGES_POPOVERARROWS_PNG" type="BINDATA"/> - <include file="Images/profileGroupIcon.png" name="IMAGES_PROFILEGROUPICON_PNG" type="BINDATA"/> - <include file="Images/profileIcon.png" name="IMAGES_PROFILEICON_PNG" type="BINDATA"/> - <include file="Images/profileSmallIcon.png" name="IMAGES_PROFILESMALLICON_PNG" type="BINDATA"/> - <include file="Images/radioDot.png" name="IMAGES_RADIODOT_PNG" type="BINDATA"/> - <include file="Images/resizeDiagonal.png" name="IMAGES_RESIZEDIAGONAL_PNG" type="BINDATA"/> - <include file="Images/resizeDiagonal_2x.png" name="IMAGES_RESIZEDIAGONAL_2X_PNG" type="BINDATA"/> - <include file="Images/resizeHorizontal.png" name="IMAGES_RESIZEHORIZONTAL_PNG" type="BINDATA"/> - <include file="Images/resizeHorizontal_2x.png" name="IMAGES_RESIZEHORIZONTAL_2X_PNG" type="BINDATA"/> - <include file="Images/resizeVertical.png" name="IMAGES_RESIZEVERTICAL_PNG" type="BINDATA"/> - <include file="Images/resizeVertical_2x.png" name="IMAGES_RESIZEVERTICAL_2X_PNG" type="BINDATA"/> - <include file="Images/resourceCSSIcon.png" name="IMAGES_RESOURCECSSICON_PNG" type="BINDATA"/> - <include file="Images/resourceDocumentIcon.png" name="IMAGES_RESOURCEDOCUMENTICON_PNG" type="BINDATA"/> - <include file="Images/resourceDocumentIconSmall.png" name="IMAGES_RESOURCEDOCUMENTICONSMALL_PNG" type="BINDATA"/> - <include file="Images/resourceJSIcon.png" name="IMAGES_RESOURCEJSICON_PNG" type="BINDATA"/> - <include file="Images/resourcePlainIcon.png" name="IMAGES_RESOURCEPLAINICON_PNG" type="BINDATA"/> - <include file="Images/resourcePlainIconSmall.png" name="IMAGES_RESOURCEPLAINICONSMALL_PNG" type="BINDATA"/> - <include file="Images/resourcesTimeGraphIcon.png" name="IMAGES_RESOURCESTIMEGRAPHICON_PNG" type="BINDATA"/> - <include file="Images/searchNext.png" name="IMAGES_SEARCHNEXT_PNG" type="BINDATA"/> - <include file="Images/searchPrev.png" name="IMAGES_SEARCHPREV_PNG" type="BINDATA"/> - <include file="Images/securityIcons.png" name="IMAGES_SECURITYICONS_PNG" type="BINDATA"/> - <include file="Images/securityIcons_2x.png" name="IMAGES_SECURITYICONS_2X_PNG" type="BINDATA"/> - <include file="Images/smallIcons.png" name="IMAGES_SMALLICONS_PNG" type="BINDATA"/> - <include file="Images/smallIcons_2x.png" name="IMAGES_SMALLICONS_2X_PNG" type="BINDATA"/> - <include file="Images/speech.png" name="IMAGES_SPEECH_PNG" type="BINDATA"/> - <include file="Images/toolbarResizerVertical.png" name="IMAGES_TOOLBARRESIZERVERTICAL_PNG" type="BINDATA"/> - <include file="Images/touchCursor.png" name="IMAGES_TOUCHCURSOR_PNG" type="BINDATA"/> - <include file="Images/touchCursor_2x.png" name="IMAGES_TOUCHCURSOR_2X_PNG" type="BINDATA"/> - <include file="Images/treeoutlineTriangles.png" name="IMAGES_TREEOUTLINETRIANGLES_PNG" type="BINDATA"/> - <include file="Images/treeoutlineTriangles_2x.png" name="IMAGES_TREEOUTLINETRIANGLES_2X_PNG" type="BINDATA"/> - <include file="Images/whatsnew.png" name="IMAGES_WHATSNEW_PNG" type="BINDATA"/></includes> - </release> -</grit> \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/diff/diff_module.js b/src/cobalt/debug/content/devtools/diff/diff_module.js deleted file mode 100644 index aba0172..0000000 --- a/src/cobalt/debug/content/devtools/diff/diff_module.js +++ /dev/null
@@ -1,10 +0,0 @@ -Diff.Diff={charDiff:function(text1,text2,cleanup){var differ=new diff_match_patch();var diff=differ.diff_main(text1,text2);if(cleanup) -differ.diff_cleanupSemantic(diff);return diff;},lineDiff:function(lines1,lines2){var idMap=new Common.CharacterIdMap();var text1=lines1.map(line=>idMap.toChar(line)).join('');var text2=lines2.map(line=>idMap.toChar(line)).join('');var diff=Diff.Diff.charDiff(text1,text2);var lineDiff=[];for(var i=0;i<diff.length;i++){var lines=[];for(var j=0;j<diff[i][1].length;j++) -lines.push(idMap.fromChar(diff[i][1][j]));lineDiff.push({0:diff[i][0],1:lines});} -return lineDiff;},convertToEditDiff:function(diff){var normalized=[];var added=0;var removed=0;for(var i=0;i<diff.length;++i){var token=diff[i];if(token[0]===Diff.Diff.Operation.Equal){flush();normalized.push([Diff.Diff.Operation.Equal,token[1].length]);}else if(token[0]===Diff.Diff.Operation.Delete){removed+=token[1].length;}else{added+=token[1].length;}} -flush();return normalized;function flush(){if(added&&removed){var min=Math.min(added,removed);normalized.push([Diff.Diff.Operation.Edit,min]);added-=min;removed-=min;} -if(added||removed){var balance=added-removed;var type=balance<0?Diff.Diff.Operation.Delete:Diff.Diff.Operation.Insert;normalized.push([type,Math.abs(balance)]);added=0;removed=0;}}}};Diff.Diff.Operation={Equal:0,Insert:1,Delete:-1,Edit:2};Diff.Diff.DiffArray;;(function(){function diff_match_patch(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=0.5;this.Match_Distance=1E3;this.Patch_DeleteThreshold=0.5;this.Patch_Margin=4;this.Match_MaxBits=32} -diff_match_patch.prototype.diff_main=function(a,b,c,d){"undefined"==typeof d&&(d=0>=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1E3*this.Diff_Timeout);if(null==a||null==b)throw Error("Null input. (diff_main)");if(a==b)return a?[[0,a]]:[];"undefined"==typeof c&&(c=!0);var e=c,f=this.diff_commonPrefix(a,b);c=a.substring(0,f);a=a.substring(f);b=b.substring(f);var f=this.diff_commonSuffix(a,b),g=a.substring(a.length-f);a=a.substring(0,a.length-f);b=b.substring(0,b.length-f);a=this.diff_compute_(a,b,e,d);c&&a.unshift([0,c]);g&&a.push([0,g]);this.diff_cleanupMerge(a);return a};diff_match_patch.prototype.diff_compute_=function(a,b,c,d){if(!a)return[[1,b]];if(!b)return[[-1,a]];var e=a.length>b.length?a:b,f=a.length>b.length?b:a,g=e.indexOf(f);return-1!=g?(c=[[1,e.substring(0,g)],[0,f],[1,e.substring(g+f.length)]],a.length>b.length&&(c[0][0]=c[2][0]=-1),c):1==f.length?[[-1,a],[1,b]]:(e=this.diff_halfMatch_(a,b))?(f=e[0],a=e[1],g=e[2],b=e[3],e=e[4],f=this.diff_main(f,g,c,d),c=this.diff_main(a,b,c,d),f.concat([[0,e]],c)):c&&100<a.length&&100<b.length?this.diff_lineMode_(a,b,d):this.diff_bisect_(a,b,d)};diff_match_patch.prototype.diff_lineMode_=function(a,b,c){var d=this.diff_linesToChars_(a,b);a=d.chars1;b=d.chars2;d=d.lineArray;a=this.diff_main(a,b,!1,c);this.diff_charsToLines_(a,d);this.diff_cleanupSemantic(a);a.push([0,""]);for(var e=d=b=0,f="",g="";b<a.length;){switch(a[b][0]){case 1:e++;g+=a[b][1];break;case-1:d++;f+=a[b][1];break;case 0:if(1<=d&&1<=e){a.splice(b-d-e,d+e);b=b-d-e;d=this.diff_main(f,g,!1,c);for(e=d.length-1;0<=e;e--)a.splice(b,0,d[e]);b+=d.length}d=e=0;g=f=""}b++}a.pop();return a};diff_match_patch.prototype.diff_bisect_=function(a,b,c){for(var d=a.length,e=b.length,f=Math.ceil((d+e)/2),g=f,h=2*f,j=Array(h),i=Array(h),k=0;k<h;k++)j[k]=-1,i[k]=-1;j[g+1]=0;i[g+1]=0;for(var k=d-e,q=0!=k%2,r=0,t=0,p=0,w=0,v=0;v<f&&!((new Date).getTime()>c);v++){for(var n=-v+r;n<=v-t;n+=2){var l=g+n,m;m=n==-v||n!=v&&j[l-1]<j[l+1]?j[l+1]:j[l-1]+1;for(var s=m-n;m<d&&s<e&&a.charAt(m)==b.charAt(s);)m++,s++;j[l]=m;if(m>d)t+=2;else if(s>e)r+=2;else if(q&&(l=g+k-n,0<=l&&l<h&&-1!=i[l])){var u=d-i[l];if(m>=u)return this.diff_bisectSplit_(a,b,m,s,c)}}for(n=-v+p;n<=v-w;n+=2){l=g+n;u=n==-v||n!=v&&i[l-1]<i[l+1]?i[l+1]:i[l-1]+1;for(m=u-n;u<d&&m<e&&a.charAt(d-u-1)==b.charAt(e-m-1);)u++,m++;i[l]=u;if(u>d)w+=2;else if(m>e)p+=2;else if(!q&&(l=g+k-n,0<=l&&(l<h&&-1!=j[l])&&(m=j[l],s=g+m-l,u=d-u,m>=u)))return this.diff_bisectSplit_(a,b,m,s,c)}}return[[-1,a],[1,b]]};diff_match_patch.prototype.diff_bisectSplit_=function(a,b,c,d,e){var f=a.substring(0,c),g=b.substring(0,d);a=a.substring(c);b=b.substring(d);f=this.diff_main(f,g,!1,e);e=this.diff_main(a,b,!1,e);return f.concat(e)};diff_match_patch.prototype.diff_linesToChars_=function(a,b){function c(a){for(var b="",c=0,f=-1,g=d.length;f<a.length-1;){f=a.indexOf("\n",c);-1==f&&(f=a.length-1);var r=a.substring(c,f+1),c=f+1;(e.hasOwnProperty?e.hasOwnProperty(r):void 0!==e[r])?b+=String.fromCharCode(e[r]):(b+=String.fromCharCode(g),e[r]=g,d[g++]=r)}return b}var d=[],e={};d[0]="";var f=c(a),g=c(b);return{chars1:f,chars2:g,lineArray:d}};diff_match_patch.prototype.diff_charsToLines_=function(a,b){for(var c=0;c<a.length;c++){for(var d=a[c][1],e=[],f=0;f<d.length;f++)e[f]=b[d.charCodeAt(f)];a[c][1]=e.join("")}};diff_match_patch.prototype.diff_commonPrefix=function(a,b){if(!a||!b||a.charAt(0)!=b.charAt(0))return 0;for(var c=0,d=Math.min(a.length,b.length),e=d,f=0;c<e;)a.substring(f,e)==b.substring(f,e)?f=c=e:d=e,e=Math.floor((d-c)/2+c);return e};diff_match_patch.prototype.diff_commonSuffix=function(a,b){if(!a||!b||a.charAt(a.length-1)!=b.charAt(b.length-1))return 0;for(var c=0,d=Math.min(a.length,b.length),e=d,f=0;c<e;)a.substring(a.length-e,a.length-f)==b.substring(b.length-e,b.length-f)?f=c=e:d=e,e=Math.floor((d-c)/2+c);return e};diff_match_patch.prototype.diff_commonOverlap_=function(a,b){var c=a.length,d=b.length;if(0==c||0==d)return 0;c>d?a=a.substring(c-d):c<d&&(b=b.substring(0,c));c=Math.min(c,d);if(a==b)return c;for(var d=0,e=1;;){var f=a.substring(c-e),f=b.indexOf(f);if(-1==f)return d;e+=f;if(0==f||a.substring(c-e)==b.substring(0,e))d=e,e++}};diff_match_patch.prototype.diff_halfMatch_=function(a,b){function c(a,b,c){for(var d=a.substring(c,c+Math.floor(a.length/4)),e=-1,g="",h,j,n,l;-1!=(e=b.indexOf(d,e+1));){var m=f.diff_commonPrefix(a.substring(c),b.substring(e)),s=f.diff_commonSuffix(a.substring(0,c),b.substring(0,e));g.length<s+m&&(g=b.substring(e-s,e)+b.substring(e,e+m),h=a.substring(0,c-s),j=a.substring(c+m),n=b.substring(0,e-s),l=b.substring(e+m))}return 2*g.length>=a.length?[h,j,n,l,g]:null}if(0>=this.Diff_Timeout)return null;var d=a.length>b.length?a:b,e=a.length>b.length?b:a;if(4>d.length||2*e.length<d.length)return null;var f=this,g=c(d,e,Math.ceil(d.length/4)),d=c(d,e,Math.ceil(d.length/2)),h;if(!g&&!d)return null;h=d?g?g[4].length>d[4].length?g:d:d:g;var j;a.length>b.length?(g=h[0],d=h[1],e=h[2],j=h[3]):(e=h[0],j=h[1],g=h[2],d=h[3]);h=h[4];return[g,d,e,j,h]};diff_match_patch.prototype.diff_cleanupSemantic=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=0,h=0,j=0,i=0;f<a.length;)0==a[f][0]?(c[d++]=f,g=j,h=i,i=j=0,e=a[f][1]):(1==a[f][0]?j+=a[f][1].length:i+=a[f][1].length,e&&(e.length<=Math.max(g,h)&&e.length<=Math.max(j,i))&&(a.splice(c[d-1],0,[-1,e]),a[c[d-1]+1][0]=1,d--,d--,f=0<d?c[d-1]:-1,i=j=h=g=0,e=null,b=!0)),f++;b&&this.diff_cleanupMerge(a);this.diff_cleanupSemanticLossless(a);for(f=1;f<a.length;){if(-1==a[f-1][0]&&1==a[f][0]){b=a[f-1][1];c=a[f][1];d=this.diff_commonOverlap_(b,c);e=this.diff_commonOverlap_(c,b);if(d>=e){if(d>=b.length/2||d>=c.length/2)a.splice(f,0,[0,c.substring(0,d)]),a[f-1][1]=b.substring(0,b.length-d),a[f+1][1]=c.substring(d),f++}else if(e>=b.length/2||e>=c.length/2)a.splice(f,0,[0,b.substring(0,e)]),a[f-1][0]=1,a[f-1][1]=c.substring(0,c.length-e),a[f+1][0]=-1,a[f+1][1]=b.substring(e),f++;f++}f++}};diff_match_patch.prototype.diff_cleanupSemanticLossless=function(a){function b(a,b){if(!a||!b)return 6;var c=a.charAt(a.length-1),d=b.charAt(0),e=c.match(diff_match_patch.nonAlphaNumericRegex_),f=d.match(diff_match_patch.nonAlphaNumericRegex_),g=e&&c.match(diff_match_patch.whitespaceRegex_),h=f&&d.match(diff_match_patch.whitespaceRegex_),c=g&&c.match(diff_match_patch.linebreakRegex_),d=h&&d.match(diff_match_patch.linebreakRegex_),i=c&&a.match(diff_match_patch.blanklineEndRegex_),j=d&&b.match(diff_match_patch.blanklineStartRegex_);return i||j?5:c||d?4:e&&!g&&h?3:g||h?2:e||f?1:0}for(var c=1;c<a.length-1;){if(0==a[c-1][0]&&0==a[c+1][0]){var d=a[c-1][1],e=a[c][1],f=a[c+1][1],g=this.diff_commonSuffix(d,e);if(g)var h=e.substring(e.length-g),d=d.substring(0,d.length-g),e=h+e.substring(0,e.length-g),f=h+f;for(var g=d,h=e,j=f,i=b(d,e)+b(e,f);e.charAt(0)===f.charAt(0);){var d=d+e.charAt(0),e=e.substring(1)+f.charAt(0),f=f.substring(1),k=b(d,e)+b(e,f);k>=i&&(i=k,g=d,h=e,j=f)}a[c-1][1]!=g&&(g?a[c-1][1]=g:(a.splice(c-1,1),c--),a[c][1]=h,j?a[c+1][1]=j:(a.splice(c+1,1),c--))}c++}};diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch.whitespaceRegex_=/\s/;diff_match_patch.linebreakRegex_=/[\r\n]/;diff_match_patch.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/;diff_match_patch.prototype.diff_cleanupEfficiency=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=!1,h=!1,j=!1,i=!1;f<a.length;){if(0==a[f][0])a[f][1].length<this.Diff_EditCost&&(j||i)?(c[d++]=f,g=j,h=i,e=a[f][1]):(d=0,e=null),j=i=!1;else if(-1==a[f][0]?i=!0:j=!0,e&&(g&&h&&j&&i||e.length<this.Diff_EditCost/2&&3==g+h+j+i))a.splice(c[d-1],0,[-1,e]),a[c[d-1]+1][0]=1,d--,e=null,g&&h?(j=i=!0,d=0):(d--,f=0<d?c[d-1]:-1,j=i=!1),b=!0;f++}b&&this.diff_cleanupMerge(a)};diff_match_patch.prototype.diff_cleanupMerge=function(a){a.push([0,""]);for(var b=0,c=0,d=0,e="",f="",g;b<a.length;)switch(a[b][0]){case 1:d++;f+=a[b][1];b++;break;case-1:c++;e+=a[b][1];b++;break;case 0:1<c+d?(0!==c&&0!==d&&(g=this.diff_commonPrefix(f,e),0!==g&&(0<b-c-d&&0==a[b-c-d-1][0]?a[b-c-d-1][1]+=f.substring(0,g):(a.splice(0,0,[0,f.substring(0,g)]),b++),f=f.substring(g),e=e.substring(g)),g=this.diff_commonSuffix(f,e),0!==g&&(a[b][1]=f.substring(f.length-g)+a[b][1],f=f.substring(0,f.length- -g),e=e.substring(0,e.length-g))),0===c?a.splice(b-d,c+d,[1,f]):0===d?a.splice(b-c,c+d,[-1,e]):a.splice(b-c-d,c+d,[-1,e],[1,f]),b=b-c-d+(c?1:0)+(d?1:0)+1):0!==b&&0==a[b-1][0]?(a[b-1][1]+=a[b][1],a.splice(b,1)):b++,c=d=0,f=e=""}""===a[a.length-1][1]&&a.pop();c=!1;for(b=1;b<a.length-1;)0==a[b-1][0]&&0==a[b+1][0]&&(a[b][1].substring(a[b][1].length-a[b-1][1].length)==a[b-1][1]?(a[b][1]=a[b-1][1]+a[b][1].substring(0,a[b][1].length-a[b-1][1].length),a[b+1][1]=a[b-1][1]+a[b+1][1],a.splice(b-1,1),c=!0):a[b][1].substring(0,a[b+1][1].length)==a[b+1][1]&&(a[b-1][1]+=a[b+1][1],a[b][1]=a[b][1].substring(a[b+1][1].length)+a[b+1][1],a.splice(b+1,1),c=!0)),b++;c&&this.diff_cleanupMerge(a)};diff_match_patch.prototype.diff_xIndex=function(a,b){var c=0,d=0,e=0,f=0,g;for(g=0;g<a.length;g++){1!==a[g][0]&&(c+=a[g][1].length);-1!==a[g][0]&&(d+=a[g][1].length);if(c>b)break;e=c;f=d}return a.length!=g&&-1===a[g][0]?f:f+(b-e)};diff_match_patch.prototype.diff_prettyHtml=function(a){for(var b=[],c=/&/g,d=/</g,e=/>/g,f=/\n/g,g=0;g<a.length;g++){var h=a[g][0],j=a[g][1],j=j.replace(c,"&").replace(d,"<").replace(e,">").replace(f,"¶<br>");switch(h){case 1:b[g]='<ins style="background:#e6ffe6;">'+j+"</ins>";break;case-1:b[g]='<del style="background:#ffe6e6;">'+j+"</del>";break;case 0:b[g]="<span>"+j+"</span>"}}return b.join("")};diff_match_patch.prototype.diff_text1=function(a){for(var b=[],c=0;c<a.length;c++)1!==a[c][0]&&(b[c]=a[c][1]);return b.join("")};diff_match_patch.prototype.diff_text2=function(a){for(var b=[],c=0;c<a.length;c++)-1!==a[c][0]&&(b[c]=a[c][1]);return b.join("")};diff_match_patch.prototype.diff_levenshtein=function(a){for(var b=0,c=0,d=0,e=0;e<a.length;e++){var f=a[e][0],g=a[e][1];switch(f){case 1:c+=g.length;break;case-1:d+=g.length;break;case 0:b+=Math.max(c,d),d=c=0}}return b+=Math.max(c,d)};diff_match_patch.prototype.diff_toDelta=function(a){for(var b=[],c=0;c<a.length;c++)switch(a[c][0]){case 1:b[c]="+"+encodeURI(a[c][1]);break;case-1:b[c]="-"+a[c][1].length;break;case 0:b[c]="="+a[c][1].length}return b.join("\t").replace(/%20/g," ")};diff_match_patch.prototype.diff_fromDelta=function(a,b){for(var c=[],d=0,e=0,f=b.split(/\t/g),g=0;g<f.length;g++){var h=f[g].substring(1);switch(f[g].charAt(0)){case"+":try{c[d++]=[1,decodeURI(h)]}catch(j){throw Error("Illegal escape in diff_fromDelta: "+h);}break;case"-":case"=":var i=parseInt(h,10);if(isNaN(i)||0>i)throw Error("Invalid number in diff_fromDelta: "+h);h=a.substring(e,e+=i);"="==f[g].charAt(0)?c[d++]=[0,h]:c[d++]=[-1,h];break;default:if(f[g])throw Error("Invalid diff operation in diff_fromDelta: "+ -f[g]);}}if(e!=a.length)throw Error("Delta length ("+e+") does not equal source text length ("+a.length+").");return c};diff_match_patch.prototype.match_main=function(a,b,c){if(null==a||null==b||null==c)throw Error("Null input. (match_main)");c=Math.max(0,Math.min(c,a.length));return a==b?0:a.length?a.substring(c,c+b.length)==b?c:this.match_bitap_(a,b,c):-1};diff_match_patch.prototype.match_bitap_=function(a,b,c){function d(a,d){var e=a/b.length,g=Math.abs(c-d);return!f.Match_Distance?g?1:e:e+g/f.Match_Distance}if(b.length>this.Match_MaxBits)throw Error("Pattern too long for this browser.");var e=this.match_alphabet_(b),f=this,g=this.Match_Threshold,h=a.indexOf(b,c);-1!=h&&(g=Math.min(d(0,h),g),h=a.lastIndexOf(b,c+b.length),-1!=h&&(g=Math.min(d(0,h),g)));for(var j=1<<b.length-1,h=-1,i,k,q=b.length+a.length,r,t=0;t<b.length;t++){i=0;for(k=q;i<k;)d(t,c+ -k)<=g?i=k:q=k,k=Math.floor((q-i)/2+i);q=k;i=Math.max(1,c-k+1);var p=Math.min(c+k,a.length)+b.length;k=Array(p+2);for(k[p+1]=(1<<t)-1;p>=i;p--){var w=e[a.charAt(p-1)];k[p]=0===t?(k[p+1]<<1|1)&w:(k[p+1]<<1|1)&w|((r[p+1]|r[p])<<1|1)|r[p+1];if(k[p]&j&&(w=d(t,p-1),w<=g))if(g=w,h=p-1,h>c)i=Math.max(1,2*c-h);else break}if(d(t+1,c)>g)break;r=k}return h};diff_match_patch.prototype.match_alphabet_=function(a){for(var b={},c=0;c<a.length;c++)b[a.charAt(c)]=0;for(c=0;c<a.length;c++)b[a.charAt(c)]|=1<<a.length-c-1;return b};diff_match_patch.prototype.patch_addContext_=function(a,b){if(0!=b.length){for(var c=b.substring(a.start2,a.start2+a.length1),d=0;b.indexOf(c)!=b.lastIndexOf(c)&&c.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)d+=this.Patch_Margin,c=b.substring(a.start2-d,a.start2+a.length1+d);d+=this.Patch_Margin;(c=b.substring(a.start2-d,a.start2))&&a.diffs.unshift([0,c]);(d=b.substring(a.start2+a.length1,a.start2+a.length1+d))&&a.diffs.push([0,d]);a.start1-=c.length;a.start2-=c.length;a.length1+=c.length+d.length;a.length2+=c.length+d.length}};diff_match_patch.prototype.patch_make=function(a,b,c){var d;if("string"==typeof a&&"string"==typeof b&&"undefined"==typeof c)d=a,b=this.diff_main(d,b,!0),2<b.length&&(this.diff_cleanupSemantic(b),this.diff_cleanupEfficiency(b));else if(a&&"object"==typeof a&&"undefined"==typeof b&&"undefined"==typeof c)b=a,d=this.diff_text1(b);else if("string"==typeof a&&b&&"object"==typeof b&&"undefined"==typeof c)d=a;else if("string"==typeof a&&"string"==typeof b&&c&&"object"==typeof c)d=a,b=c;else throw Error("Unknown call format to patch_make.");if(0===b.length)return[];c=[];a=new diff_match_patch.patch_obj;for(var e=0,f=0,g=0,h=d,j=0;j<b.length;j++){var i=b[j][0],k=b[j][1];!e&&0!==i&&(a.start1=f,a.start2=g);switch(i){case 1:a.diffs[e++]=b[j];a.length2+=k.length;d=d.substring(0,g)+k+d.substring(g);break;case-1:a.length1+=k.length;a.diffs[e++]=b[j];d=d.substring(0,g)+d.substring(g+k.length);break;case 0:k.length<=2*this.Patch_Margin&&e&&b.length!=j+1?(a.diffs[e++]=b[j],a.length1+=k.length,a.length2+=k.length):k.length>=2*this.Patch_Margin&&e&&(this.patch_addContext_(a,h),c.push(a),a=new diff_match_patch.patch_obj,e=0,h=d,f=g)}1!==i&&(f+=k.length);-1!==i&&(g+=k.length)}e&&(this.patch_addContext_(a,h),c.push(a));return c};diff_match_patch.prototype.patch_deepCopy=function(a){for(var b=[],c=0;c<a.length;c++){var d=a[c],e=new diff_match_patch.patch_obj;e.diffs=[];for(var f=0;f<d.diffs.length;f++)e.diffs[f]=d.diffs[f].slice();e.start1=d.start1;e.start2=d.start2;e.length1=d.length1;e.length2=d.length2;b[c]=e}return b};diff_match_patch.prototype.patch_apply=function(a,b){if(0==a.length)return[b,[]];a=this.patch_deepCopy(a);var c=this.patch_addPadding(a);b=c+b+c;this.patch_splitMax(a);for(var d=0,e=[],f=0;f<a.length;f++){var g=a[f].start2+d,h=this.diff_text1(a[f].diffs),j,i=-1;if(h.length>this.Match_MaxBits){if(j=this.match_main(b,h.substring(0,this.Match_MaxBits),g),-1!=j&&(i=this.match_main(b,h.substring(h.length-this.Match_MaxBits),g+h.length-this.Match_MaxBits),-1==i||j>=i))j=-1}else j=this.match_main(b,h,g);if(-1==j)e[f]=!1,d-=a[f].length2-a[f].length1;else if(e[f]=!0,d=j-g,g=-1==i?b.substring(j,j+h.length):b.substring(j,i+this.Match_MaxBits),h==g)b=b.substring(0,j)+this.diff_text2(a[f].diffs)+b.substring(j+h.length);else if(g=this.diff_main(h,g,!1),h.length>this.Match_MaxBits&&this.diff_levenshtein(g)/h.length>this.Patch_DeleteThreshold)e[f]=!1;else{this.diff_cleanupSemanticLossless(g);for(var h=0,k,i=0;i<a[f].diffs.length;i++){var q=a[f].diffs[i];0!==q[0]&&(k=this.diff_xIndex(g,h));1===q[0]?b=b.substring(0,j+k)+q[1]+b.substring(j+k):-1===q[0]&&(b=b.substring(0,j+k)+b.substring(j+this.diff_xIndex(g,h+q[1].length)));-1!==q[0]&&(h+=q[1].length)}}}b=b.substring(c.length,b.length-c.length);return[b,e]};diff_match_patch.prototype.patch_addPadding=function(a){for(var b=this.Patch_Margin,c="",d=1;d<=b;d++)c+=String.fromCharCode(d);for(d=0;d<a.length;d++)a[d].start1+=b,a[d].start2+=b;var d=a[0],e=d.diffs;if(0==e.length||0!=e[0][0])e.unshift([0,c]),d.start1-=b,d.start2-=b,d.length1+=b,d.length2+=b;else if(b>e[0][1].length){var f=b-e[0][1].length;e[0][1]=c.substring(e[0][1].length)+e[0][1];d.start1-=f;d.start2-=f;d.length1+=f;d.length2+=f}d=a[a.length-1];e=d.diffs;0==e.length||0!=e[e.length-1][0]?(e.push([0,c]),d.length1+=b,d.length2+=b):b>e[e.length-1][1].length&&(f=b-e[e.length-1][1].length,e[e.length-1][1]+=c.substring(0,f),d.length1+=f,d.length2+=f);return c};diff_match_patch.prototype.patch_splitMax=function(a){for(var b=this.Match_MaxBits,c=0;c<a.length;c++)if(!(a[c].length1<=b)){var d=a[c];a.splice(c--,1);for(var e=d.start1,f=d.start2,g="";0!==d.diffs.length;){var h=new diff_match_patch.patch_obj,j=!0;h.start1=e-g.length;h.start2=f-g.length;""!==g&&(h.length1=h.length2=g.length,h.diffs.push([0,g]));for(;0!==d.diffs.length&&h.length1<b-this.Patch_Margin;){var g=d.diffs[0][0],i=d.diffs[0][1];1===g?(h.length2+=i.length,f+=i.length,h.diffs.push(d.diffs.shift()),j=!1):-1===g&&1==h.diffs.length&&0==h.diffs[0][0]&&i.length>2*b?(h.length1+=i.length,e+=i.length,j=!1,h.diffs.push([g,i]),d.diffs.shift()):(i=i.substring(0,b-h.length1-this.Patch_Margin),h.length1+=i.length,e+=i.length,0===g?(h.length2+=i.length,f+=i.length):j=!1,h.diffs.push([g,i]),i==d.diffs[0][1]?d.diffs.shift():d.diffs[0][1]=d.diffs[0][1].substring(i.length))}g=this.diff_text2(h.diffs);g=g.substring(g.length-this.Patch_Margin);i=this.diff_text1(d.diffs).substring(0,this.Patch_Margin);""!==i&&(h.length1+=i.length,h.length2+=i.length,0!==h.diffs.length&&0===h.diffs[h.diffs.length-1][0]?h.diffs[h.diffs.length-1][1]+=i:h.diffs.push([0,i]));j||a.splice(++c,0,h)}}};diff_match_patch.prototype.patch_toText=function(a){for(var b=[],c=0;c<a.length;c++)b[c]=a[c];return b.join("")};diff_match_patch.prototype.patch_fromText=function(a){var b=[];if(!a)return b;a=a.split("\n");for(var c=0,d=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;c<a.length;){var e=a[c].match(d);if(!e)throw Error("Invalid patch string: "+a[c]);var f=new diff_match_patch.patch_obj;b.push(f);f.start1=parseInt(e[1],10);""===e[2]?(f.start1--,f.length1=1):"0"==e[2]?f.length1=0:(f.start1--,f.length1=parseInt(e[2],10));f.start2=parseInt(e[3],10);""===e[4]?(f.start2--,f.length2=1):"0"==e[4]?f.length2=0:(f.start2--,f.length2=parseInt(e[4],10));for(c++;c<a.length;){e=a[c].charAt(0);try{var g=decodeURI(a[c].substring(1))}catch(h){throw Error("Illegal escape in patch_fromText: "+g);}if("-"==e)f.diffs.push([-1,g]);else if("+"==e)f.diffs.push([1,g]);else if(" "==e)f.diffs.push([0,g]);else if("@"==e)break;else if(""!==e)throw Error('Invalid patch mode "'+e+'" in: '+g);c++}}return b};diff_match_patch.patch_obj=function(){this.diffs=[];this.start2=this.start1=null;this.length2=this.length1=0};diff_match_patch.patch_obj.prototype.toString=function(){var a,b;a=0===this.length1?this.start1+",0":1==this.length1?this.start1+1:this.start1+1+","+this.length1;b=0===this.length2?this.start2+",0":1==this.length2?this.start2+1:this.start2+1+","+this.length2;a=["@@ -"+a+" +"+b+" @@\n"];var c;for(b=0;b<this.diffs.length;b++){switch(this.diffs[b][0]){case 1:c="+";break;case-1:c="-";break;case 0:c=" "}a[b+1]=c+encodeURI(this.diffs[b][1])+"\n"}return a.join("").replace(/%20/g," ")};this.diff_match_patch=diff_match_patch;this.DIFF_DELETE=-1;this.DIFF_INSERT=1;this.DIFF_EQUAL=0;})(); \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/elements/elements_module.js b/src/cobalt/debug/content/devtools/elements/elements_module.js deleted file mode 100644 index 72c49e1..0000000 --- a/src/cobalt/debug/content/devtools/elements/elements_module.js +++ /dev/null
@@ -1,1473 +0,0 @@ -Elements.InspectElementModeController=class{constructor(){this._toggleSearchAction=UI.actionRegistry.action('elements.toggle-element-search');this._mode=Protocol.Overlay.InspectMode.None;SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._suspendStateChanged,this);SDK.targetManager.addModelListener(SDK.OverlayModel,SDK.OverlayModel.Events.ScreenshotRequested,()=>this._setMode(Protocol.Overlay.InspectMode.None));SDK.targetManager.observeModels(SDK.OverlayModel,this);} -modelAdded(overlayModel){if(this._mode===Protocol.Overlay.InspectMode.None) -return;overlayModel.setInspectMode(this._mode);} -modelRemoved(overlayModel){} -isInInspectElementMode(){return this._mode===Protocol.Overlay.InspectMode.SearchForNode||this._mode===Protocol.Overlay.InspectMode.SearchForUAShadowDOM;} -stopInspection(){if(this._mode&&this._mode!==Protocol.Overlay.InspectMode.None) -this._toggleInspectMode();} -_toggleInspectMode(){if(SDK.targetManager.allTargetsSuspended()) -return;var mode;if(this.isInInspectElementMode()){mode=Protocol.Overlay.InspectMode.None;}else{mode=Common.moduleSetting('showUAShadowDOM').get()?Protocol.Overlay.InspectMode.SearchForUAShadowDOM:Protocol.Overlay.InspectMode.SearchForNode;} -this._setMode(mode);} -_setMode(mode){this._mode=mode;for(var overlayModel of SDK.targetManager.models(SDK.OverlayModel)) -overlayModel.setInspectMode(mode);this._toggleSearchAction.setToggled(this.isInInspectElementMode());} -_suspendStateChanged(){if(!SDK.targetManager.allTargetsSuspended()) -return;this._mode=Protocol.Overlay.InspectMode.None;this._toggleSearchAction.setToggled(false);}};Elements.InspectElementModeController.ToggleSearchActionDelegate=class{handleAction(context,actionId){if(!Elements.inspectElementModeController) -return false;Elements.inspectElementModeController._toggleInspectMode();return true;}};Elements.inspectElementModeController=Runtime.queryParam('isSharedWorker')?null:new Elements.InspectElementModeController();;Elements.BezierPopoverIcon=class{constructor(treeElement,swatchPopoverHelper,swatch){this._treeElement=treeElement;this._swatchPopoverHelper=swatchPopoverHelper;this._swatch=swatch;this._swatch.iconElement().title=Common.UIString('Open cubic bezier editor.');this._swatch.iconElement().addEventListener('click',this._iconClick.bind(this),false);this._boundBezierChanged=this._bezierChanged.bind(this);this._boundOnScroll=this._onScroll.bind(this);} -_iconClick(event){event.consume(true);if(this._swatchPopoverHelper.isShowing()){this._swatchPopoverHelper.hide(true);return;} -this._bezierEditor=new InlineEditor.BezierEditor();var cubicBezier=UI.Geometry.CubicBezier.parse(this._swatch.bezierText());if(!cubicBezier){cubicBezier=(UI.Geometry.CubicBezier.parse('linear'));} -this._bezierEditor.setBezier(cubicBezier);this._bezierEditor.addEventListener(InlineEditor.BezierEditor.Events.BezierChanged,this._boundBezierChanged);this._swatchPopoverHelper.show(this._bezierEditor,this._swatch.iconElement(),this._onPopoverHidden.bind(this));this._scrollerElement=this._swatch.enclosingNodeOrSelfWithClass('style-panes-wrapper');if(this._scrollerElement) -this._scrollerElement.addEventListener('scroll',this._boundOnScroll,false);this._originalPropertyText=this._treeElement.property.propertyText;this._treeElement.parentPane().setEditingStyle(true);var uiLocation=Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property,false);if(uiLocation) -Common.Revealer.reveal(uiLocation,true);} -_bezierChanged(event){this._swatch.setBezierText((event.data));this._treeElement.applyStyleText(this._treeElement.renderedPropertyText(),false);} -_onScroll(event){this._swatchPopoverHelper.reposition();} -_onPopoverHidden(commitEdit){if(this._scrollerElement) -this._scrollerElement.removeEventListener('scroll',this._boundOnScroll,false);this._bezierEditor.removeEventListener(InlineEditor.BezierEditor.Events.BezierChanged,this._boundBezierChanged);delete this._bezierEditor;var propertyText=commitEdit?this._treeElement.renderedPropertyText():this._originalPropertyText;this._treeElement.applyStyleText(propertyText,true);this._treeElement.parentPane().setEditingStyle(false);delete this._originalPropertyText;}};Elements.ColorSwatchPopoverIcon=class{constructor(treeElement,swatchPopoverHelper,swatch){this._treeElement=treeElement;this._treeElement[Elements.ColorSwatchPopoverIcon._treeElementSymbol]=this;this._swatchPopoverHelper=swatchPopoverHelper;this._swatch=swatch;var shiftClickMessage=Common.UIString('Shift + Click to change color format.');this._swatch.iconElement().title=Common.UIString('Open color picker. %s',shiftClickMessage);this._swatch.iconElement().addEventListener('click',this._iconClick.bind(this));this._contrastInfo=null;this._boundSpectrumChanged=this._spectrumChanged.bind(this);this._boundOnScroll=this._onScroll.bind(this);} -static forTreeElement(treeElement){return treeElement[Elements.ColorSwatchPopoverIcon._treeElementSymbol]||null;} -setContrastInfo(contrastInfo){this._contrastInfo=contrastInfo;if(this._spectrum) -this._spectrum.setContrastInfo(contrastInfo);} -_iconClick(event){event.consume(true);this.showPopover();} -showPopover(){if(this._swatchPopoverHelper.isShowing()){this._swatchPopoverHelper.hide(true);return;} -var color=this._swatch.color();var format=this._swatch.format();if(format===Common.Color.Format.Original) -format=color.format();this._spectrum=new ColorPicker.Spectrum();this._spectrum.setColor(color,format);if(this._contrastInfo) -this._spectrum.setContrastInfo(this._contrastInfo);this._spectrum.addEventListener(ColorPicker.Spectrum.Events.SizeChanged,this._spectrumResized,this);this._spectrum.addEventListener(ColorPicker.Spectrum.Events.ColorChanged,this._boundSpectrumChanged);this._swatchPopoverHelper.show(this._spectrum,this._swatch.iconElement(),this._onPopoverHidden.bind(this));this._scrollerElement=this._swatch.enclosingNodeOrSelfWithClass('style-panes-wrapper');if(this._scrollerElement) -this._scrollerElement.addEventListener('scroll',this._boundOnScroll,false);this._originalPropertyText=this._treeElement.property.propertyText;this._treeElement.parentPane().setEditingStyle(true);var uiLocation=Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property,false);if(uiLocation) -Common.Revealer.reveal(uiLocation,true);} -_spectrumResized(event){this._swatchPopoverHelper.reposition();} -_spectrumChanged(event){var color=Common.Color.parse((event.data));if(!color) -return;this._swatch.setColor(color);this._treeElement.applyStyleText(this._treeElement.renderedPropertyText(),false);} -_onScroll(event){this._swatchPopoverHelper.reposition();} -_onPopoverHidden(commitEdit){if(this._scrollerElement) -this._scrollerElement.removeEventListener('scroll',this._boundOnScroll,false);this._spectrum.removeEventListener(ColorPicker.Spectrum.Events.ColorChanged,this._boundSpectrumChanged);delete this._spectrum;var propertyText=commitEdit?this._treeElement.renderedPropertyText():this._originalPropertyText;this._treeElement.applyStyleText(propertyText,true);this._treeElement.parentPane().setEditingStyle(false);delete this._originalPropertyText;}};Elements.ColorSwatchPopoverIcon._treeElementSymbol=Symbol('Elements.ColorSwatchPopoverIcon._treeElementSymbol');Elements.ShadowSwatchPopoverHelper=class{constructor(treeElement,swatchPopoverHelper,shadowSwatch){this._treeElement=treeElement;this._treeElement[Elements.ShadowSwatchPopoverHelper._treeElementSymbol]=this;this._swatchPopoverHelper=swatchPopoverHelper;this._shadowSwatch=shadowSwatch;this._iconElement=shadowSwatch.iconElement();this._iconElement.title=Common.UIString('Open shadow editor.');this._iconElement.addEventListener('click',this._iconClick.bind(this),false);this._boundShadowChanged=this._shadowChanged.bind(this);this._boundOnScroll=this._onScroll.bind(this);} -static forTreeElement(treeElement){return treeElement[Elements.ShadowSwatchPopoverHelper._treeElementSymbol]||null;} -_iconClick(event){event.consume(true);this.showPopover();} -showPopover(){if(this._swatchPopoverHelper.isShowing()){this._swatchPopoverHelper.hide(true);return;} -this._cssShadowEditor=new InlineEditor.CSSShadowEditor();this._cssShadowEditor.setModel(this._shadowSwatch.model());this._cssShadowEditor.addEventListener(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._boundShadowChanged);this._swatchPopoverHelper.show(this._cssShadowEditor,this._iconElement,this._onPopoverHidden.bind(this));this._scrollerElement=this._iconElement.enclosingNodeOrSelfWithClass('style-panes-wrapper');if(this._scrollerElement) -this._scrollerElement.addEventListener('scroll',this._boundOnScroll,false);this._originalPropertyText=this._treeElement.property.propertyText;this._treeElement.parentPane().setEditingStyle(true);var uiLocation=Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property,false);if(uiLocation) -Common.Revealer.reveal(uiLocation,true);} -_shadowChanged(event){this._shadowSwatch.setCSSShadow((event.data));this._treeElement.applyStyleText(this._treeElement.renderedPropertyText(),false);} -_onScroll(event){this._swatchPopoverHelper.reposition();} -_onPopoverHidden(commitEdit){if(this._scrollerElement) -this._scrollerElement.removeEventListener('scroll',this._boundOnScroll,false);this._cssShadowEditor.removeEventListener(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._boundShadowChanged);delete this._cssShadowEditor;var propertyText=commitEdit?this._treeElement.renderedPropertyText():this._originalPropertyText;this._treeElement.applyStyleText(propertyText,true);this._treeElement.parentPane().setEditingStyle(false);delete this._originalPropertyText;}};Elements.ShadowSwatchPopoverHelper._treeElementSymbol=Symbol('Elements.ShadowSwatchPopoverHelper._treeElementSymbol');;Elements.ComputedStyleModel=class extends Common.Object{constructor(){super();this._node=UI.context.flavor(SDK.DOMNode);this._cssModel=null;this._eventListeners=[];UI.context.addFlavorChangeListener(SDK.DOMNode,this._onNodeChanged,this);} -node(){return this._node;} -cssModel(){return this._cssModel&&this._cssModel.isEnabled()?this._cssModel:null;} -_onNodeChanged(event){this._node=(event.data);this._updateModel(this._node?this._node.domModel().cssModel():null);this._onComputedStyleChanged(null);} -_updateModel(cssModel){if(this._cssModel===cssModel) -return;Common.EventTarget.removeEventListeners(this._eventListeners);this._cssModel=cssModel;var domModel=cssModel?cssModel.domModel():null;var resourceTreeModel=cssModel?cssModel.target().model(SDK.ResourceTreeModel):null;if(cssModel&&domModel&&resourceTreeModel){this._eventListeners=[cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.FontsUpdated,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.MediaQueryResultChanged,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.PseudoStateForced,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.ModelWasEnabled,this._onComputedStyleChanged,this),domModel.addEventListener(SDK.DOMModel.Events.DOMMutated,this._onDOMModelChanged,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameResized,this._onFrameResized,this),];}} -_onComputedStyleChanged(event){delete this._computedStylePromise;this.dispatchEventToListeners(Elements.ComputedStyleModel.Events.ComputedStyleChanged,event?event.data:null);} -_onDOMModelChanged(event){var node=(event.data);if(!this._node||this._node!==node&&node.parentNode!==this._node.parentNode&&!node.isAncestor(this._node)) -return;this._onComputedStyleChanged(null);} -_onFrameResized(event){function refreshContents(){this._onComputedStyleChanged(null);delete this._frameResizedTimer;} -if(this._frameResizedTimer) -clearTimeout(this._frameResizedTimer);this._frameResizedTimer=setTimeout(refreshContents.bind(this),100);} -_elementNode(){return this.node()?this.node().enclosingElementOrSelf():null;} -fetchComputedStyle(){var elementNode=this._elementNode();var cssModel=this.cssModel();if(!elementNode||!cssModel) -return Promise.resolve((null));if(!this._computedStylePromise){this._computedStylePromise=cssModel.computedStylePromise(elementNode.id).then(verifyOutdated.bind(this,elementNode));} -return this._computedStylePromise;function verifyOutdated(elementNode,style){return elementNode===this._elementNode()&&style?new Elements.ComputedStyleModel.ComputedStyle(elementNode,style):(null);}}};Elements.ComputedStyleModel.Events={ComputedStyleChanged:Symbol('ComputedStyleChanged')};Elements.ComputedStyleModel.ComputedStyle=class{constructor(node,computedStyle){this.node=node;this.computedStyle=computedStyle;}};;Elements.ElementsBreadcrumbs=class extends UI.HBox{constructor(){super(true);this.registerRequiredCSS('elements/breadcrumbs.css');this.crumbsElement=this.contentElement.createChild('div','crumbs');this.crumbsElement.addEventListener('mousemove',this._mouseMovedInCrumbs.bind(this),false);this.crumbsElement.addEventListener('mouseleave',this._mouseMovedOutOfCrumbs.bind(this),false);this._nodeSymbol=Symbol('node');} -wasShown(){this.update();} -updateNodes(nodes){if(!nodes.length) -return;var crumbs=this.crumbsElement;for(var crumb=crumbs.firstChild;crumb;crumb=crumb.nextSibling){if(nodes.indexOf(crumb[this._nodeSymbol])!==-1){this.update(true);return;}}} -setSelectedNode(node){this._currentDOMNode=node;this.crumbsElement.window().requestAnimationFrame(()=>this.update());} -_mouseMovedInCrumbs(event){var nodeUnderMouse=event.target;var crumbElement=nodeUnderMouse.enclosingNodeOrSelfWithClass('crumb');var node=(crumbElement?crumbElement[this._nodeSymbol]:null);if(node) -node.highlight();} -_mouseMovedOutOfCrumbs(event){if(this._currentDOMNode) -SDK.OverlayModel.hideDOMNodeHighlight();} -_onClickCrumb(event){event.preventDefault();var crumb=(event.currentTarget);if(!crumb.classList.contains('collapsed')){this.dispatchEventToListeners(Elements.ElementsBreadcrumbs.Events.NodeSelected,crumb[this._nodeSymbol]);return;} -if(crumb===this.crumbsElement.firstChild){var currentCrumb=crumb;while(currentCrumb){var hidden=currentCrumb.classList.contains('hidden');var collapsed=currentCrumb.classList.contains('collapsed');if(!hidden&&!collapsed) -break;crumb=currentCrumb;currentCrumb=currentCrumb.nextSiblingElement;}} -this.updateSizes(crumb);} -_determineElementTitle(domNode){switch(domNode.nodeType()){case Node.ELEMENT_NODE:if(domNode.pseudoType()) -return'::'+domNode.pseudoType();return null;case Node.TEXT_NODE:return Common.UIString('(text)');case Node.COMMENT_NODE:return'<!-->';case Node.DOCUMENT_TYPE_NODE:return'<!DOCTYPE>';case Node.DOCUMENT_FRAGMENT_NODE:return domNode.shadowRootType()?'#shadow-root':domNode.nodeNameInCorrectCase();default:return domNode.nodeNameInCorrectCase();}} -update(force){if(!this.isShowing()) -return;var currentDOMNode=this._currentDOMNode;var crumbs=this.crumbsElement;var handled=false;var crumb=crumbs.firstChild;while(crumb){if(crumb[this._nodeSymbol]===currentDOMNode){crumb.classList.add('selected');handled=true;}else{crumb.classList.remove('selected');} -crumb=crumb.nextSibling;} -if(handled&&!force){this.updateSizes();return;} -crumbs.removeChildren();for(var current=currentDOMNode;current;current=current.parentNode){if(current.nodeType()===Node.DOCUMENT_NODE) -continue;crumb=createElementWithClass('span','crumb');crumb[this._nodeSymbol]=current;crumb.addEventListener('mousedown',this._onClickCrumb.bind(this),false);var crumbTitle=this._determineElementTitle(current);if(crumbTitle){var nameElement=createElement('span');nameElement.textContent=crumbTitle;crumb.appendChild(nameElement);crumb.title=crumbTitle;}else{Components.DOMPresentationUtils.decorateNodeLabel(current,crumb);} -if(current===currentDOMNode) -crumb.classList.add('selected');crumbs.insertBefore(crumb,crumbs.firstChild);} -this.updateSizes();} -_resetCrumbStylesAndFindSelections(focusedCrumb){var crumbs=this.crumbsElement;var selectedIndex=0;var focusedIndex=0;var selectedCrumb=null;for(var i=0;i<crumbs.childNodes.length;++i){var crumb=crumbs.children[i];if(!selectedCrumb&&crumb.classList.contains('selected')){selectedCrumb=crumb;selectedIndex=i;} -if(crumb===focusedCrumb) -focusedIndex=i;crumb.classList.remove('compact','collapsed','hidden');} -return{selectedIndex:selectedIndex,focusedIndex:focusedIndex,selectedCrumb:selectedCrumb};} -_measureElementSizes(){var crumbs=this.crumbsElement;var collapsedElement=createElementWithClass('span','crumb collapsed');crumbs.insertBefore(collapsedElement,crumbs.firstChild);var available=crumbs.offsetWidth;var collapsed=collapsedElement.offsetWidth;var normalSizes=[];for(var i=1;i<crumbs.childNodes.length;++i){var crumb=crumbs.childNodes[i];normalSizes[i-1]=crumb.offsetWidth;} -crumbs.removeChild(collapsedElement);var compactSizes=[];for(var i=0;i<crumbs.childNodes.length;++i){var crumb=crumbs.childNodes[i];crumb.classList.add('compact');} -for(var i=0;i<crumbs.childNodes.length;++i){var crumb=crumbs.childNodes[i];compactSizes[i]=crumb.offsetWidth;} -for(var i=0;i<crumbs.childNodes.length;++i){var crumb=crumbs.childNodes[i];crumb.classList.remove('compact','collapsed');} -return{normal:normalSizes,compact:compactSizes,collapsed:collapsed,available:available};} -updateSizes(focusedCrumb){if(!this.isShowing()) -return;var crumbs=this.crumbsElement;if(!crumbs.firstChild) -return;var selections=this._resetCrumbStylesAndFindSelections(focusedCrumb);var sizes=this._measureElementSizes();var selectedIndex=selections.selectedIndex;var focusedIndex=selections.focusedIndex;var selectedCrumb=selections.selectedCrumb;function crumbsAreSmallerThanContainer(){var totalSize=0;for(var i=0;i<crumbs.childNodes.length;++i){var crumb=crumbs.childNodes[i];if(crumb.classList.contains('hidden')) -continue;if(crumb.classList.contains('collapsed')){totalSize+=sizes.collapsed;continue;} -totalSize+=crumb.classList.contains('compact')?sizes.compact[i]:sizes.normal[i];} -const rightPadding=10;return totalSize+rightPadding<sizes.available;} -if(crumbsAreSmallerThanContainer()) -return;var BothSides=0;var AncestorSide=-1;var ChildSide=1;function makeCrumbsSmaller(shrinkingFunction,direction){var significantCrumb=focusedCrumb||selectedCrumb;var significantIndex=significantCrumb===selectedCrumb?selectedIndex:focusedIndex;function shrinkCrumbAtIndex(index){var shrinkCrumb=crumbs.children[index];if(shrinkCrumb&&shrinkCrumb!==significantCrumb) -shrinkingFunction(shrinkCrumb);if(crumbsAreSmallerThanContainer()) -return true;return false;} -if(direction){var index=(direction>0?0:crumbs.childNodes.length-1);while(index!==significantIndex){if(shrinkCrumbAtIndex(index)) -return true;index+=(direction>0?1:-1);}}else{var startIndex=0;var endIndex=crumbs.childNodes.length-1;while(startIndex!==significantIndex||endIndex!==significantIndex){var startDistance=significantIndex-startIndex;var endDistance=endIndex-significantIndex;if(startDistance>=endDistance) -var index=startIndex++;else -var index=endIndex--;if(shrinkCrumbAtIndex(index)) -return true;}} -return false;} -function coalesceCollapsedCrumbs(){var crumb=crumbs.firstChild;var collapsedRun=false;var newStartNeeded=false;var newEndNeeded=false;while(crumb){var hidden=crumb.classList.contains('hidden');if(!hidden){var collapsed=crumb.classList.contains('collapsed');if(collapsedRun&&collapsed){crumb.classList.add('hidden');crumb.classList.remove('compact');crumb.classList.remove('collapsed');if(crumb.classList.contains('start')){crumb.classList.remove('start');newStartNeeded=true;} -if(crumb.classList.contains('end')){crumb.classList.remove('end');newEndNeeded=true;} -continue;} -collapsedRun=collapsed;if(newEndNeeded){newEndNeeded=false;crumb.classList.add('end');}}else{collapsedRun=true;} -crumb=crumb.nextSibling;} -if(newStartNeeded){crumb=crumbs.lastChild;while(crumb){if(!crumb.classList.contains('hidden')){crumb.classList.add('start');break;} -crumb=crumb.previousSibling;}}} -function compact(crumb){if(crumb.classList.contains('hidden')) -return;crumb.classList.add('compact');} -function collapse(crumb,dontCoalesce){if(crumb.classList.contains('hidden')) -return;crumb.classList.add('collapsed');crumb.classList.remove('compact');if(!dontCoalesce) -coalesceCollapsedCrumbs();} -if(!focusedCrumb){if(makeCrumbsSmaller(compact,ChildSide)) -return;if(makeCrumbsSmaller(collapse,ChildSide)) -return;} -if(makeCrumbsSmaller(compact,focusedCrumb?BothSides:AncestorSide)) -return;if(makeCrumbsSmaller(collapse,focusedCrumb?BothSides:AncestorSide)) -return;if(!selectedCrumb) -return;compact(selectedCrumb);if(crumbsAreSmallerThanContainer()) -return;collapse(selectedCrumb,true);}};Elements.ElementsBreadcrumbs.Events={NodeSelected:Symbol('NodeSelected')};;Elements.ElementsSidebarPane=class extends UI.VBox{constructor(){super(true);this.element.classList.add('flex-none');this._computedStyleModel=new Elements.ComputedStyleModel();this._computedStyleModel.addEventListener(Elements.ComputedStyleModel.Events.ComputedStyleChanged,this.onCSSModelChanged,this);this._updateThrottler=new Common.Throttler(100);this._updateWhenVisible=false;} -node(){return this._computedStyleModel.node();} -cssModel(){return this._computedStyleModel.cssModel();} -doUpdate(){return Promise.resolve();} -update(){this._updateWhenVisible=!this.isShowing();if(this._updateWhenVisible) -return;this._updateThrottler.schedule(innerUpdate.bind(this));function innerUpdate(){return this.isShowing()?this.doUpdate():Promise.resolve();}} -wasShown(){super.wasShown();if(this._updateWhenVisible) -this.update();} -onCSSModelChanged(event){}};;Elements.ElementsTreeElement=class extends UI.TreeElement{constructor(node,elementCloseTag){super();this._node=node;this._gutterContainer=this.listItemElement.createChild('div','gutter-container');this._gutterContainer.addEventListener('click',this._showContextMenu.bind(this));var gutterMenuIcon=UI.Icon.create('largeicon-menu','gutter-menu-icon');this._gutterContainer.appendChild(gutterMenuIcon);this._decorationsElement=this._gutterContainer.createChild('div','hidden');this._elementCloseTag=elementCloseTag;if(this._node.nodeType()===Node.ELEMENT_NODE&&!elementCloseTag) -this._canAddAttributes=true;this._searchQuery=null;this._expandedChildrenLimit=Elements.ElementsTreeElement.InitialChildrenLimit;this._decorationsThrottler=new Common.Throttler(100);} -static animateOnDOMUpdate(treeElement){var tagName=treeElement.listItemElement.querySelector('.webkit-html-tag-name');UI.runCSSAnimationOnce(tagName||treeElement.listItemElement,'dom-update-highlight');} -static visibleShadowRoots(node){var roots=node.shadowRoots();if(roots.length&&!Common.moduleSetting('showUAShadowDOM').get()) -roots=roots.filter(filter);function filter(root){return root.shadowRootType()!==SDK.DOMNode.ShadowRootTypes.UserAgent;} -return roots;} -static canShowInlineText(node){if(node.importedDocument()||node.templateContent()||Elements.ElementsTreeElement.visibleShadowRoots(node).length||node.hasPseudoElements()) -return false;if(node.nodeType()!==Node.ELEMENT_NODE) -return false;if(!node.firstChild||node.firstChild!==node.lastChild||node.firstChild.nodeType()!==Node.TEXT_NODE) -return false;var textChild=node.firstChild;var maxInlineTextChildLength=80;if(textChild.nodeValue().length<maxInlineTextChildLength) -return true;return false;} -static populateForcedPseudoStateItems(contextMenu,node){const pseudoClasses=['active','hover','focus','visited'];var forcedPseudoState=node.domModel().cssModel().pseudoState(node);var stateMenu=contextMenu.debugSection().appendSubMenuItem(Common.UIString('Force state'));for(var i=0;i<pseudoClasses.length;++i){var pseudoClassForced=forcedPseudoState.indexOf(pseudoClasses[i])>=0;stateMenu.defaultSection().appendCheckboxItem(':'+pseudoClasses[i],setPseudoStateCallback.bind(null,pseudoClasses[i],!pseudoClassForced),pseudoClassForced,false);} -function setPseudoStateCallback(pseudoState,enabled){node.domModel().cssModel().forcePseudoState(node,pseudoState,enabled);}} -isClosingTag(){return!!this._elementCloseTag;} -node(){return this._node;} -isEditing(){return!!this._editing;} -highlightSearchResults(searchQuery){if(this._searchQuery!==searchQuery) -this._hideSearchHighlight();this._searchQuery=searchQuery;this._searchHighlightsVisible=true;this.updateTitle(null,true);} -hideSearchHighlights(){delete this._searchHighlightsVisible;this._hideSearchHighlight();} -_hideSearchHighlight(){if(!this._highlightResult) -return;function updateEntryHide(entry){switch(entry.type){case'added':entry.node.remove();break;case'changed':entry.node.textContent=entry.oldText;break;}} -for(var i=(this._highlightResult.length-1);i>=0;--i) -updateEntryHide(this._highlightResult[i]);delete this._highlightResult;} -setInClipboard(inClipboard){if(this._inClipboard===inClipboard) -return;this._inClipboard=inClipboard;this.listItemElement.classList.toggle('in-clipboard',inClipboard);} -get hovered(){return this._hovered;} -set hovered(x){if(this._hovered===x) -return;this._hovered=x;if(this.listItemElement){if(x){this._createSelection();this.listItemElement.classList.add('hovered');}else{this.listItemElement.classList.remove('hovered');}}} -expandedChildrenLimit(){return this._expandedChildrenLimit;} -setExpandedChildrenLimit(expandedChildrenLimit){this._expandedChildrenLimit=expandedChildrenLimit;} -_createSelection(){var listItemElement=this.listItemElement;if(!listItemElement) -return;if(!this.selectionElement){this.selectionElement=createElement('div');this.selectionElement.className='selection fill';this.selectionElement.style.setProperty('margin-left',(-this._computeLeftIndent())+'px');listItemElement.insertBefore(this.selectionElement,listItemElement.firstChild);}} -_createHint(){if(this.listItemElement&&!this._hintElement){this._hintElement=this.listItemElement.createChild('span','selected-hint');this._hintElement.title=Common.UIString('Use $0 in the console to refer to this element.');}} -onbind(){if(!this._elementCloseTag) -this._node[this.treeOutline.treeElementSymbol()]=this;} -onunbind(){if(this._node[this.treeOutline.treeElementSymbol()]===this) -this._node[this.treeOutline.treeElementSymbol()]=null;} -onattach(){if(this._hovered){this._createSelection();this.listItemElement.classList.add('hovered');} -this.updateTitle();this.listItemElement.draggable=true;} -onpopulate(){this.populated=true;this.treeOutline.populateTreeElement(this);} -expandRecursively(){this._node.getSubtree(-1).then(UI.TreeElement.prototype.expandRecursively.bind(this,Number.MAX_VALUE));} -onexpand(){if(this._elementCloseTag) -return;this.updateTitle();} -oncollapse(){if(this._elementCloseTag) -return;this.updateTitle();} -select(omitFocus,selectedByUser){if(this._editing) -return false;return super.select(omitFocus,selectedByUser);} -onselect(selectedByUser){this.treeOutline.suppressRevealAndSelect=true;this.treeOutline.selectDOMNode(this._node,selectedByUser);if(selectedByUser){this._node.highlight();Host.userMetrics.actionTaken(Host.UserMetrics.Action.ChangeInspectedNodeInElementsPanel);} -this._createSelection();this._createHint();this.treeOutline.suppressRevealAndSelect=false;return true;} -ondelete(){var startTagTreeElement=this.treeOutline.findTreeElement(this._node);startTagTreeElement?startTagTreeElement.remove():this.remove();return true;} -onenter(){if(this._editing) -return false;this._startEditing();return true;} -selectOnMouseDown(event){super.selectOnMouseDown(event);if(this._editing) -return;if(event.detail>=2) -event.preventDefault();} -ondblclick(event){if(this._editing||this._elementCloseTag) -return false;if(this._startEditingTarget((event.target))) -return false;if(this.isExpandable()&&!this.expanded) -this.expand();return false;} -hasEditableNode(){return!this._node.isShadowRoot()&&!this._node.ancestorUserAgentShadowRoot();} -_insertInLastAttributePosition(tag,node){if(tag.getElementsByClassName('webkit-html-attribute').length>0){tag.insertBefore(node,tag.lastChild);}else{var nodeName=tag.textContent.match(/^<(.*?)>$/)[1];tag.textContent='';tag.createTextChild('<'+nodeName);tag.appendChild(node);tag.createTextChild('>');}} -_startEditingTarget(eventTarget){if(this.treeOutline.selectedDOMNode()!==this._node) -return false;if(this._node.nodeType()!==Node.ELEMENT_NODE&&this._node.nodeType()!==Node.TEXT_NODE) -return false;var textNode=eventTarget.enclosingNodeOrSelfWithClass('webkit-html-text-node');if(textNode) -return this._startEditingTextNode(textNode);var attribute=eventTarget.enclosingNodeOrSelfWithClass('webkit-html-attribute');if(attribute) -return this._startEditingAttribute(attribute,eventTarget);var tagName=eventTarget.enclosingNodeOrSelfWithClass('webkit-html-tag-name');if(tagName) -return this._startEditingTagName(tagName);var newAttribute=eventTarget.enclosingNodeOrSelfWithClass('add-attribute');if(newAttribute) -return this._addNewAttribute();return false;} -_showContextMenu(event){this.treeOutline.showContextMenu(this,event);} -populateTagContextMenu(contextMenu,event){var treeElement=this._elementCloseTag?this.treeOutline.findTreeElement(this._node):this;contextMenu.editSection().appendItem(Common.UIString('Add attribute'),treeElement._addNewAttribute.bind(treeElement));var attribute=event.target.enclosingNodeOrSelfWithClass('webkit-html-attribute');var newAttribute=event.target.enclosingNodeOrSelfWithClass('add-attribute');if(attribute&&!newAttribute){contextMenu.editSection().appendItem(Common.UIString('Edit attribute'),this._startEditingAttribute.bind(this,attribute,event.target));} -this.populateNodeContextMenu(contextMenu);Elements.ElementsTreeElement.populateForcedPseudoStateItems(contextMenu,treeElement.node());this.populateScrollIntoView(contextMenu);} -populateScrollIntoView(contextMenu){contextMenu.viewSection().appendItem(Common.UIString('Scroll into view'),()=>this._node.scrollIntoView());} -populateTextContextMenu(contextMenu,textNode){if(!this._editing){contextMenu.editSection().appendItem(Common.UIString('Edit text'),this._startEditingTextNode.bind(this,textNode));} -this.populateNodeContextMenu(contextMenu);} -populateNodeContextMenu(contextMenu){var isEditable=this.hasEditableNode();if(isEditable&&!this._editing) -contextMenu.editSection().appendItem(Common.UIString('Edit as HTML'),this._editAsHTML.bind(this));var isShadowRoot=this._node.isShadowRoot();var copyMenu=contextMenu.clipboardSection().appendSubMenuItem(Common.UIString('Copy'));var createShortcut=UI.KeyboardShortcut.shortcutToString;var modifier=UI.KeyboardShortcut.Modifiers.CtrlOrMeta;var treeOutline=this.treeOutline;var menuItem;if(!isShadowRoot){var section=copyMenu.section();menuItem=section.appendItem(Common.UIString('Copy outerHTML'),treeOutline.performCopyOrCut.bind(treeOutline,false,this._node));menuItem.setShortcut(createShortcut('V',modifier));} -if(this._node.nodeType()===Node.ELEMENT_NODE) -section.appendItem(Common.UIString('Copy selector'),this._copyCSSPath.bind(this));if(!isShadowRoot) -section.appendItem(Common.UIString('Copy XPath'),this._copyXPath.bind(this));if(!isShadowRoot){menuItem=copyMenu.clipboardSection().appendItem(Common.UIString('Cut element'),treeOutline.performCopyOrCut.bind(treeOutline,true,this._node),!this.hasEditableNode());menuItem.setShortcut(createShortcut('X',modifier));menuItem=copyMenu.clipboardSection().appendItem(Common.UIString('Copy element'),treeOutline.performCopyOrCut.bind(treeOutline,false,this._node));menuItem.setShortcut(createShortcut('C',modifier));menuItem=copyMenu.clipboardSection().appendItem(Common.UIString('Paste element'),treeOutline.pasteNode.bind(treeOutline,this._node),!treeOutline.canPaste(this._node));menuItem.setShortcut(createShortcut('V',modifier));} -menuItem=contextMenu.debugSection().appendCheckboxItem(Common.UIString('Hide element'),treeOutline.toggleHideElement.bind(treeOutline,this._node),treeOutline.isToggledToHidden(this._node));menuItem.setShortcut(UI.shortcutRegistry.shortcutTitleForAction('elements.hide-element'));if(isEditable) -contextMenu.editSection().appendItem(Common.UIString('Delete element'),this.remove.bind(this));contextMenu.viewSection().appendItem(Common.UIString('Expand all'),this.expandRecursively.bind(this));contextMenu.viewSection().appendItem(Common.UIString('Collapse all'),this.collapseRecursively.bind(this));} -_startEditing(){if(this.treeOutline.selectedDOMNode()!==this._node) -return;var listItem=this.listItemElement;if(this._canAddAttributes){var attribute=listItem.getElementsByClassName('webkit-html-attribute')[0];if(attribute){return this._startEditingAttribute(attribute,attribute.getElementsByClassName('webkit-html-attribute-value')[0]);} -return this._addNewAttribute();} -if(this._node.nodeType()===Node.TEXT_NODE){var textNode=listItem.getElementsByClassName('webkit-html-text-node')[0];if(textNode) -return this._startEditingTextNode(textNode);return;}} -_addNewAttribute(){var container=createElement('span');this._buildAttributeDOM(container,' ','',null);var attr=container.firstElementChild;attr.style.marginLeft='2px';attr.style.marginRight='2px';var tag=this.listItemElement.getElementsByClassName('webkit-html-tag')[0];this._insertInLastAttributePosition(tag,attr);attr.scrollIntoViewIfNeeded(true);return this._startEditingAttribute(attr,attr);} -_triggerEditAttribute(attributeName){var attributeElements=this.listItemElement.getElementsByClassName('webkit-html-attribute-name');for(var i=0,len=attributeElements.length;i<len;++i){if(attributeElements[i].textContent===attributeName){for(var elem=attributeElements[i].nextSibling;elem;elem=elem.nextSibling){if(elem.nodeType!==Node.ELEMENT_NODE) -continue;if(elem.classList.contains('webkit-html-attribute-value')) -return this._startEditingAttribute(elem.parentNode,elem);}}}} -_startEditingAttribute(attribute,elementForSelection){console.assert(this.listItemElement.isAncestor(attribute));if(UI.isBeingEdited(attribute)) -return true;var attributeNameElement=attribute.getElementsByClassName('webkit-html-attribute-name')[0];if(!attributeNameElement) -return false;var attributeName=attributeNameElement.textContent;var attributeValueElement=attribute.getElementsByClassName('webkit-html-attribute-value')[0];elementForSelection=attributeValueElement.isAncestor(elementForSelection)?attributeValueElement:elementForSelection;function removeZeroWidthSpaceRecursive(node){if(node.nodeType===Node.TEXT_NODE){node.nodeValue=node.nodeValue.replace(/\u200B/g,'');return;} -if(node.nodeType!==Node.ELEMENT_NODE) -return;for(var child=node.firstChild;child;child=child.nextSibling) -removeZeroWidthSpaceRecursive(child);} -var attributeValue=attributeName&&attributeValueElement?this._node.getAttribute(attributeName):undefined;if(attributeValue!==undefined){attributeValueElement.setTextContentTruncatedIfNeeded(attributeValue,Common.UIString('<value is too large to edit>'));} -removeZeroWidthSpaceRecursive(attribute);var config=new UI.InplaceEditor.Config(this._attributeEditingCommitted.bind(this),this._editingCancelled.bind(this),attributeName);function postKeyDownFinishHandler(event){UI.handleElementValueModifications(event,attribute);return'';} -if(!attributeValueElement.textContent.asParsedURL()) -config.setPostKeydownFinishHandler(postKeyDownFinishHandler);this._editing=UI.InplaceEditor.startEditing(attribute,config);this.listItemElement.getComponentSelection().selectAllChildren(elementForSelection);return true;} -_startEditingTextNode(textNodeElement){if(UI.isBeingEdited(textNodeElement)) -return true;var textNode=this._node;if(textNode.nodeType()===Node.ELEMENT_NODE&&textNode.firstChild) -textNode=textNode.firstChild;var container=textNodeElement.enclosingNodeOrSelfWithClass('webkit-html-text-node');if(container) -container.textContent=textNode.nodeValue();var config=new UI.InplaceEditor.Config(this._textNodeEditingCommitted.bind(this,textNode),this._editingCancelled.bind(this));this._editing=UI.InplaceEditor.startEditing(textNodeElement,config);this.listItemElement.getComponentSelection().selectAllChildren(textNodeElement);return true;} -_startEditingTagName(tagNameElement){if(!tagNameElement){tagNameElement=this.listItemElement.getElementsByClassName('webkit-html-tag-name')[0];if(!tagNameElement) -return false;} -var tagName=tagNameElement.textContent;if(Elements.ElementsTreeElement.EditTagBlacklist.has(tagName.toLowerCase())) -return false;if(UI.isBeingEdited(tagNameElement)) -return true;var closingTagElement=this._distinctClosingTagElement();function keyupListener(event){if(closingTagElement) -closingTagElement.textContent='</'+tagNameElement.textContent+'>';} -function editingComitted(element,newTagName){tagNameElement.removeEventListener('keyup',keyupListener,false);this._tagNameEditingCommitted.apply(this,arguments);} -function editingCancelled(){tagNameElement.removeEventListener('keyup',keyupListener,false);this._editingCancelled.apply(this,arguments);} -tagNameElement.addEventListener('keyup',keyupListener,false);var config=new UI.InplaceEditor.Config(editingComitted.bind(this),editingCancelled.bind(this),tagName);this._editing=UI.InplaceEditor.startEditing(tagNameElement,config);this.listItemElement.getComponentSelection().selectAllChildren(tagNameElement);return true;} -_startEditingAsHTML(commitCallback,disposeCallback,maybeInitialValue){if(maybeInitialValue===null) -return;var initialValue=maybeInitialValue;if(this._editing) -return;function consume(event){if(event.eventPhase===Event.AT_TARGET) -event.consume(true);} -initialValue=this._convertWhitespaceToEntities(initialValue).text;this._htmlEditElement=createElement('div');this._htmlEditElement.className='source-code elements-tree-editor';var child=this.listItemElement.firstChild;while(child){child.style.display='none';child=child.nextSibling;} -if(this.childrenListElement) -this.childrenListElement.style.display='none';this.listItemElement.appendChild(this._htmlEditElement);this.treeOutline.element.addEventListener('mousedown',consume,false);self.runtime.extension(UI.TextEditorFactory).instance().then(gotFactory.bind(this));function gotFactory(factory){var editor=factory.createEditor({lineNumbers:false,lineWrapping:Common.moduleSetting('domWordWrap').get(),mimeType:'text/html',autoHeight:false,padBottom:false});this._editing={commit:commit.bind(this),cancel:dispose.bind(this),editor:editor,resize:resize.bind(this)};resize.call(this);editor.widget().show(this._htmlEditElement);editor.setText(initialValue);editor.widget().focus();editor.widget().element.addEventListener('blur',this._editing.commit,true);editor.widget().element.addEventListener('keydown',keydown.bind(this),true);this.treeOutline.setMultilineEditing(this._editing);} -function resize(){this._htmlEditElement.style.width=this.treeOutline.visibleWidth()-this._computeLeftIndent()-30+'px';this._editing.editor.onResize();} -function commit(){commitCallback(initialValue,this._editing.editor.text());dispose.call(this);} -function dispose(){this._editing.editor.widget().element.removeEventListener('blur',this._editing.commit,true);this._editing.editor.widget().detach();delete this._editing;this.listItemElement.removeChild(this._htmlEditElement);delete this._htmlEditElement;if(this.childrenListElement) -this.childrenListElement.style.removeProperty('display');var child=this.listItemElement.firstChild;while(child){child.style.removeProperty('display');child=child.nextSibling;} -if(this.treeOutline){this.treeOutline.setMultilineEditing(null);this.treeOutline.element.removeEventListener('mousedown',consume,false);this.treeOutline.focus();} -disposeCallback();} -function keydown(event){var isMetaOrCtrl=UI.KeyboardShortcut.eventHasCtrlOrMeta((event))&&!event.altKey&&!event.shiftKey;if(isEnterKey(event)&&(isMetaOrCtrl||event.isMetaOrCtrlForTest)){event.consume(true);this._editing.commit();}else if(event.keyCode===UI.KeyboardShortcut.Keys.Esc.code||event.key==='Escape'){event.consume(true);this._editing.cancel();}}} -_attributeEditingCommitted(element,newText,oldText,attributeName,moveDirection){delete this._editing;var treeOutline=this.treeOutline;function moveToNextAttributeIfNeeded(error){if(error) -this._editingCancelled(element,attributeName);if(!moveDirection) -return;treeOutline.runPendingUpdates();treeOutline.focus();var attributes=this._node.attributes();for(var i=0;i<attributes.length;++i){if(attributes[i].name!==attributeName) -continue;if(moveDirection==='backward'){if(i===0) -this._startEditingTagName();else -this._triggerEditAttribute(attributes[i-1].name);}else{if(i===attributes.length-1) -this._addNewAttribute();else -this._triggerEditAttribute(attributes[i+1].name);} -return;} -if(moveDirection==='backward'){if(newText===' '){if(attributes.length>0) -this._triggerEditAttribute(attributes[attributes.length-1].name);}else{if(attributes.length>1) -this._triggerEditAttribute(attributes[attributes.length-2].name);}}else if(moveDirection==='forward'){if(!newText.isWhitespace()) -this._addNewAttribute();else -this._startEditingTagName();}} -if((attributeName.trim()||newText.trim())&&oldText!==newText){this._node.setAttribute(attributeName,newText,moveToNextAttributeIfNeeded.bind(this));return;} -this.updateTitle();moveToNextAttributeIfNeeded.call(this);} -_tagNameEditingCommitted(element,newText,oldText,tagName,moveDirection){delete this._editing;var self=this;function cancel(){var closingTagElement=self._distinctClosingTagElement();if(closingTagElement) -closingTagElement.textContent='</'+tagName+'>';self._editingCancelled(element,tagName);moveToNextAttributeIfNeeded.call(self);} -function moveToNextAttributeIfNeeded(){if(moveDirection!=='forward'){this._addNewAttribute();return;} -var attributes=this._node.attributes();if(attributes.length>0) -this._triggerEditAttribute(attributes[0].name);else -this._addNewAttribute();} -newText=newText.trim();if(newText===oldText){cancel();return;} -var treeOutline=this.treeOutline;var wasExpanded=this.expanded;function changeTagNameCallback(error,nodeId){if(error||!nodeId){cancel();return;} -var newTreeItem=treeOutline.selectNodeAfterEdit(wasExpanded,error,nodeId);moveToNextAttributeIfNeeded.call(newTreeItem);} -this._node.setNodeName(newText,changeTagNameCallback);} -_textNodeEditingCommitted(textNode,element,newText){delete this._editing;function callback(){this.updateTitle();} -textNode.setNodeValue(newText,callback.bind(this));} -_editingCancelled(element,context){delete this._editing;this.updateTitle();} -_distinctClosingTagElement(){if(this.expanded){var closers=this.childrenListElement.querySelectorAll('.close');return closers[closers.length-1];} -var tags=this.listItemElement.getElementsByClassName('webkit-html-tag');return(tags.length===1?null:tags[tags.length-1]);} -updateTitle(updateRecord,onlySearchQueryChanged){if(this._editing) -return;if(onlySearchQueryChanged){this._hideSearchHighlight();}else{var nodeInfo=this._nodeTitleInfo(updateRecord||null);if(this._node.nodeType()===Node.DOCUMENT_FRAGMENT_NODE&&this._node.isInShadowTree()&&this._node.shadowRootType()){this.childrenListElement.classList.add('shadow-root');var depth=4;for(var node=this._node;depth&&node;node=node.parentNode){if(node.nodeType()===Node.DOCUMENT_FRAGMENT_NODE) -depth--;} -if(!depth) -this.childrenListElement.classList.add('shadow-root-deep');else -this.childrenListElement.classList.add('shadow-root-depth-'+depth);} -var highlightElement=createElement('span');highlightElement.className='highlight';highlightElement.appendChild(nodeInfo);this.title=highlightElement;this.updateDecorations();this.listItemElement.insertBefore(this._gutterContainer,this.listItemElement.firstChild);delete this._highlightResult;delete this.selectionElement;delete this._hintElement;if(this.selected){this._createSelection();this._createHint();}} -this._highlightSearchResults();} -_computeLeftIndent(){var treeElement=this.parent;var depth=0;while(treeElement!==null){depth++;treeElement=treeElement.parent;} -return 12*(depth-2)+(this.isExpandable()?1:12);} -updateDecorations(){this._gutterContainer.style.left=(-this._computeLeftIndent())+'px';if(this.isClosingTag()) -return;if(this._node.nodeType()!==Node.ELEMENT_NODE) -return;this._decorationsThrottler.schedule(this._updateDecorationsInternal.bind(this));} -_updateDecorationsInternal(){if(!this.treeOutline) -return Promise.resolve();var node=this._node;if(!this.treeOutline._decoratorExtensions) -this.treeOutline._decoratorExtensions=runtime.extensions(Components.DOMPresentationUtils.MarkerDecorator);var markerToExtension=new Map();for(var i=0;i<this.treeOutline._decoratorExtensions.length;++i){markerToExtension.set(this.treeOutline._decoratorExtensions[i].descriptor()['marker'],this.treeOutline._decoratorExtensions[i]);} -var promises=[];var decorations=[];var descendantDecorations=[];node.traverseMarkers(visitor);function visitor(n,marker){var extension=markerToExtension.get(marker);if(!extension) -return;promises.push(extension.instance().then(collectDecoration.bind(null,n)));} -function collectDecoration(n,decorator){var decoration=decorator.decorate(n);if(!decoration) -return;(n===node?decorations:descendantDecorations).push(decoration);} -return Promise.all(promises).then(updateDecorationsUI.bind(this));function updateDecorationsUI(){this._decorationsElement.removeChildren();this._decorationsElement.classList.add('hidden');this._gutterContainer.classList.toggle('has-decorations',decorations.length||descendantDecorations.length);if(!decorations.length&&!descendantDecorations.length) -return;var colors=new Set();var titles=createElement('div');for(var decoration of decorations){var titleElement=titles.createChild('div');titleElement.textContent=decoration.title;colors.add(decoration.color);} -if(this.expanded&&!decorations.length) -return;var descendantColors=new Set();if(descendantDecorations.length){var element=titles.createChild('div');element.textContent=Common.UIString('Children:');for(var decoration of descendantDecorations){element=titles.createChild('div');element.style.marginLeft='15px';element.textContent=decoration.title;descendantColors.add(decoration.color);}} -var offset=0;processColors.call(this,colors,'elements-gutter-decoration');if(!this.expanded) -processColors.call(this,descendantColors,'elements-gutter-decoration elements-has-decorated-children');UI.Tooltip.install(this._decorationsElement,titles);function processColors(colors,className){for(var color of colors){var child=this._decorationsElement.createChild('div',className);this._decorationsElement.classList.remove('hidden');child.style.backgroundColor=color;child.style.borderColor=color;if(offset) -child.style.marginLeft=offset+'px';offset+=3;}}}} -_buildAttributeDOM(parentElement,name,value,updateRecord,forceValue,node){var closingPunctuationRegex=/[\/;:\)\]\}]/g;var highlightIndex=0;var highlightCount;var additionalHighlightOffset=0;var result;function replacer(match,replaceOffset){while(highlightIndex<highlightCount&&result.entityRanges[highlightIndex].offset<replaceOffset){result.entityRanges[highlightIndex].offset+=additionalHighlightOffset;++highlightIndex;} -additionalHighlightOffset+=1;return match+'\u200B';} -function setValueWithEntities(element,value){result=this._convertWhitespaceToEntities(value);highlightCount=result.entityRanges.length;value=result.text.replace(closingPunctuationRegex,replacer);while(highlightIndex<highlightCount){result.entityRanges[highlightIndex].offset+=additionalHighlightOffset;++highlightIndex;} -element.setTextContentTruncatedIfNeeded(value);UI.highlightRangesWithStyleClass(element,result.entityRanges,'webkit-html-entity-value');} -var hasText=(forceValue||value.length>0);var attrSpanElement=parentElement.createChild('span','webkit-html-attribute');var attrNameElement=attrSpanElement.createChild('span','webkit-html-attribute-name');attrNameElement.textContent=name;if(hasText) -attrSpanElement.createTextChild('=\u200B"');var attrValueElement=attrSpanElement.createChild('span','webkit-html-attribute-value');if(updateRecord&&updateRecord.isAttributeModified(name)) -UI.runCSSAnimationOnce(hasText?attrValueElement:attrNameElement,'dom-update-highlight');function linkifyValue(value){var rewrittenHref=node.resolveURL(value);if(rewrittenHref===null){var span=createElement('span');setValueWithEntities.call(this,span,value);return span;} -value=value.replace(closingPunctuationRegex,'$&\u200B');if(value.startsWith('data:')) -value=value.trimMiddle(60);var link=node.nodeName().toLowerCase()==='a'?UI.createExternalLink(rewrittenHref,value,'',true):Components.Linkifier.linkifyURL(rewrittenHref,{text:value,preventClick:true});link[Elements.ElementsTreeElement.HrefSymbol]=rewrittenHref;return link;} -var nodeName=node?node.nodeName().toLowerCase():'';if(nodeName&&(name==='src'||name==='href')) -attrValueElement.appendChild(linkifyValue.call(this,value));else if((nodeName==='img'||nodeName==='source')&&name==='srcset') -attrValueElement.appendChild(linkifySrcset.call(this,value));else -setValueWithEntities.call(this,attrValueElement,value);if(hasText) -attrSpanElement.createTextChild('"');function linkifySrcset(value){var fragment=createDocumentFragment();var i=0;while(value.length){if(i++>0) -fragment.createTextChild(' ');value=value.trim();var url='';var descriptor='';var indexOfSpace=value.search(/\s/);if(indexOfSpace===-1){url=value;}else if(indexOfSpace>0&&value[indexOfSpace-1]===','){url=value.substring(0,indexOfSpace);}else{url=value.substring(0,indexOfSpace);var indexOfComma=value.indexOf(',',indexOfSpace);if(indexOfComma!==-1) -descriptor=value.substring(indexOfSpace,indexOfComma+1);else -descriptor=value.substring(indexOfSpace);} -if(url){if(url.endsWith(',')){fragment.appendChild(linkifyValue.call(this,url.substring(0,url.length-1)));fragment.createTextChild(',');}else{fragment.appendChild(linkifyValue.call(this,url));}} -if(descriptor) -fragment.createTextChild(descriptor);value=value.substring(url.length+descriptor.length);} -return fragment;}} -_buildPseudoElementDOM(parentElement,pseudoElementName){var pseudoElement=parentElement.createChild('span','webkit-html-pseudo-element');pseudoElement.textContent='::'+pseudoElementName;parentElement.createTextChild('\u200B');} -_buildTagDOM(parentElement,tagName,isClosingTag,isDistinctTreeElement,updateRecord){var node=this._node;var classes=['webkit-html-tag'];if(isClosingTag&&isDistinctTreeElement) -classes.push('close');var tagElement=parentElement.createChild('span',classes.join(' '));tagElement.createTextChild('<');var tagNameElement=tagElement.createChild('span',isClosingTag?'webkit-html-close-tag-name':'webkit-html-tag-name');tagNameElement.textContent=(isClosingTag?'/':'')+tagName;if(!isClosingTag){if(node.hasAttributes()){var attributes=node.attributes();for(var i=0;i<attributes.length;++i){var attr=attributes[i];tagElement.createTextChild(' ');this._buildAttributeDOM(tagElement,attr.name,attr.value,updateRecord,false,node);}} -if(updateRecord){var hasUpdates=updateRecord.hasRemovedAttributes()||updateRecord.hasRemovedChildren();hasUpdates|=!this.expanded&&updateRecord.hasChangedChildren();if(hasUpdates) -UI.runCSSAnimationOnce(tagNameElement,'dom-update-highlight');}} -tagElement.createTextChild('>');parentElement.createTextChild('\u200B');} -_convertWhitespaceToEntities(text){var result='';var lastIndexAfterEntity=0;var entityRanges=[];var charToEntity=Elements.ElementsTreeOutline.MappedCharToEntity;for(var i=0,size=text.length;i<size;++i){var char=text.charAt(i);if(charToEntity[char]){result+=text.substring(lastIndexAfterEntity,i);var entityValue='&'+charToEntity[char]+';';entityRanges.push({offset:result.length,length:entityValue.length});result+=entityValue;lastIndexAfterEntity=i+1;}} -if(result) -result+=text.substring(lastIndexAfterEntity);return{text:result||text,entityRanges:entityRanges};} -_nodeTitleInfo(updateRecord){var node=this._node;var titleDOM=createDocumentFragment();switch(node.nodeType()){case Node.ATTRIBUTE_NODE:this._buildAttributeDOM(titleDOM,(node.name),(node.value),updateRecord,true);break;case Node.ELEMENT_NODE:var pseudoType=node.pseudoType();if(pseudoType){this._buildPseudoElementDOM(titleDOM,pseudoType);break;} -var tagName=node.nodeNameInCorrectCase();if(this._elementCloseTag){this._buildTagDOM(titleDOM,tagName,true,true,updateRecord);break;} -this._buildTagDOM(titleDOM,tagName,false,false,updateRecord);if(this.isExpandable()){if(!this.expanded){var textNodeElement=titleDOM.createChild('span','webkit-html-text-node bogus');textNodeElement.textContent='\u2026';titleDOM.createTextChild('\u200B');this._buildTagDOM(titleDOM,tagName,true,false,updateRecord);} -break;} -if(Elements.ElementsTreeElement.canShowInlineText(node)){var textNodeElement=titleDOM.createChild('span','webkit-html-text-node');var result=this._convertWhitespaceToEntities(node.firstChild.nodeValue());textNodeElement.textContent=result.text;UI.highlightRangesWithStyleClass(textNodeElement,result.entityRanges,'webkit-html-entity-value');titleDOM.createTextChild('\u200B');this._buildTagDOM(titleDOM,tagName,true,false,updateRecord);if(updateRecord&&updateRecord.hasChangedChildren()) -UI.runCSSAnimationOnce(textNodeElement,'dom-update-highlight');if(updateRecord&&updateRecord.isCharDataModified()) -UI.runCSSAnimationOnce(textNodeElement,'dom-update-highlight');break;} -if(this.treeOutline.isXMLMimeType||!Elements.ElementsTreeElement.ForbiddenClosingTagElements.has(tagName)) -this._buildTagDOM(titleDOM,tagName,true,false,updateRecord);break;case Node.TEXT_NODE:if(node.parentNode&&node.parentNode.nodeName().toLowerCase()==='script'){var newNode=titleDOM.createChild('span','webkit-html-text-node webkit-html-js-node');var text=node.nodeValue();newNode.textContent=text.startsWith('\n')?text.substring(1):text;var javascriptSyntaxHighlighter=new UI.SyntaxHighlighter('text/javascript',true);javascriptSyntaxHighlighter.syntaxHighlightNode(newNode).then(updateSearchHighlight.bind(this));}else if(node.parentNode&&node.parentNode.nodeName().toLowerCase()==='style'){var newNode=titleDOM.createChild('span','webkit-html-text-node webkit-html-css-node');var text=node.nodeValue();newNode.textContent=text.startsWith('\n')?text.substring(1):text;var cssSyntaxHighlighter=new UI.SyntaxHighlighter('text/css',true);cssSyntaxHighlighter.syntaxHighlightNode(newNode).then(updateSearchHighlight.bind(this));}else{titleDOM.createTextChild('"');var textNodeElement=titleDOM.createChild('span','webkit-html-text-node');var result=this._convertWhitespaceToEntities(node.nodeValue());textNodeElement.textContent=result.text;UI.highlightRangesWithStyleClass(textNodeElement,result.entityRanges,'webkit-html-entity-value');titleDOM.createTextChild('"');if(updateRecord&&updateRecord.isCharDataModified()) -UI.runCSSAnimationOnce(textNodeElement,'dom-update-highlight');} -break;case Node.COMMENT_NODE:var commentElement=titleDOM.createChild('span','webkit-html-comment');commentElement.createTextChild('<!--'+node.nodeValue()+'-->');break;case Node.DOCUMENT_TYPE_NODE:var docTypeElement=titleDOM.createChild('span','webkit-html-doctype');docTypeElement.createTextChild('<!DOCTYPE '+node.nodeName());if(node.publicId){docTypeElement.createTextChild(' PUBLIC "'+node.publicId+'"');if(node.systemId) -docTypeElement.createTextChild(' "'+node.systemId+'"');}else if(node.systemId){docTypeElement.createTextChild(' SYSTEM "'+node.systemId+'"');} -if(node.internalSubset) -docTypeElement.createTextChild(' ['+node.internalSubset+']');docTypeElement.createTextChild('>');break;case Node.CDATA_SECTION_NODE:var cdataElement=titleDOM.createChild('span','webkit-html-text-node');cdataElement.createTextChild('<![CDATA['+node.nodeValue()+']]>');break;case Node.DOCUMENT_FRAGMENT_NODE:var fragmentElement=titleDOM.createChild('span','webkit-html-fragment');fragmentElement.textContent=node.nodeNameInCorrectCase().collapseWhitespace();break;default:titleDOM.createTextChild(node.nodeNameInCorrectCase().collapseWhitespace());} -function updateSearchHighlight(){delete this._highlightResult;this._highlightSearchResults();} -return titleDOM;} -remove(){if(this._node.pseudoType()) -return;var parentElement=this.parent;if(!parentElement) -return;if(!this._node.parentNode||this._node.parentNode.nodeType()===Node.DOCUMENT_NODE) -return;this._node.removeNode();} -toggleEditAsHTML(callback,startEditing){if(this._editing&&this._htmlEditElement){this._editing.commit();return;} -if(startEditing===false) -return;function selectNode(error){if(callback) -callback(!error);} -function commitChange(initialValue,value){if(initialValue!==value) -node.setOuterHTML(value,selectNode);} -function disposeCallback(){if(callback) -callback(false);} -var node=this._node;node.getOuterHTML().then(this._startEditingAsHTML.bind(this,commitChange,disposeCallback));} -_copyCSSPath(){InspectorFrontendHost.copyText(Components.DOMPresentationUtils.cssPath(this._node,true));} -_copyXPath(){InspectorFrontendHost.copyText(Components.DOMPresentationUtils.xPath(this._node,true));} -_highlightSearchResults(){if(!this._searchQuery||!this._searchHighlightsVisible) -return;this._hideSearchHighlight();var text=this.listItemElement.textContent;var regexObject=createPlainTextSearchRegex(this._searchQuery,'gi');var match=regexObject.exec(text);var matchRanges=[];while(match){matchRanges.push(new TextUtils.SourceRange(match.index,match[0].length));match=regexObject.exec(text);} -if(!matchRanges.length) -matchRanges.push(new TextUtils.SourceRange(0,text.length));this._highlightResult=[];UI.highlightSearchResults(this.listItemElement,matchRanges,this._highlightResult);} -_editAsHTML(){var promise=Common.Revealer.revealPromise(this.node());promise.then(()=>UI.actionRegistry.action('elements.edit-as-html').execute());}};Elements.ElementsTreeElement.HrefSymbol=Symbol('ElementsTreeElement.Href');Elements.ElementsTreeElement.InitialChildrenLimit=500;Elements.ElementsTreeElement.ForbiddenClosingTagElements=new Set(['area','base','basefont','br','canvas','col','command','embed','frame','hr','img','input','keygen','link','menuitem','meta','param','source','track','wbr']);Elements.ElementsTreeElement.EditTagBlacklist=new Set(['html','head','body']);Elements.MultilineEditorController;;Elements.ElementsTreeOutline=class extends UI.TreeOutline{constructor(domModel,omitRootDOMNode,selectEnabled){super();this._domModel=domModel;this._treeElementSymbol=Symbol('treeElement');var shadowContainer=createElement('div');this._shadowRoot=UI.createShadowRootWithCoreStyles(shadowContainer,'elements/elementsTreeOutline.css');var outlineDisclosureElement=this._shadowRoot.createChild('div','elements-disclosure');this._element=this.element;this._element.classList.add('elements-tree-outline','source-code');UI.ARIAUtils.setAccessibleName(this._element,Common.UIString('Page DOM'));this._element.addEventListener('mousedown',this._onmousedown.bind(this),false);this._element.addEventListener('mousemove',this._onmousemove.bind(this),false);this._element.addEventListener('mouseleave',this._onmouseleave.bind(this),false);this._element.addEventListener('dragstart',this._ondragstart.bind(this),false);this._element.addEventListener('dragover',this._ondragover.bind(this),false);this._element.addEventListener('dragleave',this._ondragleave.bind(this),false);this._element.addEventListener('drop',this._ondrop.bind(this),false);this._element.addEventListener('dragend',this._ondragend.bind(this),false);this._element.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),false);this._element.addEventListener('clipboard-beforecopy',this._onBeforeCopy.bind(this),false);this._element.addEventListener('clipboard-copy',this._onCopyOrCut.bind(this,false),false);this._element.addEventListener('clipboard-cut',this._onCopyOrCut.bind(this,true),false);this._element.addEventListener('clipboard-paste',this._onPaste.bind(this),false);outlineDisclosureElement.appendChild(this._element);this.element=shadowContainer;this._includeRootDOMNode=!omitRootDOMNode;this._selectEnabled=selectEnabled;this._rootDOMNode=null;this._selectedDOMNode=null;this._visible=false;this._popoverHelper=new UI.PopoverHelper(this._element,this._getPopoverRequest.bind(this));this._popoverHelper.setHasPadding(true);this._popoverHelper.setTimeout(0,100);this._updateRecords=new Map();this._treeElementsBeingUpdated=new Set();this._domModel.addEventListener(SDK.DOMModel.Events.MarkersChanged,this._markersChanged,this);this._showHTMLCommentsSetting=Common.moduleSetting('showHTMLComments');this._showHTMLCommentsSetting.addChangeListener(this._onShowHTMLCommentsChange.bind(this));} -static forDOMModel(domModel){return domModel[Elements.ElementsTreeOutline._treeOutlineSymbol]||null;} -_onShowHTMLCommentsChange(){var selectedNode=this.selectedDOMNode();if(selectedNode&&selectedNode.nodeType()===Node.COMMENT_NODE&&!this._showHTMLCommentsSetting.get()) -this.selectDOMNode(selectedNode.parentNode);this.update();} -treeElementSymbol(){return this._treeElementSymbol;} -setWordWrap(wrap){this._element.classList.toggle('elements-tree-nowrap',!wrap);} -domModel(){return this._domModel;} -setMultilineEditing(multilineEditing){this._multilineEditing=multilineEditing;} -visibleWidth(){return this._visibleWidth;} -setVisibleWidth(width){this._visibleWidth=width;if(this._multilineEditing) -this._multilineEditing.resize();} -_setClipboardData(data){if(this._clipboardNodeData){var treeElement=this.findTreeElement(this._clipboardNodeData.node);if(treeElement) -treeElement.setInClipboard(false);delete this._clipboardNodeData;} -if(data){var treeElement=this.findTreeElement(data.node);if(treeElement) -treeElement.setInClipboard(true);this._clipboardNodeData=data;}} -resetClipboardIfNeeded(removedNode){if(this._clipboardNodeData&&this._clipboardNodeData.node===removedNode) -this._setClipboardData(null);} -_onBeforeCopy(event){event.handled=true;} -_onCopyOrCut(isCut,event){this._setClipboardData(null);var originalEvent=event['original'];if(originalEvent.target.hasSelection()) -return;if(UI.isEditing()) -return;var targetNode=this.selectedDOMNode();if(!targetNode) -return;originalEvent.clipboardData.clearData();event.handled=true;this.performCopyOrCut(isCut,targetNode);} -performCopyOrCut(isCut,node){if(isCut&&(node.isShadowRoot()||node.ancestorUserAgentShadowRoot())) -return;node.copyNode();this._setClipboardData({node:node,isCut:isCut});} -canPaste(targetNode){if(targetNode.isShadowRoot()||targetNode.ancestorUserAgentShadowRoot()) -return false;if(!this._clipboardNodeData) -return false;var node=this._clipboardNodeData.node;if(this._clipboardNodeData.isCut&&(node===targetNode||node.isAncestor(targetNode))) -return false;if(targetNode.domModel()!==node.domModel()) -return false;return true;} -pasteNode(targetNode){if(this.canPaste(targetNode)) -this._performPaste(targetNode);} -_onPaste(event){if(UI.isEditing()) -return;var targetNode=this.selectedDOMNode();if(!targetNode||!this.canPaste(targetNode)) -return;event.handled=true;this._performPaste(targetNode);} -_performPaste(targetNode){if(this._clipboardNodeData.isCut){this._clipboardNodeData.node.moveTo(targetNode,null,expandCallback.bind(this));this._setClipboardData(null);}else{this._clipboardNodeData.node.copyTo(targetNode,null,expandCallback.bind(this));} -function expandCallback(error,nodeId){if(error) -return;var pastedNode=this._domModel.nodeForId(nodeId);if(!pastedNode) -return;this.selectDOMNode(pastedNode);}} -setVisible(visible){this._visible=visible;if(!this._visible){this._popoverHelper.hidePopover();if(this._multilineEditing) -this._multilineEditing.cancel();return;} -this.runPendingUpdates();if(this._selectedDOMNode) -this._revealAndSelectNode(this._selectedDOMNode,false);} -get rootDOMNode(){return this._rootDOMNode;} -set rootDOMNode(x){if(this._rootDOMNode===x) -return;this._rootDOMNode=x;this._isXMLMimeType=x&&x.isXMLNode();this.update();} -get isXMLMimeType(){return this._isXMLMimeType;} -selectedDOMNode(){return this._selectedDOMNode;} -selectDOMNode(node,focus){if(this._selectedDOMNode===node){this._revealAndSelectNode(node,!focus);return;} -this._selectedDOMNode=node;this._revealAndSelectNode(node,!focus);if(this._selectedDOMNode===node) -this._selectedNodeChanged(!!focus);} -editing(){var node=this.selectedDOMNode();if(!node) -return false;var treeElement=this.findTreeElement(node);if(!treeElement) -return false;return treeElement.isEditing()||false;} -update(){var selectedNode=this.selectedDOMNode();this.removeChildren();if(!this.rootDOMNode) -return;if(this._includeRootDOMNode){var treeElement=this._createElementTreeElement(this.rootDOMNode);this.appendChild(treeElement);}else{var children=this._visibleChildren(this.rootDOMNode);for(var child of children){var treeElement=this._createElementTreeElement(child);this.appendChild(treeElement);}} -if(selectedNode) -this._revealAndSelectNode(selectedNode,true);} -_selectedNodeChanged(focus){this.dispatchEventToListeners(Elements.ElementsTreeOutline.Events.SelectedNodeChanged,{node:this._selectedDOMNode,focus:focus});} -_fireElementsTreeUpdated(nodes){this.dispatchEventToListeners(Elements.ElementsTreeOutline.Events.ElementsTreeUpdated,nodes);} -findTreeElement(node){var treeElement=this._lookUpTreeElement(node);if(!treeElement&&node.nodeType()===Node.TEXT_NODE){treeElement=this._lookUpTreeElement(node.parentNode);} -return(treeElement);} -_lookUpTreeElement(node){if(!node) -return null;var cachedElement=node[this._treeElementSymbol];if(cachedElement) -return cachedElement;var ancestors=[];for(var currentNode=node.parentNode;currentNode;currentNode=currentNode.parentNode){ancestors.push(currentNode);if(currentNode[this._treeElementSymbol]) -break;} -if(!currentNode) -return null;for(var i=ancestors.length-1;i>=0;--i){var treeElement=ancestors[i][this._treeElementSymbol];if(treeElement) -treeElement.onpopulate();} -return node[this._treeElementSymbol];} -createTreeElementFor(node){var treeElement=this.findTreeElement(node);if(treeElement) -return treeElement;if(!node.parentNode) -return null;treeElement=this.createTreeElementFor(node.parentNode);return treeElement?this._showChild(treeElement,node):null;} -set suppressRevealAndSelect(x){if(this._suppressRevealAndSelect===x) -return;this._suppressRevealAndSelect=x;} -_revealAndSelectNode(node,omitFocus){if(this._suppressRevealAndSelect) -return;if(!this._includeRootDOMNode&&node===this.rootDOMNode&&this.rootDOMNode) -node=this.rootDOMNode.firstChild;if(!node) -return;var treeElement=this.createTreeElementFor(node);if(!treeElement) -return;treeElement.revealAndSelect(omitFocus);} -_treeElementFromEvent(event){var scrollContainer=this.element.parentElement;var x=scrollContainer.totalOffsetLeft()+scrollContainer.offsetWidth-36;var y=event.pageY;var elementUnderMouse=this.treeElementFromPoint(x,y);var elementAboveMouse=this.treeElementFromPoint(x,y-2);var element;if(elementUnderMouse===elementAboveMouse) -element=elementUnderMouse;else -element=this.treeElementFromPoint(x,y+2);return element;} -_getPopoverRequest(event){var link=event.target;while(link&&!link[Elements.ElementsTreeElement.HrefSymbol]) -link=link.parentElementOrShadowHost();if(!link) -return null;return{box:link.boxInWindow(),show:async popover=>{var listItem=link.enclosingNodeOrSelfWithNodeName('li');var node=(listItem.treeElement).node();var precomputedFeatures=await this._loadDimensionsForNode(node);var preview=await Components.DOMPresentationUtils.buildImagePreviewContents(node.domModel().target(),link[Elements.ElementsTreeElement.HrefSymbol],true,precomputedFeatures);if(preview) -popover.contentElement.appendChild(preview);return!!preview;}};} -async _loadDimensionsForNode(node){if(!node.nodeName()||node.nodeName().toLowerCase()!=='img') -return;var object=await node.resolveToObject('');if(!object) -return;var promise=object.callFunctionJSONPromise(features,undefined);object.release();return promise;function features(){return{offsetWidth:this.offsetWidth,offsetHeight:this.offsetHeight,naturalWidth:this.naturalWidth,naturalHeight:this.naturalHeight,currentSrc:this.currentSrc};}} -_onmousedown(event){var element=this._treeElementFromEvent(event);if(!element||element.isEventWithinDisclosureTriangle(event)) -return;element.select();} -setHoverEffect(treeElement){if(this._previousHoveredElement===treeElement) -return;if(this._previousHoveredElement){this._previousHoveredElement.hovered=false;delete this._previousHoveredElement;} -if(treeElement){treeElement.hovered=true;this._previousHoveredElement=treeElement;}} -_onmousemove(event){var element=this._treeElementFromEvent(event);if(element&&this._previousHoveredElement===element) -return;this.setHoverEffect(element);if(element instanceof Elements.ElementsTreeElement){this._domModel.overlayModel().highlightDOMNodeWithConfig(element.node().id,{mode:'all',showInfo:!UI.KeyboardShortcut.eventHasCtrlOrMeta(event)});return;} -if(element instanceof Elements.ElementsTreeOutline.ShortcutTreeElement){this._domModel.overlayModel().highlightDOMNodeWithConfig(undefined,{mode:'all',showInfo:!UI.KeyboardShortcut.eventHasCtrlOrMeta(event)},element.backendNodeId());}} -_onmouseleave(event){this.setHoverEffect(null);SDK.OverlayModel.hideDOMNodeHighlight();} -_ondragstart(event){if(event.target.hasSelection()) -return false;if(event.target.nodeName==='A') -return false;var treeElement=this._validDragSourceOrTarget(this._treeElementFromEvent(event));if(!treeElement) -return false;if(treeElement.node().nodeName()==='BODY'||treeElement.node().nodeName()==='HEAD') -return false;event.dataTransfer.setData('text/plain',treeElement.listItemElement.textContent.replace(/\u200b/g,''));event.dataTransfer.effectAllowed='copyMove';this._treeElementBeingDragged=treeElement;SDK.OverlayModel.hideDOMNodeHighlight();return true;} -_ondragover(event){if(!this._treeElementBeingDragged) -return false;var treeElement=this._validDragSourceOrTarget(this._treeElementFromEvent(event));if(!treeElement) -return false;var node=treeElement.node();while(node){if(node===this._treeElementBeingDragged._node) -return false;node=node.parentNode;} -treeElement.listItemElement.classList.add('elements-drag-over');this._dragOverTreeElement=treeElement;event.preventDefault();event.dataTransfer.dropEffect='move';return false;} -_ondragleave(event){this._clearDragOverTreeElementMarker();event.preventDefault();return false;} -_validDragSourceOrTarget(treeElement){if(!treeElement) -return null;if(!(treeElement instanceof Elements.ElementsTreeElement)) -return null;var elementsTreeElement=(treeElement);var node=elementsTreeElement.node();if(!node.parentNode||node.parentNode.nodeType()!==Node.ELEMENT_NODE) -return null;return elementsTreeElement;} -_ondrop(event){event.preventDefault();var treeElement=this._treeElementFromEvent(event);if(treeElement instanceof Elements.ElementsTreeElement) -this._doMove(treeElement);} -_doMove(treeElement){if(!this._treeElementBeingDragged) -return;var parentNode;var anchorNode;if(treeElement.isClosingTag()){parentNode=treeElement.node();}else{var dragTargetNode=treeElement.node();parentNode=dragTargetNode.parentNode;anchorNode=dragTargetNode;} -var wasExpanded=this._treeElementBeingDragged.expanded;this._treeElementBeingDragged._node.moveTo(parentNode,anchorNode,this.selectNodeAfterEdit.bind(this,wasExpanded));delete this._treeElementBeingDragged;} -_ondragend(event){event.preventDefault();this._clearDragOverTreeElementMarker();delete this._treeElementBeingDragged;} -_clearDragOverTreeElementMarker(){if(this._dragOverTreeElement){this._dragOverTreeElement.listItemElement.classList.remove('elements-drag-over');delete this._dragOverTreeElement;}} -_contextMenuEventFired(event){var treeElement=this._treeElementFromEvent(event);if(treeElement instanceof Elements.ElementsTreeElement) -this.showContextMenu(treeElement,event);} -showContextMenu(treeElement,event){if(UI.isEditing()) -return;var contextMenu=new UI.ContextMenu(event);var isPseudoElement=!!treeElement.node().pseudoType();var isTag=treeElement.node().nodeType()===Node.ELEMENT_NODE&&!isPseudoElement;var textNode=event.target.enclosingNodeOrSelfWithClass('webkit-html-text-node');if(textNode&&textNode.classList.contains('bogus')) -textNode=null;var commentNode=event.target.enclosingNodeOrSelfWithClass('webkit-html-comment');if(textNode) -treeElement.populateTextContextMenu(contextMenu,textNode);else if(isTag) -treeElement.populateTagContextMenu(contextMenu,event);else if(commentNode) -treeElement.populateNodeContextMenu(contextMenu);else if(isPseudoElement) -treeElement.populateScrollIntoView(contextMenu);contextMenu.appendApplicableItems(treeElement.node());contextMenu.show();} -runPendingUpdates(){this._updateModifiedNodes();} -handleShortcut(event){var node=this.selectedDOMNode();if(!node) -return;var treeElement=node[this._treeElementSymbol];if(!treeElement) -return;if(UI.KeyboardShortcut.eventHasCtrlOrMeta(event)&&node.parentNode){if(event.key==='ArrowUp'&&node.previousSibling){node.moveTo(node.parentNode,node.previousSibling,this.selectNodeAfterEdit.bind(this,treeElement.expanded));event.handled=true;return;} -if(event.key==='ArrowDown'&&node.nextSibling){node.moveTo(node.parentNode,node.nextSibling.nextSibling,this.selectNodeAfterEdit.bind(this,treeElement.expanded));event.handled=true;return;}}} -toggleEditAsHTML(node,startEditing,callback){var treeElement=node[this._treeElementSymbol];if(!treeElement||!treeElement.hasEditableNode()) -return;if(node.pseudoType()) -return;var parentNode=node.parentNode;var index=node.index;var wasExpanded=treeElement.expanded;treeElement.toggleEditAsHTML(editingFinished.bind(this),startEditing);function editingFinished(success){if(callback) -callback();if(!success) -return;this.runPendingUpdates();var newNode=parentNode?parentNode.children()[index]||parentNode:null;if(!newNode) -return;this.selectDOMNode(newNode,true);if(wasExpanded){var newTreeItem=this.findTreeElement(newNode);if(newTreeItem) -newTreeItem.expand();}}} -selectNodeAfterEdit(wasExpanded,error,nodeId){if(error) -return null;this.runPendingUpdates();var newNode=nodeId?this._domModel.nodeForId(nodeId):null;if(!newNode) -return null;this.selectDOMNode(newNode,true);var newTreeItem=this.findTreeElement(newNode);if(wasExpanded){if(newTreeItem) -newTreeItem.expand();} -return newTreeItem;} -async toggleHideElement(node){var pseudoType=node.pseudoType();var effectiveNode=pseudoType?node.parentNode:node;if(!effectiveNode) -return;var hidden=node.marker('hidden-marker');var object=await effectiveNode.resolveToObject('');if(!object) -return;var result=object.callFunction(toggleClassAndInjectStyleRule,[{value:pseudoType},{value:!hidden}]);object.release();node.setMarker('hidden-marker',hidden?null:true);return result;function toggleClassAndInjectStyleRule(pseudoType,hidden){const classNamePrefix='__web-inspector-hide';const classNameSuffix='-shortcut__';const styleTagId='__web-inspector-hide-shortcut-style__';var selectors=[];selectors.push('.__web-inspector-hide-shortcut__');selectors.push('.__web-inspector-hide-shortcut__ *');selectors.push('.__web-inspector-hidebefore-shortcut__::before');selectors.push('.__web-inspector-hideafter-shortcut__::after');var selector=selectors.join(', ');var ruleBody=' visibility: hidden !important;';var rule='\n'+selector+'\n{\n'+ruleBody+'\n}\n';var className=classNamePrefix+(pseudoType||'')+classNameSuffix;this.classList.toggle(className,hidden);var localRoot=this;while(localRoot.parentNode) -localRoot=localRoot.parentNode;if(localRoot.nodeType===Node.DOCUMENT_NODE) -localRoot=document.head;var style=localRoot.querySelector('style#'+styleTagId);if(style) -return;style=document.createElement('style');style.id=styleTagId;style.type='text/css';style.textContent=rule;localRoot.appendChild(style);}} -isToggledToHidden(node){return!!node.marker('hidden-marker');} -_reset(){this.rootDOMNode=null;this.selectDOMNode(null,false);this._popoverHelper.hidePopover();delete this._clipboardNodeData;SDK.OverlayModel.hideDOMNodeHighlight();this._updateRecords.clear();} -wireToDOMModel(){this._domModel[Elements.ElementsTreeOutline._treeOutlineSymbol]=this;this._domModel.addEventListener(SDK.DOMModel.Events.NodeInserted,this._nodeInserted,this);this._domModel.addEventListener(SDK.DOMModel.Events.NodeRemoved,this._nodeRemoved,this);this._domModel.addEventListener(SDK.DOMModel.Events.AttrModified,this._attributeModified,this);this._domModel.addEventListener(SDK.DOMModel.Events.AttrRemoved,this._attributeRemoved,this);this._domModel.addEventListener(SDK.DOMModel.Events.CharacterDataModified,this._characterDataModified,this);this._domModel.addEventListener(SDK.DOMModel.Events.DocumentUpdated,this._documentUpdated,this);this._domModel.addEventListener(SDK.DOMModel.Events.ChildNodeCountUpdated,this._childNodeCountUpdated,this);this._domModel.addEventListener(SDK.DOMModel.Events.DistributedNodesChanged,this._distributedNodesChanged,this);} -unwireFromDOMModel(){this._domModel.removeEventListener(SDK.DOMModel.Events.NodeInserted,this._nodeInserted,this);this._domModel.removeEventListener(SDK.DOMModel.Events.NodeRemoved,this._nodeRemoved,this);this._domModel.removeEventListener(SDK.DOMModel.Events.AttrModified,this._attributeModified,this);this._domModel.removeEventListener(SDK.DOMModel.Events.AttrRemoved,this._attributeRemoved,this);this._domModel.removeEventListener(SDK.DOMModel.Events.CharacterDataModified,this._characterDataModified,this);this._domModel.removeEventListener(SDK.DOMModel.Events.DocumentUpdated,this._documentUpdated,this);this._domModel.removeEventListener(SDK.DOMModel.Events.ChildNodeCountUpdated,this._childNodeCountUpdated,this);this._domModel.removeEventListener(SDK.DOMModel.Events.DistributedNodesChanged,this._distributedNodesChanged,this);delete this._domModel[Elements.ElementsTreeOutline._treeOutlineSymbol];} -_addUpdateRecord(node){var record=this._updateRecords.get(node);if(!record){record=new Elements.ElementsTreeOutline.UpdateRecord();this._updateRecords.set(node,record);} -return record;} -_updateRecordForHighlight(node){if(!this._visible) -return null;return this._updateRecords.get(node)||null;} -_documentUpdated(event){var domModel=(event.data);var inspectedRootDocument=domModel.existingDocument();this._reset();if(!inspectedRootDocument) -return;this.rootDOMNode=inspectedRootDocument;} -_attributeModified(event){var node=(event.data.node);this._addUpdateRecord(node).attributeModified(event.data.name);this._updateModifiedNodesSoon();} -_attributeRemoved(event){var node=(event.data.node);this._addUpdateRecord(node).attributeRemoved(event.data.name);this._updateModifiedNodesSoon();} -_characterDataModified(event){var node=(event.data);this._addUpdateRecord(node).charDataModified();if(node.parentNode&&node.parentNode.firstChild===node.parentNode.lastChild) -this._addUpdateRecord(node.parentNode).childrenModified();this._updateModifiedNodesSoon();} -_nodeInserted(event){var node=(event.data);this._addUpdateRecord((node.parentNode)).nodeInserted(node);this._updateModifiedNodesSoon();} -_nodeRemoved(event){var node=(event.data.node);var parentNode=(event.data.parent);this.resetClipboardIfNeeded(node);this._addUpdateRecord(parentNode).nodeRemoved(node);this._updateModifiedNodesSoon();} -_childNodeCountUpdated(event){var node=(event.data);this._addUpdateRecord(node).childrenModified();this._updateModifiedNodesSoon();} -_distributedNodesChanged(event){var node=(event.data);this._addUpdateRecord(node).childrenModified();this._updateModifiedNodesSoon();} -_updateModifiedNodesSoon(){if(!this._updateRecords.size) -return;if(this._updateModifiedNodesTimeout) -return;this._updateModifiedNodesTimeout=setTimeout(this._updateModifiedNodes.bind(this),50);} -_updateModifiedNodes(){if(this._updateModifiedNodesTimeout){clearTimeout(this._updateModifiedNodesTimeout);delete this._updateModifiedNodesTimeout;} -var updatedNodes=this._updateRecords.keysArray();var hidePanelWhileUpdating=updatedNodes.length>10;if(hidePanelWhileUpdating){var treeOutlineContainerElement=this.element.parentNode;var originalScrollTop=treeOutlineContainerElement?treeOutlineContainerElement.scrollTop:0;this._element.classList.add('hidden');} -if(this._rootDOMNode&&this._updateRecords.get(this._rootDOMNode)&&this._updateRecords.get(this._rootDOMNode).hasChangedChildren()){this.update();}else{for(var node of this._updateRecords.keys()){if(this._updateRecords.get(node).hasChangedChildren()) -this._updateModifiedParentNode(node);else -this._updateModifiedNode(node);}} -if(hidePanelWhileUpdating){this._element.classList.remove('hidden');if(originalScrollTop) -treeOutlineContainerElement.scrollTop=originalScrollTop;} -this._updateRecords.clear();this._fireElementsTreeUpdated(updatedNodes);} -_updateModifiedNode(node){var treeElement=this.findTreeElement(node);if(treeElement) -treeElement.updateTitle(this._updateRecordForHighlight(node));} -_updateModifiedParentNode(node){var parentTreeElement=this.findTreeElement(node);if(parentTreeElement){parentTreeElement.setExpandable(this._hasVisibleChildren(node));parentTreeElement.updateTitle(this._updateRecordForHighlight(node));if(parentTreeElement.populated) -this._updateChildren(parentTreeElement);}} -populateTreeElement(treeElement){if(treeElement.childCount()||!treeElement.isExpandable()) -return;this._updateModifiedParentNode(treeElement.node());} -_createElementTreeElement(node,closingTag){var treeElement=new Elements.ElementsTreeElement(node,closingTag);treeElement.setExpandable(!closingTag&&this._hasVisibleChildren(node));if(node.nodeType()===Node.ELEMENT_NODE&&node.parentNode&&node.parentNode.nodeType()===Node.DOCUMENT_NODE&&!node.parentNode.parentNode) -treeElement.setCollapsible(false);treeElement.selectable=this._selectEnabled;return treeElement;} -_showChild(treeElement,child){if(treeElement.isClosingTag()) -return null;var index=this._visibleChildren(treeElement.node()).indexOf(child);if(index===-1) -return null;if(index>=treeElement.expandedChildrenLimit()) -this.setExpandedChildrenLimit(treeElement,index+1);return(treeElement.childAt(index));} -_visibleChildren(node){var visibleChildren=Elements.ElementsTreeElement.visibleShadowRoots(node);var importedDocument=node.importedDocument();if(importedDocument) -visibleChildren.push(importedDocument);var templateContent=node.templateContent();if(templateContent) -visibleChildren.push(templateContent);var beforePseudoElement=node.beforePseudoElement();if(beforePseudoElement) -visibleChildren.push(beforePseudoElement);if(node.childNodeCount()){var children=node.children();if(!this._showHTMLCommentsSetting.get()) -children=children.filter(n=>n.nodeType()!==Node.COMMENT_NODE);visibleChildren=visibleChildren.concat(children);} -var afterPseudoElement=node.afterPseudoElement();if(afterPseudoElement) -visibleChildren.push(afterPseudoElement);return visibleChildren;} -_hasVisibleChildren(node){if(node.importedDocument()) -return true;if(node.templateContent()) -return true;if(Elements.ElementsTreeElement.visibleShadowRoots(node).length) -return true;if(node.hasPseudoElements()) -return true;if(node.isInsertionPoint()) -return true;return!!node.childNodeCount()&&!Elements.ElementsTreeElement.canShowInlineText(node);} -_createExpandAllButtonTreeElement(treeElement){var button=UI.createTextButton('',handleLoadAllChildren.bind(this));button.value='';var expandAllButtonElement=new UI.TreeElement(button);expandAllButtonElement.selectable=false;expandAllButtonElement.expandAllButton=true;expandAllButtonElement.button=button;return expandAllButtonElement;function handleLoadAllChildren(event){var visibleChildCount=this._visibleChildren(treeElement.node()).length;this.setExpandedChildrenLimit(treeElement,Math.max(visibleChildCount,treeElement.expandedChildrenLimit()+Elements.ElementsTreeElement.InitialChildrenLimit));event.consume();}} -setExpandedChildrenLimit(treeElement,expandedChildrenLimit){if(treeElement.expandedChildrenLimit()===expandedChildrenLimit) -return;treeElement.setExpandedChildrenLimit(expandedChildrenLimit);if(treeElement.treeOutline&&!this._treeElementsBeingUpdated.has(treeElement)) -this._updateModifiedParentNode(treeElement.node());} -_updateChildren(treeElement){if(!treeElement.isExpandable()){var selectedTreeElement=treeElement.treeOutline.selectedTreeElement;if(selectedTreeElement&&selectedTreeElement.hasAncestor(treeElement)) -treeElement.select(true);treeElement.removeChildren();return;} -console.assert(!treeElement.isClosingTag());treeElement.node().getChildNodes(children=>{if(!children) -return;this._innerUpdateChildren(treeElement);});} -insertChildElement(treeElement,child,index,closingTag){var newElement=this._createElementTreeElement(child,closingTag);treeElement.insertChild(newElement,index);return newElement;} -_moveChild(treeElement,child,targetIndex){if(treeElement.indexOfChild(child)===targetIndex) -return;var wasSelected=child.selected;if(child.parent) -child.parent.removeChild(child);treeElement.insertChild(child,targetIndex);if(wasSelected) -child.select();} -_innerUpdateChildren(treeElement){if(this._treeElementsBeingUpdated.has(treeElement)) -return;this._treeElementsBeingUpdated.add(treeElement);var node=treeElement.node();var visibleChildren=this._visibleChildren(node);var visibleChildrenSet=new Set(visibleChildren);var existingTreeElements=new Map();for(var i=treeElement.childCount()-1;i>=0;--i){var existingTreeElement=treeElement.childAt(i);if(!(existingTreeElement instanceof Elements.ElementsTreeElement)){treeElement.removeChildAtIndex(i);continue;} -var elementsTreeElement=(existingTreeElement);var existingNode=elementsTreeElement.node();if(visibleChildrenSet.has(existingNode)){existingTreeElements.set(existingNode,existingTreeElement);continue;} -treeElement.removeChildAtIndex(i);} -for(var i=0;i<visibleChildren.length&&i<treeElement.expandedChildrenLimit();++i){var child=visibleChildren[i];var existingTreeElement=existingTreeElements.get(child)||this.findTreeElement(child);if(existingTreeElement&&existingTreeElement!==treeElement){this._moveChild(treeElement,existingTreeElement,i);}else{var newElement=this.insertChildElement(treeElement,child,i);if(this._updateRecordForHighlight(node)&&treeElement.expanded) -Elements.ElementsTreeElement.animateOnDOMUpdate(newElement);if(treeElement.childCount()>treeElement.expandedChildrenLimit()) -this.setExpandedChildrenLimit(treeElement,treeElement.expandedChildrenLimit()+1);}} -var expandedChildCount=treeElement.childCount();if(visibleChildren.length>expandedChildCount){var targetButtonIndex=expandedChildCount;if(!treeElement.expandAllButtonElement) -treeElement.expandAllButtonElement=this._createExpandAllButtonTreeElement(treeElement);treeElement.insertChild(treeElement.expandAllButtonElement,targetButtonIndex);treeElement.expandAllButtonElement.button.textContent=Common.UIString('Show All Nodes (%d More)',visibleChildren.length-expandedChildCount);}else if(treeElement.expandAllButtonElement){delete treeElement.expandAllButtonElement;} -if(node.isInsertionPoint()){for(var distributedNode of node.distributedNodes()) -treeElement.appendChild(new Elements.ElementsTreeOutline.ShortcutTreeElement(distributedNode));} -if(node.nodeType()===Node.ELEMENT_NODE&&treeElement.isExpandable()) -this.insertChildElement(treeElement,node,treeElement.childCount(),true);this._treeElementsBeingUpdated.delete(treeElement);} -_markersChanged(event){var node=(event.data);var treeElement=node[this._treeElementSymbol];if(treeElement) -treeElement.updateDecorations();}};Elements.ElementsTreeOutline._treeOutlineSymbol=Symbol('treeOutline');Elements.ElementsTreeOutline.ClipboardData;Elements.ElementsTreeOutline.Events={SelectedNodeChanged:Symbol('SelectedNodeChanged'),ElementsTreeUpdated:Symbol('ElementsTreeUpdated')};Elements.ElementsTreeOutline.MappedCharToEntity={'\u00a0':'nbsp','\u0093':'#147','\u00ad':'shy','\u2002':'ensp','\u2003':'emsp','\u2009':'thinsp','\u200a':'#8202','\u200b':'#8203','\u200c':'zwnj','\u200d':'zwj','\u200e':'lrm','\u200f':'rlm','\u202a':'#8234','\u202b':'#8235','\u202c':'#8236','\u202d':'#8237','\u202e':'#8238','\ufeff':'#65279'};Elements.ElementsTreeOutline.UpdateRecord=class{attributeModified(attrName){if(this._removedAttributes&&this._removedAttributes.has(attrName)) -this._removedAttributes.delete(attrName);if(!this._modifiedAttributes) -this._modifiedAttributes=(new Set());this._modifiedAttributes.add(attrName);} -attributeRemoved(attrName){if(this._modifiedAttributes&&this._modifiedAttributes.has(attrName)) -this._modifiedAttributes.delete(attrName);if(!this._removedAttributes) -this._removedAttributes=(new Set());this._removedAttributes.add(attrName);} -nodeInserted(node){this._hasChangedChildren=true;} -nodeRemoved(node){this._hasChangedChildren=true;this._hasRemovedChildren=true;} -charDataModified(){this._charDataModified=true;} -childrenModified(){this._hasChangedChildren=true;} -isAttributeModified(attributeName){return this._modifiedAttributes&&this._modifiedAttributes.has(attributeName);} -hasRemovedAttributes(){return!!this._removedAttributes&&!!this._removedAttributes.size;} -isCharDataModified(){return!!this._charDataModified;} -hasChangedChildren(){return!!this._hasChangedChildren;} -hasRemovedChildren(){return!!this._hasRemovedChildren;}};Elements.ElementsTreeOutline.Renderer=class{render(object){return new Promise(renderPromise);function renderPromise(resolve,reject){if(object instanceof SDK.DOMNode) -onNodeResolved((object));else if(object instanceof SDK.DeferredDOMNode) -((object)).resolve(onNodeResolved);else -reject(new Error('Can\'t reveal not a node.'));function onNodeResolved(node){if(!node){reject(new Error('Could not resolve node.'));return;} -var treeOutline=new Elements.ElementsTreeOutline(node.domModel(),false,false);treeOutline.rootDOMNode=node;if(!treeOutline.firstChild().isExpandable()) -treeOutline._element.classList.add('single-node');treeOutline.setVisible(true);treeOutline.element.treeElementForTest=treeOutline.firstChild();resolve(treeOutline.element);}}}};Elements.ElementsTreeOutline.ShortcutTreeElement=class extends UI.TreeElement{constructor(nodeShortcut){super('');this.listItemElement.createChild('div','selection fill');var title=this.listItemElement.createChild('span','elements-tree-shortcut-title');var text=nodeShortcut.nodeName.toLowerCase();if(nodeShortcut.nodeType===Node.ELEMENT_NODE) -text='<'+text+'>';title.textContent='\u21AA '+text;var link=Components.DOMPresentationUtils.linkifyDeferredNodeReference(nodeShortcut.deferredNode);this.listItemElement.createTextChild(' ');link.classList.add('elements-tree-shortcut-link');link.textContent=Common.UIString('reveal');this.listItemElement.appendChild(link);this._nodeShortcut=nodeShortcut;} -get hovered(){return this._hovered;} -set hovered(x){if(this._hovered===x) -return;this._hovered=x;this.listItemElement.classList.toggle('hovered',x);} -backendNodeId(){return this._nodeShortcut.deferredNode.backendNodeId();} -onselect(selectedByUser){if(!selectedByUser) -return true;this._nodeShortcut.deferredNode.highlight();this._nodeShortcut.deferredNode.resolve(resolved.bind(this));function resolved(node){if(node){this.treeOutline._selectedDOMNode=node;this.treeOutline._selectedNodeChanged();}} -return true;}};;Elements.EventListenersWidget=class extends UI.ThrottledWidget{constructor(){super();this._toolbarItems=[];this._showForAncestorsSetting=Common.settings.moduleSetting('showEventListenersForAncestors');this._showForAncestorsSetting.addChangeListener(this.update.bind(this));this._dispatchFilterBySetting=Common.settings.createSetting('eventListenerDispatchFilterType',Elements.EventListenersWidget.DispatchFilterBy.All);this._dispatchFilterBySetting.addChangeListener(this.update.bind(this));this._showFrameworkListenersSetting=Common.settings.createSetting('showFrameowkrListeners',true);this._showFrameworkListenersSetting.setTitle(Common.UIString('Framework listeners'));this._showFrameworkListenersSetting.addChangeListener(this._showFrameworkListenersChanged.bind(this));this._eventListenersView=new EventListeners.EventListenersView(this.update.bind(this));this._eventListenersView.show(this.element);var refreshButton=new UI.ToolbarButton(Common.UIString('Refresh'),'largeicon-refresh');refreshButton.addEventListener(UI.ToolbarButton.Events.Click,this.update.bind(this));this._toolbarItems.push(refreshButton);this._toolbarItems.push(new UI.ToolbarSettingCheckbox(this._showForAncestorsSetting,Common.UIString('Show listeners on the ancestors'),Common.UIString('Ancestors')));var dispatchFilter=new UI.ToolbarComboBox(this._onDispatchFilterTypeChanged.bind(this));function addDispatchFilterOption(name,value){var option=dispatchFilter.createOption(name,'',value);if(value===this._dispatchFilterBySetting.get()) -dispatchFilter.select(option);} -addDispatchFilterOption.call(this,Common.UIString('All'),Elements.EventListenersWidget.DispatchFilterBy.All);addDispatchFilterOption.call(this,Common.UIString('Passive'),Elements.EventListenersWidget.DispatchFilterBy.Passive);addDispatchFilterOption.call(this,Common.UIString('Blocking'),Elements.EventListenersWidget.DispatchFilterBy.Blocking);dispatchFilter.setMaxWidth(200);this._toolbarItems.push(dispatchFilter);this._toolbarItems.push(new UI.ToolbarSettingCheckbox(this._showFrameworkListenersSetting,Common.UIString('Resolve event listeners bound with framework')));UI.context.addFlavorChangeListener(SDK.DOMNode,this.update,this);this.update();} -doUpdate(){if(this._lastRequestedNode){this._lastRequestedNode.domModel().runtimeModel().releaseObjectGroup(Elements.EventListenersWidget._objectGroupName);delete this._lastRequestedNode;} -var node=UI.context.flavor(SDK.DOMNode);if(!node){this._eventListenersView.reset();this._eventListenersView.addEmptyHolderIfNeeded();return Promise.resolve();} -this._lastRequestedNode=node;var selectedNodeOnly=!this._showForAncestorsSetting.get();var promises=[];promises.push(node.resolveToObject(Elements.EventListenersWidget._objectGroupName));if(!selectedNodeOnly){var currentNode=node.parentNode;while(currentNode){promises.push(currentNode.resolveToObject(Elements.EventListenersWidget._objectGroupName));currentNode=currentNode.parentNode;} -promises.push(this._windowObjectInNodeContext(node));} -return Promise.all(promises).then(this._eventListenersView.addObjects.bind(this._eventListenersView)).then(this._showFrameworkListenersChanged.bind(this));} -toolbarItems(){return this._toolbarItems;} -_onDispatchFilterTypeChanged(event){this._dispatchFilterBySetting.set(event.target.value);} -_showFrameworkListenersChanged(){var dispatchFilter=this._dispatchFilterBySetting.get();var showPassive=dispatchFilter===Elements.EventListenersWidget.DispatchFilterBy.All||dispatchFilter===Elements.EventListenersWidget.DispatchFilterBy.Passive;var showBlocking=dispatchFilter===Elements.EventListenersWidget.DispatchFilterBy.All||dispatchFilter===Elements.EventListenersWidget.DispatchFilterBy.Blocking;this._eventListenersView.showFrameworkListeners(this._showFrameworkListenersSetting.get(),showPassive,showBlocking);} -_windowObjectInNodeContext(node){var executionContexts=node.domModel().runtimeModel().executionContexts();var context=null;if(node.frameId()){for(var i=0;i<executionContexts.length;++i){var executionContext=executionContexts[i];if(executionContext.frameId===node.frameId()&&executionContext.isDefault) -context=executionContext;}}else{context=executionContexts[0];} -return context.evaluate({expression:'self',objectGroup:Elements.EventListenersWidget._objectGroupName,includeCommandLineAPI:false,silent:true,returnByValue:false,generatePreview:false},false,false).then(result=>result.object||null);} -_eventListenersArrivedForTest(){}};Elements.EventListenersWidget.DispatchFilterBy={All:'All',Blocking:'Blocking',Passive:'Passive'};Elements.EventListenersWidget._objectGroupName='event-listeners-panel';;Elements.MetricsSidebarPane=class extends Elements.ElementsSidebarPane{constructor(){super();this.registerRequiredCSS('elements/metricsSidebarPane.css');this._inlineStyle=null;} -doUpdate(){if(this._isEditingMetrics) -return Promise.resolve();var node=this.node();var cssModel=this.cssModel();if(!node||node.nodeType()!==Node.ELEMENT_NODE||!cssModel){this.contentElement.removeChildren();return Promise.resolve();} -function callback(style){if(!style||this.node()!==node) -return;this._updateMetrics(style);} -function inlineStyleCallback(inlineStyleResult){if(inlineStyleResult&&this.node()===node) -this._inlineStyle=inlineStyleResult.inlineStyle;} -var promises=[cssModel.computedStylePromise(node.id).then(callback.bind(this)),cssModel.inlineStylesPromise(node.id).then(inlineStyleCallback.bind(this))];return Promise.all(promises);} -onCSSModelChanged(){this.update();} -_getPropertyValueAsPx(style,propertyName){return Number(style.get(propertyName).replace(/px$/,'')||0);} -_getBox(computedStyle,componentName){var suffix=componentName==='border'?'-width':'';var left=this._getPropertyValueAsPx(computedStyle,componentName+'-left'+suffix);var top=this._getPropertyValueAsPx(computedStyle,componentName+'-top'+suffix);var right=this._getPropertyValueAsPx(computedStyle,componentName+'-right'+suffix);var bottom=this._getPropertyValueAsPx(computedStyle,componentName+'-bottom'+suffix);return{left:left,top:top,right:right,bottom:bottom};} -_highlightDOMNode(showHighlight,mode,event){event.consume();if(showHighlight&&this.node()){if(this._highlightMode===mode) -return;this._highlightMode=mode;this.node().highlight(mode);}else{delete this._highlightMode;SDK.OverlayModel.hideDOMNodeHighlight();} -for(var i=0;this._boxElements&&i<this._boxElements.length;++i){var element=this._boxElements[i];if(!this.node()||mode==='all'||element._name===mode) -element.style.backgroundColor=element._backgroundColor;else -element.style.backgroundColor='';}} -_updateMetrics(style){var metricsElement=createElement('div');metricsElement.className='metrics';var self=this;function createBoxPartElement(style,name,side,suffix){var propertyName=(name!=='position'?name+'-':'')+side+suffix;var value=style.get(propertyName);if(value===''||(name!=='position'&&value==='0px')) -value='\u2012';else if(name==='position'&&value==='auto') -value='\u2012';value=value.replace(/px$/,'');value=Number.toFixedIfFloating(value);var element=createElement('div');element.className=side;element.textContent=value;element.addEventListener('dblclick',this.startEditing.bind(this,element,name,propertyName,style),false);return element;} -function getContentAreaWidthPx(style){var width=style.get('width').replace(/px$/,'');if(!isNaN(width)&&style.get('box-sizing')==='border-box'){var borderBox=self._getBox(style,'border');var paddingBox=self._getBox(style,'padding');width=width-borderBox.left-borderBox.right-paddingBox.left-paddingBox.right;} -return Number.toFixedIfFloating(width.toString());} -function getContentAreaHeightPx(style){var height=style.get('height').replace(/px$/,'');if(!isNaN(height)&&style.get('box-sizing')==='border-box'){var borderBox=self._getBox(style,'border');var paddingBox=self._getBox(style,'padding');height=height-borderBox.top-borderBox.bottom-paddingBox.top-paddingBox.bottom;} -return Number.toFixedIfFloating(height.toString());} -var noMarginDisplayType={'table-cell':true,'table-column':true,'table-column-group':true,'table-footer-group':true,'table-header-group':true,'table-row':true,'table-row-group':true};var noPaddingDisplayType={'table-column':true,'table-column-group':true,'table-footer-group':true,'table-header-group':true,'table-row':true,'table-row-group':true};var noPositionType={'static':true};var boxes=['content','padding','border','margin','position'];var boxColors=[Common.Color.PageHighlight.Content,Common.Color.PageHighlight.Padding,Common.Color.PageHighlight.Border,Common.Color.PageHighlight.Margin,Common.Color.fromRGBA([0,0,0,0])];var boxLabels=[Common.UIString('content'),Common.UIString('padding'),Common.UIString('border'),Common.UIString('margin'),Common.UIString('position')];var previousBox=null;this._boxElements=[];for(var i=0;i<boxes.length;++i){var name=boxes[i];if(name==='margin'&&noMarginDisplayType[style.get('display')]) -continue;if(name==='padding'&&noPaddingDisplayType[style.get('display')]) -continue;if(name==='position'&&noPositionType[style.get('position')]) -continue;var boxElement=createElement('div');boxElement.className=name;boxElement._backgroundColor=boxColors[i].asString(Common.Color.Format.RGBA);boxElement._name=name;boxElement.style.backgroundColor=boxElement._backgroundColor;boxElement.addEventListener('mouseover',this._highlightDOMNode.bind(this,true,name==='position'?'all':name),false);this._boxElements.push(boxElement);if(name==='content'){var widthElement=createElement('span');widthElement.textContent=getContentAreaWidthPx(style);widthElement.addEventListener('dblclick',this.startEditing.bind(this,widthElement,'width','width',style),false);var heightElement=createElement('span');heightElement.textContent=getContentAreaHeightPx(style);heightElement.addEventListener('dblclick',this.startEditing.bind(this,heightElement,'height','height',style),false);boxElement.appendChild(widthElement);boxElement.createTextChild(' \u00D7 ');boxElement.appendChild(heightElement);}else{var suffix=(name==='border'?'-width':'');var labelElement=createElement('div');labelElement.className='label';labelElement.textContent=boxLabels[i];boxElement.appendChild(labelElement);boxElement.appendChild(createBoxPartElement.call(this,style,name,'top',suffix));boxElement.appendChild(createElement('br'));boxElement.appendChild(createBoxPartElement.call(this,style,name,'left',suffix));if(previousBox) -boxElement.appendChild(previousBox);boxElement.appendChild(createBoxPartElement.call(this,style,name,'right',suffix));boxElement.appendChild(createElement('br'));boxElement.appendChild(createBoxPartElement.call(this,style,name,'bottom',suffix));} -previousBox=boxElement;} -metricsElement.appendChild(previousBox);metricsElement.addEventListener('mouseover',this._highlightDOMNode.bind(this,false,'all'),false);this.contentElement.removeChildren();this.contentElement.appendChild(metricsElement);} -startEditing(targetElement,box,styleProperty,computedStyle){if(UI.isBeingEdited(targetElement)) -return;var context={box:box,styleProperty:styleProperty,computedStyle:computedStyle};var boundKeyDown=this._handleKeyDown.bind(this,context,styleProperty);context.keyDownHandler=boundKeyDown;targetElement.addEventListener('keydown',boundKeyDown,false);this._isEditingMetrics=true;var config=new UI.InplaceEditor.Config(this._editingCommitted.bind(this),this.editingCancelled.bind(this),context);UI.InplaceEditor.startEditing(targetElement,config);targetElement.getComponentSelection().selectAllChildren(targetElement);} -_handleKeyDown(context,styleProperty,event){var element=event.currentTarget;function finishHandler(originalValue,replacementString){this._applyUserInput(element,replacementString,originalValue,context,false);} -function customNumberHandler(prefix,number,suffix){if(styleProperty!=='margin'&&number<0) -number=0;return prefix+number+suffix;} -UI.handleElementValueModifications(event,element,finishHandler.bind(this),undefined,customNumberHandler);} -editingEnded(element,context){delete this.originalPropertyData;delete this.previousPropertyDataCandidate;element.removeEventListener('keydown',context.keyDownHandler,false);delete this._isEditingMetrics;} -editingCancelled(element,context){if('originalPropertyData'in this&&this._inlineStyle){if(!this.originalPropertyData){var pastLastSourcePropertyIndex=this._inlineStyle.pastLastSourcePropertyIndex();if(pastLastSourcePropertyIndex) -this._inlineStyle.allProperties()[pastLastSourcePropertyIndex-1].setText('',false);}else{this._inlineStyle.allProperties()[this.originalPropertyData.index].setText(this.originalPropertyData.propertyText,false);}} -this.editingEnded(element,context);this.update();} -_applyUserInput(element,userInput,previousContent,context,commitEditor){if(!this._inlineStyle){return this.editingCancelled(element,context);} -if(commitEditor&&userInput===previousContent) -return this.editingCancelled(element,context);if(context.box!=='position'&&(!userInput||userInput==='\u2012')) -userInput='0px';else if(context.box==='position'&&(!userInput||userInput==='\u2012')) -userInput='auto';userInput=userInput.toLowerCase();if(/^\d+$/.test(userInput)) -userInput+='px';var styleProperty=context.styleProperty;var computedStyle=context.computedStyle;if(computedStyle.get('box-sizing')==='border-box'&&(styleProperty==='width'||styleProperty==='height')){if(!userInput.match(/px$/)){Common.console.error('For elements with box-sizing: border-box, only absolute content area dimensions can be applied');return;} -var borderBox=this._getBox(computedStyle,'border');var paddingBox=this._getBox(computedStyle,'padding');var userValuePx=Number(userInput.replace(/px$/,''));if(isNaN(userValuePx)) -return;if(styleProperty==='width') -userValuePx+=borderBox.left+borderBox.right+paddingBox.left+paddingBox.right;else -userValuePx+=borderBox.top+borderBox.bottom+paddingBox.top+paddingBox.bottom;userInput=userValuePx+'px';} -this.previousPropertyDataCandidate=null;var allProperties=this._inlineStyle.allProperties();for(var i=0;i<allProperties.length;++i){var property=allProperties[i];if(property.name!==context.styleProperty||!property.activeInStyle()) -continue;this.previousPropertyDataCandidate=property;property.setValue(userInput,commitEditor,true,callback.bind(this));return;} -this._inlineStyle.appendProperty(context.styleProperty,userInput,callback.bind(this));function callback(success){if(!success) -return;if(!('originalPropertyData'in this)) -this.originalPropertyData=this.previousPropertyDataCandidate;if(typeof this._highlightMode!=='undefined') -this.node().highlight(this._highlightMode);if(commitEditor) -this.update();}} -_editingCommitted(element,userInput,previousContent,context){this.editingEnded(element,context);this._applyUserInput(element,userInput,previousContent,context,true);}};;Elements.PlatformFontsWidget=class extends UI.ThrottledWidget{constructor(sharedModel){super(true);this.registerRequiredCSS('elements/platformFontsWidget.css');this._sharedModel=sharedModel;this._sharedModel.addEventListener(Elements.ComputedStyleModel.Events.ComputedStyleChanged,this.update,this);this._sectionTitle=createElementWithClass('div','title');this.contentElement.classList.add('platform-fonts');this.contentElement.appendChild(this._sectionTitle);this._sectionTitle.textContent=Common.UIString('Rendered Fonts');this._fontStatsSection=this.contentElement.createChild('div','stats-section');} -doUpdate(){var cssModel=this._sharedModel.cssModel();var node=this._sharedModel.node();if(!node||!cssModel) -return Promise.resolve();return cssModel.platformFontsPromise(node.id).then(this._refreshUI.bind(this,node));} -_refreshUI(node,platformFonts){if(this._sharedModel.node()!==node) -return;this._fontStatsSection.removeChildren();var isEmptySection=!platformFonts||!platformFonts.length;this._sectionTitle.classList.toggle('hidden',isEmptySection);if(isEmptySection) -return;platformFonts.sort(function(a,b){return b.glyphCount-a.glyphCount;});for(var i=0;i<platformFonts.length;++i){var fontStatElement=this._fontStatsSection.createChild('div','font-stats-item');var fontNameElement=fontStatElement.createChild('span','font-name');fontNameElement.textContent=platformFonts[i].familyName;var fontDelimeterElement=fontStatElement.createChild('span','font-delimeter');fontDelimeterElement.textContent='\u2014';var fontOrigin=fontStatElement.createChild('span');fontOrigin.textContent=platformFonts[i].isCustomFont?Common.UIString('Network resource'):Common.UIString('Local file');var fontUsageElement=fontStatElement.createChild('span','font-usage');var usage=platformFonts[i].glyphCount;fontUsageElement.textContent=usage===1?Common.UIString('(%d glyph)',usage):Common.UIString('(%d glyphs)',usage);}}};;Elements.PropertiesWidget=class extends UI.ThrottledWidget{constructor(){super(true);this.registerRequiredCSS('elements/propertiesWidget.css');SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.AttrModified,this._onNodeChange,this);SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.AttrRemoved,this._onNodeChange,this);SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.CharacterDataModified,this._onNodeChange,this);SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.ChildNodeCountUpdated,this._onNodeChange,this);UI.context.addFlavorChangeListener(SDK.DOMNode,this._setNode,this);this._node=UI.context.flavor(SDK.DOMNode);this.update();} -_setNode(event){this._node=(event.data);this.update();} -doUpdate(){if(this._lastRequestedNode){this._lastRequestedNode.domModel().runtimeModel().releaseObjectGroup(Elements.PropertiesWidget._objectGroupName);delete this._lastRequestedNode;} -if(!this._node){this.contentElement.removeChildren();this.sections=[];return Promise.resolve();} -this._lastRequestedNode=this._node;return this._node.resolveToObject(Elements.PropertiesWidget._objectGroupName).then(nodeResolved.bind(this));function nodeResolved(object){if(!object) -return;function protoList(){var proto=this;var result={__proto__:null};var counter=1;while(proto){result[counter++]=proto;proto=proto.__proto__;} -return result;} -var promise=object.callFunctionPromise(protoList).then(nodePrototypesReady.bind(this));object.release();return promise;} -function nodePrototypesReady(result){if(!result.object||result.wasThrown) -return;var promise=result.object.getOwnPropertiesPromise(false).then(fillSection.bind(this));result.object.release();return promise;} -function fillSection(result){if(!result||!result.properties) -return;var properties=result.properties;var expanded=[];var sections=this.sections||[];for(var i=0;i<sections.length;++i) -expanded.push(sections[i].expanded);this.contentElement.removeChildren();this.sections=[];for(var i=0;i<properties.length;++i){if(!parseInt(properties[i].name,10)) -continue;var property=properties[i].value;var title=property.description;title=title.replace(/Prototype$/,'');var section=new ObjectUI.ObjectPropertiesSection(property,title);section.element.classList.add('properties-widget-section');this.sections.push(section);this.contentElement.appendChild(section.element);if(expanded[this.sections.length-1]) -section.expand();section.addEventListener(UI.TreeOutline.Events.ElementExpanded,this._propertyExpanded,this);}}} -_propertyExpanded(event){Host.userMetrics.actionTaken(Host.UserMetrics.Action.DOMPropertiesExpanded);for(var section of this.sections) -section.removeEventListener(UI.TreeOutline.Events.ElementExpanded,this._propertyExpanded,this);} -_onNodeChange(event){if(!this._node) -return;var data=event.data;var node=(data instanceof SDK.DOMNode?data:data.node);if(this._node!==node) -return;this.update();}};Elements.PropertiesWidget._objectGroupName='properties-sidebar-pane';;Elements.StylePropertyHighlighter=class{constructor(ssp,cssProperty){this._styleSidebarPane=ssp;this._cssProperty=cssProperty;} -perform(){for(var section of this._styleSidebarPane.allSections()){for(var treeElement=section.propertiesTreeOutline.firstChild();treeElement;treeElement=treeElement.nextSibling) -treeElement.onpopulate();} -var highlightTreeElement=null;for(var section of this._styleSidebarPane.allSections()){var treeElement=section.propertiesTreeOutline.firstChild();while(treeElement&&!highlightTreeElement){if(treeElement.property===this._cssProperty){highlightTreeElement=treeElement;break;} -treeElement=treeElement.traverseNextTreeElement(false,null,true);} -if(highlightTreeElement) -break;} -if(!highlightTreeElement) -return;highlightTreeElement.parent.expand();highlightTreeElement.listItemElement.scrollIntoViewIfNeeded();highlightTreeElement.listItemElement.animate([{offset:0,backgroundColor:'rgba(255, 255, 0, 0.2)'},{offset:0.1,backgroundColor:'rgba(255, 255, 0, 0.7)'},{offset:1,backgroundColor:'transparent'}],{duration:2000,easing:'cubic-bezier(0, 0, 0.2, 1)'});}};;Elements.StylesSidebarPane=class extends Elements.ElementsSidebarPane{constructor(){super();this.setMinimumSize(96,26);this.registerRequiredCSS('elements/stylesSidebarPane.css');this.element.tabIndex=-1;Common.moduleSetting('colorFormat').addChangeListener(this.update.bind(this));Common.moduleSetting('textEditorIndent').addChangeListener(this.update.bind(this));this._currentToolbarPane=null;this._animatedToolbarPane=null;this._pendingWidget=null;this._pendingWidgetToggle=null;this._toolbarPaneElement=this._createStylesSidebarToolbar();this._sectionsContainer=this.contentElement.createChild('div');this._sectionsContainer.addEventListener('keydown',this._sectionsContainerKeyDown.bind(this),false);this._sectionsContainer.addEventListener('focusin',this._sectionsContainerFocusChanged.bind(this),false);this._sectionsContainer.addEventListener('focusout',this._sectionsContainerFocusChanged.bind(this),false);this._swatchPopoverHelper=new InlineEditor.SwatchPopoverHelper();this._linkifier=new Components.Linkifier(Elements.StylesSidebarPane._maxLinkLength,true);this._decorator=null;this._userOperation=false;this._isEditingStyle=false;this._filterRegex=null;this._mouseDownTreeElement=null;this._mouseDownTreeElementIsName=false;this._mouseDownTreeElementIsValue=false;this.contentElement.classList.add('styles-pane');this._sectionBlocks=[];Elements.StylesSidebarPane._instance=this;UI.context.addFlavorChangeListener(SDK.DOMNode,this.forceUpdate,this);this.contentElement.addEventListener('copy',this._clipboardCopy.bind(this));this._resizeThrottler=new Common.Throttler(100);} -static createExclamationMark(property){var exclamationElement=createElement('label','dt-icon-label');exclamationElement.className='exclamation-mark';if(!Elements.StylesSidebarPane.ignoreErrorsForProperty(property)) -exclamationElement.type='smallicon-warning';exclamationElement.title=SDK.cssMetadata().isCSSPropertyName(property.name)?Common.UIString('Invalid property value'):Common.UIString('Unknown property name');return exclamationElement;} -static ignoreErrorsForProperty(property){function hasUnknownVendorPrefix(string){return!string.startsWith('-webkit-')&&/^[-_][\w\d]+-\w/.test(string);} -var name=property.name.toLowerCase();if(name.charAt(0)==='_') -return true;if(name==='filter') -return true;if(name.startsWith('scrollbar-')) -return true;if(hasUnknownVendorPrefix(name)) -return true;var value=property.value.toLowerCase();if(value.endsWith('\\9')) -return true;if(hasUnknownVendorPrefix(value)) -return true;return false;} -static createPropertyFilterElement(placeholder,container,filterCallback,activeClassName){var input=createElementWithClass('input');input.placeholder=placeholder;function searchHandler(){var regex=input.value?new RegExp(input.value.escapeForRegExp(),'i'):null;filterCallback(regex);container.classList.toggle(activeClassName,!!input.value);} -input.addEventListener('input',searchHandler,false);function keydownHandler(event){if(event.key!=='Escape'||!input.value) -return;event.consume(true);input.value='';searchHandler();} -input.addEventListener('keydown',keydownHandler,false);input.setFilterValue=setFilterValue;function setFilterValue(value){input.value=value;input.focus();searchHandler();} -return input;} -revealProperty(cssProperty){this._decorator=new Elements.StylePropertyHighlighter(this,cssProperty);this._decorator.perform();this.update();} -forceUpdate(){this._swatchPopoverHelper.hide();this._resetCache();this.update();} -_sectionsContainerKeyDown(event){var activeElement=this._sectionsContainer.ownerDocument.deepActiveElement();if(!activeElement) -return;var section=activeElement._section;if(!section) -return;switch(event.key){case'ArrowUp':case'ArrowLeft':var sectionToFocus=section.previousSibling()||section.lastSibling();sectionToFocus.element.focus();event.consume(true);break;case'ArrowDown':case'ArrowRight':var sectionToFocus=section.nextSibling()||section.firstSibling();sectionToFocus.element.focus();event.consume(true);break;}} -_sectionsContainerFocusChanged(){if(this._sectionBlocks[0]&&this._sectionBlocks[0].sections[0]) -this._sectionBlocks[0].sections[0].element.tabIndex=this._sectionsContainer.hasFocus()?-1:0;} -_onAddButtonLongClick(event){var cssModel=this.cssModel();if(!cssModel) -return;var headers=cssModel.styleSheetHeaders().filter(styleSheetResourceHeader);var contextMenuDescriptors=[];for(var i=0;i<headers.length;++i){var header=headers[i];var handler=this._createNewRuleInStyleSheet.bind(this,header);contextMenuDescriptors.push({text:Bindings.displayNameForURL(header.resourceURL()),handler:handler});} -contextMenuDescriptors.sort(compareDescriptors);var contextMenu=new UI.ContextMenu(event);for(var i=0;i<contextMenuDescriptors.length;++i){var descriptor=contextMenuDescriptors[i];contextMenu.defaultSection().appendItem(descriptor.text,descriptor.handler);} -contextMenu.footerSection().appendItem('inspector-stylesheet',this._createNewRuleInViaInspectorStyleSheet.bind(this));contextMenu.show();function compareDescriptors(descriptor1,descriptor2){return String.naturalOrderComparator(descriptor1.text,descriptor2.text);} -function styleSheetResourceHeader(header){return!header.isViaInspector()&&!header.isInline&&!!header.resourceURL();}} -_onFilterChanged(regex){this._filterRegex=regex;this._updateFilter();} -_refreshUpdate(editedSection){var node=this.node();if(!node) -return;var fullRefresh=Runtime.experiments.isEnabled('liveSASS');for(var section of this.allSections()){if(section.isBlank) -continue;section.update(fullRefresh||section===editedSection);} -if(this._filterRegex) -this._updateFilter();this._nodeStylesUpdatedForTest(node,false);} -doUpdate(){return this._fetchMatchedCascade().then(this._innerRebuildUpdate.bind(this));} -onResize(){this._resizeThrottler.schedule(this._innerResize.bind(this));} -_innerResize(){var width=this.contentElement.getBoundingClientRect().width+'px';this.allSections().forEach(section=>section.propertiesTreeOutline.element.style.width=width);return Promise.resolve();} -_resetCache(){if(this.cssModel()) -this.cssModel().discardCachedMatchedCascade();} -_fetchMatchedCascade(){var node=this.node();if(!node||!this.cssModel()) -return Promise.resolve((null));return this.cssModel().cachedMatchedCascadeForNode(node).then(validateStyles.bind(this));function validateStyles(matchedStyles){return matchedStyles&&matchedStyles.node()===this.node()?matchedStyles:null;}} -setEditingStyle(editing){if(this._isEditingStyle===editing) -return;this.contentElement.classList.toggle('is-editing-style',editing);this._isEditingStyle=editing;} -onCSSModelChanged(event){var edit=event&&event.data?(event.data.edit):null;if(edit){for(var section of this.allSections()) -section._styleSheetEdited(edit);return;} -if(this._userOperation||this._isEditingStyle) -return;this._resetCache();this.update();} -_focusedSectionIndex(){var index=0;for(var block of this._sectionBlocks){for(var section of block.sections){if(section.element.hasFocus()) -return index;index++;}} -return-1;} -_innerRebuildUpdate(matchedStyles){var focusedIndex=this._focusedSectionIndex();this._linkifier.reset();this._sectionsContainer.removeChildren();this._sectionBlocks=[];var node=this.node();if(!matchedStyles||!node) -return;this._sectionBlocks=this._rebuildSectionsForMatchedStyleRules(matchedStyles);var pseudoTypes=[];var keys=new Set(matchedStyles.pseudoStyles().keys());if(keys.delete(Protocol.DOM.PseudoType.Before)) -pseudoTypes.push(Protocol.DOM.PseudoType.Before);pseudoTypes=pseudoTypes.concat(keys.valuesArray().sort());for(var pseudoType of pseudoTypes){var block=Elements.SectionBlock.createPseudoTypeBlock(pseudoType);var styles=(matchedStyles.pseudoStyles().get(pseudoType));for(var style of styles){var section=new Elements.StylePropertiesSection(this,matchedStyles,style);block.sections.push(section);} -this._sectionBlocks.push(block);} -for(var keyframesRule of matchedStyles.keyframes()){var block=Elements.SectionBlock.createKeyframesBlock(keyframesRule.name().text);for(var keyframe of keyframesRule.keyframes()) -block.sections.push(new Elements.KeyframePropertiesSection(this,matchedStyles,keyframe.style));this._sectionBlocks.push(block);} -var index=0;for(var block of this._sectionBlocks){var titleElement=block.titleElement();if(titleElement) -this._sectionsContainer.appendChild(titleElement);for(var section of block.sections){this._sectionsContainer.appendChild(section.element);if(index===focusedIndex) -section.element.focus();index++;}} -if(focusedIndex>=index) -this._sectionBlocks[0].sections[0].element.focus();this._sectionsContainerFocusChanged();if(this._filterRegex) -this._updateFilter();this._nodeStylesUpdatedForTest(node,true);if(this._decorator){this._decorator.perform();this._decorator=null;}} -_nodeStylesUpdatedForTest(node,rebuild){} -_rebuildSectionsForMatchedStyleRules(matchedStyles){var blocks=[new Elements.SectionBlock(null)];var lastParentNode=null;for(var style of matchedStyles.nodeStyles()){var parentNode=matchedStyles.isInherited(style)?matchedStyles.nodeForStyle(style):null;if(parentNode&&parentNode!==lastParentNode){lastParentNode=parentNode;var block=Elements.SectionBlock.createInheritedNodeBlock(lastParentNode);blocks.push(block);} -var section=new Elements.StylePropertiesSection(this,matchedStyles,style);blocks.peekLast().sections.push(section);} -return blocks;} -async _createNewRuleInViaInspectorStyleSheet(){var cssModel=this.cssModel();var node=this.node();if(!cssModel||!node) -return;this._userOperation=true;var styleSheetHeader=await cssModel.requestViaInspectorStylesheet((node));this._userOperation=false;this._createNewRuleInStyleSheet(styleSheetHeader);} -_createNewRuleInStyleSheet(styleSheetHeader){if(!styleSheetHeader) -return;styleSheetHeader.requestContent().then(onStyleSheetContent.bind(this,styleSheetHeader.id));function onStyleSheetContent(styleSheetId,text){text=text||'';var lines=text.split('\n');var range=TextUtils.TextRange.createFromLocation(lines.length-1,lines[lines.length-1].length);this._addBlankSection(this._sectionBlocks[0].sections[0],styleSheetId,range);}} -_addBlankSection(insertAfterSection,styleSheetId,ruleLocation){var node=this.node();var blankSection=new Elements.BlankStylePropertiesSection(this,insertAfterSection._matchedStyles,node?Components.DOMPresentationUtils.simpleSelector(node):'',styleSheetId,ruleLocation,insertAfterSection._style);this._sectionsContainer.insertBefore(blankSection.element,insertAfterSection.element.nextSibling);for(var block of this._sectionBlocks){var index=block.sections.indexOf(insertAfterSection);if(index===-1) -continue;block.sections.splice(index+1,0,blankSection);blankSection.startEditingSelector();}} -removeSection(section){for(var block of this._sectionBlocks){var index=block.sections.indexOf(section);if(index===-1) -continue;block.sections.splice(index,1);section.element.remove();}} -filterRegex(){return this._filterRegex;} -_updateFilter(){for(var block of this._sectionBlocks) -block.updateFilter();} -willHide(){this._swatchPopoverHelper.hide();super.willHide();} -allSections(){var sections=[];for(var block of this._sectionBlocks) -sections=sections.concat(block.sections);return sections;} -_clipboardCopy(event){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleCopied);} -_createStylesSidebarToolbar(){var container=this.contentElement.createChild('div','styles-sidebar-pane-toolbar-container');var hbox=container.createChild('div','hbox styles-sidebar-pane-toolbar');var filterContainerElement=hbox.createChild('div','styles-sidebar-pane-filter-box');var filterInput=Elements.StylesSidebarPane.createPropertyFilterElement(Common.UIString('Filter'),hbox,this._onFilterChanged.bind(this),'styles-filter-engaged');UI.ARIAUtils.setAccessibleName(filterInput,Common.UIString('Filter Styles'));filterContainerElement.appendChild(filterInput);var toolbar=new UI.Toolbar('styles-pane-toolbar',hbox);toolbar.makeToggledGray();toolbar.appendLocationItems('styles-sidebarpane-toolbar');var toolbarPaneContainer=container.createChild('div','styles-sidebar-toolbar-pane-container');var toolbarPaneContent=toolbarPaneContainer.createChild('div','styles-sidebar-toolbar-pane');return toolbarPaneContent;} -showToolbarPane(widget,toggle){if(this._pendingWidgetToggle) -this._pendingWidgetToggle.setToggled(false);this._pendingWidgetToggle=toggle;if(this._animatedToolbarPane) -this._pendingWidget=widget;else -this._startToolbarPaneAnimation(widget);if(widget&&toggle) -toggle.setToggled(true);} -_startToolbarPaneAnimation(widget){if(widget===this._currentToolbarPane) -return;if(widget&&this._currentToolbarPane){this._currentToolbarPane.detach();widget.show(this._toolbarPaneElement);this._currentToolbarPane=widget;this._currentToolbarPane.focus();return;} -this._animatedToolbarPane=widget;if(this._currentToolbarPane) -this._toolbarPaneElement.style.animationName='styles-element-state-pane-slideout';else if(widget) -this._toolbarPaneElement.style.animationName='styles-element-state-pane-slidein';if(widget) -widget.show(this._toolbarPaneElement);var listener=onAnimationEnd.bind(this);this._toolbarPaneElement.addEventListener('animationend',listener,false);function onAnimationEnd(){this._toolbarPaneElement.style.removeProperty('animation-name');this._toolbarPaneElement.removeEventListener('animationend',listener,false);if(this._currentToolbarPane) -this._currentToolbarPane.detach();this._currentToolbarPane=this._animatedToolbarPane;if(this._currentToolbarPane) -this._currentToolbarPane.focus();this._animatedToolbarPane=null;if(this._pendingWidget){this._startToolbarPaneAnimation(this._pendingWidget);this._pendingWidget=null;}}}};Elements.StylesSidebarPane._maxLinkLength=30;Elements.SectionBlock=class{constructor(titleElement){this._titleElement=titleElement;this.sections=[];} -static createPseudoTypeBlock(pseudoType){var separatorElement=createElement('div');separatorElement.className='sidebar-separator';separatorElement.textContent=Common.UIString('Pseudo ::%s element',pseudoType);return new Elements.SectionBlock(separatorElement);} -static createKeyframesBlock(keyframesName){var separatorElement=createElement('div');separatorElement.className='sidebar-separator';separatorElement.textContent=Common.UIString('@keyframes '+keyframesName);return new Elements.SectionBlock(separatorElement);} -static createInheritedNodeBlock(node){var separatorElement=createElement('div');separatorElement.className='sidebar-separator';var link=Components.DOMPresentationUtils.linkifyNodeReference(node);separatorElement.createTextChild(Common.UIString('Inherited from')+' ');separatorElement.appendChild(link);return new Elements.SectionBlock(separatorElement);} -updateFilter(){var hasAnyVisibleSection=false;for(var section of this.sections) -hasAnyVisibleSection|=section._updateFilter();if(this._titleElement) -this._titleElement.classList.toggle('hidden',!hasAnyVisibleSection);} -titleElement(){return this._titleElement;}};Elements.StylePropertiesSection=class{constructor(parentPane,matchedStyles,style){this._parentPane=parentPane;this._style=style;this._matchedStyles=matchedStyles;this.editable=!!(style.styleSheetId&&style.range);this._hoverTimer=null;this._afterUpdate=null;this._willCauseCancelEditing=false;var rule=style.parentRule;this.element=createElementWithClass('div','styles-section matched-styles monospace');this.element.tabIndex=-1;this._editing=false;this.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this.element._section=this;this._innerElement=this.element.createChild('div');this._titleElement=this._innerElement.createChild('div','styles-section-title '+(rule?'styles-selector':''));this.propertiesTreeOutline=new UI.TreeOutlineInShadow();this.propertiesTreeOutline.setFocusable(false);this.propertiesTreeOutline.registerRequiredCSS('elements/stylesSectionTree.css');this.propertiesTreeOutline.element.classList.add('style-properties','matched-styles','monospace');this.propertiesTreeOutline.section=this;this._innerElement.appendChild(this.propertiesTreeOutline.element);var selectorContainer=createElement('div');this._selectorElement=createElementWithClass('span','selector');this._selectorElement.textContent=this._headerText();selectorContainer.appendChild(this._selectorElement);this._selectorElement.addEventListener('mouseenter',this._onMouseEnterSelector.bind(this),false);this._selectorElement.addEventListener('mouseleave',this._onMouseOutSelector.bind(this),false);var openBrace=createElement('span');openBrace.textContent=' {';selectorContainer.appendChild(openBrace);selectorContainer.addEventListener('mousedown',this._handleEmptySpaceMouseDown.bind(this),false);selectorContainer.addEventListener('click',this._handleSelectorContainerClick.bind(this),false);var closeBrace=this._innerElement.createChild('div','sidebar-pane-closing-brace');closeBrace.textContent='}';this._createHoverMenuToolbar(closeBrace);this._selectorElement.addEventListener('click',this._handleSelectorClick.bind(this),false);this.element.addEventListener('mousedown',this._handleEmptySpaceMouseDown.bind(this),false);this.element.addEventListener('click',this._handleEmptySpaceClick.bind(this),false);this.element.addEventListener('mousemove',this._onMouseMove.bind(this),false);this.element.addEventListener('mouseleave',this._setSectionHovered.bind(this,false),false);if(rule){if(rule.isUserAgent()||rule.isInjected()){this.editable=false;}else{if(rule.styleSheetId){var header=rule.cssModel().styleSheetHeaderForId(rule.styleSheetId);this.navigable=!header.isAnonymousInlineStyleSheet();}}} -this._mediaListElement=this._titleElement.createChild('div','media-list media-matches');this._selectorRefElement=this._titleElement.createChild('div','styles-section-subtitle');this._updateMediaList();this._updateRuleOrigin();this._titleElement.appendChild(selectorContainer);this._selectorContainer=selectorContainer;if(this.navigable) -this.element.classList.add('navigable');if(!this.editable){this.element.classList.add('read-only');this.propertiesTreeOutline.element.classList.add('read-only');} -var throttler=new Common.Throttler(100);this._scheduleHeightUpdate=()=>throttler.schedule(this._manuallySetHeight.bind(this));this._hoverableSelectorsMode=false;this._markSelectorMatches();this.onpopulate();} -static createRuleOriginNode(matchedStyles,linkifier,rule){if(!rule) -return createTextNode('');var ruleLocation;if(rule instanceof SDK.CSSStyleRule) -ruleLocation=rule.style.range;else if(rule instanceof SDK.CSSKeyframeRule) -ruleLocation=rule.key().range;var header=rule.styleSheetId?matchedStyles.cssModel().styleSheetHeaderForId(rule.styleSheetId):null;if(ruleLocation&&rule.styleSheetId&&header&&!header.isAnonymousInlineStyleSheet()){return Elements.StylePropertiesSection._linkifyRuleLocation(matchedStyles.cssModel(),linkifier,rule.styleSheetId,ruleLocation);} -if(rule.isUserAgent()) -return createTextNode(Common.UIString('user agent stylesheet'));if(rule.isInjected()) -return createTextNode(Common.UIString('injected stylesheet'));if(rule.isViaInspector()) -return createTextNode(Common.UIString('via inspector'));if(header&&header.ownerNode){var link=Components.DOMPresentationUtils.linkifyDeferredNodeReference(header.ownerNode);link.textContent='<style>…</style>';return link;} -return createTextNode('');} -static _linkifyRuleLocation(cssModel,linkifier,styleSheetId,ruleLocation){var styleSheetHeader=cssModel.styleSheetHeaderForId(styleSheetId);var lineNumber=styleSheetHeader.lineNumberInSource(ruleLocation.startLine);var columnNumber=styleSheetHeader.columnNumberInSource(ruleLocation.startLine,ruleLocation.startColumn);var matchingSelectorLocation=new SDK.CSSLocation(styleSheetHeader,lineNumber,columnNumber);return linkifier.linkifyCSSLocation(matchingSelectorLocation);} -_onKeyDown(event){if(this._editing||!this.editable||event.altKey||event.ctrlKey||event.metaKey) -return;switch(event.key){case'Enter':case' ':this._startEditingAtFirstPosition();event.consume(true);break;default:if(event.key.length===1) -this.addNewBlankProperty(0).startEditing();break;}} -_setSectionHovered(isHovered){this.element.classList.toggle('styles-panel-hovered',isHovered);this.propertiesTreeOutline.element.classList.toggle('styles-panel-hovered',isHovered);if(this._hoverableSelectorsMode!==isHovered){this._hoverableSelectorsMode=isHovered;this._markSelectorMatches();}} -_onMouseMove(event){var hasCtrlOrMeta=UI.KeyboardShortcut.eventHasCtrlOrMeta((event));this._setSectionHovered(hasCtrlOrMeta);} -_createHoverMenuToolbar(container){if(!this.editable) -return;var items=[];var textShadowButton=new UI.ToolbarButton(Common.UIString('Add text-shadow'),'largeicon-text-shadow');textShadowButton.addEventListener(UI.ToolbarButton.Events.Click,this._onInsertShadowPropertyClick.bind(this,'text-shadow'));textShadowButton.element.tabIndex=-1;items.push(textShadowButton);var boxShadowButton=new UI.ToolbarButton(Common.UIString('Add box-shadow'),'largeicon-box-shadow');boxShadowButton.addEventListener(UI.ToolbarButton.Events.Click,this._onInsertShadowPropertyClick.bind(this,'box-shadow'));boxShadowButton.element.tabIndex=-1;items.push(boxShadowButton);var colorButton=new UI.ToolbarButton(Common.UIString('Add color'),'largeicon-foreground-color');colorButton.addEventListener(UI.ToolbarButton.Events.Click,this._onInsertColorPropertyClick,this);colorButton.element.tabIndex=-1;items.push(colorButton);var backgroundButton=new UI.ToolbarButton(Common.UIString('Add background-color'),'largeicon-background-color');backgroundButton.addEventListener(UI.ToolbarButton.Events.Click,this._onInsertBackgroundColorPropertyClick,this);backgroundButton.element.tabIndex=-1;items.push(backgroundButton);var newRuleButton=null;if(this._style.parentRule){newRuleButton=new UI.ToolbarButton(Common.UIString('Insert Style Rule Below'),'largeicon-add');newRuleButton.addEventListener(UI.ToolbarButton.Events.Click,this._onNewRuleClick,this);newRuleButton.element.tabIndex=-1;items.push(newRuleButton);} -var sectionToolbar=new UI.Toolbar('sidebar-pane-section-toolbar',container);for(var i=0;i<items.length;++i) -sectionToolbar.appendToolbarItem(items[i]);var menuButton=new UI.ToolbarButton(Common.UIString('More tools\u2026'),'largeicon-menu');menuButton.element.tabIndex=-1;sectionToolbar.appendToolbarItem(menuButton);setItemsVisibility.call(this,items,false);sectionToolbar.element.addEventListener('mouseenter',setItemsVisibility.bind(this,items,true));sectionToolbar.element.addEventListener('mouseleave',setItemsVisibility.bind(this,items,false));function setItemsVisibility(items,value){for(var i=0;i<items.length;++i) -items[i].setVisible(value);menuButton.setVisible(!value);if(this._isSASSStyle()) -newRuleButton.setVisible(false);}} -_isSASSStyle(){var header=this._style.styleSheetId?this._style.cssModel().styleSheetHeaderForId(this._style.styleSheetId):null;if(!header) -return false;var sourceMap=header.cssModel().sourceMapManager().sourceMapForClient(header);return sourceMap?sourceMap.editable():false;} -style(){return this._style;} -_headerText(){var node=this._matchedStyles.nodeForStyle(this._style);if(this._style.type===SDK.CSSStyleDeclaration.Type.Inline) -return this._matchedStyles.isInherited(this._style)?Common.UIString('Style Attribute'):'element.style';if(this._style.type===SDK.CSSStyleDeclaration.Type.Attributes) -return node.nodeNameInCorrectCase()+'['+Common.UIString('Attributes Style')+']';return this._style.parentRule.selectorText();} -_onMouseOutSelector(){if(this._hoverTimer) -clearTimeout(this._hoverTimer);SDK.OverlayModel.hideDOMNodeHighlight();} -_onMouseEnterSelector(){if(this._hoverTimer) -clearTimeout(this._hoverTimer);this._hoverTimer=setTimeout(this._highlight.bind(this),300);} -_highlight(){SDK.OverlayModel.hideDOMNodeHighlight();var node=this._parentPane.node();var selectors=this._style.parentRule?this._style.parentRule.selectorText():undefined;node.domModel().overlayModel().highlightDOMNodeWithConfig(node.id,{mode:'all',showInfo:undefined,selectors:selectors});} -firstSibling(){var parent=this.element.parentElement;if(!parent) -return null;var childElement=parent.firstChild;while(childElement){if(childElement._section) -return childElement._section;childElement=childElement.nextSibling;} -return null;} -lastSibling(){var parent=this.element.parentElement;if(!parent) -return null;var childElement=parent.lastChild;while(childElement){if(childElement._section) -return childElement._section;childElement=childElement.previousSibling;} -return null;} -nextSibling(){var curElement=this.element;do -curElement=curElement.nextSibling;while(curElement&&!curElement._section);return curElement?curElement._section:null;} -previousSibling(){var curElement=this.element;do -curElement=curElement.previousSibling;while(curElement&&!curElement._section);return curElement?curElement._section:null;} -_onNewRuleClick(event){event.data.consume();var rule=this._style.parentRule;var range=TextUtils.TextRange.createFromLocation(rule.style.range.endLine,rule.style.range.endColumn+1);this._parentPane._addBlankSection(this,(rule.styleSheetId),range);} -_onInsertShadowPropertyClick(propertyName,event){event.data.consume(true);var treeElement=this.addNewBlankProperty();treeElement.property.name=propertyName;treeElement.property.value='0 0 black';treeElement.updateTitle();var shadowSwatchPopoverHelper=Elements.ShadowSwatchPopoverHelper.forTreeElement(treeElement);if(shadowSwatchPopoverHelper) -shadowSwatchPopoverHelper.showPopover();} -_onInsertColorPropertyClick(event){event.data.consume(true);var treeElement=this.addNewBlankProperty();treeElement.property.name='color';treeElement.property.value='black';treeElement.updateTitle();var colorSwatch=Elements.ColorSwatchPopoverIcon.forTreeElement(treeElement);if(colorSwatch) -colorSwatch.showPopover();} -_onInsertBackgroundColorPropertyClick(event){event.data.consume(true);var treeElement=this.addNewBlankProperty();treeElement.property.name='background-color';treeElement.property.value='white';treeElement.updateTitle();var colorSwatch=Elements.ColorSwatchPopoverIcon.forTreeElement(treeElement);if(colorSwatch) -colorSwatch.showPopover();} -_styleSheetEdited(edit){var rule=this._style.parentRule;if(rule) -rule.rebase(edit);else -this._style.rebase(edit);this._updateMediaList();this._updateRuleOrigin();} -_createMediaList(mediaRules){for(var i=mediaRules.length-1;i>=0;--i){var media=mediaRules[i];if(!media.text.includes('(')&&media.text!=='print') -continue;var mediaDataElement=this._mediaListElement.createChild('div','media');var mediaContainerElement=mediaDataElement.createChild('span');var mediaTextElement=mediaContainerElement.createChild('span','media-text');switch(media.source){case SDK.CSSMedia.Source.LINKED_SHEET:case SDK.CSSMedia.Source.INLINE_SHEET:mediaTextElement.textContent='media="'+media.text+'"';break;case SDK.CSSMedia.Source.MEDIA_RULE:var decoration=mediaContainerElement.createChild('span');mediaContainerElement.insertBefore(decoration,mediaTextElement);decoration.textContent='@media ';mediaTextElement.textContent=media.text;if(media.styleSheetId){mediaDataElement.classList.add('editable-media');mediaTextElement.addEventListener('click',this._handleMediaRuleClick.bind(this,media,mediaTextElement),false);} -break;case SDK.CSSMedia.Source.IMPORT_RULE:mediaTextElement.textContent='@import '+media.text;break;}}} -_updateMediaList(){this._mediaListElement.removeChildren();if(this._style.parentRule&&this._style.parentRule instanceof SDK.CSSStyleRule) -this._createMediaList(this._style.parentRule.media);} -isPropertyInherited(propertyName){if(this._matchedStyles.isInherited(this._style)){return!SDK.cssMetadata().isPropertyInherited(propertyName);} -return false;} -nextEditableSibling(){var curSection=this;do -curSection=curSection.nextSibling();while(curSection&&!curSection.editable);if(!curSection){curSection=this.firstSibling();while(curSection&&!curSection.editable) -curSection=curSection.nextSibling();} -return(curSection&&curSection.editable)?curSection:null;} -previousEditableSibling(){var curSection=this;do -curSection=curSection.previousSibling();while(curSection&&!curSection.editable);if(!curSection){curSection=this.lastSibling();while(curSection&&!curSection.editable) -curSection=curSection.previousSibling();} -return(curSection&&curSection.editable)?curSection:null;} -update(full){this._selectorElement.textContent=this._headerText();this._markSelectorMatches();if(full){this.propertiesTreeOutline.removeChildren();this.onpopulate();}else{var child=this.propertiesTreeOutline.firstChild();while(child){child.setOverloaded(this._isPropertyOverloaded(child.property));child=child.traverseNextTreeElement(false,null,true);}} -this.afterUpdate();} -afterUpdate(){if(this._afterUpdate){this._afterUpdate(this);this._afterUpdate=null;this._afterUpdateFinishedForTest();}} -_afterUpdateFinishedForTest(){} -onpopulate(){var style=this._style;for(var property of style.leadingProperties()){var isShorthand=!!style.longhandProperties(property.name).length;var inherited=this.isPropertyInherited(property.name);var overloaded=this._isPropertyOverloaded(property);var item=new Elements.StylePropertyTreeElement(this._parentPane,this._matchedStyles,property,isShorthand,inherited,overloaded);this.propertiesTreeOutline.appendChild(item);}} -_isPropertyOverloaded(property){return this._matchedStyles.propertyState(property)===SDK.CSSMatchedStyles.PropertyState.Overloaded;} -_updateFilter(){var hasMatchingChild=false;for(var child of this.propertiesTreeOutline.rootElement().children()) -hasMatchingChild|=child._updateFilter();var regex=this._parentPane.filterRegex();var hideRule=!hasMatchingChild&&!!regex&&!regex.test(this.element.deepTextContent());this.element.classList.toggle('hidden',hideRule);if(!hideRule&&this._style.parentRule) -this._markSelectorHighlights();return!hideRule;} -_markSelectorMatches(){var rule=this._style.parentRule;if(!rule) -return;this._mediaListElement.classList.toggle('media-matches',this._matchedStyles.mediaMatches(this._style));var selectorTexts=rule.selectors.map(selector=>selector.text);var matchingSelectorIndexes=this._matchedStyles.matchingSelectors((rule));var matchingSelectors=(new Array(selectorTexts.length).fill(false));for(var matchingIndex of matchingSelectorIndexes) -matchingSelectors[matchingIndex]=true;if(this._parentPane._isEditingStyle) -return;var fragment=this._hoverableSelectorsMode?this._renderHoverableSelectors(selectorTexts,matchingSelectors):this._renderSimplifiedSelectors(selectorTexts,matchingSelectors);this._selectorElement.removeChildren();this._selectorElement.appendChild(fragment);this._markSelectorHighlights();} -_renderHoverableSelectors(selectors,matchingSelectors){var fragment=createDocumentFragment();for(var i=0;i<selectors.length;++i){if(i) -fragment.createTextChild(', ');fragment.appendChild(this._createSelectorElement(selectors[i],matchingSelectors[i],i));} -return fragment;} -_createSelectorElement(text,isMatching,navigationIndex){var element=createElementWithClass('span','simple-selector');element.classList.toggle('selector-matches',isMatching);if(typeof navigationIndex==='number') -element._selectorIndex=navigationIndex;element.textContent=text;return element;} -_renderSimplifiedSelectors(selectors,matchingSelectors){var fragment=createDocumentFragment();var currentMatching=false;var text='';for(var i=0;i<selectors.length;++i){if(currentMatching!==matchingSelectors[i]&&text){fragment.appendChild(this._createSelectorElement(text,currentMatching));text='';} -currentMatching=matchingSelectors[i];text+=selectors[i]+(i===selectors.length-1?'':', ');} -if(text) -fragment.appendChild(this._createSelectorElement(text,currentMatching));return fragment;} -_markSelectorHighlights(){var selectors=this._selectorElement.getElementsByClassName('simple-selector');var regex=this._parentPane.filterRegex();for(var i=0;i<selectors.length;++i){var selectorMatchesFilter=!!regex&®ex.test(selectors[i].textContent);selectors[i].classList.toggle('filter-match',selectorMatchesFilter);}} -_checkWillCancelEditing(){var willCauseCancelEditing=this._willCauseCancelEditing;this._willCauseCancelEditing=false;return willCauseCancelEditing;} -_handleSelectorContainerClick(event){if(this._checkWillCancelEditing()||!this.editable) -return;if(event.target===this._selectorContainer){this.addNewBlankProperty(0).startEditing();event.consume(true);}} -addNewBlankProperty(index){var property=this._style.newBlankProperty(index);var item=new Elements.StylePropertyTreeElement(this._parentPane,this._matchedStyles,property,false,false,false);index=property.index;this.propertiesTreeOutline.insertChild(item,index);item.listItemElement.textContent='';item._newProperty=true;item.updateTitle();return item;} -_handleEmptySpaceMouseDown(){this._willCauseCancelEditing=this._parentPane._isEditingStyle;} -_handleEmptySpaceClick(event){if(!this.editable||this.element.hasSelection()||this._checkWillCancelEditing()) -return;if(event.target.classList.contains('header')||this.element.classList.contains('read-only')||event.target.enclosingNodeOrSelfWithClass('media')){event.consume();return;} -this.addNewBlankProperty().startEditing();event.consume(true);} -_handleMediaRuleClick(media,element,event){if(UI.isBeingEdited(element)) -return;if(UI.KeyboardShortcut.eventHasCtrlOrMeta((event))&&this.navigable){var location=media.rawLocation();if(!location){event.consume(true);return;} -var uiLocation=Bindings.cssWorkspaceBinding.rawLocationToUILocation(location);if(uiLocation) -Common.Revealer.reveal(uiLocation);event.consume(true);return;} -if(!this.editable||this._isSASSStyle()) -return;var config=new UI.InplaceEditor.Config(this._editingMediaCommitted.bind(this,media),this._editingMediaCancelled.bind(this,element),undefined,this._editingMediaBlurHandler.bind(this));UI.InplaceEditor.startEditing(element,config);this._startEditing();element.getComponentSelection().selectAllChildren(element);this._parentPane.setEditingStyle(true);var parentMediaElement=element.enclosingNodeOrSelfWithClass('media');parentMediaElement.classList.add('editing-media');event.consume(true);} -_editingMediaFinished(element){this._parentPane.setEditingStyle(false);var parentMediaElement=element.enclosingNodeOrSelfWithClass('media');parentMediaElement.classList.remove('editing-media');this._stopEditing();} -_editingMediaCancelled(element){this._editingMediaFinished(element);this._markSelectorMatches();element.getComponentSelection().collapse(element,0);} -_editingMediaBlurHandler(editor,blurEvent){return true;} -_editingMediaCommitted(media,element,newContent,oldContent,context,moveDirection){this._parentPane.setEditingStyle(false);this._editingMediaFinished(element);if(newContent) -newContent=newContent.trim();function userCallback(success){if(success){this._matchedStyles.resetActiveProperties();this._parentPane._refreshUpdate(this);} -this._parentPane._userOperation=false;this._editingMediaTextCommittedForTest();} -this._parentPane._userOperation=true;this._parentPane.cssModel().setMediaText(media.styleSheetId,media.range,newContent).then(userCallback.bind(this));} -_editingMediaTextCommittedForTest(){} -_handleSelectorClick(event){if(UI.KeyboardShortcut.eventHasCtrlOrMeta((event))&&this.navigable&&event.target.classList.contains('simple-selector')){this._navigateToSelectorSource(event.target._selectorIndex,true);event.consume(true);return;} -this._startEditingAtFirstPosition();event.consume(true);} -_navigateToSelectorSource(index,focus){var cssModel=this._parentPane.cssModel();var rule=this._style.parentRule;var header=cssModel.styleSheetHeaderForId((rule.styleSheetId));if(!header) -return;var rawLocation=new SDK.CSSLocation(header,rule.lineNumberInSource(index),rule.columnNumberInSource(index));var uiLocation=Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation);if(uiLocation) -Common.Revealer.reveal(uiLocation,!focus);} -_startEditingAtFirstPosition(){if(!this.editable||this._isSASSStyle()) -return;if(!this._style.parentRule){this._moveEditorFromSelector('forward');return;} -this.startEditingSelector();} -startEditingSelector(){var element=this._selectorElement;if(UI.isBeingEdited(element)) -return;element.scrollIntoViewIfNeeded(false);element.textContent=element.textContent.replace(/\s+/g,' ').trim();var config=new UI.InplaceEditor.Config(this.editingSelectorCommitted.bind(this),this.editingSelectorCancelled.bind(this));UI.InplaceEditor.startEditing(this._selectorElement,config);this._startEditing();element.getComponentSelection().selectAllChildren(element);this._parentPane.setEditingStyle(true);if(element.classList.contains('simple-selector')) -this._navigateToSelectorSource(0,false);} -_moveEditorFromSelector(moveDirection){this._markSelectorMatches();if(!moveDirection) -return;if(moveDirection==='forward'){var firstChild=this.propertiesTreeOutline.firstChild();while(firstChild&&firstChild.inherited()) -firstChild=firstChild.nextSibling;if(!firstChild) -this.addNewBlankProperty().startEditing();else -firstChild.startEditing(firstChild.nameElement);}else{var previousSection=this.previousEditableSibling();if(!previousSection) -return;previousSection.addNewBlankProperty().startEditing();}} -editingSelectorCommitted(element,newContent,oldContent,context,moveDirection){this._editingSelectorEnded();if(newContent) -newContent=newContent.trim();if(newContent===oldContent){this._selectorElement.textContent=newContent;this._moveEditorFromSelector(moveDirection);return;} -var rule=this._style.parentRule;if(!rule) -return;function headerTextCommitted(){this._parentPane._userOperation=false;this._moveEditorFromSelector(moveDirection);this._editingSelectorCommittedForTest();} -this._parentPane._userOperation=true;this._setHeaderText(rule,newContent).then(headerTextCommitted.bind(this));} -_setHeaderText(rule,newContent){function onSelectorsUpdated(rule,success){if(!success) -return Promise.resolve();return this._matchedStyles.recomputeMatchingSelectors(rule).then(updateSourceRanges.bind(this,rule));} -function updateSourceRanges(rule){var doesAffectSelectedNode=this._matchedStyles.matchingSelectors(rule).length>0;this.propertiesTreeOutline.element.classList.toggle('no-affect',!doesAffectSelectedNode);this._matchedStyles.resetActiveProperties();this._parentPane._refreshUpdate(this);} -console.assert(rule instanceof SDK.CSSStyleRule);var oldSelectorRange=rule.selectorRange();if(!oldSelectorRange) -return Promise.resolve();return rule.setSelectorText(newContent).then(onSelectorsUpdated.bind(this,(rule),oldSelectorRange));} -_editingSelectorCommittedForTest(){} -_updateRuleOrigin(){this._selectorRefElement.removeChildren();this._selectorRefElement.appendChild(Elements.StylePropertiesSection.createRuleOriginNode(this._matchedStyles,this._parentPane._linkifier,this._style.parentRule));} -_editingSelectorEnded(){this._parentPane.setEditingStyle(false);this._stopEditing();} -editingSelectorCancelled(){this._editingSelectorEnded();this._markSelectorMatches();} -_startEditing(){this._manuallySetHeight();this.element.addEventListener('input',this._scheduleHeightUpdate,true);this._editing=true;} -_manuallySetHeight(){this.element.style.height=(this._innerElement.clientHeight+1)+'px';this.element.style.contain='strict';return Promise.resolve();} -_stopEditing(){this.element.style.removeProperty('height');this.element.style.removeProperty('contain');this.element.removeEventListener('input',this._scheduleHeightUpdate,true);this._editing=false;if(this._parentPane.element.hasFocus()) -this.element.focus();}};Elements.BlankStylePropertiesSection=class extends Elements.StylePropertiesSection{constructor(stylesPane,matchedStyles,defaultSelectorText,styleSheetId,ruleLocation,insertAfterStyle){var cssModel=(stylesPane.cssModel());var rule=SDK.CSSStyleRule.createDummyRule(cssModel,defaultSelectorText);super(stylesPane,matchedStyles,rule.style);this._normal=false;this._ruleLocation=ruleLocation;this._styleSheetId=styleSheetId;this._selectorRefElement.removeChildren();this._selectorRefElement.appendChild(Elements.StylePropertiesSection._linkifyRuleLocation(cssModel,this._parentPane._linkifier,styleSheetId,this._actualRuleLocation()));if(insertAfterStyle&&insertAfterStyle.parentRule) -this._createMediaList(insertAfterStyle.parentRule.media);this.element.classList.add('blank-section');} -_actualRuleLocation(){var prefix=this._rulePrefix();var lines=prefix.split('\n');var editRange=new TextUtils.TextRange(0,0,lines.length-1,lines.peekLast().length);return this._ruleLocation.rebaseAfterTextEdit(TextUtils.TextRange.createFromLocation(0,0),editRange);} -_rulePrefix(){return this._ruleLocation.startLine===0&&this._ruleLocation.startColumn===0?'':'\n\n';} -get isBlank(){return!this._normal;} -editingSelectorCommitted(element,newContent,oldContent,context,moveDirection){if(!this.isBlank){super.editingSelectorCommitted(element,newContent,oldContent,context,moveDirection);return;} -function onRuleAdded(newRule){if(!newRule){this.editingSelectorCancelled();this._editingSelectorCommittedForTest();return Promise.resolve();} -return this._matchedStyles.addNewRule(newRule,this._matchedStyles.node()).then(onAddedToCascade.bind(this,newRule));} -function onAddedToCascade(newRule){var doesSelectorAffectSelectedNode=this._matchedStyles.matchingSelectors(newRule).length>0;this._makeNormal(newRule);if(!doesSelectorAffectSelectedNode) -this.propertiesTreeOutline.element.classList.add('no-affect');this._updateRuleOrigin();if(this.element.parentElement) -this._moveEditorFromSelector(moveDirection);this._parentPane._userOperation=false;this._editingSelectorEnded();this._markSelectorMatches();this._editingSelectorCommittedForTest();} -if(newContent) -newContent=newContent.trim();this._parentPane._userOperation=true;var cssModel=this._parentPane.cssModel();var ruleText=this._rulePrefix()+newContent+' {}';cssModel.addRule(this._styleSheetId,ruleText,this._ruleLocation).then(onRuleAdded.bind(this));} -editingSelectorCancelled(){this._parentPane._userOperation=false;if(!this.isBlank){super.editingSelectorCancelled();return;} -this._editingSelectorEnded();this._parentPane.removeSection(this);} -_makeNormal(newRule){this.element.classList.remove('blank-section');this._style=newRule.style;this._normal=true;}};Elements.KeyframePropertiesSection=class extends Elements.StylePropertiesSection{constructor(stylesPane,matchedStyles,style){super(stylesPane,matchedStyles,style);this._selectorElement.className='keyframe-key';} -_headerText(){return this._style.parentRule.key().text;} -_setHeaderText(rule,newContent){function updateSourceRanges(success){if(!success) -return;this._parentPane._refreshUpdate(this);} -console.assert(rule instanceof SDK.CSSKeyframeRule);var oldRange=rule.key().range;if(!oldRange) -return Promise.resolve();return rule.setKeyText(newContent).then(updateSourceRanges.bind(this));} -isPropertyInherited(propertyName){return false;} -_isPropertyOverloaded(property){return false;} -_markSelectorHighlights(){} -_markSelectorMatches(){this._selectorElement.textContent=this._style.parentRule.key().text;} -_highlight(){}};Elements.StylePropertyTreeElement=class extends UI.TreeElement{constructor(stylesPane,matchedStyles,property,isShorthand,inherited,overloaded){super('',isShorthand);this._style=property.ownerStyle;this._matchedStyles=matchedStyles;this.property=property;this._inherited=inherited;this._overloaded=overloaded;this.selectable=false;this._parentPane=stylesPane;this.isShorthand=isShorthand;this._applyStyleThrottler=new Common.Throttler(0);this._newProperty=false;this._expandedDueToFilter=false;this.valueElement=null;this.nameElement=null;this._expandElement=null;this._originalPropertyText='';this._prompt=null;this._propertyHasBeenEditedIncrementally=false;} -_editable(){return!!(this._style.styleSheetId&&this._style.range);} -inherited(){return this._inherited;} -overloaded(){return this._overloaded;} -setOverloaded(x){if(x===this._overloaded) -return;this._overloaded=x;this._updateState();} -get name(){return this.property.name;} -get value(){return this.property.value;} -_updateFilter(){var regex=this._parentPane.filterRegex();var matches=!!regex&&(regex.test(this.property.name)||regex.test(this.property.value));this.listItemElement.classList.toggle('filter-match',matches);this.onpopulate();var hasMatchingChildren=false;for(var i=0;i<this.childCount();++i) -hasMatchingChildren|=this.childAt(i)._updateFilter();if(!regex){if(this._expandedDueToFilter) -this.collapse();this._expandedDueToFilter=false;}else if(hasMatchingChildren&&!this.expanded){this.expand();this._expandedDueToFilter=true;}else if(!hasMatchingChildren&&this.expanded&&this._expandedDueToFilter){this.collapse();this._expandedDueToFilter=false;} -return matches;} -_processColor(text){var color=Common.Color.parse(text);if(!color) -return createTextNode(text);if(!this._editable()){var swatch=InlineEditor.ColorSwatch.create();swatch.setColor(color);return swatch;} -var swatchPopoverHelper=this._parentPane._swatchPopoverHelper;var swatch=InlineEditor.ColorSwatch.create();swatch.setColor(color);swatch.setFormat(Common.Color.detectColorFormat(swatch.color()));var swatchIcon=new Elements.ColorSwatchPopoverIcon(this,swatchPopoverHelper,swatch);function computedCallback(contrastInfo){swatchIcon.setContrastInfo(contrastInfo);} -if(Runtime.experiments.isEnabled('colorContrastRatio')&&this.property.name==='color'&&this._parentPane.cssModel()&&this.node()){var cssModel=this._parentPane.cssModel();cssModel.backgroundColorsPromise(this.node().id).then(computedCallback);} -return swatch;} -renderedPropertyText(){return this.nameElement.textContent+': '+this.valueElement.textContent;} -_processBezier(text){if(!this._editable()||!UI.Geometry.CubicBezier.parse(text)) -return createTextNode(text);var swatchPopoverHelper=this._parentPane._swatchPopoverHelper;var swatch=InlineEditor.BezierSwatch.create();swatch.setBezierText(text);new Elements.BezierPopoverIcon(this,swatchPopoverHelper,swatch);return swatch;} -_processShadow(propertyValue,propertyName){if(!this._editable()) -return createTextNode(propertyValue);var shadows;if(propertyName==='text-shadow') -shadows=InlineEditor.CSSShadowModel.parseTextShadow(propertyValue);else -shadows=InlineEditor.CSSShadowModel.parseBoxShadow(propertyValue);if(!shadows.length) -return createTextNode(propertyValue);var container=createDocumentFragment();var swatchPopoverHelper=this._parentPane._swatchPopoverHelper;for(var i=0;i<shadows.length;i++){if(i!==0) -container.appendChild(createTextNode(', '));var cssShadowSwatch=InlineEditor.CSSShadowSwatch.create();cssShadowSwatch.setCSSShadow(shadows[i]);new Elements.ShadowSwatchPopoverHelper(this,swatchPopoverHelper,cssShadowSwatch);var colorSwatch=cssShadowSwatch.colorSwatch();if(colorSwatch) -new Elements.ColorSwatchPopoverIcon(this,swatchPopoverHelper,colorSwatch);container.appendChild(cssShadowSwatch);} -return container;} -_updateState(){if(!this.listItemElement) -return;if(this._style.isPropertyImplicit(this.name)) -this.listItemElement.classList.add('implicit');else -this.listItemElement.classList.remove('implicit');var hasIgnorableError=!this.property.parsedOk&&Elements.StylesSidebarPane.ignoreErrorsForProperty(this.property);if(hasIgnorableError) -this.listItemElement.classList.add('has-ignorable-error');else -this.listItemElement.classList.remove('has-ignorable-error');if(this.inherited()) -this.listItemElement.classList.add('inherited');else -this.listItemElement.classList.remove('inherited');if(this.overloaded()) -this.listItemElement.classList.add('overloaded');else -this.listItemElement.classList.remove('overloaded');if(this.property.disabled) -this.listItemElement.classList.add('disabled');else -this.listItemElement.classList.remove('disabled');} -node(){return this._parentPane.node();} -parentPane(){return this._parentPane;} -section(){return this.treeOutline&&this.treeOutline.section;} -_updatePane(){var section=this.section();if(section&§ion._parentPane) -section._parentPane._refreshUpdate(section);} -_toggleEnabled(event){var disabled=!event.target.checked;var oldStyleRange=this._style.range;if(!oldStyleRange) -return;function callback(success){this._parentPane._userOperation=false;if(!success) -return;this._matchedStyles.resetActiveProperties();this._updatePane();this.styleTextAppliedForTest();} -event.consume();this._parentPane._userOperation=true;this.property.setDisabled(disabled).then(callback.bind(this));} -onpopulate(){if(this.childCount()||!this.isShorthand) -return;var longhandProperties=this._style.longhandProperties(this.name);for(var i=0;i<longhandProperties.length;++i){var name=longhandProperties[i].name;var inherited=false;var overloaded=false;var section=this.section();if(section){inherited=section.isPropertyInherited(name);overloaded=this._matchedStyles.propertyState(longhandProperties[i])===SDK.CSSMatchedStyles.PropertyState.Overloaded;} -var item=new Elements.StylePropertyTreeElement(this._parentPane,this._matchedStyles,longhandProperties[i],false,inherited,overloaded);this.appendChild(item);}} -onattach(){this.updateTitle();this.listItemElement.addEventListener('mousedown',this._mouseDown.bind(this));this.listItemElement.addEventListener('mouseup',this._resetMouseDownElement.bind(this));this.listItemElement.addEventListener('click',this._mouseClick.bind(this));} -_mouseDown(event){if(this._parentPane){this._parentPane._mouseDownTreeElement=this;this._parentPane._mouseDownTreeElementIsName=this.nameElement&&this.nameElement.isSelfOrAncestor(event.target);this._parentPane._mouseDownTreeElementIsValue=this.valueElement&&this.valueElement.isSelfOrAncestor(event.target);}} -_resetMouseDownElement(){if(this._parentPane){this._parentPane._mouseDownTreeElement=null;this._parentPane._mouseDownTreeElementIsName=false;this._parentPane._mouseDownTreeElementIsValue=false;}} -onexpand(){this._updateExpandElement();} -oncollapse(){this._updateExpandElement();} -_updateExpandElement(){if(this.expanded) -this._expandElement.setIconType('smallicon-triangle-down');else -this._expandElement.setIconType('smallicon-triangle-right');} -updateTitle(){this._updateState();this._expandElement=UI.Icon.create('smallicon-triangle-right','expand-icon');var propertyRenderer=new Elements.StylesSidebarPropertyRenderer(this._style.parentRule,this.node(),this.name,this.value);if(this.property.parsedOk){propertyRenderer.setColorHandler(this._processColor.bind(this));propertyRenderer.setBezierHandler(this._processBezier.bind(this));propertyRenderer.setShadowHandler(this._processShadow.bind(this));} -this.listItemElement.removeChildren();this.nameElement=propertyRenderer.renderName();this.valueElement=propertyRenderer.renderValue();if(!this.treeOutline) -return;var indent=Common.moduleSetting('textEditorIndent').get();this.listItemElement.createChild('span','styles-clipboard-only').createTextChild(indent+(this.property.disabled?'/* ':''));this.listItemElement.appendChild(this.nameElement);this.listItemElement.createTextChild(': ');this.listItemElement.appendChild(this._expandElement);this.listItemElement.appendChild(this.valueElement);this.listItemElement.createTextChild(';');if(this.property.disabled) -this.listItemElement.createChild('span','styles-clipboard-only').createTextChild(' */');if(!this.property.parsedOk){this.listItemElement.classList.add('not-parsed-ok');this.listItemElement.insertBefore(Elements.StylesSidebarPane.createExclamationMark(this.property),this.listItemElement.firstChild);} -if(!this.property.activeInStyle()) -this.listItemElement.classList.add('inactive');this._updateFilter();if(this.property.parsedOk&&this.section()&&this.parent.root){var enabledCheckboxElement=createElement('input');enabledCheckboxElement.className='enabled-button';enabledCheckboxElement.type='checkbox';enabledCheckboxElement.checked=!this.property.disabled;enabledCheckboxElement.addEventListener('click',this._toggleEnabled.bind(this),false);this.listItemElement.insertBefore(enabledCheckboxElement,this.listItemElement.firstChild);}} -_mouseClick(event){if(event.target.hasSelection()) -return;event.consume(true);if(event.target===this.listItemElement){var section=this.section();if(!section||!section.editable) -return;if(section._checkWillCancelEditing()) -return;section.addNewBlankProperty(this.property.index+1).startEditing();return;} -if(UI.KeyboardShortcut.eventHasCtrlOrMeta((event))&&this.section().navigable){this._navigateToSource((event.target));return;} -this.startEditing((event.target));} -_navigateToSource(element,omitFocus){if(!this.section().navigable) -return;var propertyNameClicked=element===this.nameElement;var uiLocation=Bindings.cssWorkspaceBinding.propertyUILocation(this.property,propertyNameClicked);if(uiLocation) -Common.Revealer.reveal(uiLocation,omitFocus);} -startEditing(selectElement){if(this.parent.isShorthand) -return;if(selectElement===this._expandElement) -return;var section=this.section();if(section&&!section.editable) -return;if(selectElement){selectElement=selectElement.enclosingNodeOrSelfWithClass('webkit-css-property')||selectElement.enclosingNodeOrSelfWithClass('value');} -if(!selectElement) -selectElement=this.nameElement;if(UI.isBeingEdited(selectElement)) -return;var isEditingName=selectElement===this.nameElement;if(!isEditingName) -this.valueElement.textContent=restoreURLs(this.valueElement.textContent,this.value);function restoreURLs(fieldValue,modelValue){const urlRegex=/\b(url\([^)]*\))/g;var splitFieldValue=fieldValue.split(urlRegex);if(splitFieldValue.length===1) -return fieldValue;var modelUrlRegex=new RegExp(urlRegex);for(var i=1;i<splitFieldValue.length;i+=2){var match=modelUrlRegex.exec(modelValue);if(match) -splitFieldValue[i]=match[0];} -return splitFieldValue.join('');} -var context={expanded:this.expanded,hasChildren:this.isExpandable(),isEditingName:isEditingName,previousContent:selectElement.textContent};this.setExpandable(false);if(selectElement.parentElement) -selectElement.parentElement.classList.add('child-editing');selectElement.textContent=selectElement.textContent;function pasteHandler(context,event){var data=event.clipboardData.getData('Text');if(!data) -return;var colonIdx=data.indexOf(':');if(colonIdx<0) -return;var name=data.substring(0,colonIdx).trim();var value=data.substring(colonIdx+1).trim();event.preventDefault();if(!('originalName'in context)){context.originalName=this.nameElement.textContent;context.originalValue=this.valueElement.textContent;} -this.property.name=name;this.property.value=value;this.nameElement.textContent=name;this.valueElement.textContent=value;this.nameElement.normalize();this.valueElement.normalize();this._editingCommitted(event.target.textContent,context,'forward');} -function blurListener(context,event){var treeElement=this._parentPane._mouseDownTreeElement;var moveDirection='';if(treeElement===this){if(isEditingName&&this._parentPane._mouseDownTreeElementIsValue) -moveDirection='forward';if(!isEditingName&&this._parentPane._mouseDownTreeElementIsName) -moveDirection='backward';} -var text=event.target.textContent;if(!context.isEditingName) -text=this.value||text;this._editingCommitted(text,context,moveDirection);} -this._originalPropertyText=this.property.propertyText;this._parentPane.setEditingStyle(true);if(selectElement.parentElement) -selectElement.parentElement.scrollIntoViewIfNeeded(false);var cssCompletions=[];if(isEditingName){cssCompletions=SDK.cssMetadata().allProperties();cssCompletions=cssCompletions.filter(property=>SDK.cssMetadata().isSVGProperty(property)===this.node().isSVGNode());}else{cssCompletions=SDK.cssMetadata().propertyValues(this.nameElement.textContent);} -var cssVariables=this._matchedStyles.cssVariables().sort(String.naturalOrderComparator);this._prompt=new Elements.StylesSidebarPane.CSSPropertyPrompt(cssCompletions,cssVariables,this,isEditingName);this._prompt.setAutocompletionTimeout(0);if(section) -section._startEditing();if(!isEditingName&&(!this._parentPane.node().pseudoType()||this.name!=='content')) -this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged,this._applyFreeFlowStyleTextEdit.bind(this));var proxyElement=this._prompt.attachAndStartEditing(selectElement,blurListener.bind(this,context));this._navigateToSource(selectElement,true);proxyElement.addEventListener('keydown',this._editingNameValueKeyDown.bind(this,context),false);proxyElement.addEventListener('keypress',this._editingNameValueKeyPress.bind(this,context),false);if(isEditingName) -proxyElement.addEventListener('paste',pasteHandler.bind(this,context),false);selectElement.getComponentSelection().selectAllChildren(selectElement);} -_editingNameValueKeyDown(context,event){if(event.handled) -return;var result;if(isEnterKey(event)){result='forward';}else if(event.keyCode===UI.KeyboardShortcut.Keys.Esc.code||event.key==='Escape'){result='cancel';}else if(!context.isEditingName&&this._newProperty&&event.keyCode===UI.KeyboardShortcut.Keys.Backspace.code){var selection=event.target.getComponentSelection();if(selection.isCollapsed&&!selection.focusOffset){event.preventDefault();result='backward';}}else if(event.key==='Tab'){result=event.shiftKey?'backward':'forward';event.preventDefault();} -if(result){switch(result){case'cancel':this.editingCancelled(null,context);break;case'forward':case'backward':this._editingCommitted(event.target.textContent,context,result);break;} -event.consume();return;}} -_editingNameValueKeyPress(context,event){function shouldCommitValueSemicolon(text,cursorPosition){var openQuote='';for(var i=0;i<cursorPosition;++i){var ch=text[i];if(ch==='\\'&&openQuote!=='') -++i;else if(!openQuote&&(ch==='"'||ch==='\'')) -openQuote=ch;else if(openQuote===ch) -openQuote='';} -return!openQuote;} -var keyChar=String.fromCharCode(event.charCode);var isFieldInputTerminated=(context.isEditingName?keyChar===':':keyChar===';'&&shouldCommitValueSemicolon(event.target.textContent,event.target.selectionLeftOffset()));if(isFieldInputTerminated){event.consume(true);this._editingCommitted(event.target.textContent,context,'forward');return;}} -_applyFreeFlowStyleTextEdit(){var valueText=this._prompt.textWithCurrentSuggestion();if(valueText.indexOf(';')===-1) -this.applyStyleText(this.nameElement.textContent+': '+valueText,false);} -kickFreeFlowStyleEditForTest(){this._applyFreeFlowStyleTextEdit();} -editingEnded(context){this._resetMouseDownElement();this.setExpandable(context.hasChildren);if(context.expanded) -this.expand();var editedElement=context.isEditingName?this.nameElement:this.valueElement;if(editedElement.parentElement) -editedElement.parentElement.classList.remove('child-editing');this._parentPane.setEditingStyle(false);} -editingCancelled(element,context){this._removePrompt();this._revertStyleUponEditingCanceled();this.editingEnded(context);} -_revertStyleUponEditingCanceled(){if(this._propertyHasBeenEditedIncrementally){this.applyStyleText(this._originalPropertyText,false);this._originalPropertyText='';}else if(this._newProperty){this.treeOutline.removeChild(this);}else{this.updateTitle();}} -_findSibling(moveDirection){var target=this;do -target=(moveDirection==='forward'?target.nextSibling:target.previousSibling);while(target&&target.inherited());return target;} -_editingCommitted(userInput,context,moveDirection){this._removePrompt();this.editingEnded(context);var isEditingName=context.isEditingName;var createNewProperty,moveToSelector;var isDataPasted='originalName'in context;var isDirtyViaPaste=isDataPasted&&(this.nameElement.textContent!==context.originalName||this.valueElement.textContent!==context.originalValue);var isPropertySplitPaste=isDataPasted&&isEditingName&&this.valueElement.textContent!==context.originalValue;var moveTo=this;var moveToOther=(isEditingName^(moveDirection==='forward'));var abandonNewProperty=this._newProperty&&!userInput&&(moveToOther||isEditingName);if(moveDirection==='forward'&&(!isEditingName||isPropertySplitPaste)||moveDirection==='backward'&&isEditingName){moveTo=moveTo._findSibling(moveDirection);if(!moveTo){if(moveDirection==='forward'&&(!this._newProperty||userInput)) -createNewProperty=true;else if(moveDirection==='backward') -moveToSelector=true;}} -var moveToIndex=moveTo&&this.treeOutline?this.treeOutline.rootElement().indexOfChild(moveTo):-1;var blankInput=userInput.isWhitespace();var shouldCommitNewProperty=this._newProperty&&(isPropertySplitPaste||moveToOther||(!moveDirection&&!isEditingName)||(isEditingName&&blankInput));var section=(this.section());if(((userInput!==context.previousContent||isDirtyViaPaste)&&!this._newProperty)||shouldCommitNewProperty){this._parentPane.element.focus();section._afterUpdate=moveToNextCallback.bind(this,this._newProperty,!blankInput,section);var propertyText;if(blankInput||(this._newProperty&&this.valueElement.textContent.isWhitespace())){propertyText='';}else{if(isEditingName) -propertyText=userInput+': '+this.property.value;else -propertyText=this.property.name+': '+userInput;} -this.applyStyleText(propertyText,true);}else{if(isEditingName) -this.property.name=userInput;else -this.property.value=userInput;if(!isDataPasted&&!this._newProperty) -this.updateTitle();moveToNextCallback.call(this,this._newProperty,false,section);} -function moveToNextCallback(alreadyNew,valueChanged,section){if(!moveDirection) -return;if(moveTo&&moveTo.parent){moveTo.startEditing(!isEditingName?moveTo.nameElement:moveTo.valueElement);return;} -if(moveTo&&!moveTo.parent){var rootElement=section.propertiesTreeOutline.rootElement();if(moveDirection==='forward'&&blankInput&&!isEditingName) ---moveToIndex;if(moveToIndex>=rootElement.childCount()&&!this._newProperty){createNewProperty=true;}else{var treeElement=moveToIndex>=0?rootElement.childAt(moveToIndex):null;if(treeElement){var elementToEdit=!isEditingName||isPropertySplitPaste?treeElement.nameElement:treeElement.valueElement;if(alreadyNew&&blankInput) -elementToEdit=moveDirection==='forward'?treeElement.nameElement:treeElement.valueElement;treeElement.startEditing(elementToEdit);return;}else if(!alreadyNew){moveToSelector=true;}}} -if(createNewProperty){if(alreadyNew&&!valueChanged&&(isEditingName^(moveDirection==='backward'))) -return;section.addNewBlankProperty().startEditing();return;} -if(abandonNewProperty){moveTo=this._findSibling(moveDirection);var sectionToEdit=(moveTo||moveDirection==='backward')?section:section.nextEditableSibling();if(sectionToEdit){if(sectionToEdit.style().parentRule) -sectionToEdit.startEditingSelector();else -sectionToEdit._moveEditorFromSelector(moveDirection);} -return;} -if(moveToSelector){if(section.style().parentRule) -section.startEditingSelector();else -section._moveEditorFromSelector(moveDirection);}}} -_removePrompt(){if(this._prompt){this._prompt.detach();this._prompt=null;} -var section=this.section();if(section) -section._stopEditing();} -styleTextAppliedForTest(){} -applyStyleText(styleText,majorChange){this._applyStyleThrottler.schedule(this._innerApplyStyleText.bind(this,styleText,majorChange));} -_innerApplyStyleText(styleText,majorChange){if(!this.treeOutline) -return Promise.resolve();var oldStyleRange=this._style.range;if(!oldStyleRange) -return Promise.resolve();styleText=styleText.replace(/\s/g,' ').trim();if(!styleText.length&&majorChange&&this._newProperty&&!this._propertyHasBeenEditedIncrementally){var section=this.section();this.parent.removeChild(this);section.afterUpdate();return Promise.resolve();} -var currentNode=this._parentPane.node();this._parentPane._userOperation=true;function callback(success){this._parentPane._userOperation=false;if(!success){if(majorChange){this._revertStyleUponEditingCanceled();} -this.styleTextAppliedForTest();return;} -this._matchedStyles.resetActiveProperties();this._propertyHasBeenEditedIncrementally=true;this.property=this._style.propertyAt(this.property.index);if(!this._parentPane._isEditingStyle&¤tNode===this.node()) -this._updatePane();this.styleTextAppliedForTest();} -if(styleText.length&&!/;\s*$/.test(styleText)) -styleText+=';';var overwriteProperty=!this._newProperty||this._propertyHasBeenEditedIncrementally;return this.property.setText(styleText,majorChange,overwriteProperty).then(callback.bind(this));} -ondblclick(){return true;} -isEventWithinDisclosureTriangle(event){return event.target===this._expandElement;}};Elements.StylePropertyTreeElement.Context;Elements.StylesSidebarPane.CSSPropertyPrompt=class extends UI.TextPrompt{constructor(cssCompletions,cssVariables,treeElement,isEditingName){super();this.initialize(this._buildPropertyCompletions.bind(this),UI.StyleValueDelimiters);this._cssCompletions=cssCompletions;this._cssVariables=cssVariables;this._treeElement=treeElement;this._isEditingName=isEditingName;if(!isEditingName){this.disableDefaultSuggestionForEmptyInput();if(treeElement&&treeElement.valueElement){var cssValueText=treeElement.valueElement.textContent;if(cssValueText.match(/#[\da-f]{3,6}$/i)){this.setTitle(Common.UIString('Increment/decrement with mousewheel or up/down keys. %s: R ±1, Shift: G ±1, Alt: B ±1',Host.isMac()?'Cmd':'Ctrl'));}else if(cssValueText.match(/\d+/)){this.setTitle(Common.UIString('Increment/decrement with mousewheel or up/down keys. %s: ±100, Shift: ±10, Alt: ±0.1',Host.isMac()?'Cmd':'Ctrl'));}}}} -onKeyDown(event){switch(event.key){case'ArrowUp':case'ArrowDown':case'PageUp':case'PageDown':if(this._handleNameOrValueUpDown(event)){event.preventDefault();return;} -break;case'Enter':if(this.textWithCurrentSuggestion()!==this.text()){this.tabKeyPressed();return;} -break;} -super.onKeyDown(event);} -onMouseWheel(event){if(this._handleNameOrValueUpDown(event)){event.consume(true);return;} -super.onMouseWheel(event);} -tabKeyPressed(){this.acceptAutoComplete();return false;} -_handleNameOrValueUpDown(event){function finishHandler(originalValue,replacementString){this._treeElement.applyStyleText(this._treeElement.nameElement.textContent+': '+this._treeElement.valueElement.textContent,false);} -function customNumberHandler(prefix,number,suffix){if(number!==0&&!suffix.length&&SDK.cssMetadata().isLengthProperty(this._treeElement.property.name)) -suffix='px';return prefix+number+suffix;} -if(!this._isEditingName&&this._treeElement.valueElement&&UI.handleElementValueModifications(event,this._treeElement.valueElement,finishHandler.bind(this),this._isValueSuggestion.bind(this),customNumberHandler.bind(this))) -return true;return false;} -_isValueSuggestion(word){if(!word) -return false;word=word.toLowerCase();return this._cssCompletions.indexOf(word)!==-1||word.startsWith('--');} -_buildPropertyCompletions(expression,query,force){var lowerQuery=query.toLowerCase();var editingVariable=!this._isEditingName&&expression.trim().endsWith('var(');if(!query&&!force&&!editingVariable&&(this._isEditingName||expression)) -return Promise.resolve([]);var prefixResults=[];var anywhereResults=[];if(!editingVariable) -this._cssCompletions.forEach(filterCompletions.bind(this));if(this._isEditingName||editingVariable) -this._cssVariables.forEach(filterCompletions.bind(this));var results=prefixResults.concat(anywhereResults);if(!this._isEditingName&&!results.length&&query.length>1&&'!important'.startsWith(lowerQuery)) -results.push({text:'!important'});var userEnteredText=query.replace('-','');if(userEnteredText&&(userEnteredText===userEnteredText.toUpperCase())){for(var i=0;i<results.length;++i){if(!results[i].text.startsWith('--')) -results[i].text=results[i].text.toUpperCase();}} -if(editingVariable) -results.forEach(result=>result.text+=')');return Promise.resolve(results);function filterCompletions(completion){var index=completion.toLowerCase().indexOf(lowerQuery);if(index===0){var priority=this._isEditingName?SDK.cssMetadata().propertyUsageWeight(completion):1;prefixResults.push({text:completion,priority:priority});}else if(index>-1){anywhereResults.push({text:completion});}}}};Elements.StylesSidebarPropertyRenderer=class{constructor(rule,node,name,value){this._rule=rule;this._node=node;this._propertyName=name;this._propertyValue=value;this._colorHandler=null;this._bezierHandler=null;this._shadowHandler=null;} -setColorHandler(handler){this._colorHandler=handler;} -setBezierHandler(handler){this._bezierHandler=handler;} -setShadowHandler(handler){this._shadowHandler=handler;} -renderName(){var nameElement=createElement('span');nameElement.className='webkit-css-property';nameElement.textContent=this._propertyName;nameElement.normalize();return nameElement;} -renderValue(){var valueElement=createElement('span');valueElement.className='value';if(!this._propertyValue) -return valueElement;if(this._shadowHandler&&(this._propertyName==='box-shadow'||this._propertyName==='text-shadow'||this._propertyName==='-webkit-box-shadow')&&!SDK.CSSMetadata.VariableRegex.test(this._propertyValue)){valueElement.appendChild(this._shadowHandler(this._propertyValue,this._propertyName));valueElement.normalize();return valueElement;} -var regexes=[SDK.CSSMetadata.VariableRegex,SDK.CSSMetadata.URLRegex];var processors=[createTextNode,this._processURL.bind(this)];if(this._bezierHandler&&SDK.cssMetadata().isBezierAwareProperty(this._propertyName)){regexes.push(UI.Geometry.CubicBezier.Regex);processors.push(this._bezierHandler);} -if(this._colorHandler&&SDK.cssMetadata().isColorAwareProperty(this._propertyName)){regexes.push(Common.Color.Regex);processors.push(this._colorHandler);} -var results=TextUtils.TextUtils.splitStringByRegexes(this._propertyValue,regexes);for(var i=0;i<results.length;i++){var result=results[i];var processor=result.regexIndex===-1?createTextNode:processors[result.regexIndex];valueElement.appendChild(processor(result.value));} -valueElement.normalize();return valueElement;} -_processURL(text){var url=text.substring(4,text.length-1).trim();var isQuoted=/^'.*'$/.test(url)||/^".*"$/.test(url);if(isQuoted) -url=url.substring(1,url.length-1);var container=createDocumentFragment();container.createTextChild('url(');var hrefUrl=null;if(this._rule&&this._rule.resourceURL()) -hrefUrl=Common.ParsedURL.completeURL(this._rule.resourceURL(),url);else if(this._node) -hrefUrl=this._node.resolveURL(url);container.appendChild(Components.Linkifier.linkifyURL(hrefUrl||url,{text:url,preventClick:true}));container.createTextChild(')');return container;}};Elements.StylesSidebarPane.ButtonProvider=class{constructor(){this._button=new UI.ToolbarButton(Common.UIString('New Style Rule'),'largeicon-add');this._button.addEventListener(UI.ToolbarButton.Events.Click,this._clicked,this);var longclickTriangle=UI.Icon.create('largeicon-longclick-triangle','long-click-glyph');this._button.element.appendChild(longclickTriangle);new UI.LongClickController(this._button.element,this._longClicked.bind(this));UI.context.addFlavorChangeListener(SDK.DOMNode,onNodeChanged.bind(this));onNodeChanged.call(this);function onNodeChanged(){var node=UI.context.flavor(SDK.DOMNode);node=node?node.enclosingElementOrSelf():null;this._button.setEnabled(!!node);}} -_clicked(event){Elements.StylesSidebarPane._instance._createNewRuleInViaInspectorStyleSheet();} -_longClicked(e){Elements.StylesSidebarPane._instance._onAddButtonLongClick(e);} -item(){return this._button;}};;Elements.ComputedStyleWidget=class extends UI.ThrottledWidget{constructor(){super(true);this.registerRequiredCSS('elements/computedStyleSidebarPane.css');this._alwaysShowComputedProperties={'display':true,'height':true,'width':true};this._computedStyleModel=new Elements.ComputedStyleModel();this._computedStyleModel.addEventListener(Elements.ComputedStyleModel.Events.ComputedStyleChanged,this.update,this);this._showInheritedComputedStylePropertiesSetting=Common.settings.createSetting('showInheritedComputedStyleProperties',false);this._showInheritedComputedStylePropertiesSetting.addChangeListener(this._showInheritedComputedStyleChanged.bind(this));var hbox=this.contentElement.createChild('div','hbox styles-sidebar-pane-toolbar');var filterContainerElement=hbox.createChild('div','styles-sidebar-pane-filter-box');var filterInput=Elements.StylesSidebarPane.createPropertyFilterElement(Common.UIString('Filter'),hbox,filterCallback.bind(this),'styles-filter-engaged');UI.ARIAUtils.setAccessibleName(filterInput,Common.UIString('Filter Computed Styles'));filterContainerElement.appendChild(filterInput);var toolbar=new UI.Toolbar('styles-pane-toolbar',hbox);toolbar.appendToolbarItem(new UI.ToolbarSettingCheckbox(this._showInheritedComputedStylePropertiesSetting,undefined,Common.UIString('Show all')));this._propertiesOutline=new UI.TreeOutlineInShadow();this._propertiesOutline.hideOverflow();this._propertiesOutline.registerRequiredCSS('elements/computedStyleWidgetTree.css');this._propertiesOutline.element.classList.add('monospace','computed-properties');this.contentElement.appendChild(this._propertiesOutline.element);this._linkifier=new Components.Linkifier(Elements.ComputedStyleWidget._maxLinkLength);function filterCallback(regex){this._filterRegex=regex;this._updateFilter(regex);} -var fontsWidget=new Elements.PlatformFontsWidget(this._computedStyleModel);fontsWidget.show(this.contentElement);} -_showInheritedComputedStyleChanged(){this.update();} -doUpdate(){var promises=[this._computedStyleModel.fetchComputedStyle(),this._fetchMatchedCascade()];return Promise.all(promises).spread(this._innerRebuildUpdate.bind(this));} -_fetchMatchedCascade(){var node=this._computedStyleModel.node();if(!node||!this._computedStyleModel.cssModel()) -return Promise.resolve((null));return this._computedStyleModel.cssModel().cachedMatchedCascadeForNode(node).then(validateStyles.bind(this));function validateStyles(matchedStyles){return matchedStyles&&matchedStyles.node()===this._computedStyleModel.node()?matchedStyles:null;}} -_processColor(text){var color=Common.Color.parse(text);if(!color) -return createTextNode(text);var swatch=InlineEditor.ColorSwatch.create();swatch.setColor(color);swatch.setFormat(Common.Color.detectColorFormat(color));return swatch;} -_innerRebuildUpdate(nodeStyle,matchedStyles){var expandedProperties=new Set();for(var treeElement of this._propertiesOutline.rootElement().children()){if(!treeElement.expanded) -continue;var propertyName=treeElement[Elements.ComputedStyleWidget._propertySymbol].name;expandedProperties.add(propertyName);} -this._propertiesOutline.removeChildren();this._linkifier.reset();var cssModel=this._computedStyleModel.cssModel();if(!nodeStyle||!matchedStyles||!cssModel) -return;var uniqueProperties=nodeStyle.computedStyle.keysArray();uniqueProperties.sort(propertySorter);var propertyTraces=this._computePropertyTraces(matchedStyles);var inhertiedProperties=this._computeInheritedProperties(matchedStyles);var showInherited=this._showInheritedComputedStylePropertiesSetting.get();for(var i=0;i<uniqueProperties.length;++i){var propertyName=uniqueProperties[i];var propertyValue=nodeStyle.computedStyle.get(propertyName);var canonicalName=SDK.cssMetadata().canonicalPropertyName(propertyName);var inherited=!inhertiedProperties.has(canonicalName);if(!showInherited&&inherited&&!(propertyName in this._alwaysShowComputedProperties)) -continue;if(!showInherited&&propertyName.startsWith('--')) -continue;if(propertyName!==canonicalName&&propertyValue===nodeStyle.computedStyle.get(canonicalName)) -continue;var propertyElement=createElement('div');propertyElement.classList.add('computed-style-property');propertyElement.classList.toggle('computed-style-property-inherited',inherited);var renderer=new Elements.StylesSidebarPropertyRenderer(null,nodeStyle.node,propertyName,(propertyValue));renderer.setColorHandler(this._processColor.bind(this));var propertyNameElement=renderer.renderName();propertyNameElement.classList.add('property-name');propertyElement.appendChild(propertyNameElement);var colon=createElementWithClass('span','delimeter');colon.textContent=':';propertyNameElement.appendChild(colon);var propertyValueElement=propertyElement.createChild('span','property-value');var propertyValueText=renderer.renderValue();propertyValueText.classList.add('property-value-text');propertyValueElement.appendChild(propertyValueText);var semicolon=createElementWithClass('span','delimeter');semicolon.textContent=';';propertyValueElement.appendChild(semicolon);var treeElement=new UI.TreeElement();treeElement.selectable=false;treeElement.title=propertyElement;treeElement[Elements.ComputedStyleWidget._propertySymbol]={name:propertyName,value:propertyValue};var isOdd=this._propertiesOutline.rootElement().children().length%2===0;treeElement.listItemElement.classList.toggle('odd-row',isOdd);this._propertiesOutline.appendChild(treeElement);var trace=propertyTraces.get(propertyName);if(trace){var activeProperty=this._renderPropertyTrace(cssModel,matchedStyles,nodeStyle.node,treeElement,trace);treeElement.listItemElement.addEventListener('mousedown',e=>e.consume(),false);treeElement.listItemElement.addEventListener('dblclick',e=>e.consume(),false);treeElement.listItemElement.addEventListener('click',handleClick.bind(null,treeElement),false);var gotoSourceElement=UI.Icon.create('mediumicon-arrow-in-circle','goto-source-icon');gotoSourceElement.addEventListener('click',this._navigateToSource.bind(this,activeProperty));propertyValueElement.appendChild(gotoSourceElement);if(expandedProperties.has(propertyName)) -treeElement.expand();}} -this._updateFilter(this._filterRegex);function propertySorter(a,b){if(a.startsWith('--')^b.startsWith('--')) -return a.startsWith('--')?1:-1;if(a.startsWith('-webkit')^b.startsWith('-webkit')) -return a.startsWith('-webkit')?1:-1;var canonical1=SDK.cssMetadata().canonicalPropertyName(a);var canonical2=SDK.cssMetadata().canonicalPropertyName(b);return canonical1.compareTo(canonical2);} -function handleClick(treeElement,event){if(!treeElement.expanded) -treeElement.expand();else -treeElement.collapse();event.consume();}} -_navigateToSource(cssProperty,event){Common.Revealer.reveal(cssProperty);event.consume(true);} -_renderPropertyTrace(cssModel,matchedStyles,node,rootTreeElement,tracedProperties){var activeProperty=null;for(var property of tracedProperties){var trace=createElement('div');trace.classList.add('property-trace');if(matchedStyles.propertyState(property)===SDK.CSSMatchedStyles.PropertyState.Overloaded) -trace.classList.add('property-trace-inactive');else -activeProperty=property;var renderer=new Elements.StylesSidebarPropertyRenderer(null,node,property.name,(property.value));renderer.setColorHandler(this._processColor.bind(this));var valueElement=renderer.renderValue();valueElement.classList.add('property-trace-value');valueElement.addEventListener('click',this._navigateToSource.bind(this,property),false);var gotoSourceElement=UI.Icon.create('mediumicon-arrow-in-circle','goto-source-icon');gotoSourceElement.addEventListener('click',this._navigateToSource.bind(this,property));valueElement.insertBefore(gotoSourceElement,valueElement.firstChild);trace.appendChild(valueElement);var rule=property.ownerStyle.parentRule;var selectorElement=trace.createChild('span','property-trace-selector');selectorElement.textContent=rule?rule.selectorText():'element.style';selectorElement.title=selectorElement.textContent;if(rule){var linkSpan=trace.createChild('span','trace-link');linkSpan.appendChild(Elements.StylePropertiesSection.createRuleOriginNode(matchedStyles,this._linkifier,rule));} -var traceTreeElement=new UI.TreeElement();traceTreeElement.title=trace;traceTreeElement.selectable=false;rootTreeElement.appendChild(traceTreeElement);} -return(activeProperty);} -_computePropertyTraces(matchedStyles){var result=new Map();for(var style of matchedStyles.nodeStyles()){var allProperties=style.allProperties();for(var property of allProperties){if(!property.activeInStyle()||!matchedStyles.propertyState(property)) -continue;if(!result.has(property.name)) -result.set(property.name,[]);result.get(property.name).push(property);}} -return result;} -_computeInheritedProperties(matchedStyles){var result=new Set();for(var style of matchedStyles.nodeStyles()){for(var property of style.allProperties()){if(!matchedStyles.propertyState(property)) -continue;result.add(SDK.cssMetadata().canonicalPropertyName(property.name));}} -return result;} -_updateFilter(regex){var children=this._propertiesOutline.rootElement().children();for(var child of children){var property=child[Elements.ComputedStyleWidget._propertySymbol];var matched=!regex||regex.test(property.name)||regex.test(property.value);child.hidden=!matched;}}};Elements.ComputedStyleWidget._maxLinkLength=30;Elements.ComputedStyleWidget._propertySymbol=Symbol('property');;Elements.ElementsPanel=class extends UI.Panel{constructor(){super('elements');this.registerRequiredCSS('elements/elementsPanel.css');this._splitWidget=new UI.SplitWidget(true,true,'elementsPanelSplitViewState',325,325);this._splitWidget.addEventListener(UI.SplitWidget.Events.SidebarSizeChanged,this._updateTreeOutlineVisibleWidth.bind(this));this._splitWidget.show(this.element);this._searchableView=new UI.SearchableView(this);this._searchableView.setMinimumSize(25,28);this._searchableView.setPlaceholder(Common.UIString('Find by string, selector, or XPath'));var stackElement=this._searchableView.element;this._contentElement=createElement('div');var crumbsContainer=createElement('div');stackElement.appendChild(this._contentElement);stackElement.appendChild(crumbsContainer);this._splitWidget.setMainWidget(this._searchableView);this._splitMode=null;this._contentElement.id='elements-content';if(Common.moduleSetting('domWordWrap').get()) -this._contentElement.classList.add('elements-wrap');Common.moduleSetting('domWordWrap').addChangeListener(this._domWordWrapSettingChanged.bind(this));crumbsContainer.id='elements-crumbs';this._breadcrumbs=new Elements.ElementsBreadcrumbs();this._breadcrumbs.show(crumbsContainer);this._breadcrumbs.addEventListener(Elements.ElementsBreadcrumbs.Events.NodeSelected,this._crumbNodeSelected,this);this._stylesWidget=new Elements.StylesSidebarPane();this._computedStyleWidget=new Elements.ComputedStyleWidget();this._metricsWidget=new Elements.MetricsSidebarPane();Common.moduleSetting('sidebarPosition').addChangeListener(this._updateSidebarPosition.bind(this));this._updateSidebarPosition();this._treeOutlines=[];this._treeOutlineHeaders=new Map();SDK.targetManager.observeModels(SDK.DOMModel,this);SDK.targetManager.addEventListener(SDK.TargetManager.Events.NameChanged,event=>this._targetNameChanged((event.data)));Common.moduleSetting('showUAShadowDOM').addChangeListener(this._showUAShadowDOMChanged.bind(this));SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.DocumentUpdated,this._documentUpdatedEvent,this);Extensions.extensionServer.addEventListener(Extensions.ExtensionServer.Events.SidebarPaneAdded,this._extensionSidebarPaneAdded,this);} -static instance(){return(self.runtime.sharedInstance(Elements.ElementsPanel));} -_revealProperty(cssProperty){return this.sidebarPaneView.showView(this._stylesViewToReveal).then(()=>{this._stylesWidget.revealProperty((cssProperty));});} -resolveLocation(locationName){return this.sidebarPaneView;} -showToolbarPane(widget,toggle){this._stylesWidget.showToolbarPane(widget,toggle);} -modelAdded(domModel){var treeOutline=new Elements.ElementsTreeOutline(domModel,true,true);treeOutline.setWordWrap(Common.moduleSetting('domWordWrap').get());treeOutline.wireToDOMModel();treeOutline.addEventListener(Elements.ElementsTreeOutline.Events.SelectedNodeChanged,this._selectedNodeChanged,this);treeOutline.addEventListener(Elements.ElementsTreeOutline.Events.ElementsTreeUpdated,this._updateBreadcrumbIfNeeded,this);new Elements.ElementsTreeElementHighlighter(treeOutline);this._treeOutlines.push(treeOutline);if(domModel.target().parentTarget()){this._treeOutlineHeaders.set(treeOutline,createElementWithClass('div','elements-tree-header'));this._targetNameChanged(domModel.target());} -if(this.isShowing()) -this.wasShown();} -modelRemoved(domModel){var treeOutline=Elements.ElementsTreeOutline.forDOMModel(domModel);treeOutline.unwireFromDOMModel();this._treeOutlines.remove(treeOutline);var header=this._treeOutlineHeaders.get(treeOutline);if(header) -header.remove();this._treeOutlineHeaders.delete(treeOutline);treeOutline.element.remove();} -_targetNameChanged(target){var domModel=target.model(SDK.DOMModel);if(!domModel) -return;var treeOutline=Elements.ElementsTreeOutline.forDOMModel(domModel);if(!treeOutline) -return;var header=this._treeOutlineHeaders.get(treeOutline);if(!header) -return;header.removeChildren();header.createChild('div','elements-tree-header-frame').textContent=Common.UIString('Frame');header.appendChild(Components.Linkifier.linkifyURL(target.inspectedURL(),{text:target.name()}));} -_updateTreeOutlineVisibleWidth(){if(!this._treeOutlines.length) -return;var width=this._splitWidget.element.offsetWidth;if(this._splitWidget.isVertical()) -width-=this._splitWidget.sidebarSize();for(var i=0;i<this._treeOutlines.length;++i) -this._treeOutlines[i].setVisibleWidth(width);this._breadcrumbs.updateSizes();} -focus(){if(this._treeOutlines.length) -this._treeOutlines[0].focus();} -searchableView(){return this._searchableView;} -wasShown(){UI.context.setFlavor(Elements.ElementsPanel,this);for(var i=0;i<this._treeOutlines.length;++i){var treeOutline=this._treeOutlines[i];if(treeOutline.element.parentElement!==this._contentElement){var header=this._treeOutlineHeaders.get(treeOutline);if(header) -this._contentElement.appendChild(header);this._contentElement.appendChild(treeOutline.element);}} -super.wasShown();this._breadcrumbs.update();for(var i=0;i<this._treeOutlines.length;++i){var treeOutline=this._treeOutlines[i];treeOutline.setVisible(true);if(!treeOutline.rootDOMNode){if(treeOutline.domModel().existingDocument()) -this._documentUpdated(treeOutline.domModel(),treeOutline.domModel().existingDocument());else -treeOutline.domModel().requestDocumentPromise();}}} -willHide(){UI.context.setFlavor(Elements.ElementsPanel,null);SDK.OverlayModel.hideDOMNodeHighlight();for(var i=0;i<this._treeOutlines.length;++i){var treeOutline=this._treeOutlines[i];treeOutline.setVisible(false);this._contentElement.removeChild(treeOutline.element);var header=this._treeOutlineHeaders.get(treeOutline);if(header) -this._contentElement.removeChild(header);} -if(this._popoverHelper) -this._popoverHelper.hidePopover();super.willHide();} -onResize(){this.element.window().requestAnimationFrame(this._updateSidebarPosition.bind(this));this._updateTreeOutlineVisibleWidth();} -_selectedNodeChanged(event){var selectedNode=(event.data.node);var focus=(event.data.focus);for(var i=0;i<this._treeOutlines.length;++i){if(!selectedNode||selectedNode.domModel()!==this._treeOutlines[i].domModel()) -this._treeOutlines[i].selectDOMNode(null);} -this._breadcrumbs.setSelectedNode(selectedNode);UI.context.setFlavor(SDK.DOMNode,selectedNode);if(!selectedNode) -return;selectedNode.setAsInspectedNode();if(focus){this._selectedNodeOnReset=selectedNode;this._hasNonDefaultSelectedNode=true;} -var executionContexts=selectedNode.domModel().runtimeModel().executionContexts();var nodeFrameId=selectedNode.frameId();for(var context of executionContexts){if(context.frameId===nodeFrameId){UI.context.setFlavor(SDK.ExecutionContext,context);break;}}} -_reset(){delete this.currentQuery;} -_documentUpdatedEvent(event){var domModel=(event.data);this._documentUpdated(domModel,domModel.existingDocument());} -_documentUpdated(domModel,inspectedRootDocument){this._reset();this.searchCanceled();var treeOutline=Elements.ElementsTreeOutline.forDOMModel(domModel);treeOutline.rootDOMNode=inspectedRootDocument;if(!inspectedRootDocument){if(this.isShowing()) -domModel.requestDocumentPromise();return;} -this._hasNonDefaultSelectedNode=false;if(this._omitDefaultSelection) -return;var savedSelectedNodeOnReset=this._selectedNodeOnReset;restoreNode.call(this,domModel,this._selectedNodeOnReset);async function restoreNode(domModel,staleNode){var nodePath=staleNode?staleNode.path():null;var restoredNodeId=nodePath?await domModel.pushNodeByPathToFrontend(nodePath):null;if(savedSelectedNodeOnReset!==this._selectedNodeOnReset) -return;var node=restoredNodeId?domModel.nodeForId(restoredNodeId):null;if(!node){var inspectedDocument=domModel.existingDocument();node=inspectedDocument?inspectedDocument.body||inspectedDocument.documentElement:null;} -this._setDefaultSelectedNode(node);this._lastSelectedNodeSelectedForTest();}} -_lastSelectedNodeSelectedForTest(){} -_setDefaultSelectedNode(node){if(!node||this._hasNonDefaultSelectedNode||this._pendingNodeReveal) -return;var treeOutline=Elements.ElementsTreeOutline.forDOMModel(node.domModel());if(!treeOutline) -return;this.selectDOMNode(node);if(treeOutline.selectedTreeElement) -treeOutline.selectedTreeElement.expand();} -searchCanceled(){delete this._searchConfig;this._hideSearchHighlights();this._searchableView.updateSearchMatchesCount(0);delete this._currentSearchResultIndex;delete this._searchResults;SDK.DOMModel.cancelSearch();} -performSearch(searchConfig,shouldJump,jumpBackwards){var query=searchConfig.query;const whitespaceTrimmedQuery=query.trim();if(!whitespaceTrimmedQuery.length) -return;if(!this._searchConfig||this._searchConfig.query!==query) -this.searchCanceled();else -this._hideSearchHighlights();this._searchConfig=searchConfig;var showUAShadowDOM=Common.moduleSetting('showUAShadowDOM').get();var domModels=SDK.targetManager.models(SDK.DOMModel);var promises=domModels.map(domModel=>domModel.performSearch(whitespaceTrimmedQuery,showUAShadowDOM));Promise.all(promises).then(resultCountCallback.bind(this));function resultCountCallback(resultCounts){this._searchResults=[];for(var i=0;i<resultCounts.length;++i){var resultCount=resultCounts[i];for(var j=0;j<resultCount;++j) -this._searchResults.push({domModel:domModels[i],index:j,node:undefined});} -this._searchableView.updateSearchMatchesCount(this._searchResults.length);if(!this._searchResults.length) -return;if(this._currentSearchResultIndex>=this._searchResults.length) -this._currentSearchResultIndex=undefined;var index=this._currentSearchResultIndex;if(shouldJump){if(this._currentSearchResultIndex===undefined) -index=jumpBackwards?-1:0;else -index=jumpBackwards?index-1:index+1;this._jumpToSearchResult(index);}}} -_domWordWrapSettingChanged(event){this._contentElement.classList.toggle('elements-wrap',event.data);for(var i=0;i<this._treeOutlines.length;++i) -this._treeOutlines[i].setWordWrap((event.data));} -switchToAndFocus(node){this._searchableView.cancelSearch();UI.viewManager.showView('elements').then(()=>this.selectDOMNode(node,true));} -_getPopoverRequest(event){var link=event.target;while(link&&!link[Elements.ElementsTreeElement.HrefSymbol]) -link=link.parentElementOrShadowHost();if(!link) -return null;return{box:link.boxInWindow(),show:async popover=>{var node=this.selectedDOMNode();if(!node) -return false;var preview=await Components.DOMPresentationUtils.buildImagePreviewContents(node.domModel().target(),link[Elements.ElementsTreeElement.HrefSymbol],true);if(preview) -popover.contentElement.appendChild(preview);return!!preview;}};} -_jumpToSearchResult(index){this._currentSearchResultIndex=(index+this._searchResults.length)%this._searchResults.length;this._highlightCurrentSearchResult();} -jumpToNextSearchResult(){if(!this._searchResults) -return;this.performSearch(this._searchConfig,true);} -jumpToPreviousSearchResult(){if(!this._searchResults) -return;this.performSearch(this._searchConfig,true,true);} -supportsCaseSensitiveSearch(){return false;} -supportsRegexSearch(){return false;} -_highlightCurrentSearchResult(){var index=this._currentSearchResultIndex;var searchResults=this._searchResults;var searchResult=searchResults[index];this._searchableView.updateCurrentMatchIndex(index);if(searchResult.node===null) -return;if(typeof searchResult.node==='undefined'){searchResult.domModel.searchResult(searchResult.index).then(node=>{searchResult.node=node;this._highlightCurrentSearchResult();});return;} -var treeElement=this._treeElementForNode(searchResult.node);searchResult.node.scrollIntoView();if(treeElement){treeElement.highlightSearchResults(this._searchConfig.query);treeElement.reveal();var matches=treeElement.listItemElement.getElementsByClassName(UI.highlightedSearchResultClassName);if(matches.length) -matches[0].scrollIntoViewIfNeeded(false);}} -_hideSearchHighlights(){if(!this._searchResults||!this._searchResults.length||this._currentSearchResultIndex===undefined) -return;var searchResult=this._searchResults[this._currentSearchResultIndex];if(!searchResult.node) -return;var treeOutline=Elements.ElementsTreeOutline.forDOMModel(searchResult.node.domModel());var treeElement=treeOutline.findTreeElement(searchResult.node);if(treeElement) -treeElement.hideSearchHighlights();} -selectedDOMNode(){for(var i=0;i<this._treeOutlines.length;++i){var treeOutline=this._treeOutlines[i];if(treeOutline.selectedDOMNode()) -return treeOutline.selectedDOMNode();} -return null;} -selectDOMNode(node,focus){for(var i=0;i<this._treeOutlines.length;++i){var treeOutline=this._treeOutlines[i];if(treeOutline.domModel()===node.domModel()) -treeOutline.selectDOMNode(node,focus);else -treeOutline.selectDOMNode(null);}} -_updateBreadcrumbIfNeeded(event){var nodes=(event.data);this._breadcrumbs.updateNodes(nodes);} -_crumbNodeSelected(event){var node=(event.data);this.selectDOMNode(node,true);} -handleShortcut(event){function handleUndoRedo(treeOutline){if(UI.KeyboardShortcut.eventHasCtrlOrMeta(event)&&!event.shiftKey&&(event.key==='Z'||event.key==='z')){treeOutline.domModel().undo();event.handled=true;return;} -var isRedoKey=Host.isMac()?event.metaKey&&event.shiftKey&&(event.key==='Z'||event.key==='z'):event.ctrlKey&&(event.key==='Y'||event.key==='y');if(isRedoKey){treeOutline.domModel().redo();event.handled=true;}} -if(UI.isEditing()&&event.keyCode!==UI.KeyboardShortcut.Keys.F2.code) -return;var treeOutline=null;for(var i=0;i<this._treeOutlines.length;++i){if(this._treeOutlines[i].selectedDOMNode()) -treeOutline=this._treeOutlines[i];} -if(!treeOutline) -return;if(!treeOutline.editing()){handleUndoRedo.call(null,treeOutline);if(event.handled){this._stylesWidget.forceUpdate();return;}} -treeOutline.handleShortcut(event);if(event.handled) -return;super.handleShortcut(event);} -_treeOutlineForNode(node){if(!node) -return null;return Elements.ElementsTreeOutline.forDOMModel(node.domModel());} -_treeElementForNode(node){var treeOutline=this._treeOutlineForNode(node);return(treeOutline.findTreeElement(node));} -_leaveUserAgentShadowDOM(node){var userAgentShadowRoot;while((userAgentShadowRoot=node.ancestorUserAgentShadowRoot())&&userAgentShadowRoot.parentNode) -node=userAgentShadowRoot.parentNode;return node;} -revealAndSelectNode(node,focus){if(Elements.inspectElementModeController&&Elements.inspectElementModeController.isInInspectElementMode()) -Elements.inspectElementModeController.stopInspection();this._omitDefaultSelection=true;node=Common.moduleSetting('showUAShadowDOM').get()?node:this._leaveUserAgentShadowDOM(node);node.highlightForTwoSeconds();return UI.viewManager.showView('elements',false,!focus).then(()=>{this.selectDOMNode(node,focus);delete this._omitDefaultSelection;if(!this._notFirstInspectElement) -InspectorFrontendHost.inspectElementCompleted();this._notFirstInspectElement=true;});} -_showUAShadowDOMChanged(){for(var i=0;i<this._treeOutlines.length;++i) -this._treeOutlines[i].update();} -_updateSidebarPosition(){if(this.sidebarPaneView&&this.sidebarPaneView.tabbedPane().shouldHideOnDetach()) -return;var splitMode;var position=Common.moduleSetting('sidebarPosition').get();if(position==='right'||(position==='auto'&&UI.inspectorView.element.offsetWidth>680)) -splitMode=Elements.ElementsPanel._splitMode.Vertical;else if(UI.inspectorView.element.offsetWidth>415) -splitMode=Elements.ElementsPanel._splitMode.Horizontal;else -splitMode=Elements.ElementsPanel._splitMode.Slim;if(this.sidebarPaneView&&splitMode===this._splitMode) -return;this._splitMode=splitMode;var extensionSidebarPanes=Extensions.extensionServer.sidebarPanes();var lastSelectedTabId=null;if(this.sidebarPaneView){lastSelectedTabId=this.sidebarPaneView.tabbedPane().selectedTabId;this.sidebarPaneView.tabbedPane().detach();this._splitWidget.uninstallResizer(this.sidebarPaneView.tabbedPane().headerElement());} -this._splitWidget.setVertical(this._splitMode===Elements.ElementsPanel._splitMode.Vertical);this.showToolbarPane(null,null);var matchedStylePanesWrapper=new UI.VBox();matchedStylePanesWrapper.element.classList.add('style-panes-wrapper');this._stylesWidget.show(matchedStylePanesWrapper.element);var computedStylePanesWrapper=new UI.VBox();computedStylePanesWrapper.element.classList.add('style-panes-wrapper');this._computedStyleWidget.show(computedStylePanesWrapper.element);function showMetrics(inComputedStyle){if(inComputedStyle) -this._metricsWidget.show(computedStylePanesWrapper.element,this._computedStyleWidget.element);else -this._metricsWidget.show(matchedStylePanesWrapper.element);} -function tabSelected(event){var tabId=(event.data.tabId);if(tabId===Common.UIString('Computed')) -showMetrics.call(this,true);else if(tabId===Common.UIString('Styles')) -showMetrics.call(this,false);} -this.sidebarPaneView=UI.viewManager.createTabbedLocation(()=>UI.viewManager.showView('elements'));var tabbedPane=this.sidebarPaneView.tabbedPane();if(this._popoverHelper) -this._popoverHelper.hidePopover();this._popoverHelper=new UI.PopoverHelper(tabbedPane.element,this._getPopoverRequest.bind(this));this._popoverHelper.setHasPadding(true);this._popoverHelper.setTimeout(0);if(this._splitMode!==Elements.ElementsPanel._splitMode.Vertical) -this._splitWidget.installResizer(tabbedPane.headerElement());var stylesView=new UI.SimpleView(Common.UIString('Styles'));this.sidebarPaneView.appendView(stylesView);if(splitMode===Elements.ElementsPanel._splitMode.Horizontal){stylesView.element.classList.add('flex-auto');var splitWidget=new UI.SplitWidget(true,true,'stylesPaneSplitViewState',215);splitWidget.show(stylesView.element);splitWidget.setMainWidget(matchedStylePanesWrapper);splitWidget.setSidebarWidget(computedStylePanesWrapper);}else{stylesView.element.classList.add('flex-auto');matchedStylePanesWrapper.show(stylesView.element);var computedView=new UI.SimpleView(Common.UIString('Computed'));computedView.element.classList.add('composite','fill');computedStylePanesWrapper.show(computedView.element);tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,tabSelected,this);this.sidebarPaneView.appendView(computedView);} -this._stylesViewToReveal=stylesView;showMetrics.call(this,this._splitMode===Elements.ElementsPanel._splitMode.Horizontal);this.sidebarPaneView.appendApplicableItems('elements-sidebar');for(var i=0;i<extensionSidebarPanes.length;++i) -this._addExtensionSidebarPane(extensionSidebarPanes[i]);if(lastSelectedTabId) -this.sidebarPaneView.tabbedPane().selectTab(lastSelectedTabId);this._splitWidget.setSidebarWidget(this.sidebarPaneView.tabbedPane());} -_extensionSidebarPaneAdded(event){var pane=(event.data);this._addExtensionSidebarPane(pane);} -_addExtensionSidebarPane(pane){if(pane.panelName()===this.name) -this.sidebarPaneView.appendView(pane);}};Elements.ElementsPanel._elementsSidebarViewTitleSymbol=Symbol('title');Elements.ElementsPanel._splitMode={Vertical:Symbol('Vertical'),Horizontal:Symbol('Horizontal'),Slim:Symbol('Slim'),};Elements.ElementsPanel.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,object){if(!(object instanceof SDK.RemoteObject&&((object)).isNode())&&!(object instanceof SDK.DOMNode)&&!(object instanceof SDK.DeferredDOMNode)) -return;if(Elements.ElementsPanel.instance().element.isAncestor((event.target))) -return;var commandCallback=Common.Revealer.reveal.bind(Common.Revealer,object);contextMenu.revealSection().appendItem(Common.UIString('Reveal in Elements panel'),commandCallback);}};Elements.ElementsPanel.DOMNodeRevealer=class{reveal(node,omitFocus){var panel=Elements.ElementsPanel.instance();panel._pendingNodeReveal=true;return new Promise(revealPromise);function revealPromise(resolve,reject){if(node instanceof SDK.DOMNode){onNodeResolved((node));}else if(node instanceof SDK.DeferredDOMNode){((node)).resolve(onNodeResolved);}else if(node instanceof SDK.RemoteObject){var domModel=(node).runtimeModel().target().model(SDK.DOMModel);if(domModel) -domModel.pushObjectAsNodeToFrontend(node).then(onNodeResolved);else -reject(new Error('Could not resolve a node to reveal.'));}else{reject(new Error('Can\'t reveal a non-node.'));panel._pendingNodeReveal=false;} -function onNodeResolved(resolvedNode){panel._pendingNodeReveal=false;if(resolvedNode){panel.revealAndSelectNode(resolvedNode,!omitFocus).then(resolve);return;} -reject(new Error('Could not resolve node to reveal.'));}}}};Elements.ElementsPanel.CSSPropertyRevealer=class{reveal(property){var panel=Elements.ElementsPanel.instance();return panel._revealProperty((property));}};Elements.ElementsActionDelegate=class{handleAction(context,actionId){var node=UI.context.flavor(SDK.DOMNode);if(!node) -return true;var treeOutline=Elements.ElementsTreeOutline.forDOMModel(node.domModel());if(!treeOutline) -return true;switch(actionId){case'elements.hide-element':treeOutline.toggleHideElement(node);return true;case'elements.edit-as-html':treeOutline.toggleEditAsHTML(node);return true;} -return false;}};Elements.ElementsPanel.PseudoStateMarkerDecorator=class{decorate(node){return{color:'orange',title:Common.UIString('Element state: %s',':'+node.domModel().cssModel().pseudoState(node).join(', :'))};}};;Elements.ClassesPaneWidget=class extends UI.Widget{constructor(){super(true);this.registerRequiredCSS('elements/classesPaneWidget.css');this.contentElement.className='styles-element-classes-pane';var container=this.contentElement.createChild('div','title-container');this._input=container.createChild('div','new-class-input monospace');this.setDefaultFocusedElement(this._input);this._classesContainer=this.contentElement.createChild('div','source-code');this._classesContainer.classList.add('styles-element-classes-container');this._prompt=new Elements.ClassesPaneWidget.ClassNamePrompt();this._prompt.setAutocompletionTimeout(0);this._prompt.renderAsBlock();var proxyElement=this._prompt.attach(this._input);this._prompt.setPlaceholder(Common.UIString('Add new class'));this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged,this._onTextChanged,this);proxyElement.addEventListener('keydown',this._onKeyDown.bind(this),false);SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.DOMMutated,this._onDOMMutated,this);this._mutatingNodes=new Set();this._pendingNodeClasses=new Map();this._updateNodeThrottler=new Common.Throttler(0);this._previousTarget=null;UI.context.addFlavorChangeListener(SDK.DOMNode,this._onSelectedNodeChanged,this);} -_splitTextIntoClasses(text){return text.split(/[.,\s]/).map(className=>className.trim()).filter(className=>className.length);} -_onKeyDown(event){if(!isEnterKey(event)&&!isEscKey(event)) -return;if(isEnterKey(event)){event.consume();if(this._prompt.acceptAutoComplete()) -return;} -var text=event.target.textContent;if(isEscKey(event)){if(!text.isWhitespace()) -event.consume(true);text='';} -this._prompt.clearAutocomplete();event.target.textContent='';var node=UI.context.flavor(SDK.DOMNode);if(!node) -return;var classNames=this._splitTextIntoClasses(text);for(var className of classNames) -this._toggleClass(node,className,true);this._installNodeClasses(node);this._update();} -_onTextChanged(){var node=UI.context.flavor(SDK.DOMNode);if(!node) -return;this._installNodeClasses(node);} -_onDOMMutated(event){var node=(event.data);if(this._mutatingNodes.has(node)) -return;delete node[Elements.ClassesPaneWidget._classesSymbol];this._update();} -_onSelectedNodeChanged(event){if(this._previousTarget&&this._prompt.text()){this._input.textContent='';this._installNodeClasses(this._previousTarget);} -this._previousTarget=(event.data);this._update();} -wasShown(){this._update();} -_update(){if(!this.isShowing()) -return;var node=UI.context.flavor(SDK.DOMNode);if(node) -node=node.enclosingElementOrSelf();this._classesContainer.removeChildren();this._input.disabled=!node;if(!node) -return;var classes=this._nodeClasses(node);var keys=classes.keysArray();keys.sort(String.caseInsensetiveComparator);for(var i=0;i<keys.length;++i){var className=keys[i];var label=UI.CheckboxLabel.create(className,classes.get(className));label.classList.add('monospace');label.checkboxElement.addEventListener('click',this._onClick.bind(this,className),false);this._classesContainer.appendChild(label);}} -_onClick(className,event){var node=UI.context.flavor(SDK.DOMNode);if(!node) -return;var enabled=event.target.checked;this._toggleClass(node,className,enabled);this._installNodeClasses(node);} -_nodeClasses(node){var result=node[Elements.ClassesPaneWidget._classesSymbol];if(!result){var classAttribute=node.getAttribute('class')||'';var classes=classAttribute.split(/\s/);result=new Map();for(var i=0;i<classes.length;++i){var className=classes[i].trim();if(!className.length) -continue;result.set(className,true);} -node[Elements.ClassesPaneWidget._classesSymbol]=result;} -return result;} -_toggleClass(node,className,enabled){var classes=this._nodeClasses(node);classes.set(className,enabled);} -_installNodeClasses(node){var classes=this._nodeClasses(node);var activeClasses=new Set();for(var className of classes.keys()){if(classes.get(className)) -activeClasses.add(className);} -var additionalClasses=this._splitTextIntoClasses(this._prompt.textWithCurrentSuggestion());for(className of additionalClasses) -activeClasses.add(className);var newClasses=activeClasses.valuesArray();newClasses.sort();this._pendingNodeClasses.set(node,newClasses.join(' '));this._updateNodeThrottler.schedule(this._flushPendingClasses.bind(this));} -_flushPendingClasses(){var promises=[];for(var node of this._pendingNodeClasses.keys()){this._mutatingNodes.add(node);var promise=node.setAttributeValuePromise('class',this._pendingNodeClasses.get(node)).then(onClassValueUpdated.bind(this,node));promises.push(promise);} -this._pendingNodeClasses.clear();return Promise.all(promises);function onClassValueUpdated(node){this._mutatingNodes.delete(node);}}};Elements.ClassesPaneWidget._classesSymbol=Symbol('Elements.ClassesPaneWidget._classesSymbol');Elements.ClassesPaneWidget.ButtonProvider=class{constructor(){this._button=new UI.ToolbarToggle(Common.UIString('Element Classes'),'');this._button.setText('.cls');this._button.element.classList.add('monospace');this._button.addEventListener(UI.ToolbarButton.Events.Click,this._clicked,this);this._view=new Elements.ClassesPaneWidget();} -_clicked(){Elements.ElementsPanel.instance().showToolbarPane(!this._view.isShowing()?this._view:null,this._button);} -item(){return this._button;}};Elements.ClassesPaneWidget.ClassNamePrompt=class extends UI.TextPrompt{constructor(){super();this.initialize(this._buildClassNameCompletions.bind(this),' ');this.disableDefaultSuggestionForEmptyInput();this._selectedFrameId='';this._classNamesPromise=null;} -_getClassNames(selectedNode){var promises=[];var completions=new Set();this._selectedFrameId=selectedNode.frameId();var cssModel=selectedNode.domModel().cssModel();var allStyleSheets=cssModel.allStyleSheets();for(var stylesheet of allStyleSheets){if(stylesheet.frameId!==this._selectedFrameId) -continue;var cssPromise=cssModel.classNamesPromise(stylesheet.id).then(classes=>completions.addAll(classes));promises.push(cssPromise);} -var domPromise=selectedNode.domModel().classNamesPromise(selectedNode.ownerDocument.id).then(classes=>completions.addAll(classes));promises.push(domPromise);return Promise.all(promises).then(()=>completions.valuesArray());} -_buildClassNameCompletions(expression,prefix,force){if(!prefix||force) -this._classNamesPromise=null;var selectedNode=UI.context.flavor(SDK.DOMNode);if(!selectedNode||(!prefix&&!force&&!expression.trim())) -return Promise.resolve([]);if(!this._classNamesPromise||this._selectedFrameId!==selectedNode.frameId()) -this._classNamesPromise=this._getClassNames(selectedNode);return this._classNamesPromise.then(completions=>{if(prefix[0]==='.') -completions=completions.map(value=>'.'+value);return completions.filter(value=>value.startsWith(prefix)).map(completion=>({text:completion}));});}};;Elements.ElementStatePaneWidget=class extends UI.Widget{constructor(){super(true);this.registerRequiredCSS('elements/elementStatePaneWidget.css');this.contentElement.className='styles-element-state-pane';this.contentElement.createChild('div').createTextChild(Common.UIString('Force element state'));var table=createElementWithClass('table','source-code');var inputs=[];this._inputs=inputs;function clickListener(event){var node=UI.context.flavor(SDK.DOMNode);if(!node) -return;node.domModel().cssModel().forcePseudoState(node,event.target.state,event.target.checked);} -function createCheckbox(state){var td=createElement('td');var label=UI.CheckboxLabel.create(':'+state);var input=label.checkboxElement;input.state=state;input.addEventListener('click',clickListener,false);inputs.push(input);td.appendChild(label);return td;} -var tr=table.createChild('tr');tr.appendChild(createCheckbox.call(null,'active'));tr.appendChild(createCheckbox.call(null,'hover'));tr=table.createChild('tr');tr.appendChild(createCheckbox.call(null,'focus'));tr.appendChild(createCheckbox.call(null,'visited'));this.contentElement.appendChild(table);UI.context.addFlavorChangeListener(SDK.DOMNode,this._update,this);} -_updateModel(cssModel){if(this._cssModel===cssModel) -return;if(this._cssModel) -this._cssModel.removeEventListener(SDK.CSSModel.Events.PseudoStateForced,this._update,this);this._cssModel=cssModel;if(this._cssModel) -this._cssModel.addEventListener(SDK.CSSModel.Events.PseudoStateForced,this._update,this);} -wasShown(){this._update();} -_update(){if(!this.isShowing()) -return;var node=UI.context.flavor(SDK.DOMNode);if(node) -node=node.enclosingElementOrSelf();this._updateModel(node?node.domModel().cssModel():null);if(node){var nodePseudoState=node.domModel().cssModel().pseudoState(node);for(var input of this._inputs){input.disabled=!!node.pseudoType();input.checked=nodePseudoState.indexOf(input.state)>=0;}}else{for(var input of this._inputs){input.disabled=true;input.checked=false;}}}};Elements.ElementStatePaneWidget.ButtonProvider=class{constructor(){this._button=new UI.ToolbarToggle(Common.UIString('Toggle Element State'),'');this._button.setText(Common.UIString(':hov'));this._button.addEventListener(UI.ToolbarButton.Events.Click,this._clicked,this);this._button.element.classList.add('monospace');this._view=new Elements.ElementStatePaneWidget();} -_clicked(){Elements.ElementsPanel.instance().showToolbarPane(!this._view.isShowing()?this._view:null,this._button);} -item(){return this._button;}};;Elements.ElementsTreeElementHighlighter=class{constructor(treeOutline){this._throttler=new Common.Throttler(100);this._treeOutline=treeOutline;this._treeOutline.addEventListener(UI.TreeOutline.Events.ElementExpanded,this._clearState,this);this._treeOutline.addEventListener(UI.TreeOutline.Events.ElementCollapsed,this._clearState,this);this._treeOutline.addEventListener(Elements.ElementsTreeOutline.Events.SelectedNodeChanged,this._clearState,this);SDK.targetManager.addModelListener(SDK.OverlayModel,SDK.OverlayModel.Events.HighlightNodeRequested,this._highlightNode,this);this._treeOutline.domModel().overlayModel().addEventListener(SDK.OverlayModel.Events.InspectModeWillBeToggled,this._clearState,this);} -_highlightNode(event){if(!Common.moduleSetting('highlightNodeOnHoverInOverlay').get()) -return;var domNode=(event.data);this._throttler.schedule(callback.bind(this));this._pendingHighlightNode=this._treeOutline.domModel()===domNode.domModel()?domNode:null;function callback(){this._highlightNodeInternal(this._pendingHighlightNode);delete this._pendingHighlightNode;return Promise.resolve();}} -_highlightNodeInternal(node){this._isModifyingTreeOutline=true;var treeElement=null;if(this._currentHighlightedElement){var currentTreeElement=this._currentHighlightedElement;while(currentTreeElement!==this._alreadyExpandedParentElement){if(currentTreeElement.expanded) -currentTreeElement.collapse();currentTreeElement=currentTreeElement.parent;}} -delete this._currentHighlightedElement;delete this._alreadyExpandedParentElement;if(node){var deepestExpandedParent=node;var treeElementSymbol=this._treeOutline.treeElementSymbol();while(deepestExpandedParent&&(!deepestExpandedParent[treeElementSymbol]||!deepestExpandedParent[treeElementSymbol].expanded)) -deepestExpandedParent=deepestExpandedParent.parentNode;this._alreadyExpandedParentElement=deepestExpandedParent?deepestExpandedParent[treeElementSymbol]:this._treeOutline.rootElement();treeElement=this._treeOutline.createTreeElementFor(node);} -this._currentHighlightedElement=treeElement;this._treeOutline.setHoverEffect(treeElement);if(treeElement) -treeElement.reveal(true);this._isModifyingTreeOutline=false;} -_clearState(){if(this._isModifyingTreeOutline) -return;delete this._currentHighlightedElement;delete this._alreadyExpandedParentElement;delete this._pendingHighlightNode;}};;Runtime.cachedResources["elements/breadcrumbs.css"]="/*\n * Copyright 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.crumbs {\n display: inline-block;\n pointer-events: auto;\n cursor: default;\n white-space: nowrap;\n}\n\n.crumbs .crumb {\n display: inline-block;\n padding: 0 7px;\n height: 18px;\n line-height: 18px;\n white-space: nowrap;\n}\n\n.crumbs .crumb.collapsed > * {\n display: none;\n}\n\n.crumbs .crumb.collapsed::before {\n content: \"\\2026\";\n font-weight: bold;\n}\n\n.crumbs .crumb.compact .extra {\n display: none;\n}\n\n.crumbs .crumb.selected, .crumbs .crumb.selected:hover {\n background-color: rgb(56, 121, 217);\n color: white;\n text-shadow: rgba(255, 255, 255, 0.5) 0 0 0;\n}\n\n.crumbs .crumb:hover {\n background-color: rgb(216, 216, 216);\n}\n\n/*# sourceURL=elements/breadcrumbs.css */";Runtime.cachedResources["elements/classesPaneWidget.css"]="/**\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.styles-element-classes-pane {\n background-color: #f3f3f3;\n border-bottom: 1px solid rgb(189, 189, 189);\n padding: 6px 2px 2px;\n}\n\n.styles-element-classes-container {\n display: flex;\n flex-wrap: wrap;\n justify-content: flex-start;\n}\n\n.styles-element-classes-pane label {\n margin-right: 15px;\n}\n\n.styles-element-classes-pane .title-container {\n padding-bottom: 2px;\n}\n\n.styles-element-classes-pane .new-class-input {\n padding-left: 3px;\n padding-right: 3px;\n overflow: hidden;\n border: 1px solid #ddd;\n line-height: 15px;\n margin-left: 3px;\n width: calc(100% - 7px);\n background-color: #fff;\n cursor: text;\n}\n\n/*# sourceURL=elements/classesPaneWidget.css */";Runtime.cachedResources["elements/computedStyleSidebarPane.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.computed-properties {\n -webkit-user-select: text;\n flex-shrink: 0;\n}\n\n.styles-sidebar-pane-toolbar {\n border-bottom: 1px solid #eee;\n flex-shrink: 0;\n}\n\n.styles-sidebar-pane-filter-box {\n flex: auto;\n display: flex;\n}\n\n.styles-sidebar-pane-filter-box > input {\n outline: none !important;\n border: none;\n width: 100%;\n background: transparent;\n margin-left: 4px;\n}\n\n.styles-filter-engaged {\n background-color: rgba(255, 255, 0, 0.5);\n}\n\n:host-context(.-theme-with-dark-background) .styles-filter-engaged {\n background-color: hsla(133, 100%, 30%, 0.5);\n}\n\n/*# sourceURL=elements/computedStyleSidebarPane.css */";Runtime.cachedResources["elements/computedStyleWidgetTree.css"]="/*\n * Copyright (c) 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.computed-style-property {\n display: flex;\n overflow: hidden;\n flex: auto;\n}\n\n.computed-style-property .property-name {\n min-width: 5em;\n text-overflow: ellipsis;\n overflow: hidden;\n flex-shrink: 1;\n flex-basis: 16em;\n flex-grow: 1;\n}\n\n.computed-style-property .property-value {\n margin-left: 2em;\n position: relative;\n display: flex;\n flex-shrink: 0;\n flex-basis: 5em;\n flex-grow: 10;\n}\n\n.computed-style-property .property-value-text {\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.tree-outline li:hover .goto-source-icon {\n display: block;\n margin-top: -2px;\n}\n\n.goto-source-icon {\n background-color: #5a5a5a;\n display: none;\n position: absolute;\n left: -16px;\n}\n\n.goto-source-icon:hover {\n background-color: #333;\n}\n\n.computed-style-property-inherited {\n opacity: 0.5;\n}\n\n.trace-link {\n user-select: none;\n float: right;\n padding-left: 1em;\n position: relative;\n z-index: 1;\n}\n\n.property-trace {\n text-overflow: ellipsis;\n overflow: hidden;\n flex-grow: 1;\n}\n\n.property-trace-selector {\n color: gray;\n padding-left: 2em;\n}\n\n.property-trace-value {\n position: relative;\n display: inline-block;\n margin-left: 2em;\n}\n\n.property-trace-inactive .property-trace-value::before {\n position: absolute;\n content: \".\";\n border-bottom: 1px solid rgba(0, 0, 0, 0.35);\n top: 0;\n bottom: 5px;\n left: 0;\n right: 0;\n}\n\n.tree-outline li.odd-row {\n position: relative;\n background-color: #F5F5F5;\n}\n\n.tree-outline, .tree-outline ol {\n padding-left: 0;\n}\n\n.tree-outline li:hover {\n background-color: rgb(235, 242, 252);\n cursor: pointer;\n}\n\n.tree-outline li::before {\n margin-left: 4px;\n}\n\n.delimeter {\n color: transparent;\n}\n\n.delimeter::selection {\n color: transparent;\n}\n\n/*# sourceURL=elements/computedStyleWidgetTree.css */";Runtime.cachedResources["elements/elementsPanel.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#elements-content {\n flex: 1 1;\n overflow: auto;\n padding: 2px 0 0 0;\n}\n\n#elements-content:not(.elements-wrap) > div {\n display: inline-block;\n min-width: 100%;\n}\n\n#elements-content.elements-wrap {\n overflow-x: hidden;\n}\n\n#elements-crumbs {\n flex: 0 0 19px;\n background-color: white;\n border-top: 1px solid #ccc;\n overflow: hidden;\n height: 19px;\n width: 100%;\n}\n\n.style-panes-wrapper {\n overflow: auto;\n}\n\n.style-panes-wrapper > div:not(:first-child) {\n border-top: 1px solid #ccc;\n}\n\n.elements-tree-header {\n height: 24px;\n border-top: 1px solid #eee;\n border-bottom: 1px solid #eee;\n display: flex;\n flex-direction: row;\n align-items: center;\n}\n\n.elements-tree-header-frame {\n margin-left: 6px;\n margin-right: 6px;\n flex: none;\n}\n\n/*# sourceURL=elements/elementsPanel.css */";Runtime.cachedResources["elements/elementStatePaneWidget.css"]="/**\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.styles-element-state-pane {\n overflow: hidden;\n height: 66px;\n padding-left: 2px;\n background-color: #f3f3f3;\n border-bottom: 1px solid rgb(189, 189, 189);\n margin-top: 0;\n}\n\n.styles-element-state-pane > div {\n margin: 8px 4px 6px;\n}\n\n.styles-element-state-pane > table {\n width: 100%;\n border-spacing: 0;\n}\n\n.styles-element-state-pane td {\n padding: 0;\n}\n\n/*# sourceURL=elements/elementStatePaneWidget.css */";Runtime.cachedResources["elements/elementsTreeOutline.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.elements-disclosure {\n width: 100%;\n display: inline-block;\n line-height: normal;\n}\n\n.elements-disclosure li {\n /** Keep margin-left & padding-left in sync with ElementsTreeElements.updateDecorators **/\n padding: 0 0 0 14px;\n margin-top: 1px;\n margin-left: -2px;\n word-wrap: break-word;\n position: relative;\n min-height: 14px;\n}\n\n.elements-disclosure li.parent {\n /** Keep it in sync with ElementsTreeElements.updateDecorators **/\n margin-left: -13px;\n}\n\n.elements-disclosure li.selected .selected-hint:before {\n font-style: italic;\n content: \" == $0\";\n opacity: 0.6;\n position: absolute;\n white-space: pre;\n}\n\n.elements-disclosure li.parent::before {\n box-sizing: border-box;\n}\n\n.elements-disclosure li.parent::before {\n -webkit-user-select: none;\n -webkit-mask-image: url(Images/treeoutlineTriangles.png);\n -webkit-mask-size: 32px 24px;\n content: '\\00a0\\00a0';\n color: transparent;\n text-shadow: none;\n margin-right: -3px;\n}\n\n.elements-disclosure li.always-parent::before {\n visibility: hidden;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\n.elements-disclosure li.parent::before {\n -webkit-mask-image: url(Images/treeoutlineTriangles_2x.png);\n}\n} /* media */\n\n.elements-disclosure li.parent::before {\n -webkit-mask-position: 0 0;\n background-color: rgb(110, 110, 110);\n}\n\n.elements-disclosure li .selection {\n display: none;\n z-index: -1;\n}\n\n.elements-disclosure li.hovered:not(.selected) .selection {\n display: block;\n left: 3px;\n right: 3px;\n background-color: rgba(56, 121, 217, 0.1);\n border-radius: 5px;\n}\n\n.elements-disclosure li.parent.expanded::before {\n -webkit-mask-position: -16px 0;\n}\n\n.elements-disclosure li.selected .selection {\n display: block;\n background-color: #dadada;\n}\n\n.elements-disclosure ol {\n list-style-type: none;\n /** Keep it in sync with ElementsTreeElements.updateDecorators **/\n -webkit-padding-start: 12px;\n margin: 0;\n}\n\n.elements-disclosure ol.children {\n display: none;\n}\n\n.elements-disclosure ol.children.expanded {\n display: block;\n}\n\n.elements-disclosure li .webkit-html-tag.close {\n margin-left: -12px;\n}\n\n.elements-disclosure > ol {\n position: relative;\n margin: 0;\n cursor: default;\n min-width: 100%;\n min-height: 100%;\n padding-left: 2px;\n}\n\n.elements-disclosure ol li.selected:focus {\n color: white;\n}\n\n.elements-disclosure ol li.parent.selected:focus::before {\n background-color: white;\n}\n\n.elements-disclosure ol li.selected:focus * {\n color: inherit;\n}\n\n.elements-disclosure ol li.selected:focus .selection {\n background-color: rgb(56, 121, 217);\n}\n\n.elements-tree-outline ol.shadow-root-depth-4 {\n background-color: rgba(0, 0, 0, 0.04);\n}\n\n.elements-tree-outline ol.shadow-root-depth-3 {\n background-color: rgba(0, 0, 0, 0.03);\n}\n\n.elements-tree-outline ol.shadow-root-depth-2 {\n background-color: rgba(0, 0, 0, 0.02);\n}\n\n.elements-tree-outline ol.shadow-root-depth-1 {\n background-color: rgba(0, 0, 0, 0.01);\n}\n\n.elements-tree-outline ol.shadow-root-deep {\n background-color: transparent;\n}\n\n.elements-tree-editor {\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2),\n 0 2px 4px rgba(0, 0, 0, 0.2),\n 0 2px 6px rgba(0, 0, 0, 0.1);\n margin-right: 4px;\n}\n\n.elements-disclosure li.elements-drag-over .selection {\n display: block;\n margin-top: -2px;\n border-top: 2px solid rgb(56, 121, 217);\n}\n\n.elements-disclosure li.in-clipboard .highlight {\n outline: 1px dotted darkgrey;\n}\n\n.CodeMirror {\n background-color: white;\n height: 300px !important;\n}\n\n.CodeMirror-lines {\n padding: 0;\n}\n\n.CodeMirror pre {\n padding: 0;\n}\n\nbutton, input, select {\n font-family: inherit;\n font-size: inherit;\n}\n\n.editing {\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2),\n 0 2px 4px rgba(0, 0, 0, 0.2),\n 0 2px 6px rgba(0, 0, 0, 0.1);\n background-color: white;\n text-overflow: clip !important;\n padding-left: 2px;\n margin-left: -2px;\n padding-right: 2px;\n margin-right: -2px;\n margin-bottom: -1px;\n padding-bottom: 1px;\n opacity: 1.0 !important;\n}\n\n.editing,\n.editing * {\n color: #222 !important;\n text-decoration: none !important;\n}\n\n.editing br {\n display: none;\n}\n\n.elements-gutter-decoration {\n position: absolute;\n left: 2px;\n margin-top: 2px;\n height: 9px;\n width: 9px;\n border-radius: 5px;\n border: 1px solid orange;\n background-color: orange;\n cursor: pointer;\n}\n\n.elements-gutter-decoration.elements-has-decorated-children {\n opacity: 0.5;\n}\n\n.add-attribute {\n margin-left: 1px;\n margin-right: 1px;\n white-space: nowrap;\n}\n\n.elements-tree-nowrap, .elements-tree-nowrap .li {\n white-space: pre !important;\n}\n\n.elements-disclosure .elements-tree-nowrap li {\n word-wrap: normal;\n}\n\n/* DOM update highlight */\n@-webkit-keyframes dom-update-highlight-animation {\n from {\n background-color: rgb(158, 54, 153);\n color: white;\n }\n 80% {\n background-color: rgb(245, 219, 244);\n color: inherit;\n }\n to {\n background-color: inherit;\n }\n}\n\n@-webkit-keyframes dom-update-highlight-animation-dark {\n from {\n background-color: rgb(158, 54, 153);\n color: white;\n }\n 80% {\n background-color: #333;\n color: inherit;\n }\n to {\n background-color: inherit;\n }\n}\n\n.dom-update-highlight {\n -webkit-animation: dom-update-highlight-animation 1.4s 1 cubic-bezier(0, 0, 0.2, 1);\n border-radius: 2px;\n}\n\n:host-context(.-theme-with-dark-background) .dom-update-highlight {\n -webkit-animation: dom-update-highlight-animation-dark 1.4s 1 cubic-bezier(0, 0, 0.2, 1);\n}\n\n.elements-disclosure.single-node li {\n padding-left: 2px;\n}\n\n.elements-tree-shortcut-title {\n color: rgb(87, 87, 87);\n}\n\nol:hover > li > .elements-tree-shortcut-link {\n display: initial;\n}\n\n.elements-tree-shortcut-link {\n color: rgb(87, 87, 87);\n display: none;\n}\n\nol li.selected:focus .webkit-html-tag {\n color: #a5a5a5;\n}\n\nol li.selected:focus .webkit-html-tag-name,\nol li.selected:focus .webkit-html-close-tag-name,\nol li.selected:focus .webkit-html-attribute-value,\nol li.selected:focus .devtools-link {\n color: white;\n}\n\nol li.selected:focus .webkit-html-attribute-name {\n color: #ccc;\n}\n\n.elements-disclosure .gutter-container {\n position: absolute;\n top: 0;\n left: 0;\n cursor: pointer;\n width: 15px;\n height: 15px;\n}\n\n.gutter-menu-icon {\n display: none;\n transform: rotate(-90deg) scale(0.8);\n background-color: white;\n position: relative;\n left: -7px;\n top: -3px;\n}\n\n.elements-disclosure li.selected .gutter-container:not(.has-decorations) .gutter-menu-icon {\n display: block;\n}\n\n/** Guide line */\nli.selected {\n z-index: 0;\n}\n\nli.hovered:not(.always-parent) + ol.children, .elements-tree-outline ol.shadow-root, li.selected:not(.always-parent) + ol.children {\n margin-left: 5px;\n -webkit-padding-start: 6px;\n border-width: 1px;\n border-left-style: solid;\n}\n\nli.hovered:not(.always-parent) + ol.children:not(.shadow-root) {\n border-color: hsla(0,0%,0%,0.1);\n}\n\n.elements-tree-outline ol.shadow-root {\n border-color: hsla(0,0%,80%,1);\n}\n\nli.selected:not(.always-parent) + ol.children {\n border-color: hsla(216,68%,80%,1) !important;\n}\n\n/*# sourceURL=elements/elementsTreeOutline.css */";Runtime.cachedResources["elements/metricsSidebarPane.css"]="/**\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.metrics {\n padding: 8px;\n font-size: 10px;\n text-align: center;\n white-space: nowrap;\n min-height: 190px;\n display: flex;\n flex-direction: column;\n -webkit-align-items: center;\n -webkit-justify-content: center;\n}\n\n:host-context(.-theme-with-dark-background) .metrics {\n color: #222;\n}\n\n:host-context(.-theme-with-dark-background) .metrics > div:hover {\n color: #ccc;\n}\n\n.metrics .label {\n position: absolute;\n font-size: 10px;\n margin-left: 3px;\n padding-left: 2px;\n padding-right: 2px;\n}\n\n.metrics .position {\n border: 1px rgb(66%, 66%, 66%) dotted;\n background-color: white;\n display: inline-block;\n text-align: center;\n padding: 3px;\n margin: 3px;\n}\n\n.metrics .margin {\n border: 1px dashed;\n background-color: white;\n display: inline-block;\n text-align: center;\n vertical-align: middle;\n padding: 3px;\n margin: 3px;\n}\n\n.metrics .border {\n border: 1px black solid;\n background-color: white;\n display: inline-block;\n text-align: center;\n vertical-align: middle;\n padding: 3px;\n margin: 3px;\n}\n\n.metrics .padding {\n border: 1px grey dashed;\n background-color: white;\n display: inline-block;\n text-align: center;\n vertical-align: middle;\n padding: 3px;\n margin: 3px;\n}\n\n.metrics .content {\n position: static;\n border: 1px gray solid;\n background-color: white;\n display: inline-block;\n text-align: center;\n vertical-align: middle;\n padding: 3px;\n margin: 3px;\n min-width: 80px;\n overflow: visible;\n}\n\n.metrics .content span {\n display: inline-block;\n}\n\n.metrics .editing {\n position: relative;\n z-index: 100;\n cursor: text;\n}\n\n.metrics .left {\n display: inline-block;\n vertical-align: middle;\n}\n\n.metrics .right {\n display: inline-block;\n vertical-align: middle;\n}\n\n.metrics .top {\n display: inline-block;\n}\n\n.metrics .bottom {\n display: inline-block;\n}\n\n/*# sourceURL=elements/metricsSidebarPane.css */";Runtime.cachedResources["elements/platformFontsWidget.css"]="/**\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n -webkit-user-select: text;\n}\n\n.platform-fonts {\n flex-shrink: 0;\n}\n\n.font-name {\n font-weight: bold;\n}\n\n.font-usage {\n color: #888;\n padding-left: 3px;\n}\n\n.title {\n padding: 0 5px;\n border-top: 1px solid;\n border-bottom: 1px solid;\n border-color: #ddd;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n height: 24px;\n background-color: #f1f1f1;\n display: flex;\n align-items: center;\n}\n\n.stats-section {\n margin: 5px 0;\n}\n\n.font-stats-item {\n padding-left: 1em;\n}\n\n.font-stats-item .font-delimeter {\n margin: 0 1ex 0 1ex;\n}\n\n\n/*# sourceURL=elements/platformFontsWidget.css */";Runtime.cachedResources["elements/propertiesWidget.css"]="/*\n * Copyright (c) 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.properties-widget-section {\n padding: 2px 0px 2px 5px;\n flex: none;\n}\n\n/*# sourceURL=elements/propertiesWidget.css */";Runtime.cachedResources["elements/stylesSectionTree.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tree-outline {\n padding: 0;\n}\n\n.tree-outline li.not-parsed-ok {\n margin-left: 0;\n}\n\n.tree-outline li.filter-match {\n background-color: rgba(255, 255, 0, 0.5);\n}\n\n:host-context(.-theme-with-dark-background) .tree-outline li.filter-match {\n background-color: hsla(133, 100%, 30%, 0.5);\n}\n\n.tree-outline li.overloaded.filter-match {\n background-color: rgba(255, 255, 0, 0.25);\n}\n\n:host-context(.-theme-with-dark-background) .tree-outline li.overloaded.filter-match {\n background-color: hsla(133, 100%, 30%, 0.25);\n}\n\n.tree-outline li.not-parsed-ok .exclamation-mark {\n display: inline-block;\n position: relative;\n width: 11px;\n height: 10px;\n margin: 0 7px 0 0;\n top: 1px;\n left: -36px; /* outdent to compensate for the top-level property indent */\n -webkit-user-select: none;\n cursor: default;\n z-index: 1;\n}\n\n.tree-outline li {\n margin-left: 12px;\n padding-left: 22px;\n white-space: normal;\n text-overflow: ellipsis;\n cursor: auto;\n display: block;\n}\n\n.tree-outline li::before {\n display: none;\n}\n\n.tree-outline li .webkit-css-property {\n margin-left: -22px; /* outdent the first line of longhand properties (in an expanded shorthand) to compensate for the \"padding-left\" shift in .tree-outline li */\n}\n\n.tree-outline > li {\n padding-left: 38px;\n clear: both;\n min-height: 14px;\n}\n\n.tree-outline > li .webkit-css-property {\n margin-left: -38px; /* outdent the first line of the top-level properties to compensate for the \"padding-left\" shift in .tree-outline > li */\n}\n\n.tree-outline > li.child-editing {\n padding-left: 8px;\n}\n\n.tree-outline > li.child-editing .webkit-css-property {\n margin-left: 0;\n}\n\n.tree-outline li.child-editing {\n word-wrap: break-word !important;\n white-space: normal !important;\n padding-left: 0;\n}\n\nol:not(.tree-outline) {\n display: none;\n margin: 0;\n -webkit-padding-start: 12px;\n list-style: none;\n}\n\nol.expanded {\n display: block;\n}\n\n.tree-outline li .info {\n padding-top: 4px;\n padding-bottom: 3px;\n}\n\n.enabled-button {\n visibility: hidden;\n float: left;\n font-size: 10px;\n margin: 0;\n vertical-align: top;\n position: relative;\n z-index: 1;\n width: 18px;\n left: -40px; /* original -2px + (-38px) to compensate for the first line outdent */\n top: 1px;\n height: 13px;\n}\n\n.tree-outline li.editing .enabled-button {\n display: none !important;\n}\n\n.overloaded:not(.has-ignorable-error),\n.inactive,\n.disabled,\n.not-parsed-ok:not(.has-ignorable-error) {\n text-decoration: line-through;\n}\n\n.has-ignorable-error .webkit-css-property {\n color: inherit;\n}\n\n.implicit,\n.inherited {\n opacity: 0.5;\n}\n\n.has-ignorable-error {\n color: gray;\n}\n\n.tree-outline li.editing {\n margin-left: 10px;\n text-overflow: clip;\n}\n\n.tree-outline li.editing-sub-part {\n padding: 3px 6px 8px 18px;\n margin: -1px -6px -8px -6px;\n text-overflow: clip;\n}\n\n:host-context(.no-affect) .tree-outline li {\n opacity: 0.5;\n}\n\n:host-context(.no-affect) .tree-outline li.editing {\n opacity: 1.0;\n}\n\n:host-context(.styles-panel-hovered:not(.read-only)) .webkit-css-property:hover,\n:host-context(.styles-panel-hovered:not(.read-only)) .value:hover {\n text-decoration: underline;\n cursor: default;\n}\n\n.styles-clipboard-only {\n display: inline-block;\n width: 0;\n opacity: 0;\n pointer-events: none;\n white-space: pre;\n}\n\n.tree-outline li.child-editing .styles-clipboard-only {\n display: none;\n}\n\n/* Matched styles */\n\n:host-context(.matched-styles) .tree-outline li {\n margin-left: 0 !important;\n}\n\n.expand-icon {\n -webkit-user-select: none;\n margin-left: -6px;\n margin-right: 2px;\n margin-bottom: -2px;\n}\n\n.tree-outline li:not(.parent) .expand-icon {\n display: none;\n}\n\n:host-context(.matched-styles:not(.read-only):hover) .enabled-button {\n visibility: visible;\n}\n\n:host-context(.matched-styles:not(.read-only)) .tree-outline li.disabled .enabled-button {\n visibility: visible;\n}\n\n:host-context(.matched-styles) ol.expanded {\n margin-left: 16px;\n}\n\n/*# sourceURL=elements/stylesSectionTree.css */";Runtime.cachedResources["elements/stylesSidebarPane.css"]="/**\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.styles-section {\n min-height: 18px;\n white-space: nowrap;\n -webkit-user-select: text;\n border-bottom: 1px solid #eee;\n position: relative;\n overflow: hidden;\n}\n\n.styles-section > div {\n padding: 2px 2px 4px 4px;\n}\n\n.styles-section:last-child {\n border-bottom: none;\n}\n\n.styles-pane .sidebar-separator {\n border-top: 0 none;\n}\n\n.styles-section.read-only {\n background-color: #eee;\n}\n\n.styles-section[data-keyboard-focus=\"true\"]:focus {\n background-color: hsl(214, 67%, 95%);\n}\n.styles-section.read-only[data-keyboard-focus=\"true\"]:focus {\n background-color: hsl(215, 25%, 91%);\n}\n\n.styles-filter-engaged,\n.styles-section .simple-selector.filter-match {\n background-color: rgba(255, 255, 0, 0.5);\n}\n\n:host-context(.-theme-with-dark-background) .styles-filter-engaged,\n:host-context(.-theme-with-dark-background) .styles-section .simple-selector.filter-match {\n background-color: hsla(133, 100%, 30%, 0.5);\n}\n\n.sidebar-pane-closing-brace {\n clear: both;\n}\n\n.styles-section-title {\n background-origin: padding;\n background-clip: padding;\n word-wrap: break-word;\n white-space: normal;\n}\n\n.styles-section-title .media-list {\n color: #888;\n}\n\n.styles-section-title .media-list.media-matches .media.editable-media {\n color: #222;\n}\n\n.styles-section-title .media:not(.editing-media),\n.styles-section-title .media:not(.editing-media) .subtitle {\n overflow: hidden;\n}\n\n.styles-section-title .media .subtitle {\n float: right;\n color: rgb(85, 85, 85);\n}\n\n.styles-section-subtitle {\n color: rgb(85, 85, 85);\n float: right;\n margin-left: 5px;\n max-width: 100%;\n text-overflow: ellipsis;\n overflow: hidden;\n white-space: nowrap;\n height: 15px;\n margin-bottom: -1px;\n}\n\n.styles-section .styles-section-subtitle .devtools-link {\n color: inherit;\n}\n\n.styles-section .selector {\n color: #888;\n}\n\n.styles-section .simple-selector.selector-matches, .styles-section.keyframe-key {\n color: #222;\n}\n\n.styles-section .devtools-link {\n user-select: none;\n}\n\n.styles-section .style-properties {\n margin: 0;\n padding: 2px 4px 0 0;\n list-style: none;\n clear: both;\n display: flex;\n}\n\n.styles-section.matched-styles .style-properties {\n padding-left: 0;\n}\n\n@keyframes styles-element-state-pane-slidein {\n from {\n margin-top: -60px;\n }\n to {\n margin-top: 0px;\n }\n}\n\n@keyframes styles-element-state-pane-slideout {\n from {\n margin-top: 0px;\n }\n to {\n margin-top: -60px;\n }\n}\n\n.styles-sidebar-toolbar-pane {\n position: relative;\n animation-duration: 0.1s;\n animation-direction: normal;\n}\n\n.styles-sidebar-toolbar-pane-container {\n position: relative;\n overflow: hidden;\n flex-shrink: 0;\n}\n\n.styles-selector {\n cursor: text;\n}\n\n.styles-sidebar-pane-toolbar-container {\n flex-shrink: 0;\n overflow: hidden;\n position: sticky;\n top: 0;\n background-color: #fff;\n z-index: 1;\n}\n\n.styles-sidebar-pane-toolbar {\n border-bottom: 1px solid #eee;\n flex-shrink: 0;\n}\n\n.styles-sidebar-pane-filter-box {\n flex: auto;\n display: flex;\n}\n\n.styles-sidebar-pane-filter-box > input {\n outline: none !important;\n border: none;\n width: 100%;\n background: transparent;\n margin-left: 4px;\n}\n\n.styles-section.styles-panel-hovered:not(.read-only) span.simple-selector:hover,\n.styles-section.styles-panel-hovered:not(.read-only) .media-text :hover{\n text-decoration: underline;\n cursor: default;\n}\n\n.sidebar-separator {\n background-color: #ddd;\n padding: 0 5px;\n border-top: 1px solid #ccc;\n border-bottom: 1px solid #ccc;\n color: rgb(50, 50, 50);\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n line-height: 16px;\n}\n\n.sidebar-separator > span.monospace {\n background: rgb(255, 255, 255);\n padding: 0px 3px;\n border-radius: 2px;\n border: 1px solid #C1C1C1;\n}\n\n.sidebar-pane-section-toolbar {\n position: absolute;\n right: 0;\n bottom: 0;\n visibility: hidden;\n background-color: rgba(255, 255, 255, 0.9);\n z-index: 0;\n}\n\n.styles-section[data-keyboard-focus=\"true\"]:focus .sidebar-pane-section-toolbar {\n background-color: hsla(214, 67%, 95%, 0.9);\n}\n\n.styles-pane:not(.is-editing-style) .styles-section.matched-styles:not(.read-only):hover .sidebar-pane-section-toolbar {\n visibility: visible;\n}\n\n/*# sourceURL=elements/stylesSidebarPane.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/event_listeners/event_listeners_module.js b/src/cobalt/debug/content/devtools/event_listeners/event_listeners_module.js deleted file mode 100644 index 6daaa33..0000000 --- a/src/cobalt/debug/content/devtools/event_listeners/event_listeners_module.js +++ /dev/null
@@ -1,102 +0,0 @@ -EventListeners.EventListenersResult;EventListeners.EventListenersView=class extends UI.VBox{constructor(changeCallback){super();this._changeCallback=changeCallback;this._treeOutline=new UI.TreeOutlineInShadow();this._treeOutline.hideOverflow();this._treeOutline.registerRequiredCSS('object_ui/objectValue.css');this._treeOutline.registerRequiredCSS('event_listeners/eventListenersView.css');this._treeOutline.setComparator(EventListeners.EventListenersTreeElement.comparator);this._treeOutline.element.classList.add('monospace');this.element.appendChild(this._treeOutline.element);this._emptyHolder=createElementWithClass('div','gray-info-message');this._emptyHolder.textContent=Common.UIString('No event listeners');this._linkifier=new Components.Linkifier();this._treeItemMap=new Map();} -async addObjects(objects){this.reset();await Promise.all(objects.map(obj=>obj?this._addObject(obj):Promise.resolve()));this.addEmptyHolderIfNeeded();this._eventListenersArrivedForTest();} -_addObject(object){var eventListeners;var frameworkEventListenersObject=null;var promises=[];var domDebuggerModel=object.runtimeModel().target().model(SDK.DOMDebuggerModel);if(domDebuggerModel) -promises.push(domDebuggerModel.eventListeners(object).then(storeEventListeners));promises.push(EventListeners.frameworkEventListeners(object).then(storeFrameworkEventListenersObject));return Promise.all(promises).then(markInternalEventListeners).then(addEventListeners.bind(this));function storeEventListeners(result){eventListeners=result;} -function storeFrameworkEventListenersObject(result){frameworkEventListenersObject=result;} -function markInternalEventListeners(){if(!frameworkEventListenersObject.internalHandlers) -return Promise.resolve(undefined);return frameworkEventListenersObject.internalHandlers.object().callFunctionJSONPromise(isInternalEventListener,eventListeners.map(handlerArgument)).then(setIsInternal);function handlerArgument(listener){return SDK.RemoteObject.toCallArgument(listener.handler());} -function isInternalEventListener(){var isInternal=[];var internalHandlersSet=new Set(this);for(var handler of arguments) -isInternal.push(internalHandlersSet.has(handler));return isInternal;} -function setIsInternal(isInternal){for(var i=0;i<eventListeners.length;++i){if(isInternal[i]) -eventListeners[i].markAsFramework();}}} -function addEventListeners(){this._addObjectEventListeners(object,eventListeners);this._addObjectEventListeners(object,frameworkEventListenersObject.eventListeners);}} -_addObjectEventListeners(object,eventListeners){if(!eventListeners) -return;for(var eventListener of eventListeners){var treeItem=this._getOrCreateTreeElementForType(eventListener.type());treeItem.addObjectEventListener(eventListener,object);}} -showFrameworkListeners(showFramework,showPassive,showBlocking){var eventTypes=this._treeOutline.rootElement().children();for(var eventType of eventTypes){var hiddenEventType=true;for(var listenerElement of eventType.children()){var listenerOrigin=listenerElement.eventListener().origin();var hidden=false;if(listenerOrigin===SDK.EventListener.Origin.FrameworkUser&&!showFramework) -hidden=true;if(listenerOrigin===SDK.EventListener.Origin.Framework&&showFramework) -hidden=true;if(!showPassive&&listenerElement.eventListener().passive()) -hidden=true;if(!showBlocking&&!listenerElement.eventListener().passive()) -hidden=true;listenerElement.hidden=hidden;hiddenEventType=hiddenEventType&&hidden;} -eventType.hidden=hiddenEventType;}} -_getOrCreateTreeElementForType(type){var treeItem=this._treeItemMap.get(type);if(!treeItem){treeItem=new EventListeners.EventListenersTreeElement(type,this._linkifier,this._changeCallback);this._treeItemMap.set(type,treeItem);treeItem.hidden=true;this._treeOutline.appendChild(treeItem);} -this._emptyHolder.remove();return treeItem;} -addEmptyHolderIfNeeded(){var allHidden=true;for(var eventType of this._treeOutline.rootElement().children()){eventType.hidden=!eventType.firstChild();allHidden=allHidden&&eventType.hidden;} -if(allHidden&&!this._emptyHolder.parentNode) -this.element.appendChild(this._emptyHolder);} -reset(){var eventTypes=this._treeOutline.rootElement().children();for(var eventType of eventTypes) -eventType.removeChildren();this._linkifier.reset();} -_eventListenersArrivedForTest(){}};EventListeners.EventListenersTreeElement=class extends UI.TreeElement{constructor(type,linkifier,changeCallback){super(type);this.toggleOnClick=true;this.selectable=false;this._linkifier=linkifier;this._changeCallback=changeCallback;} -static comparator(element1,element2){if(element1.title===element2.title) -return 0;return element1.title>element2.title?1:-1;} -addObjectEventListener(eventListener,object){var treeElement=new EventListeners.ObjectEventListenerBar(eventListener,object,this._linkifier,this._changeCallback);this.appendChild((treeElement));}};EventListeners.ObjectEventListenerBar=class extends UI.TreeElement{constructor(eventListener,object,linkifier,changeCallback){super('',true);this._eventListener=eventListener;this.editable=false;this.selectable=false;this._setTitle(object,linkifier);this._changeCallback=changeCallback;} -onpopulate(){var properties=[];var eventListener=this._eventListener;var runtimeModel=eventListener.domDebuggerModel().runtimeModel();properties.push(runtimeModel.createRemotePropertyFromPrimitiveValue('useCapture',eventListener.useCapture()));properties.push(runtimeModel.createRemotePropertyFromPrimitiveValue('passive',eventListener.passive()));properties.push(runtimeModel.createRemotePropertyFromPrimitiveValue('once',eventListener.once()));if(typeof eventListener.handler()!=='undefined') -properties.push(new SDK.RemoteObjectProperty('handler',eventListener.handler()));ObjectUI.ObjectPropertyTreeElement.populateWithProperties(this,properties,[],true,null);} -_setTitle(object,linkifier){var title=this.listItemElement.createChild('span');var subtitle=this.listItemElement.createChild('span','event-listener-tree-subtitle');subtitle.appendChild(linkifier.linkifyRawLocation(this._eventListener.location(),this._eventListener.sourceURL()));title.appendChild(ObjectUI.ObjectPropertiesSection.createValueElement(object,false,false));if(this._eventListener.canRemove()){var deleteButton=title.createChild('span','event-listener-button');deleteButton.textContent=Common.UIString('Remove');deleteButton.title=Common.UIString('Delete event listener');deleteButton.addEventListener('click',removeListener.bind(this),false);title.appendChild(deleteButton);} -if(this._eventListener.isScrollBlockingType()&&this._eventListener.canTogglePassive()){var passiveButton=title.createChild('span','event-listener-button');passiveButton.textContent=Common.UIString('Toggle Passive');passiveButton.title=Common.UIString('Toggle whether event listener is passive or blocking');passiveButton.addEventListener('click',togglePassiveListener.bind(this),false);title.appendChild(passiveButton);} -function removeListener(event){event.consume();this._removeListenerBar();this._eventListener.remove();} -function togglePassiveListener(event){event.consume();this._eventListener.togglePassive().then(this._changeCallback());}} -_removeListenerBar(){var parent=this.parent;parent.removeChild(this);if(!parent.childCount()) -parent.collapse();var allHidden=true;for(var i=0;i<parent.childCount();++i){if(!parent.childAt(i).hidden) -allHidden=false;} -parent.hidden=allHidden;} -eventListener(){return this._eventListener;}};;EventListeners.FrameworkEventListenersObject;EventListeners.EventListenerObjectInInspectedPage;EventListeners.frameworkEventListeners=function(object){var domDebuggerModel=object.runtimeModel().target().model(SDK.DOMDebuggerModel);if(!domDebuggerModel){return Promise.resolve(({eventListeners:[],internalHandlers:null}));} -var listenersResult=({eventListeners:[]});return object.callFunctionPromise(frameworkEventListeners,undefined).then(assertCallFunctionResult).then(getOwnProperties).then(createEventListeners).then(returnResult).catchException(listenersResult);function getOwnProperties(object){return object.getOwnPropertiesPromise(false);} -function createEventListeners(result){if(!result.properties) -throw new Error('Object properties is empty');var promises=[];for(var property of result.properties){if(property.name==='eventListeners'&&property.value) -promises.push(convertToEventListeners(property.value).then(storeEventListeners));if(property.name==='internalHandlers'&&property.value) -promises.push(convertToInternalHandlers(property.value).then(storeInternalHandlers));if(property.name==='errorString'&&property.value) -printErrorString(property.value);} -return(Promise.all(promises));} -function convertToEventListeners(pageEventListenersObject){return SDK.RemoteArray.objectAsArray(pageEventListenersObject).map(toEventListener).then(filterOutEmptyObjects);function toEventListener(listenerObject){var type;var useCapture;var passive;var once;var handler=null;var originalHandler=null;var location=null;var removeFunctionObject=null;var promises=[];promises.push(listenerObject.callFunctionJSONPromise(truncatePageEventListener,undefined).then(storeTruncatedListener));function truncatePageEventListener(){return{type:this.type,useCapture:this.useCapture,passive:this.passive,once:this.once};} -function storeTruncatedListener(truncatedListener){type=truncatedListener.type;useCapture=truncatedListener.useCapture;passive=truncatedListener.passive;once=truncatedListener.once;} -promises.push(listenerObject.callFunctionPromise(handlerFunction).then(assertCallFunctionResult).then(storeOriginalHandler).then(toTargetFunction).then(storeFunctionWithDetails));function handlerFunction(){return this.handler;} -function storeOriginalHandler(functionObject){originalHandler=functionObject;return originalHandler;} -function storeFunctionWithDetails(functionObject){handler=functionObject;return(functionObject.debuggerModel().functionDetailsPromise(functionObject).then(storeFunctionDetails));} -function storeFunctionDetails(functionDetails){location=functionDetails?functionDetails.location:null;} -promises.push(listenerObject.callFunctionPromise(getRemoveFunction).then(assertCallFunctionResult).then(storeRemoveFunction));function getRemoveFunction(){return this.remove;} -function storeRemoveFunction(functionObject){if(functionObject.type!=='function') -return;removeFunctionObject=functionObject;} -return Promise.all(promises).then(createEventListener).catchException((null));function createEventListener(){if(!location) -throw new Error('Empty event listener\'s location');return new SDK.EventListener((domDebuggerModel),object,type,useCapture,passive,once,handler,originalHandler,location,removeFunctionObject,SDK.EventListener.Origin.FrameworkUser);}}} -function convertToInternalHandlers(pageInternalHandlersObject){return SDK.RemoteArray.objectAsArray(pageInternalHandlersObject).map(toTargetFunction).then(SDK.RemoteArray.createFromRemoteObjects);} -function toTargetFunction(functionObject){return SDK.RemoteFunction.objectAsFunction(functionObject).targetFunction();} -function storeEventListeners(eventListeners){listenersResult.eventListeners=eventListeners;} -function storeInternalHandlers(internalHandlers){listenersResult.internalHandlers=internalHandlers;} -function printErrorString(errorString){Common.console.error(String(errorString.value));} -function returnResult(){return listenersResult;} -function assertCallFunctionResult(result){if(result.wasThrown||!result.object) -throw new Error('Exception in callFunction or empty result');return result.object;} -function filterOutEmptyObjects(objects){return objects.filter(filterOutEmpty);function filterOutEmpty(object){return!!object;}} -function frameworkEventListeners(){var errorLines=[];var eventListeners=[];var internalHandlers=[];var fetchers=[jQueryFetcher];try{if(self.devtoolsFrameworkEventListeners&&isArrayLike(self.devtoolsFrameworkEventListeners)) -fetchers=fetchers.concat(self.devtoolsFrameworkEventListeners);}catch(e){errorLines.push('devtoolsFrameworkEventListeners call produced error: '+toString(e));} -for(var i=0;i<fetchers.length;++i){try{var fetcherResult=fetchers[i](this);if(fetcherResult.eventListeners&&isArrayLike(fetcherResult.eventListeners)){eventListeners=eventListeners.concat(fetcherResult.eventListeners.map(checkEventListener).filter(nonEmptyObject));} -if(fetcherResult.internalHandlers&&isArrayLike(fetcherResult.internalHandlers)){internalHandlers=internalHandlers.concat(fetcherResult.internalHandlers.map(checkInternalHandler).filter(nonEmptyObject));}}catch(e){errorLines.push('fetcher call produced error: '+toString(e));}} -var result={eventListeners:eventListeners};if(internalHandlers.length) -result.internalHandlers=internalHandlers;if(errorLines.length){var errorString='Framework Event Listeners API Errors:\n\t'+errorLines.join('\n\t');errorString=errorString.substr(0,errorString.length-1);result.errorString=errorString;} -return result;function isArrayLike(obj){if(!obj||typeof obj!=='object') -return false;try{if(typeof obj.splice==='function'){var len=obj.length;return typeof len==='number'&&(len>>>0===len&&(len>0||1/len>0));}}catch(e){} -return false;} -function checkEventListener(eventListener){try{var errorString='';if(!eventListener) -errorString+='empty event listener, ';var type=eventListener.type;if(!type||(typeof type!=='string')) -errorString+='event listener\'s type isn\'t string or empty, ';var useCapture=eventListener.useCapture;if(typeof useCapture!=='boolean') -errorString+='event listener\'s useCapture isn\'t boolean or undefined, ';var passive=eventListener.passive;if(typeof passive!=='boolean') -errorString+='event listener\'s passive isn\'t boolean or undefined, ';var once=eventListener.once;if(typeof once!=='boolean') -errorString+='event listener\'s once isn\'t boolean or undefined, ';var handler=eventListener.handler;if(!handler||(typeof handler!=='function')) -errorString+='event listener\'s handler isn\'t a function or empty, ';var remove=eventListener.remove;if(remove&&(typeof remove!=='function')) -errorString+='event listener\'s remove isn\'t a function, ';if(!errorString){return{type:type,useCapture:useCapture,passive:passive,once:once,handler:handler,remove:remove};}else{errorLines.push(errorString.substr(0,errorString.length-2));return null;}}catch(e){errorLines.push(toString(e));return null;}} -function checkInternalHandler(handler){if(handler&&(typeof handler==='function')) -return handler;errorLines.push('internal handler isn\'t a function or empty');return null;} -function toString(obj){try{return''+obj;}catch(e){return'<error>';}} -function nonEmptyObject(obj){return!!obj;} -function jQueryFetcher(node){if(!node||!(node instanceof Node)) -return{eventListeners:[]};var jQuery=(window['jQuery']);if(!jQuery||!jQuery.fn) -return{eventListeners:[]};var jQueryFunction=(jQuery);var data=jQuery._data||jQuery.data;var eventListeners=[];var internalHandlers=[];if(typeof data==='function'){var events=data(node,'events');for(var type in events){for(var key in events[type]){var frameworkListener=events[type][key];if(typeof frameworkListener==='object'||typeof frameworkListener==='function'){var listener={handler:frameworkListener.handler||frameworkListener,useCapture:true,passive:false,once:false,type:type};listener.remove=jQueryRemove.bind(node,frameworkListener.selector);eventListeners.push(listener);}}} -var nodeData=data(node);if(nodeData&&typeof nodeData.handle==='function') -internalHandlers.push(nodeData.handle);} -var entry=jQueryFunction(node)[0];if(entry){var entryEvents=entry['$events'];for(var type in entryEvents){var events=entryEvents[type];for(var key in events){if(typeof events[key]==='function'){var listener={handler:events[key],useCapture:true,passive:false,once:false,type:type};eventListeners.push(listener);}}} -if(entry&&entry['$handle']) -internalHandlers.push(entry['$handle']);} -return{eventListeners:eventListeners,internalHandlers:internalHandlers};} -function jQueryRemove(selector,type,handler){if(!this||!(this instanceof Node)) -return;var node=(this);var jQuery=(window['jQuery']);if(!jQuery||!jQuery.fn) -return;var jQueryFunction=(jQuery);jQueryFunction(node).off(type,selector,handler);}}};;Runtime.cachedResources["event_listeners/eventListenersView.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tree-outline-disclosure li {\n padding: 2px 0 0 5px;\n overflow: hidden;\n display: list-item;\n min-height: 17px;\n}\n\n.tree-outline-disclosure > li {\n border-top: 1px solid #f0f0f0;\n}\n\n.tree-outline-disclosure > li:first-of-type {\n border-top: none;\n}\n\n.tree-outline-disclosure {\n padding-left: 0 !important;\n padding-right: 3px;\n}\n\n.tree-outline-disclosure li.parent::before {\n top: 0 !important;\n}\n\n.tree-outline-disclosure .name {\n color: rgb(136, 19, 145);\n}\n\n.event-listener-tree-subtitle {\n float: right;\n margin-left: 5px;\n}\n\n.event-listener-button {\n padding: 0 3px;\n background-color: #f2f2f2;\n border-radius: 3px;\n border: 1px solid #c3c3c3;\n margin-left: 10px;\n display: none;\n cursor: pointer;\n}\n\n.event-listener-button:hover {\n background-color: #e0e0e0;\n}\n\n.tree-outline-disclosure li:hover .event-listener-button {\n display: inline;\n}\n\n/*# sourceURL=event_listeners/eventListenersView.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/formatter/formatter_module.js b/src/cobalt/debug/content/devtools/formatter/formatter_module.js deleted file mode 100644 index 98e7fce..0000000 --- a/src/cobalt/debug/content/devtools/formatter/formatter_module.js +++ /dev/null
@@ -1,34 +0,0 @@ -Formatter.FormatterWorkerPool=class{constructor(){this._taskQueue=[];this._workerTasks=new Map();} -_createWorker(){var worker=new Common.Worker('formatter_worker');worker.onmessage=this._onWorkerMessage.bind(this,worker);worker.onerror=this._onWorkerError.bind(this,worker);return worker;} -_processNextTask(){if(!this._taskQueue.length) -return;var freeWorker=this._workerTasks.keysArray().find(worker=>!this._workerTasks.get(worker));if(!freeWorker&&this._workerTasks.size<Formatter.FormatterWorkerPool.MaxWorkers) -freeWorker=this._createWorker();if(!freeWorker) -return;var task=this._taskQueue.shift();this._workerTasks.set(freeWorker,task);freeWorker.postMessage({method:task.method,params:task.params});} -_onWorkerMessage(worker,event){var task=this._workerTasks.get(worker);if(task.isChunked&&event.data&&!event.data['isLastChunk']){task.callback(event.data);return;} -this._workerTasks.set(worker,null);this._processNextTask();task.callback(event.data?event.data:null);} -_onWorkerError(worker,event){console.error(event);var task=this._workerTasks.get(worker);worker.terminate();this._workerTasks.delete(worker);var newWorker=this._createWorker();this._workerTasks.set(newWorker,null);this._processNextTask();task.callback(null);} -_runChunkedTask(methodName,params,callback){var task=new Formatter.FormatterWorkerPool.Task(methodName,params,onData,true);this._taskQueue.push(task);this._processNextTask();function onData(data){if(!data){callback(true,null);return;} -var isLastChunk=!!data['isLastChunk'];var chunk=data['chunk'];callback(isLastChunk,chunk);}} -_runTask(methodName,params){var callback;var promise=new Promise(fulfill=>callback=fulfill);var task=new Formatter.FormatterWorkerPool.Task(methodName,params,callback,false);this._taskQueue.push(task);this._processNextTask();return promise;} -parseJSONRelaxed(content){return this._runTask('parseJSONRelaxed',{content:content});} -parseSCSS(content){return this._runTask('parseSCSS',{content:content}).then(rules=>rules||[]);} -format(mimeType,content,indentString){var parameters={mimeType:mimeType,content:content,indentString:indentString};return(this._runTask('format',parameters));} -javaScriptIdentifiers(content){return this._runTask('javaScriptIdentifiers',{content:content}).then(ids=>ids||[]);} -evaluatableJavaScriptSubstring(content){return this._runTask('evaluatableJavaScriptSubstring',{content:content}).then(text=>text||'');} -preprocessTopLevelAwaitExpressions(content){return this._runTask('preprocessTopLevelAwaitExpressions',{content:content}).then(text=>text||'');} -parseCSS(content,callback){this._runChunkedTask('parseCSS',{content:content},onDataChunk);function onDataChunk(isLastChunk,data){var rules=(data||[]);callback(isLastChunk,rules);}} -javaScriptOutline(content,callback){this._runChunkedTask('javaScriptOutline',{content:content},onDataChunk);function onDataChunk(isLastChunk,data){var items=(data||[]);callback(isLastChunk,items);}} -outlineForMimetype(content,mimeType,callback){switch(mimeType){case'text/html':case'text/javascript':this.javaScriptOutline(content,javaScriptCallback);return true;case'text/css':this.parseCSS(content,cssCallback);return true;} -return false;function javaScriptCallback(isLastChunk,items){callback(isLastChunk,items.map(item=>({line:item.line,column:item.column,title:item.name,subtitle:item.arguments})));} -function cssCallback(isLastChunk,rules){callback(isLastChunk,rules.map(rule=>({line:rule.lineNumber,column:rule.columnNumber,title:rule.selectorText||rule.atRule})));}}};Formatter.FormatterWorkerPool.MaxWorkers=2;Formatter.FormatterWorkerPool.Task=class{constructor(method,params,callback,isChunked){this.method=method;this.params=params;this.callback=callback;this.isChunked=isChunked;}};Formatter.FormatterWorkerPool.FormatResult=class{constructor(){this.content;this.mapping;}};Formatter.FormatterWorkerPool.FormatMapping;Formatter.FormatterWorkerPool.OutlineItem;Formatter.FormatterWorkerPool.JSOutlineItem=class{constructor(){this.name;this.arguments;this.line;this.column;}};Formatter.FormatterWorkerPool.TextRange;Formatter.FormatterWorkerPool.CSSProperty=class{constructor(){this.name;this.nameRange;this.value;this.valueRange;this.range;this.disabled;}};Formatter.FormatterWorkerPool.CSSStyleRule=class{constructor(){this.selectorText;this.styleRange;this.lineNumber;this.columnNumber;this.properties;}};Formatter.FormatterWorkerPool.CSSAtRule;Formatter.FormatterWorkerPool.CSSRule;Formatter.FormatterWorkerPool.SCSSProperty=class{constructor(){this.range;this.name;this.value;this.disabled;}};Formatter.FormatterWorkerPool.SCSSRule=class{constructor(){this.selectors;this.properties;this.styleRange;}};Formatter.formatterWorkerPool=function(){if(!Formatter._formatterWorkerPool) -Formatter._formatterWorkerPool=new Formatter.FormatterWorkerPool();return Formatter._formatterWorkerPool;};;Formatter.Formatter=function(){};Formatter.Formatter.format=function(contentType,mimeType,content,callback){if(contentType.isDocumentOrScriptOrStyleSheet()) -new Formatter.ScriptFormatter(mimeType,content,callback);else -new Formatter.ScriptIdentityFormatter(mimeType,content,callback);};Formatter.Formatter.locationToPosition=function(lineEndings,lineNumber,columnNumber){var position=lineNumber?lineEndings[lineNumber-1]+1:0;return position+columnNumber;};Formatter.Formatter.positionToLocation=function(lineEndings,position){var lineNumber=lineEndings.upperBound(position-1);if(!lineNumber) -var columnNumber=position;else -var columnNumber=position-lineEndings[lineNumber-1]-1;return[lineNumber,columnNumber];};Formatter.ScriptFormatter=class{constructor(mimeType,content,callback){content=content.replace(/\r\n?|[\n\u2028\u2029]/g,'\n').replace(/^\uFEFF/,'');this._callback=callback;this._originalContent=content;Formatter.formatterWorkerPool().format(mimeType,content,Common.moduleSetting('textEditorIndent').get()).then(this._didFormatContent.bind(this));} -_didFormatContent(formatResult){var sourceMapping=new Formatter.FormatterSourceMappingImpl(this._originalContent.computeLineEndings(),formatResult.content.computeLineEndings(),formatResult.mapping);this._callback(formatResult.content,sourceMapping);}};Formatter.ScriptIdentityFormatter=class{constructor(mimeType,content,callback){callback(content,new Formatter.IdentityFormatterSourceMapping());}};Formatter.FormatterSourceMapping=function(){};Formatter.FormatterSourceMapping.prototype={originalToFormatted(lineNumber,columnNumber){},formattedToOriginal(lineNumber,columnNumber){}};Formatter.IdentityFormatterSourceMapping=class{originalToFormatted(lineNumber,columnNumber){return[lineNumber,columnNumber||0];} -formattedToOriginal(lineNumber,columnNumber){return[lineNumber,columnNumber||0];}};Formatter.FormatterSourceMappingImpl=class{constructor(originalLineEndings,formattedLineEndings,mapping){this._originalLineEndings=originalLineEndings;this._formattedLineEndings=formattedLineEndings;this._mapping=mapping;} -originalToFormatted(lineNumber,columnNumber){var originalPosition=Formatter.Formatter.locationToPosition(this._originalLineEndings,lineNumber,columnNumber||0);var formattedPosition=this._convertPosition(this._mapping.original,this._mapping.formatted,originalPosition||0);return Formatter.Formatter.positionToLocation(this._formattedLineEndings,formattedPosition);} -formattedToOriginal(lineNumber,columnNumber){var formattedPosition=Formatter.Formatter.locationToPosition(this._formattedLineEndings,lineNumber,columnNumber||0);var originalPosition=this._convertPosition(this._mapping.formatted,this._mapping.original,formattedPosition);return Formatter.Formatter.positionToLocation(this._originalLineEndings,originalPosition||0);} -_convertPosition(positions1,positions2,position){var index=positions1.upperBound(position)-1;var convertedPosition=positions2[index]+position-positions1[index];if(index<positions2.length-1&&convertedPosition>positions2[index+1]) -convertedPosition=positions2[index+1];return convertedPosition;}};; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/formatter_worker.js b/src/cobalt/debug/content/devtools/formatter_worker.js deleted file mode 100644 index 7d5f8aa..0000000 --- a/src/cobalt/debug/content/devtools/formatter_worker.js +++ /dev/null
@@ -1,2816 +0,0 @@ -var allDescriptors=[{"skip_compilation":["gonzales-scss.js"],"dependencies":["formatter_worker"],"extensions":[{"className":"Gonzales.SCSSParser","mimeType":"text/x-scss","type":"@FormatterWorker.FormatterWorkerContentParser"}],"name":"gonzales","scripts":["gonzales_module.js"]},{"skip_compilation":["acorn/acorn.js","acorn/acorn_loose.js","../cm_web_modes/css.js","../cm_web_modes/xml.js"],"dependencies":["platform","text_utils","cm_headless"],"name":"formatter_worker"},{"dependencies":["platform"],"name":"text_utils"},{"skip_compilation":["headlesscodemirror.js"],"name":"cm_headless"},{"dependencies":[],"name":"platform"}];var applicationDescriptor;var _loadedScripts={};for(var k of[]){} -(function(){var baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();var Runtime=class{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(var i=0;i<descriptors.length;++i) -this._registerModule(descriptors[i]);} -static loadResourcePromise(url){return new Promise(load);function load(fulfill,reject){var xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE) -return;if([0,200,304].indexOf(xhr.status)===-1) -reject(new Error('While loading from url '+url+' server responded with a status of '+xhr.status));else -fulfill(e.target.response);} -xhr.send(null);}} -static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1) -return path;var normalizedSegments=[];var segments=path.split('/');for(var i=0;i<segments.length;i++){var segment=segments[i];if(segment==='.') -continue;else if(segment==='..') -normalizedSegments.pop();else if(segment) -normalizedSegments.push(segment);} -var normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/') -return normalizedPath;if(path[0]==='/'&&normalizedPath) -normalizedPath='/'+normalizedPath;if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..')) -normalizedPath=normalizedPath+'/';return normalizedPath;} -static _loadScriptsPromise(scriptNames,base){var promises=[];var urls=[];var sources=new Array(scriptNames.length);var scriptToEval=0;for(var i=0;i<scriptNames.length;++i){var scriptName=scriptNames[i];var sourceURL=(base||self._importScriptPathPrefix)+scriptName;var schemaIndex=sourceURL.indexOf('://')+3;var pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1) -pathIndex=sourceURL.length;sourceURL=sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));if(_loadedScripts[sourceURL]) -continue;urls.push(sourceURL);promises.push(Runtime.loadResourcePromise(sourceURL).then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));} -return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}} -function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;} -self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}} -static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;} -var sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}} -static startApplication(appName){console.timeStamp('Runtime.startApplication');var allDescriptorsByName={};for(var i=0;i<allDescriptors.length;++i){var d=allDescriptors[i];allDescriptorsByName[d['name']]=d;} -var applicationPromise;if(applicationDescriptor) -applicationPromise=Promise.resolve(applicationDescriptor);else -applicationPromise=Runtime.loadResourcePromise(appName+'.json').then(JSON.parse.bind(JSON));return applicationPromise.then(parseModuleDescriptors);function parseModuleDescriptors(appDescriptor){var configuration=appDescriptor.modules;var moduleJSONPromises=[];var coreModuleNames=[];for(var i=0;i<configuration.length;++i){var descriptor=configuration[i];var name=descriptor['name'];var moduleJSON=allDescriptorsByName[name];if(moduleJSON) -moduleJSONPromises.push(Promise.resolve(moduleJSON));else -moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));if(descriptor['type']==='autostart') -coreModuleNames.push(name);} -return Promise.all(moduleJSONPromises).then(instantiateRuntime);function instantiateRuntime(moduleDescriptors){for(var i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';} -self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames) -return(self.runtime._loadAutoStartModules(coreModuleNames));return Promise.resolve();}}} -static startWorker(appName){return Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}} -static queryParam(name){return Runtime._queryParamsObject[name]||null;} -static queryParamsString(){return location.search;} -static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}} -static _assert(value,message){if(value) -return;Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);} -static setPlatform(platform){Runtime._platform=platform;} -static _isDescriptorEnabled(descriptor){var activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*') -return Runtime.experiments.supportEnabled();if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1))) -return false;if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment)) -return false;var condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition)) -return false;if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1))) -return false;return true;} -static resolveSourceURL(path){var sourceURL=self.location.href;if(self.location.search) -sourceURL=sourceURL.replace(self.location.search,'');sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';} -useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend')) -Runtime._remoteBase+='debug/';} -_registerModule(descriptor){var module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;} -loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();} -_loadAutoStartModules(moduleNames){var promises=[];for(var i=0;i<moduleNames.length;++i) -promises.push(this.loadModulePromise(moduleNames[i]));return Promise.all(promises);} -_checkExtensionApplicability(extension,predicate){if(!predicate) -return false;var contextTypes=extension.descriptor().contextTypes;if(!contextTypes) -return true;for(var i=0;i<contextTypes.length;++i){var contextType=this._resolve(contextTypes[i]);var isMatching=!!contextType&&predicate(contextType);if(isMatching) -return true;} -return false;} -isExtensionApplicableToContext(extension,context){if(!context) -return true;return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}} -isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes) -return true;return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}} -extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type) -return false;if(!extension.enabled()) -return false;return!context||extension.isApplicable(context);} -function orderComparator(extension1,extension2){var order1=extension1.descriptor()['order']||0;var order2=extension2.descriptor()['order']||0;return order1-order2;} -function titleComparator(extension1,extension2){var title1=extension1.title()||'';var title2=extension2.title()||'';return title1.localeCompare(title2);}} -extension(type,context){return this.extensions(type,context)[0]||null;} -allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));} -_resolve(typeName){if(!this._cachedTypeClasses[typeName]){var path=typeName.split('.');var object=self;for(var i=0;object&&(i<path.length);++i) -object=object[path[i]];if(object) -this._cachedTypeClasses[typeName]=(object);} -return this._cachedTypeClasses[typeName]||null;} -sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction) -return constructorFunction[Runtime._instanceSymbol];var instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}};Runtime._queryParamsObject={__proto__:null};Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';Runtime.ModuleDescriptor=class{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.condition;this.remote;}};Runtime.ExtensionDescriptor=class{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}};Runtime.Module=class{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();var extensions=(descriptor.extensions);for(var i=0;extensions&&i<extensions.length;++i){var extension=new Runtime.Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);} -this._loadedForTest=false;} -name(){return this._name;} -enabled(){return Runtime._isDescriptorEnabled(this._descriptor);} -resource(name){var fullName=this._name+'/'+name;var content=Runtime.cachedResources[fullName];if(!content) -throw new Error(fullName+' not preloaded. Check module.json');return content;} -_loadPromise(){if(!this.enabled()) -return Promise.reject(new Error('Module '+this._name+' is not enabled'));if(this._pendingLoadPromise) -return this._pendingLoadPromise;var dependencies=this._descriptor.dependencies;var dependencyPromises=[];for(var i=0;dependencies&&i<dependencies.length;++i) -dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;} -_loadResources(){var resources=this._descriptor['resources'];if(!resources||!resources.length) -return Promise.resolve();var promises=[];for(var i=0;i<resources.length;++i){var url=this._modularizeURL(resources[i]);promises.push(Runtime._loadResourceIntoCache(url,true));} -return Promise.all(promises).then(undefined);} -_loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length) -return Promise.resolve();const specialCases={'sdk':'SDK','ui':'UI','object_ui':'ObjectUI','perf_ui':'PerfUI','har_importer':'HARImporter','sass_test_runner':'SASSTestRunner','sdk_test_runner':'SDKTestRunner'};var namespace=specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());} -_modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);} -_remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;} -substituteURL(value){var base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}};Runtime.Extension=class{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;} -descriptor(){return this._descriptor;} -module(){return this._module;} -enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());} -_typeClass(){if(!this._hasTypeClass) -return null;return this._module._manager._resolve(this._type.substring(1));} -isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);} -instance(){return this._module._loadPromise().then(this._createInstance.bind(this));} -_createInstance(){var className=this._className||this._factoryName;if(!className) -throw new Error('Could not instantiate extension with no class');var constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function)) -throw new Error('Could not instantiate: '+className);if(this._className) -return this._module._manager.sharedInstance(constructorFunction);return new constructorFunction(this);} -title(){return this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];} -hasContextType(contextType){var contextTypes=this.descriptor().contextTypes;if(!contextTypes) -return false;for(var i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i])) -return true;} -return false;}};Runtime.ExperimentsSupport=class{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};} -allConfigurableExperiments(){var result=[];for(var i=0;i<this._experiments.length;i++){var experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name]) -result.push(experiment);} -return result;} -supportEnabled(){return this._supportEnabled;} -_setExperimentsSetting(value){if(!self.localStorage) -return;self.localStorage['experiments']=JSON.stringify(value);} -register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));} -isEnabled(experimentName){this._checkExperiment(experimentName);if(this._enabledTransiently[experimentName]) -return true;if(!this.supportEnabled()) -return false;return!!Runtime._experimentsSetting()[experimentName];} -setEnabled(experimentName,enabled){this._checkExperiment(experimentName);var experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);} -setDefaultExperiments(experimentNames){for(var i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}} -enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;} -clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};} -cleanUpStaleExperiments(){var experimentsSetting=Runtime._experimentsSetting();var cleanedUpExperimentSetting={};for(var i=0;i<this._experiments.length;++i){var experimentName=this._experiments[i].name;if(experimentsSetting[experimentName]) -cleanedUpExperimentSetting[experimentName]=true;} -this._setExperimentsSetting(cleanedUpExperimentSetting);} -_checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}};Runtime.Experiment=class{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;} -isEnabled(){return this._experiments.isEnabled(this.name);} -setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}};{(function parseQueryParameters(){var queryParams=Runtime.queryParamsString();if(!queryParams) -return;var params=queryParams.substring(1).split('&');for(var i=0;i<params.length;++i){var pair=params[i].split('=');var name=pair.shift();Runtime._queryParamsObject[name]=pair.join('=');}})();} -Runtime.experiments=new Runtime.ExperimentsSupport();Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('chrome-devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){var versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch) -Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}})();function ServicePort(){} -ServicePort.prototype={setHandlers(messageHandler,closeHandler){},send(message){},close(){}};var runtime;self['Platform']=self['Platform']||{};var ArrayLike;function mod(m,n){return((m%n)+n)%n;} -String.prototype.findAll=function(string){var matches=[];var i=this.indexOf(string);while(i!==-1){matches.push(i);i=this.indexOf(string,i+string.length);} -return matches;};String.prototype.reverse=function(){return this.split('').reverse().join('');};String.prototype.replaceControlCharacters=function(){return this.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u0080-\u009f]/g,'�');};String.prototype.isWhitespace=function(){return/^\s*$/.test(this);};String.prototype.computeLineEndings=function(){var endings=this.findAll('\n');endings.push(this.length);return endings;};String.prototype.escapeCharacters=function(chars){var foundChar=false;for(var i=0;i<chars.length;++i){if(this.indexOf(chars.charAt(i))!==-1){foundChar=true;break;}} -if(!foundChar) -return String(this);var result='';for(var i=0;i<this.length;++i){if(chars.indexOf(this.charAt(i))!==-1) -result+='\\';result+=this.charAt(i);} -return result;};String.regexSpecialCharacters=function(){return'^[]{}()\\.^$*+?|-,';};String.prototype.escapeForRegExp=function(){return this.escapeCharacters(String.regexSpecialCharacters());};String.prototype.escapeHTML=function(){return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');};String.prototype.unescapeHTML=function(){return this.replace(/</g,'<').replace(/>/g,'>').replace(/:/g,':').replace(/"/g,'"').replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');};String.prototype.collapseWhitespace=function(){return this.replace(/[\s\xA0]+/g,' ');};String.prototype.trimMiddle=function(maxLength){if(this.length<=maxLength) -return String(this);var leftHalf=maxLength>>1;var rightHalf=maxLength-leftHalf-1;if(this.codePointAt(this.length-rightHalf-1)>=0x10000){--rightHalf;++leftHalf;} -if(leftHalf>0&&this.codePointAt(leftHalf-1)>=0x10000) ---leftHalf;return this.substr(0,leftHalf)+'\u2026'+this.substr(this.length-rightHalf,rightHalf);};String.prototype.trimEnd=function(maxLength){if(this.length<=maxLength) -return String(this);return this.substr(0,maxLength-1)+'\u2026';};String.prototype.trimURL=function(baseURLDomain){var result=this.replace(/^(https|http|file):\/\//i,'');if(baseURLDomain){if(result.toLowerCase().startsWith(baseURLDomain.toLowerCase())) -result=result.substr(baseURLDomain.length);} -return result;};String.prototype.toTitleCase=function(){return this.substring(0,1).toUpperCase()+this.substring(1);};String.prototype.compareTo=function(other){if(this>other) -return 1;if(this<other) -return-1;return 0;};String.prototype.removeURLFragment=function(){var fragmentIndex=this.indexOf('#');if(fragmentIndex===-1) -fragmentIndex=this.length;return this.substring(0,fragmentIndex);};String.hashCode=function(string){if(!string) -return 0;var p=((1<<30)*4-5);var z=0x5033d967;var z2=0x59d2f15d;var s=0;var zi=1;for(var i=0;i<string.length;i++){var xi=string.charCodeAt(i)*z2;s=(s+zi*xi)%p;zi=(zi*z)%p;} -s=(s+zi*(p-1))%p;return Math.abs(s|0);};String.isDigitAt=function(string,index){var c=string.charCodeAt(index);return(48<=c&&c<=57);};String.prototype.toBase64=function(){function encodeBits(b){return b<26?b+65:b<52?b+71:b<62?b-4:b===62?43:b===63?47:65;} -var encoder=new TextEncoder();var data=encoder.encode(this.toString());var n=data.length;var encoded='';if(n===0) -return encoded;var shift;var v=0;for(var i=0;i<n;i++){shift=i%3;v|=data[i]<<(16>>>shift&24);if(shift===2){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),encodeBits(v&63));v=0;}} -if(shift===0) -encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),61,61);else if(shift===1) -encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),61);return encoded;};String.naturalOrderComparator=function(a,b){var chunk=/^\d+|^\D+/;var chunka,chunkb,anum,bnum;while(1){if(a){if(!b) -return 1;}else{if(b) -return-1;else -return 0;} -chunka=a.match(chunk)[0];chunkb=b.match(chunk)[0];anum=!isNaN(chunka);bnum=!isNaN(chunkb);if(anum&&!bnum) -return-1;if(bnum&&!anum) -return 1;if(anum&&bnum){var diff=chunka-chunkb;if(diff) -return diff;if(chunka.length!==chunkb.length){if(!+chunka&&!+chunkb) -return chunka.length-chunkb.length;else -return chunkb.length-chunka.length;}}else if(chunka!==chunkb){return(chunka<chunkb)?-1:1;} -a=a.substring(chunka.length);b=b.substring(chunkb.length);}};String.caseInsensetiveComparator=function(a,b){a=a.toUpperCase();b=b.toUpperCase();if(a===b) -return 0;return a>b?1:-1;};Number.constrain=function(num,min,max){if(num<min) -num=min;else if(num>max) -num=max;return num;};Number.gcd=function(a,b){if(b===0) -return a;else -return Number.gcd(b,a%b);};Number.toFixedIfFloating=function(value){if(!value||isNaN(value)) -return value;var number=Number(value);return number%1?number.toFixed(3):String(number);};Date.prototype.isValid=function(){return!isNaN(this.getTime());};Date.prototype.toISO8601Compact=function(){function leadZero(x){return(x>9?'':'0')+x;} -return this.getFullYear()+leadZero(this.getMonth()+1)+leadZero(this.getDate())+'T'+ -leadZero(this.getHours())+leadZero(this.getMinutes())+leadZero(this.getSeconds());};Object.defineProperty(Array.prototype,'remove',{value:function(value,firstOnly){var index=this.indexOf(value);if(index===-1) -return false;if(firstOnly){this.splice(index,1);return true;} -for(var i=index+1,n=this.length;i<n;++i){if(this[i]!==value) -this[index++]=this[i];} -this.length=index;return true;}});Object.defineProperty(Array.prototype,'pushAll',{value:function(array){for(var i=0;i<array.length;++i) -this.push(array[i]);}});Object.defineProperty(Array.prototype,'rotate',{value:function(index){var result=[];for(var i=index;i<index+this.length;++i) -result.push(this[i%this.length]);return result;}});Object.defineProperty(Array.prototype,'sortNumbers',{value:function(){function numericComparator(a,b){return a-b;} -this.sort(numericComparator);}});Object.defineProperty(Uint32Array.prototype,'sort',{value:Array.prototype.sort});(function(){var partition={value:function(comparator,left,right,pivotIndex){function swap(array,i1,i2){var temp=array[i1];array[i1]=array[i2];array[i2]=temp;} -var pivotValue=this[pivotIndex];swap(this,right,pivotIndex);var storeIndex=left;for(var i=left;i<right;++i){if(comparator(this[i],pivotValue)<0){swap(this,storeIndex,i);++storeIndex;}} -swap(this,right,storeIndex);return storeIndex;}};Object.defineProperty(Array.prototype,'partition',partition);Object.defineProperty(Uint32Array.prototype,'partition',partition);var sortRange={value:function(comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight){function quickSortRange(array,comparator,left,right,sortWindowLeft,sortWindowRight){if(right<=left) -return;var pivotIndex=Math.floor(Math.random()*(right-left))+left;var pivotNewIndex=array.partition(comparator,left,right,pivotIndex);if(sortWindowLeft<pivotNewIndex) -quickSortRange(array,comparator,left,pivotNewIndex-1,sortWindowLeft,sortWindowRight);if(pivotNewIndex<sortWindowRight) -quickSortRange(array,comparator,pivotNewIndex+1,right,sortWindowLeft,sortWindowRight);} -if(leftBound===0&&rightBound===(this.length-1)&&sortWindowLeft===0&&sortWindowRight>=rightBound) -this.sort(comparator);else -quickSortRange(this,comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight);return this;}};Object.defineProperty(Array.prototype,'sortRange',sortRange);Object.defineProperty(Uint32Array.prototype,'sortRange',sortRange);})();Object.defineProperty(Array.prototype,'stableSort',{value:function(comparator){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);} -comparator=comparator||defaultComparator;var indices=new Array(this.length);for(var i=0;i<this.length;++i) -indices[i]=i;var self=this;function indexComparator(a,b){var result=comparator(self[a],self[b]);return result?result:a-b;} -indices.sort(indexComparator);for(var i=0;i<this.length;++i){if(indices[i]<0||i===indices[i]) -continue;var cyclical=i;var saved=this[i];while(true){var next=indices[cyclical];indices[cyclical]=-1;if(next===i){this[cyclical]=saved;break;}else{this[cyclical]=this[next];cyclical=next;}}} -return this;}});Object.defineProperty(Array.prototype,'qselect',{value:function(k,comparator){if(k<0||k>=this.length) -return;if(!comparator){comparator=function(a,b){return a-b;};} -var low=0;var high=this.length-1;for(;;){var pivotPosition=this.partition(comparator,low,high,Math.floor((high+low)/2));if(pivotPosition===k) -return this[k];else if(pivotPosition>k) -high=pivotPosition-1;else -low=pivotPosition+1;}}});Object.defineProperty(Array.prototype,'lowerBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);} -comparator=comparator||defaultComparator;var l=left||0;var r=right!==undefined?right:this.length;while(l<r){var m=(l+r)>>1;if(comparator(object,this[m])>0) -l=m+1;else -r=m;} -return r;}});Object.defineProperty(Array.prototype,'upperBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);} -comparator=comparator||defaultComparator;var l=left||0;var r=right!==undefined?right:this.length;while(l<r){var m=(l+r)>>1;if(comparator(object,this[m])>=0) -l=m+1;else -r=m;} -return r;}});Object.defineProperty(Uint32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Uint32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Int32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Int32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Float64Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Array.prototype,'binaryIndexOf',{value:function(value,comparator){var index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,'select',{value:function(field){var result=new Array(this.length);for(var i=0;i<this.length;++i) -result[i]=this[i][field];return result;}});Object.defineProperty(Array.prototype,'peekLast',{value:function(){return this[this.length-1];}});(function(){function mergeOrIntersect(array1,array2,comparator,mergeNotIntersect){var result=[];var i=0;var j=0;while(i<array1.length&&j<array2.length){var compareValue=comparator(array1[i],array2[j]);if(mergeNotIntersect||!compareValue) -result.push(compareValue<=0?array1[i]:array2[j]);if(compareValue<=0) -i++;if(compareValue>=0) -j++;} -if(mergeNotIntersect){while(i<array1.length) -result.push(array1[i++]);while(j<array2.length) -result.push(array2[j++]);} -return result;} -Object.defineProperty(Array.prototype,'intersectOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,false);}});Object.defineProperty(Array.prototype,'mergeOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,true);}});})();String.sprintf=function(format,var_arg){return String.vsprintf(format,Array.prototype.slice.call(arguments,1));};String.tokenizeFormatString=function(format,formatters){var tokens=[];var substitutionIndex=0;function addStringToken(str){if(tokens.length&&tokens[tokens.length-1].type==='string') -tokens[tokens.length-1].value+=str;else -tokens.push({type:'string',value:str});} -function addSpecifierToken(specifier,precision,substitutionIndex){tokens.push({type:'specifier',specifier:specifier,precision:precision,substitutionIndex:substitutionIndex});} -var index=0;for(var precentIndex=format.indexOf('%',index);precentIndex!==-1;precentIndex=format.indexOf('%',index)){if(format.length===index) -break;addStringToken(format.substring(index,precentIndex));index=precentIndex+1;if(format[index]==='%'){addStringToken('%');++index;continue;} -if(String.isDigitAt(format,index)){var number=parseInt(format.substring(index),10);while(String.isDigitAt(format,index)) -++index;if(number>0&&format[index]==='$'){substitutionIndex=(number-1);++index;}} -var precision=-1;if(format[index]==='.'){++index;precision=parseInt(format.substring(index),10);if(isNaN(precision)) -precision=0;while(String.isDigitAt(format,index)) -++index;} -if(!(format[index]in formatters)){addStringToken(format.substring(precentIndex,index+1));++index;continue;} -addSpecifierToken(format[index],precision,substitutionIndex);++substitutionIndex;++index;} -addStringToken(format.substring(index));return tokens;};String.standardFormatters={d:function(substitution){return!isNaN(substitution)?substitution:0;},f:function(substitution,token){if(substitution&&token.precision>-1) -substitution=substitution.toFixed(token.precision);return!isNaN(substitution)?substitution:(token.precision>-1?Number(0).toFixed(token.precision):0);},s:function(substitution){return substitution;}};String.vsprintf=function(format,substitutions){return String.format(format,substitutions,String.standardFormatters,'',function(a,b){return a+b;}).formattedResult;};String.format=function(format,substitutions,formatters,initialValue,append,tokenizedFormat){if(!format||!substitutions||!substitutions.length) -return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName(){return'String.format("'+format+'", "'+Array.prototype.join.call(substitutions,'", "')+'")';} -function warn(msg){console.warn(prettyFunctionName()+': '+msg);} -function error(msg){console.error(prettyFunctionName()+': '+msg);} -var result=initialValue;var tokens=tokenizedFormat||String.tokenizeFormatString(format,formatters);var usedSubstitutionIndexes={};for(var i=0;i<tokens.length;++i){var token=tokens[i];if(token.type==='string'){result=append(result,token.value);continue;} -if(token.type!=='specifier'){error('Unknown token type "'+token.type+'" found.');continue;} -if(token.substitutionIndex>=substitutions.length){error('not enough substitution arguments. Had '+substitutions.length+' but needed '+ -(token.substitutionIndex+1)+', so substitution was skipped.');result=append(result,'%'+(token.precision>-1?token.precision:'')+token.specifier);continue;} -usedSubstitutionIndexes[token.substitutionIndex]=true;if(!(token.specifier in formatters)){warn('unsupported format character \u201C'+token.specifier+'\u201D. Treating as a string.');result=append(result,substitutions[token.substitutionIndex]);continue;} -result=append(result,formatters[token.specifier](substitutions[token.substitutionIndex],token));} -var unusedSubstitutions=[];for(var i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes) -continue;unusedSubstitutions.push(substitutions[i]);} -return{formattedResult:result,unusedSubstitutions:unusedSubstitutions};};function createSearchRegex(query,caseSensitive,isRegex){var regexFlags=caseSensitive?'g':'gi';var regexObject;if(isRegex){try{regexObject=new RegExp(query,regexFlags);}catch(e){}} -if(!regexObject) -regexObject=createPlainTextSearchRegex(query,regexFlags);return regexObject;} -function createPlainTextSearchRegex(query,flags){var regexSpecialCharacters=String.regexSpecialCharacters();var regex='';for(var i=0;i<query.length;++i){var c=query.charAt(i);if(regexSpecialCharacters.indexOf(c)!==-1) -regex+='\\';regex+=c;} -return new RegExp(regex,flags||'');} -function countRegexMatches(regex,content){var text=content;var result=0;var match;while(text&&(match=regex.exec(text))){if(match[0].length>0) -++result;text=text.substring(match.index+1);} -return result;} -function spacesPadding(spacesCount){return'\u00a0'.repeat(spacesCount);} -function numberToStringWithSpacesPadding(value,symbolsCount){var numberString=value.toString();var paddingLength=Math.max(0,symbolsCount-numberString.length);return spacesPadding(paddingLength)+numberString;} -Set.prototype.valuesArray=function(){return Array.from(this.values());};Set.prototype.firstValue=function(){if(!this.size) -return null;return this.values().next().value;};Set.prototype.addAll=function(iterable){for(var e of iterable) -this.add(e);};Set.prototype.containsAll=function(iterable){for(var e of iterable){if(!this.has(e)) -return false;} -return true;};Map.prototype.remove=function(key){var value=this.get(key);this.delete(key);return value;};Map.prototype.valuesArray=function(){return Array.from(this.values());};Map.prototype.keysArray=function(){return Array.from(this.keys());};Map.prototype.inverse=function(){var result=new Multimap();for(var key of this.keys()){var value=this.get(key);result.set(value,key);} -return result;};var Multimap=function(){this._map=new Map();};Multimap.prototype={set:function(key,value){var set=this._map.get(key);if(!set){set=new Set();this._map.set(key,set);} -set.add(value);},get:function(key){var result=this._map.get(key);if(!result) -result=new Set();return result;},has:function(key){return this._map.has(key);},hasValue:function(key,value){var set=this._map.get(key);if(!set) -return false;return set.has(value);},get size(){return this._map.size;},delete:function(key,value){var values=this.get(key);if(!values) -return false;var result=values.delete(value);if(!values.size) -this._map.delete(key);return result;},deleteAll:function(key){this._map.delete(key);},keysArray:function(){return this._map.keysArray();},valuesArray:function(){var result=[];var keys=this.keysArray();for(var i=0;i<keys.length;++i) -result.pushAll(this.get(keys[i]).valuesArray());return result;},clear:function(){this._map.clear();}};function loadXHR(url){return new Promise(load);function load(successCallback,failureCallback){function onReadyStateChanged(){if(xhr.readyState!==XMLHttpRequest.DONE) -return;if(xhr.status!==200){xhr.onreadystatechange=null;failureCallback(new Error(xhr.status));return;} -xhr.onreadystatechange=null;successCallback(xhr.responseText);} -var xhr=new XMLHttpRequest();xhr.withCredentials=false;xhr.open('GET',url,true);xhr.onreadystatechange=onReadyStateChanged;xhr.send(null);}} -function suppressUnused(value){} -self.setImmediate=function(callback){const args=[...arguments].slice(1);Promise.resolve().then(()=>callback(...args));return 0;};Promise.prototype.spread=function(callback){return this.then(spreadPromise);function spreadPromise(arg){return callback.apply(null,arg);}};Promise.prototype.catchException=function(defaultValue){return this.catch(function(error){console.error(error);return defaultValue;});};Map.prototype.diff=function(other,isEqual){var leftKeys=this.keysArray();var rightKeys=other.keysArray();leftKeys.sort((a,b)=>a-b);rightKeys.sort((a,b)=>a-b);var removed=[];var added=[];var equal=[];var leftIndex=0;var rightIndex=0;while(leftIndex<leftKeys.length&&rightIndex<rightKeys.length){var leftKey=leftKeys[leftIndex];var rightKey=rightKeys[rightIndex];if(leftKey===rightKey&&isEqual(this.get(leftKey),other.get(rightKey))){equal.push(this.get(leftKey));++leftIndex;++rightIndex;continue;} -if(leftKey<=rightKey){removed.push(this.get(leftKey));++leftIndex;continue;} -added.push(other.get(rightKey));++rightIndex;} -while(leftIndex<leftKeys.length){var leftKey=leftKeys[leftIndex++];removed.push(this.get(leftKey));} -while(rightIndex<rightKeys.length){var rightKey=rightKeys[rightIndex++];added.push(other.get(rightKey));} -return{added:added,removed:removed,equal:equal};};function runOnWindowLoad(callback){function windowLoaded(){self.removeEventListener('DOMContentLoaded',windowLoaded,false);callback();} -if(document.readyState==='complete'||document.readyState==='interactive') -callback();else -self.addEventListener('DOMContentLoaded',windowLoaded,false);} -var _singletonSymbol=Symbol('singleton');function singleton(constructorFunction){if(_singletonSymbol in constructorFunction) -return constructorFunction[_singletonSymbol];var instance=new constructorFunction();constructorFunction[_singletonSymbol]=instance;return instance;};self['TextUtils']=self['TextUtils']||{};TextUtils.Text=class{constructor(value){this._value=value;} -lineEndings(){if(!this._lineEndings) -this._lineEndings=this._value.computeLineEndings();return this._lineEndings;} -value(){return this._value;} -lineCount(){var lineEndings=this.lineEndings();return lineEndings.length;} -offsetFromPosition(lineNumber,columnNumber){return(lineNumber?this.lineEndings()[lineNumber-1]+1:0)+columnNumber;} -positionFromOffset(offset){var lineEndings=this.lineEndings();var lineNumber=lineEndings.lowerBound(offset);return{lineNumber:lineNumber,columnNumber:offset-(lineNumber&&(lineEndings[lineNumber-1]+1))};} -lineAt(lineNumber){var lineEndings=this.lineEndings();var lineStart=lineNumber>0?lineEndings[lineNumber-1]+1:0;var lineEnd=lineEndings[lineNumber];var lineContent=this._value.substring(lineStart,lineEnd);if(lineContent.length>0&&lineContent.charAt(lineContent.length-1)==='\r') -lineContent=lineContent.substring(0,lineContent.length-1);return lineContent;} -toSourceRange(range){var start=this.offsetFromPosition(range.startLine,range.startColumn);var end=this.offsetFromPosition(range.endLine,range.endColumn);return new TextUtils.SourceRange(start,end-start);} -toTextRange(sourceRange){var cursor=new TextUtils.TextCursor(this.lineEndings());var result=TextUtils.TextRange.createFromLocation(0,0);cursor.resetTo(sourceRange.offset);result.startLine=cursor.lineNumber();result.startColumn=cursor.columnNumber();cursor.advance(sourceRange.offset+sourceRange.length);result.endLine=cursor.lineNumber();result.endColumn=cursor.columnNumber();return result;} -replaceRange(range,replacement){var sourceRange=this.toSourceRange(range);return this._value.substring(0,sourceRange.offset)+replacement+ -this._value.substring(sourceRange.offset+sourceRange.length);} -extract(range){var sourceRange=this.toSourceRange(range);return this._value.substr(sourceRange.offset,sourceRange.length);}};TextUtils.Text.Position;TextUtils.TextCursor=class{constructor(lineEndings){this._lineEndings=lineEndings;this._offset=0;this._lineNumber=0;this._columnNumber=0;} -advance(offset){this._offset=offset;while(this._lineNumber<this._lineEndings.length&&this._lineEndings[this._lineNumber]<this._offset) -++this._lineNumber;this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;} -offset(){return this._offset;} -resetTo(offset){this._offset=offset;this._lineNumber=this._lineEndings.lowerBound(offset);this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;} -lineNumber(){return this._lineNumber;} -columnNumber(){return this._columnNumber;}};;TextUtils.TextUtils={isStopChar:function(char){return(char>' '&&char<'0')||(char>'9'&&char<'A')||(char>'Z'&&char<'_')||(char>'_'&&char<'a')||(char>'z'&&char<='~');},isWordChar:function(char){return!TextUtils.TextUtils.isStopChar(char)&&!TextUtils.TextUtils.isSpaceChar(char);},isSpaceChar:function(char){return TextUtils.TextUtils._SpaceCharRegex.test(char);},isWord:function(word){for(var i=0;i<word.length;++i){if(!TextUtils.TextUtils.isWordChar(word.charAt(i))) -return false;} -return true;},isOpeningBraceChar:function(char){return char==='('||char==='{';},isClosingBraceChar:function(char){return char===')'||char==='}';},isBraceChar:function(char){return TextUtils.TextUtils.isOpeningBraceChar(char)||TextUtils.TextUtils.isClosingBraceChar(char);},textToWords:function(text,isWordChar,wordCallback){var startWord=-1;for(var i=0;i<text.length;++i){if(!isWordChar(text.charAt(i))){if(startWord!==-1) -wordCallback(text.substring(startWord,i));startWord=-1;}else if(startWord===-1){startWord=i;}} -if(startWord!==-1) -wordCallback(text.substring(startWord));},lineIndent:function(line){var indentation=0;while(indentation<line.length&&TextUtils.TextUtils.isSpaceChar(line.charAt(indentation))) -++indentation;return line.substr(0,indentation);},isUpperCase:function(text){return text===text.toUpperCase();},isLowerCase:function(text){return text===text.toLowerCase();},splitStringByRegexes(text,regexes){var matches=[];var globalRegexes=[];for(var i=0;i<regexes.length;i++){var regex=regexes[i];if(!regex.global) -globalRegexes.push(new RegExp(regex.source,regex.flags?regex.flags+'g':'g'));else -globalRegexes.push(regex);} -doSplit(text,0,0);return matches;function doSplit(text,regexIndex,startIndex){if(regexIndex>=globalRegexes.length){matches.push({value:text,position:startIndex,regexIndex:-1,captureGroups:[]});return;} -var regex=globalRegexes[regexIndex];var currentIndex=0;var result;regex.lastIndex=0;while((result=regex.exec(text))!==null){var stringBeforeMatch=text.substring(currentIndex,result.index);if(stringBeforeMatch) -doSplit(stringBeforeMatch,regexIndex+1,startIndex+currentIndex);var match=result[0];matches.push({value:match,position:startIndex+result.index,regexIndex:regexIndex,captureGroups:result.slice(1)});currentIndex=result.index+match.length;} -var stringAfterMatches=text.substring(currentIndex);if(stringAfterMatches) -doSplit(stringAfterMatches,regexIndex+1,startIndex+currentIndex);}}};TextUtils.FilterParser=class{constructor(keys){this._keys=keys;} -static cloneFilter(filter){return{key:filter.key,text:filter.text,regex:filter.regex,negative:filter.negative};} -parse(query){var splitResult=TextUtils.TextUtils.splitStringByRegexes(query,[TextUtils.TextUtils._keyValueFilterRegex,TextUtils.TextUtils._regexFilterRegex,TextUtils.TextUtils._textFilterRegex]);var filters=[];for(var i=0;i<splitResult.length;i++){var regexIndex=splitResult[i].regexIndex;if(regexIndex===-1) -continue;var result=splitResult[i].captureGroups;if(regexIndex===0){if(this._keys.indexOf((result[1]))!==-1) -filters.push({key:result[1],text:result[2],negative:!!result[0]});else -filters.push({text:result[1]+':'+result[2],negative:!!result[0]});}else if(regexIndex===1){try{filters.push({regex:new RegExp(result[1],'i'),negative:!!result[0]});}catch(e){filters.push({text:'/'+result[1]+'/',negative:!!result[0]});}}else if(regexIndex===2){filters.push({text:result[1],negative:!!result[0]});}} -return filters;}};TextUtils.FilterParser.ParsedFilter;TextUtils.TextUtils._keyValueFilterRegex=/(?:^|\s)(\-)?([\w\-]+):([^\s]+)/;TextUtils.TextUtils._regexFilterRegex=/(?:^|\s)(\-)?\/([^\s]+)\//;TextUtils.TextUtils._textFilterRegex=/(?:^|\s)(\-)?([^\s]+)/;TextUtils.TextUtils._SpaceCharRegex=/\s/;TextUtils.TextUtils.Indent={TwoSpaces:' ',FourSpaces:' ',EightSpaces:' ',TabCharacter:'\t'};TextUtils.TextUtils.BalancedJSONTokenizer=class{constructor(callback,findMultiple){this._callback=callback;this._index=0;this._balance=0;this._buffer='';this._findMultiple=findMultiple||false;this._closingDoubleQuoteRegex=/[^\\](?:\\\\)*"/g;} -write(chunk){this._buffer+=chunk;var lastIndex=this._buffer.length;var buffer=this._buffer;for(var index=this._index;index<lastIndex;++index){var character=buffer[index];if(character==='"'){this._closingDoubleQuoteRegex.lastIndex=index;if(!this._closingDoubleQuoteRegex.test(buffer)) -break;index=this._closingDoubleQuoteRegex.lastIndex-1;}else if(character==='{'){++this._balance;}else if(character==='}'){--this._balance;if(this._balance<0){this._reportBalanced();return false;} -if(!this._balance){this._lastBalancedIndex=index+1;if(!this._findMultiple) -break;}}else if(character===']'&&!this._balance){this._reportBalanced();return false;}} -this._index=index;this._reportBalanced();return true;} -_reportBalanced(){if(!this._lastBalancedIndex) -return;this._callback(this._buffer.slice(0,this._lastBalancedIndex));this._buffer=this._buffer.slice(this._lastBalancedIndex);this._index-=this._lastBalancedIndex;this._lastBalancedIndex=0;} -remainder(){return this._buffer;}};TextUtils.TokenizerFactory=function(){};TextUtils.TokenizerFactory.prototype={createTokenizer(mimeType){}};TextUtils.isMinified=function(text){var kMaxNonMinifiedLength=500;var linesToCheck=10;var lastPosition=0;do{var eolIndex=text.indexOf('\n',lastPosition);if(eolIndex<0) -eolIndex=text.length;if(eolIndex-lastPosition>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#') -return true;lastPosition=eolIndex+1;}while(--linesToCheck>=0&&lastPosition<text.length);return false;};;TextUtils.TextRange=class{constructor(startLine,startColumn,endLine,endColumn){this.startLine=startLine;this.startColumn=startColumn;this.endLine=endLine;this.endColumn=endColumn;} -static createFromLocation(line,column){return new TextUtils.TextRange(line,column,line,column);} -static fromObject(serializedTextRange){return new TextUtils.TextRange(serializedTextRange.startLine,serializedTextRange.startColumn,serializedTextRange.endLine,serializedTextRange.endColumn);} -static comparator(range1,range2){return range1.compareTo(range2);} -static fromEdit(oldRange,newText){var endLine=oldRange.startLine;var endColumn=oldRange.startColumn+newText.length;var lineEndings=newText.computeLineEndings();if(lineEndings.length>1){endLine=oldRange.startLine+lineEndings.length-1;var len=lineEndings.length;endColumn=lineEndings[len-1]-lineEndings[len-2]-1;} -return new TextUtils.TextRange(oldRange.startLine,oldRange.startColumn,endLine,endColumn);} -isEmpty(){return this.startLine===this.endLine&&this.startColumn===this.endColumn;} -immediatelyPrecedes(range){if(!range) -return false;return this.endLine===range.startLine&&this.endColumn===range.startColumn;} -immediatelyFollows(range){if(!range) -return false;return range.immediatelyPrecedes(this);} -follows(range){return(range.endLine===this.startLine&&range.endColumn<=this.startColumn)||range.endLine<this.startLine;} -get linesCount(){return this.endLine-this.startLine;} -collapseToEnd(){return new TextUtils.TextRange(this.endLine,this.endColumn,this.endLine,this.endColumn);} -collapseToStart(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.startLine,this.startColumn);} -normalize(){if(this.startLine>this.endLine||(this.startLine===this.endLine&&this.startColumn>this.endColumn)) -return new TextUtils.TextRange(this.endLine,this.endColumn,this.startLine,this.startColumn);else -return this.clone();} -clone(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.endLine,this.endColumn);} -serializeToObject(){var serializedTextRange={};serializedTextRange.startLine=this.startLine;serializedTextRange.startColumn=this.startColumn;serializedTextRange.endLine=this.endLine;serializedTextRange.endColumn=this.endColumn;return serializedTextRange;} -compareTo(other){if(this.startLine>other.startLine) -return 1;if(this.startLine<other.startLine) -return-1;if(this.startColumn>other.startColumn) -return 1;if(this.startColumn<other.startColumn) -return-1;return 0;} -compareToPosition(lineNumber,columnNumber){if(lineNumber<this.startLine||(lineNumber===this.startLine&&columnNumber<this.startColumn)) -return-1;if(lineNumber>this.endLine||(lineNumber===this.endLine&&columnNumber>this.endColumn)) -return 1;return 0;} -equal(other){return this.startLine===other.startLine&&this.endLine===other.endLine&&this.startColumn===other.startColumn&&this.endColumn===other.endColumn;} -relativeTo(line,column){var relative=this.clone();if(this.startLine===line) -relative.startColumn-=column;if(this.endLine===line) -relative.endColumn-=column;relative.startLine-=line;relative.endLine-=line;return relative;} -rebaseAfterTextEdit(originalRange,editedRange){console.assert(originalRange.startLine===editedRange.startLine);console.assert(originalRange.startColumn===editedRange.startColumn);var rebase=this.clone();if(!this.follows(originalRange)) -return rebase;var lineDelta=editedRange.endLine-originalRange.endLine;var columnDelta=editedRange.endColumn-originalRange.endColumn;rebase.startLine+=lineDelta;rebase.endLine+=lineDelta;if(rebase.startLine===editedRange.endLine) -rebase.startColumn+=columnDelta;if(rebase.endLine===editedRange.endLine) -rebase.endColumn+=columnDelta;return rebase;} -toString(){return JSON.stringify(this);} -containsLocation(lineNumber,columnNumber){if(this.startLine===this.endLine) -return this.startLine===lineNumber&&this.startColumn<=columnNumber&&columnNumber<=this.endColumn;if(this.startLine===lineNumber) -return this.startColumn<=columnNumber;if(this.endLine===lineNumber) -return columnNumber<=this.endColumn;return this.startLine<lineNumber&&lineNumber<this.endLine;}};TextUtils.SourceRange=class{constructor(offset,length){this.offset=offset;this.length=length;}};TextUtils.SourceEdit=class{constructor(sourceURL,oldRange,newText){this.sourceURL=sourceURL;this.oldRange=oldRange;this.newText=newText;} -static comparator(edit1,edit2){return TextUtils.TextRange.comparator(edit1.oldRange,edit2.oldRange);} -newRange(){return TextUtils.TextRange.fromEdit(this.oldRange,this.newText);}};;self['CmHeadless']=self['CmHeadless']||{};(function(window){window.CodeMirror={};(function(){"use strict";function splitLines(string){return string.split(/\r?\n|\r/);};function StringStream(string){this.pos=this.start=0;this.string=string;this.lineStart=0;} -StringStream.prototype={eol:function(){return this.pos>=this.string.length;},sol:function(){return this.pos==0;},peek:function(){return this.string.charAt(this.pos)||null;},next:function(){if(this.pos<this.string.length) -return this.string.charAt(this.pos++);},eat:function(match){var ch=this.string.charAt(this.pos);if(typeof match=="string")var ok=ch==match;else var ok=ch&&(match.test?match.test(ch):match(ch));if(ok){++this.pos;return ch;}},eatWhile:function(match){var start=this.pos;while(this.eat(match)){} -return this.pos>start;},eatSpace:function(){var start=this.pos;while(/[\s\u00a0]/.test(this.string.charAt(this.pos)))++this.pos;return this.pos>start;},skipToEnd:function(){this.pos=this.string.length;},skipTo:function(ch){var found=this.string.indexOf(ch,this.pos);if(found>-1){this.pos=found;return true;}},backUp:function(n){this.pos-=n;},column:function(){return this.start-this.lineStart;},indentation:function(){return 0;},match:function(pattern,consume,caseInsensitive){if(typeof pattern=="string"){var cased=function(str){return caseInsensitive?str.toLowerCase():str;};var substr=this.string.substr(this.pos,pattern.length);if(cased(substr)==cased(pattern)){if(consume!==false)this.pos+=pattern.length;return true;}}else{var match=this.string.slice(this.pos).match(pattern);if(match&&match.index>0)return null;if(match&&consume!==false)this.pos+=match[0].length;return match;}},current:function(){return this.string.slice(this.start,this.pos);},hideFirstChars:function(n,inner){this.lineStart+=n;try{return inner();} -finally{this.lineStart-=n;}}};CodeMirror.StringStream=StringStream;CodeMirror.startState=function(mode,a1,a2){return mode.startState?mode.startState(a1,a2):true;};var modes=CodeMirror.modes={},mimeModes=CodeMirror.mimeModes={};CodeMirror.defineMode=function(name,mode){if(arguments.length>2) -mode.dependencies=Array.prototype.slice.call(arguments,2);modes[name]=mode;};CodeMirror.defineMIME=function(mime,spec){mimeModes[mime]=spec;};CodeMirror.resolveMode=function(spec){if(typeof spec=="string"&&mimeModes.hasOwnProperty(spec)){spec=mimeModes[spec];}else if(spec&&typeof spec.name=="string"&&mimeModes.hasOwnProperty(spec.name)){spec=mimeModes[spec.name];} -if(typeof spec=="string")return{name:spec};else return spec||{name:"null"};};CodeMirror.getMode=function(options,spec){spec=CodeMirror.resolveMode(spec);var mfactory=modes[spec.name];if(!mfactory)throw new Error("Unknown mode: "+spec);return mfactory(options,spec);};CodeMirror.registerHelper=CodeMirror.registerGlobalHelper=Math.min;CodeMirror.defineMode("null",function(){return{token:function(stream){stream.skipToEnd();}};});CodeMirror.defineMIME("text/plain","null");CodeMirror.runMode=function(string,modespec,callback,options){var mode=CodeMirror.getMode({indentUnit:2},modespec);if(callback.nodeType==1){var tabSize=(options&&options.tabSize)||4;var node=callback,col=0;node.innerHTML="";callback=function(text,style){if(text=="\n"){node.appendChild(document.createElement("br"));col=0;return;} -var content="";for(var pos=0;;){var idx=text.indexOf("\t",pos);if(idx==-1){content+=text.slice(pos);col+=text.length-pos;break;}else{col+=idx-pos;content+=text.slice(pos,idx);var size=tabSize-col%tabSize;col+=size;for(var i=0;i<size;++i)content+=" ";pos=idx+1;}} -if(style){var sp=node.appendChild(document.createElement("span"));sp.className="cm-"+style.replace(/ +/g," cm-");sp.appendChild(document.createTextNode(content));}else{node.appendChild(document.createTextNode(content));}};} -var lines=splitLines(string),state=(options&&options.state)||CodeMirror.startState(mode);for(var i=0,e=lines.length;i<e;++i){if(i)callback("\n");var stream=new CodeMirror.StringStream(lines[i]);if(!stream.string&&mode.blankLine)mode.blankLine(state);while(!stream.eol()){var style=mode.token(stream,state);callback(stream.current(),style,i,stream.start,state);stream.start=stream.pos;}}};})();}(this));self['FormatterWorker']=self['FormatterWorker']||{};(function(mod){if(typeof exports=="object"&&typeof module=="object") -mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd) -define(["../../lib/codemirror"],mod);else -mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.defineMode("css",function(config,parserConfig){var inline=parserConfig.inline -if(!parserConfig.propertyKeywords)parserConfig=CodeMirror.resolveMode("text/css");var indentUnit=config.indentUnit,tokenHooks=parserConfig.tokenHooks,documentTypes=parserConfig.documentTypes||{},mediaTypes=parserConfig.mediaTypes||{},mediaFeatures=parserConfig.mediaFeatures||{},mediaValueKeywords=parserConfig.mediaValueKeywords||{},propertyKeywords=parserConfig.propertyKeywords||{},nonStandardPropertyKeywords=parserConfig.nonStandardPropertyKeywords||{},fontProperties=parserConfig.fontProperties||{},counterDescriptors=parserConfig.counterDescriptors||{},colorKeywords=parserConfig.colorKeywords||{},valueKeywords=parserConfig.valueKeywords||{},allowNested=parserConfig.allowNested,lineComment=parserConfig.lineComment,supportsAtComponent=parserConfig.supportsAtComponent===true;var type,override;function ret(style,tp){type=tp;return style;} -function tokenBase(stream,state){var ch=stream.next();if(tokenHooks[ch]){var result=tokenHooks[ch](stream,state);if(result!==false)return result;} -if(ch=="@"){stream.eatWhile(/[\w\\\-]/);return ret("def",stream.current());}else if(ch=="="||(ch=="~"||ch=="|")&&stream.eat("=")){return ret(null,"compare");}else if(ch=="\""||ch=="'"){state.tokenize=tokenString(ch);return state.tokenize(stream,state);}else if(ch=="#"){stream.eatWhile(/[\w\\\-]/);return ret("atom","hash");}else if(ch=="!"){stream.match(/^\s*\w*/);return ret("keyword","important");}else if(/\d/.test(ch)||ch=="."&&stream.eat(/\d/)){stream.eatWhile(/[\w.%]/);return ret("number","unit");}else if(ch==="-"){if(/[\d.]/.test(stream.peek())){stream.eatWhile(/[\w.%]/);return ret("number","unit");}else if(stream.match(/^-[\w\\\-]+/)){stream.eatWhile(/[\w\\\-]/);if(stream.match(/^\s*:/,false)) -return ret("variable-2","variable-definition");return ret("variable-2","variable");}else if(stream.match(/^\w+-/)){return ret("meta","meta");}}else if(/[,+>*\/]/.test(ch)){return ret(null,"select-op");}else if(ch=="."&&stream.match(/^-?[_a-z][_a-z0-9-]*/i)){return ret("qualifier","qualifier");}else if(/[:;{}\[\]\(\)]/.test(ch)){return ret(null,ch);}else if((ch=="u"&&stream.match(/rl(-prefix)?\(/))||(ch=="d"&&stream.match("omain("))||(ch=="r"&&stream.match("egexp("))){stream.backUp(1);state.tokenize=tokenParenthesized;return ret("property","word");}else if(/[\w\\\-]/.test(ch)){stream.eatWhile(/[\w\\\-]/);return ret("property","word");}else{return ret(null,null);}} -function tokenString(quote){return function(stream,state){var escaped=false,ch;while((ch=stream.next())!=null){if(ch==quote&&!escaped){if(quote==")")stream.backUp(1);break;} -escaped=!escaped&&ch=="\\";} -if(ch==quote||!escaped&"e!=")")state.tokenize=null;return ret("string","string");};} -function tokenParenthesized(stream,state){stream.next();if(!stream.match(/\s*[\"\')]/,false)) -state.tokenize=tokenString(")");else -state.tokenize=null;return ret(null,"(");} -function Context(type,indent,prev){this.type=type;this.indent=indent;this.prev=prev;} -function pushContext(state,stream,type,indent){state.context=new Context(type,stream.indentation()+(indent===false?0:indentUnit),state.context);return type;} -function popContext(state){if(state.context.prev) -state.context=state.context.prev;return state.context.type;} -function pass(type,stream,state){return states[state.context.type](type,stream,state);} -function popAndPass(type,stream,state,n){for(var i=n||1;i>0;i--) -state.context=state.context.prev;return pass(type,stream,state);} -function wordAsValue(stream){var word=stream.current().toLowerCase();if(valueKeywords.hasOwnProperty(word)) -override="atom";else if(colorKeywords.hasOwnProperty(word)) -override="keyword";else -override="variable";} -var states={};states.top=function(type,stream,state){if(type=="{"){return pushContext(state,stream,"block");}else if(type=="}"&&state.context.prev){return popContext(state);}else if(supportsAtComponent&&/@component/.test(type)){return pushContext(state,stream,"atComponentBlock");}else if(/^@(-moz-)?document$/.test(type)){return pushContext(state,stream,"documentTypes");}else if(/^@(media|supports|(-moz-)?document|import)$/.test(type)){return pushContext(state,stream,"atBlock");}else if(/^@(font-face|counter-style)/.test(type)){state.stateArg=type;return"restricted_atBlock_before";}else if(/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)){return"keyframes";}else if(type&&type.charAt(0)=="@"){return pushContext(state,stream,"at");}else if(type=="hash"){override="builtin";}else if(type=="word"){override="tag";}else if(type=="variable-definition"){return"maybeprop";}else if(type=="interpolation"){return pushContext(state,stream,"interpolation");}else if(type==":"){return"pseudo";}else if(allowNested&&type=="("){return pushContext(state,stream,"parens");} -return state.context.type;};states.block=function(type,stream,state){if(type=="word"){var word=stream.current().toLowerCase();if(propertyKeywords.hasOwnProperty(word)){override="property";return"maybeprop";}else if(nonStandardPropertyKeywords.hasOwnProperty(word)){override="string-2";return"maybeprop";}else if(allowNested){override=stream.match(/^\s*:(?:\s|$)/,false)?"property":"tag";return"block";}else{override+=" error";return"maybeprop";}}else if(type=="meta"){return"block";}else if(!allowNested&&(type=="hash"||type=="qualifier")){override="error";return"block";}else{return states.top(type,stream,state);}};states.maybeprop=function(type,stream,state){if(type==":")return pushContext(state,stream,"prop");return pass(type,stream,state);};states.prop=function(type,stream,state){if(type==";")return popContext(state);if(type=="{"&&allowNested)return pushContext(state,stream,"propBlock");if(type=="}"||type=="{")return popAndPass(type,stream,state);if(type=="(")return pushContext(state,stream,"parens");if(type=="hash"&&!/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())){override+=" error";}else if(type=="word"){wordAsValue(stream);}else if(type=="interpolation"){return pushContext(state,stream,"interpolation");} -return"prop";};states.propBlock=function(type,_stream,state){if(type=="}")return popContext(state);if(type=="word"){override="property";return"maybeprop";} -return state.context.type;};states.parens=function(type,stream,state){if(type=="{"||type=="}")return popAndPass(type,stream,state);if(type==")")return popContext(state);if(type=="(")return pushContext(state,stream,"parens");if(type=="interpolation")return pushContext(state,stream,"interpolation");if(type=="word")wordAsValue(stream);return"parens";};states.pseudo=function(type,stream,state){if(type=="meta")return"pseudo";if(type=="word"){override="variable-3";return state.context.type;} -return pass(type,stream,state);};states.documentTypes=function(type,stream,state){if(type=="word"&&documentTypes.hasOwnProperty(stream.current())){override="tag";return state.context.type;}else{return states.atBlock(type,stream,state);}};states.atBlock=function(type,stream,state){if(type=="(")return pushContext(state,stream,"atBlock_parens");if(type=="}"||type==";")return popAndPass(type,stream,state);if(type=="{")return popContext(state)&&pushContext(state,stream,allowNested?"block":"top");if(type=="interpolation")return pushContext(state,stream,"interpolation");if(type=="word"){var word=stream.current().toLowerCase();if(word=="only"||word=="not"||word=="and"||word=="or") -override="keyword";else if(mediaTypes.hasOwnProperty(word)) -override="attribute";else if(mediaFeatures.hasOwnProperty(word)) -override="property";else if(mediaValueKeywords.hasOwnProperty(word)) -override="keyword";else if(propertyKeywords.hasOwnProperty(word)) -override="property";else if(nonStandardPropertyKeywords.hasOwnProperty(word)) -override="string-2";else if(valueKeywords.hasOwnProperty(word)) -override="atom";else if(colorKeywords.hasOwnProperty(word)) -override="keyword";else -override="error";} -return state.context.type;};states.atComponentBlock=function(type,stream,state){if(type=="}") -return popAndPass(type,stream,state);if(type=="{") -return popContext(state)&&pushContext(state,stream,allowNested?"block":"top",false);if(type=="word") -override="error";return state.context.type;};states.atBlock_parens=function(type,stream,state){if(type==")")return popContext(state);if(type=="{"||type=="}")return popAndPass(type,stream,state,2);return states.atBlock(type,stream,state);};states.restricted_atBlock_before=function(type,stream,state){if(type=="{") -return pushContext(state,stream,"restricted_atBlock");if(type=="word"&&state.stateArg=="@counter-style"){override="variable";return"restricted_atBlock_before";} -return pass(type,stream,state);};states.restricted_atBlock=function(type,stream,state){if(type=="}"){state.stateArg=null;return popContext(state);} -if(type=="word"){if((state.stateArg=="@font-face"&&!fontProperties.hasOwnProperty(stream.current().toLowerCase()))||(state.stateArg=="@counter-style"&&!counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) -override="error";else -override="property";return"maybeprop";} -return"restricted_atBlock";};states.keyframes=function(type,stream,state){if(type=="word"){override="variable";return"keyframes";} -if(type=="{")return pushContext(state,stream,"top");return pass(type,stream,state);};states.at=function(type,stream,state){if(type==";")return popContext(state);if(type=="{"||type=="}")return popAndPass(type,stream,state);if(type=="word")override="tag";else if(type=="hash")override="builtin";return"at";};states.interpolation=function(type,stream,state){if(type=="}")return popContext(state);if(type=="{"||type==";")return popAndPass(type,stream,state);if(type=="word")override="variable";else if(type!="variable"&&type!="("&&type!=")")override="error";return"interpolation";};return{startState:function(base){return{tokenize:null,state:inline?"block":"top",stateArg:null,context:new Context(inline?"block":"top",base||0,null)};},token:function(stream,state){if(!state.tokenize&&stream.eatSpace())return null;var style=(state.tokenize||tokenBase)(stream,state);if(style&&typeof style=="object"){type=style[1];style=style[0];} -override=style;state.state=states[state.state](type,stream,state);return override;},indent:function(state,textAfter){var cx=state.context,ch=textAfter&&textAfter.charAt(0);var indent=cx.indent;if(cx.type=="prop"&&(ch=="}"||ch==")"))cx=cx.prev;if(cx.prev){if(ch=="}"&&(cx.type=="block"||cx.type=="top"||cx.type=="interpolation"||cx.type=="restricted_atBlock")){cx=cx.prev;indent=cx.indent;}else if(ch==")"&&(cx.type=="parens"||cx.type=="atBlock_parens")||ch=="{"&&(cx.type=="at"||cx.type=="atBlock")){indent=Math.max(0,cx.indent-indentUnit);cx=cx.prev;}} -return indent;},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:lineComment,fold:"brace"};});function keySet(array){var keys={};for(var i=0;i<array.length;++i){keys[array[i].toLowerCase()]=true;} -return keys;} -var documentTypes_=["domain","regexp","url","url-prefix"],documentTypes=keySet(documentTypes_);var mediaTypes_=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],mediaTypes=keySet(mediaTypes_);var mediaFeatures_=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover"],mediaFeatures=keySet(mediaFeatures_);var mediaValueKeywords_=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],mediaValueKeywords=keySet(mediaValueKeywords_);var propertyKeywords_=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","user-select","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","will-change","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],propertyKeywords=keySet(propertyKeywords_);var nonStandardPropertyKeywords_=["scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","shape-inside","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","zoom"],nonStandardPropertyKeywords=keySet(nonStandardPropertyKeywords_);var fontProperties_=["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"],fontProperties=keySet(fontProperties_);var counterDescriptors_=["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"],counterDescriptors=keySet(counterDescriptors_);var colorKeywords_=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],colorKeywords=keySet(colorKeywords_);var valueKeywords_=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","devanagari","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","georgian","graytext","grid","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hard-light","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","luminosity","malayalam","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","multiply","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","opacity","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","spell-out","square","square-button","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unset","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],valueKeywords=keySet(valueKeywords_);var allWords=documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_).concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_).concat(valueKeywords_);CodeMirror.registerHelper("hintWords","css",allWords);function tokenCComment(stream,state){var maybeEnd=false,ch;while((ch=stream.next())!=null){if(maybeEnd&&ch=="/"){state.tokenize=null;break;} -maybeEnd=(ch=="*");} -return["comment","comment"];} -CodeMirror.defineMIME("text/css",{documentTypes:documentTypes,mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,fontProperties:fontProperties,counterDescriptors:counterDescriptors,colorKeywords:colorKeywords,valueKeywords:valueKeywords,tokenHooks:{"/":function(stream,state){if(!stream.eat("*"))return false;state.tokenize=tokenCComment;return tokenCComment(stream,state);}},name:"css"});CodeMirror.defineMIME("text/x-scss",{mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,colorKeywords:colorKeywords,valueKeywords:valueKeywords,fontProperties:fontProperties,allowNested:true,lineComment:"//",tokenHooks:{"/":function(stream,state){if(stream.eat("/")){stream.skipToEnd();return["comment","comment"];}else if(stream.eat("*")){state.tokenize=tokenCComment;return tokenCComment(stream,state);}else{return["operator","operator"];}},":":function(stream){if(stream.match(/\s*\{/)) -return[null,"{"];return false;},"$":function(stream){stream.match(/^[\w-]+/);if(stream.match(/^\s*:/,false)) -return["variable-2","variable-definition"];return["variable-2","variable"];},"#":function(stream){if(!stream.eat("{"))return false;return[null,"interpolation"];}},name:"css",helperType:"scss"});CodeMirror.defineMIME("text/x-less",{mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,colorKeywords:colorKeywords,valueKeywords:valueKeywords,fontProperties:fontProperties,allowNested:true,lineComment:"//",tokenHooks:{"/":function(stream,state){if(stream.eat("/")){stream.skipToEnd();return["comment","comment"];}else if(stream.eat("*")){state.tokenize=tokenCComment;return tokenCComment(stream,state);}else{return["operator","operator"];}},"@":function(stream){if(stream.eat("{"))return[null,"interpolation"];if(stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/,false))return false;stream.eatWhile(/[\w\\\-]/);if(stream.match(/^\s*:/,false)) -return["variable-2","variable-definition"];return["variable-2","variable"];},"&":function(){return["atom","atom"];}},name:"css",helperType:"less"});CodeMirror.defineMIME("text/x-gss",{documentTypes:documentTypes,mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,fontProperties:fontProperties,counterDescriptors:counterDescriptors,colorKeywords:colorKeywords,valueKeywords:valueKeywords,supportsAtComponent:true,tokenHooks:{"/":function(stream,state){if(!stream.eat("*"))return false;state.tokenize=tokenCComment;return tokenCComment(stream,state);}},name:"css",helperType:"gss"});});;(function(mod){if(typeof exports=="object"&&typeof module=="object") -mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd) -define(["../../lib/codemirror"],mod);else -mod(CodeMirror);})(function(CodeMirror){"use strict";var htmlConfig={autoSelfClosers:{'area':true,'base':true,'br':true,'col':true,'command':true,'embed':true,'frame':true,'hr':true,'img':true,'input':true,'keygen':true,'link':true,'meta':true,'param':true,'source':true,'track':true,'wbr':true,'menuitem':true},implicitlyClosed:{'dd':true,'li':true,'optgroup':true,'option':true,'p':true,'rp':true,'rt':true,'tbody':true,'td':true,'tfoot':true,'th':true,'tr':true},contextGrabbers:{'dd':{'dd':true,'dt':true},'dt':{'dd':true,'dt':true},'li':{'li':true},'option':{'option':true,'optgroup':true},'optgroup':{'optgroup':true},'p':{'address':true,'article':true,'aside':true,'blockquote':true,'dir':true,'div':true,'dl':true,'fieldset':true,'footer':true,'form':true,'h1':true,'h2':true,'h3':true,'h4':true,'h5':true,'h6':true,'header':true,'hgroup':true,'hr':true,'menu':true,'nav':true,'ol':true,'p':true,'pre':true,'section':true,'table':true,'ul':true},'rp':{'rp':true,'rt':true},'rt':{'rp':true,'rt':true},'tbody':{'tbody':true,'tfoot':true},'td':{'td':true,'th':true},'tfoot':{'tbody':true},'th':{'td':true,'th':true},'thead':{'tbody':true,'tfoot':true},'tr':{'tr':true}},doNotIndent:{"pre":true},allowUnquoted:true,allowMissing:true,caseFold:true} -var xmlConfig={autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:false,allowMissing:false,caseFold:false} -CodeMirror.defineMode("xml",function(editorConf,config_){var indentUnit=editorConf.indentUnit -var config={} -var defaults=config_.htmlMode?htmlConfig:xmlConfig -for(var prop in defaults)config[prop]=defaults[prop] -for(var prop in config_)config[prop]=config_[prop] -var type,setStyle;function inText(stream,state){function chain(parser){state.tokenize=parser;return parser(stream,state);} -var ch=stream.next();if(ch=="<"){if(stream.eat("!")){if(stream.eat("[")){if(stream.match("CDATA["))return chain(inBlock("atom","]]>"));else return null;}else if(stream.match("--")){return chain(inBlock("comment","-->"));}else if(stream.match("DOCTYPE",true,true)){stream.eatWhile(/[\w\._\-]/);return chain(doctype(1));}else{return null;}}else if(stream.eat("?")){stream.eatWhile(/[\w\._\-]/);state.tokenize=inBlock("meta","?>");return"meta";}else{type=stream.eat("/")?"closeTag":"openTag";state.tokenize=inTag;return"tag bracket";}}else if(ch=="&"){var ok;if(stream.eat("#")){if(stream.eat("x")){ok=stream.eatWhile(/[a-fA-F\d]/)&&stream.eat(";");}else{ok=stream.eatWhile(/[\d]/)&&stream.eat(";");}}else{ok=stream.eatWhile(/[\w\.\-:]/)&&stream.eat(";");} -return ok?"atom":"error";}else{stream.eatWhile(/[^&<]/);return null;}} -inText.isInText=true;function inTag(stream,state){var ch=stream.next();if(ch==">"||(ch=="/"&&stream.eat(">"))){state.tokenize=inText;type=ch==">"?"endTag":"selfcloseTag";return"tag bracket";}else if(ch=="="){type="equals";return null;}else if(ch=="<"){state.tokenize=inText;state.state=baseState;state.tagName=state.tagStart=null;var next=state.tokenize(stream,state);return next?next+" tag error":"tag error";}else if(/[\'\"]/.test(ch)){state.tokenize=inAttribute(ch);state.stringStartCol=stream.column();return state.tokenize(stream,state);}else{stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);return"word";}} -function inAttribute(quote){var closure=function(stream,state){while(!stream.eol()){if(stream.next()==quote){state.tokenize=inTag;break;}} -return"string";};closure.isInAttribute=true;return closure;} -function inBlock(style,terminator){return function(stream,state){while(!stream.eol()){if(stream.match(terminator)){state.tokenize=inText;break;} -stream.next();} -return style;};} -function doctype(depth){return function(stream,state){var ch;while((ch=stream.next())!=null){if(ch=="<"){state.tokenize=doctype(depth+1);return state.tokenize(stream,state);}else if(ch==">"){if(depth==1){state.tokenize=inText;break;}else{state.tokenize=doctype(depth-1);return state.tokenize(stream,state);}}} -return"meta";};} -function Context(state,tagName,startOfLine){this.prev=state.context;this.tagName=tagName;this.indent=state.indented;this.startOfLine=startOfLine;if(config.doNotIndent.hasOwnProperty(tagName)||(state.context&&state.context.noIndent)) -this.noIndent=true;} -function popContext(state){if(state.context)state.context=state.context.prev;} -function maybePopContext(state,nextTagName){var parentTagName;while(true){if(!state.context){return;} -parentTagName=state.context.tagName;if(!config.contextGrabbers.hasOwnProperty(parentTagName)||!config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)){return;} -popContext(state);}} -function baseState(type,stream,state){if(type=="openTag"){state.tagStart=stream.column();return tagNameState;}else if(type=="closeTag"){return closeTagNameState;}else{return baseState;}} -function tagNameState(type,stream,state){if(type=="word"){state.tagName=stream.current();setStyle="tag";return attrState;}else{setStyle="error";return tagNameState;}} -function closeTagNameState(type,stream,state){if(type=="word"){var tagName=stream.current();if(state.context&&state.context.tagName!=tagName&&config.implicitlyClosed.hasOwnProperty(state.context.tagName)) -popContext(state);if((state.context&&state.context.tagName==tagName)||config.matchClosing===false){setStyle="tag";return closeState;}else{setStyle="tag error";return closeStateErr;}}else{setStyle="error";return closeStateErr;}} -function closeState(type,_stream,state){if(type!="endTag"){setStyle="error";return closeState;} -popContext(state);return baseState;} -function closeStateErr(type,stream,state){setStyle="error";return closeState(type,stream,state);} -function attrState(type,_stream,state){if(type=="word"){setStyle="attribute";return attrEqState;}else if(type=="endTag"||type=="selfcloseTag"){var tagName=state.tagName,tagStart=state.tagStart;state.tagName=state.tagStart=null;if(type=="selfcloseTag"||config.autoSelfClosers.hasOwnProperty(tagName)){maybePopContext(state,tagName);}else{maybePopContext(state,tagName);state.context=new Context(state,tagName,tagStart==state.indented);} -return baseState;} -setStyle="error";return attrState;} -function attrEqState(type,stream,state){if(type=="equals")return attrValueState;if(!config.allowMissing)setStyle="error";return attrState(type,stream,state);} -function attrValueState(type,stream,state){if(type=="string")return attrContinuedState;if(type=="word"&&config.allowUnquoted){setStyle="string";return attrState;} -setStyle="error";return attrState(type,stream,state);} -function attrContinuedState(type,stream,state){if(type=="string")return attrContinuedState;return attrState(type,stream,state);} -return{startState:function(baseIndent){var state={tokenize:inText,state:baseState,indented:baseIndent||0,tagName:null,tagStart:null,context:null} -if(baseIndent!=null)state.baseIndent=baseIndent -return state},token:function(stream,state){if(!state.tagName&&stream.sol()) -state.indented=stream.indentation();if(stream.eatSpace())return null;type=null;var style=state.tokenize(stream,state);if((style||type)&&style!="comment"){setStyle=null;state.state=state.state(type||style,stream,state);if(setStyle) -style=setStyle=="error"?style+" error":setStyle;} -return style;},indent:function(state,textAfter,fullLine){var context=state.context;if(state.tokenize.isInAttribute){if(state.tagStart==state.indented) -return state.stringStartCol+1;else -return state.indented+indentUnit;} -if(context&&context.noIndent)return CodeMirror.Pass;if(state.tokenize!=inTag&&state.tokenize!=inText) -return fullLine?fullLine.match(/^(\s*)/)[0].length:0;if(state.tagName){if(config.multilineTagIndentPastTag!==false) -return state.tagStart+state.tagName.length+2;else -return state.tagStart+indentUnit*(config.multilineTagIndentFactor||1);} -if(config.alignCDATA&&/<!\[CDATA\[/.test(textAfter))return 0;var tagAfter=textAfter&&/^<(\/)?([\w_:\.-]*)/.exec(textAfter);if(tagAfter&&tagAfter[1]){while(context){if(context.tagName==tagAfter[2]){context=context.prev;break;}else if(config.implicitlyClosed.hasOwnProperty(context.tagName)){context=context.prev;}else{break;}}}else if(tagAfter){while(context){var grabbers=config.contextGrabbers[context.tagName];if(grabbers&&grabbers.hasOwnProperty(tagAfter[2])) -context=context.prev;else -break;}} -while(context&&context.prev&&!context.startOfLine) -context=context.prev;if(context)return context.indent+indentUnit;else return state.baseIndent||0;},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:config.htmlMode?"html":"xml",helperType:config.htmlMode?"html":"xml",skipAttribute:function(state){if(state.state==attrValueState) -state.state=attrState}};});CodeMirror.defineMIME("text/xml","xml");CodeMirror.defineMIME("application/xml","xml");if(!CodeMirror.mimeModes.hasOwnProperty("text/html")) -CodeMirror.defineMIME("text/html",{name:"xml",htmlMode:true});});;FormatterWorker.ESTreeWalker=class{constructor(beforeVisit,afterVisit){this._beforeVisit=beforeVisit;this._afterVisit=afterVisit||new Function();this._walkNulls=false;} -setWalkNulls(value){this._walkNulls=value;} -walk(ast){this._innerWalk(ast,null);} -_innerWalk(node,parent){if(!node&&parent&&this._walkNulls){var result=({raw:'null',value:null});result.type='Literal';node=(result);} -if(!node) -return;node.parent=parent;if(this._beforeVisit.call(null,node)===FormatterWorker.ESTreeWalker.SkipSubtree){this._afterVisit.call(null,node);return;} -var walkOrder=FormatterWorker.ESTreeWalker._walkOrder[node.type];if(!walkOrder){console.error('Walk order not defined for '+node.type);return;} -if(node.type==='TemplateLiteral'){var templateLiteral=(node);var expressionsLength=templateLiteral.expressions.length;for(var i=0;i<expressionsLength;++i){this._innerWalk(templateLiteral.quasis[i],templateLiteral);this._innerWalk(templateLiteral.expressions[i],templateLiteral);} -this._innerWalk(templateLiteral.quasis[expressionsLength],templateLiteral);}else{for(var i=0;i<walkOrder.length;++i){var entity=node[walkOrder[i]];if(Array.isArray(entity)) -this._walkArray(entity,node);else -this._innerWalk(entity,node);}} -this._afterVisit.call(null,node);} -_walkArray(nodeArray,parentNode){for(var i=0;i<nodeArray.length;++i) -this._innerWalk(nodeArray[i],parentNode);}};FormatterWorker.ESTreeWalker.SkipSubtree={};FormatterWorker.ESTreeWalker._walkOrder={'AwaitExpression':['arguments'],'ArrayExpression':['elements'],'ArrayPattern':['elements'],'ArrowFunctionExpression':['params','body'],'AssignmentExpression':['left','right'],'BinaryExpression':['left','right'],'BlockStatement':['body'],'BreakStatement':['label'],'CallExpression':['callee','arguments'],'CatchClause':['param','body'],'ClassBody':['body'],'ClassDeclaration':['id','superClass','body'],'ClassExpression':['id','superClass','body'],'ConditionalExpression':['test','consequent','alternate'],'ContinueStatement':['label'],'DebuggerStatement':[],'DoWhileStatement':['body','test'],'EmptyStatement':[],'ExpressionStatement':['expression'],'ForInStatement':['left','right','body'],'ForOfStatement':['left','right','body'],'ForStatement':['init','test','update','body'],'FunctionDeclaration':['id','params','body'],'FunctionExpression':['id','params','body'],'Identifier':[],'IfStatement':['test','consequent','alternate'],'LabeledStatement':['label','body'],'Literal':[],'LogicalExpression':['left','right'],'MemberExpression':['object','property'],'MethodDefinition':['key','value'],'NewExpression':['callee','arguments'],'ObjectExpression':['properties'],'ObjectPattern':['properties'],'ParenthesizedExpression':['expression'],'Program':['body'],'Property':['key','value'],'ReturnStatement':['argument'],'SequenceExpression':['expressions'],'Super':[],'SwitchCase':['test','consequent'],'SwitchStatement':['discriminant','cases'],'TaggedTemplateExpression':['tag','quasi'],'TemplateElement':[],'TemplateLiteral':['quasis','expressions'],'ThisExpression':[],'ThrowStatement':['argument'],'TryStatement':['block','handler','finalizer'],'UnaryExpression':['argument'],'UpdateExpression':['argument'],'VariableDeclaration':['declarations'],'VariableDeclarator':['id','init'],'WhileStatement':['test','body'],'WithStatement':['object','body'],'YieldExpression':['argument']};;FormatterWorker.createTokenizer=function(mimeType){var mode=CodeMirror.getMode({indentUnit:2},mimeType);var state=CodeMirror.startState(mode);function tokenize(line,callback){var stream=new CodeMirror.StringStream(line);while(!stream.eol()){var style=mode.token(stream,state);var value=stream.current();if(callback(value,style,stream.start,stream.start+value.length)===FormatterWorker.AbortTokenization) -return;stream.start=stream.pos;}} -return tokenize;};FormatterWorker.AbortTokenization={};self.onmessage=function(event){var method=(event.data.method);var params=(event.data.params);if(!method) -return;switch(method){case'format':FormatterWorker.format(params.mimeType,params.content,params.indentString);break;case'parseCSS':FormatterWorker.parseCSS(params.content);break;case'parseSCSS':FormatterWorker.FormatterWorkerContentParser.parse(params.content,'text/x-scss');break;case'javaScriptOutline':FormatterWorker.javaScriptOutline(params.content);break;case'javaScriptIdentifiers':FormatterWorker.javaScriptIdentifiers(params.content);break;case'evaluatableJavaScriptSubstring':FormatterWorker.evaluatableJavaScriptSubstring(params.content);break;case'parseJSONRelaxed':FormatterWorker.parseJSONRelaxed(params.content);break;case'preprocessTopLevelAwaitExpressions':FormatterWorker.preprocessTopLevelAwaitExpressions(params.content);break;default:console.error('Unsupport method name: '+method);}};FormatterWorker.parseJSONRelaxed=function(content){postMessage(FormatterWorker.RelaxedJSONParser.parse(content));};FormatterWorker.evaluatableJavaScriptSubstring=function(content){var tokenizer=acorn.tokenizer(content,{ecmaVersion:8});var result='';try{var token=tokenizer.getToken();while(token.type!==acorn.tokTypes.eof&&FormatterWorker.AcornTokenizer.punctuator(token)) -token=tokenizer.getToken();var startIndex=token.start;var endIndex=token.end;var openBracketsCounter=0;while(token.type!==acorn.tokTypes.eof){var isIdentifier=FormatterWorker.AcornTokenizer.identifier(token);var isThis=FormatterWorker.AcornTokenizer.keyword(token,'this');var isString=token.type===acorn.tokTypes.string;if(!isThis&&!isIdentifier&&!isString) -break;endIndex=token.end;token=tokenizer.getToken();while(FormatterWorker.AcornTokenizer.punctuator(token,'.[]')){if(FormatterWorker.AcornTokenizer.punctuator(token,'[')) -openBracketsCounter++;if(FormatterWorker.AcornTokenizer.punctuator(token,']')){endIndex=openBracketsCounter>0?token.end:endIndex;openBracketsCounter--;} -token=tokenizer.getToken();}} -result=content.substring(startIndex,endIndex);}catch(e){console.error(e);} -postMessage(result);};FormatterWorker.preprocessTopLevelAwaitExpressions=function(content){var wrapped='(async () => {'+content+'})()';var root=acorn.parse(wrapped,{ecmaVersion:8});var body=root.body[0].expression.callee.body;var changes=[];var containsAwait=false;var containsReturn=false;class Visitor{ClassDeclaration(node){if(node.parent===body) -changes.push({text:node.id.name+'=',start:node.start,end:node.start});} -FunctionDeclaration(node){changes.push({text:node.id.name+'=',start:node.start,end:node.start});return FormatterWorker.ESTreeWalker.SkipSubtree;} -FunctionExpression(node){return FormatterWorker.ESTreeWalker.SkipSubtree;} -ArrowFunctionExpression(node){return FormatterWorker.ESTreeWalker.SkipSubtree;} -MethodDefinition(node){return FormatterWorker.ESTreeWalker.SkipSubtree;} -AwaitExpression(node){containsAwait=true;} -ReturnStatement(node){containsReturn=true;} -VariableDeclaration(node){if(node.kind!=='var'&&node.parent!==body) -return;var onlyOneDeclaration=node.declarations.length===1;changes.push({text:onlyOneDeclaration?'void':'void (',start:node.start,end:node.start+node.kind.length});for(var declaration of node.declarations){if(!declaration.init){changes.push({text:'(',start:declaration.start,end:declaration.start});changes.push({text:'=undefined)',start:declaration.end,end:declaration.end});continue;} -changes.push({text:'(',start:declaration.start,end:declaration.start});changes.push({text:')',start:declaration.end,end:declaration.end});} -if(!onlyOneDeclaration){var last=node.declarations.peekLast();changes.push({text:')',start:last.end,end:last.end});}}} -var walker=new FormatterWorker.ESTreeWalker(visit.bind(new Visitor()));walker.walk(body);function visit(node){if(node.type in this) -return this[node.type](node);} -if(!containsAwait||containsReturn){postMessage('');return;} -var last=body.body[body.body.length-1];if(last.type==='ExpressionStatement'){changes.push({text:'return (',start:last.start,end:last.start});if(wrapped[last.end-1]!==';') -changes.push({text:')',start:last.end,end:last.end});else -changes.push({text:')',start:last.end-1,end:last.end-1});} -while(changes.length){var change=changes.pop();wrapped=wrapped.substr(0,change.start)+change.text+wrapped.substr(change.end);} -postMessage(wrapped);};FormatterWorker.javaScriptIdentifiers=function(content){var root=acorn.parse(content,{ranges:false,ecmaVersion:8});var identifiers=[];var walker=new FormatterWorker.ESTreeWalker(beforeVisit);function isFunction(node){return node.type==='FunctionDeclaration'||node.type==='FunctionExpression'||node.type==='ArrowFunctionExpression';} -function beforeVisit(node){if(isFunction(node)){if(node.id) -identifiers.push(node.id);return FormatterWorker.ESTreeWalker.SkipSubtree;} -if(node.type!=='Identifier') -return;if(node.parent&&node.parent.type==='MemberExpression'&&node.parent.property===node&&!node.parent.computed) -return;identifiers.push(node);} -if(!root||root.type!=='Program'||root.body.length!==1||!isFunction(root.body[0])){postMessage([]);return;} -var functionNode=root.body[0];for(var param of functionNode.params) -walker.walk(param);walker.walk(functionNode.body);var reduced=identifiers.map(id=>({name:id.name,offset:id.start}));postMessage(reduced);};FormatterWorker.format=function(mimeType,text,indentString){indentString=indentString||' ';var result={};var builder=new FormatterWorker.FormattedContentBuilder(indentString);var lineEndings=text.computeLineEndings();try{switch(mimeType){case'text/html':var formatter=new FormatterWorker.HTMLFormatter(builder);formatter.format(text,lineEndings);break;case'text/css':var formatter=new FormatterWorker.CSSFormatter(builder);formatter.format(text,lineEndings,0,text.length);break;case'text/javascript':var formatter=new FormatterWorker.JavaScriptFormatter(builder);formatter.format(text,lineEndings,0,text.length);break;default:var formatter=new FormatterWorker.IdentityFormatter(builder);formatter.format(text,lineEndings,0,text.length);} -result.mapping=builder.mapping();result.content=builder.content();}catch(e){console.error(e);result.mapping={original:[0],formatted:[0]};result.content=text;} -postMessage(result);};FormatterWorker.FormatterWorkerContentParser=function(){};FormatterWorker.FormatterWorkerContentParser.prototype={parse(content){}};FormatterWorker.FormatterWorkerContentParser.parse=function(content,mimeType){var extension=self.runtime.extensions(FormatterWorker.FormatterWorkerContentParser).find(findExtension);console.assert(extension);extension.instance().then(instance=>instance.parse(content)).catchException(null).then(postMessage);function findExtension(extension){return extension.descriptor()['mimeType']===mimeType;}};(function disableLoggingForTest(){if(Runtime.queryParam('test')) -console.error=()=>undefined;})();;(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?factory(exports):typeof define==='function'&&define.amd?define(['exports'],factory):(factory((global.acorn=global.acorn||{})));}(this,(function(exports){'use strict';var reservedWords={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"} -var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this" -var keywords={5:ecma5AndLessKeywords,6:ecma5AndLessKeywords+" const class extends export import super"} -var nonASCIIidentifierStartChars="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc" -var nonASCIIidentifierChars="\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f" -var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]") -var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]") -nonASCIIidentifierStartChars=nonASCIIidentifierChars=null -var astralIdentifierStartCodes=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541] -var astralIdentifierCodes=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239] -function isInAstralSet(code,set){var pos=0x10000 -for(var i=0;i<set.length;i+=2){pos+=set[i] -if(pos>code)return false -pos+=set[i+1] -if(pos>=code)return true}} -function isIdentifierStart(code,astral){if(code<65)return code===36 -if(code<91)return true -if(code<97)return code===95 -if(code<123)return true -if(code<=0xffff)return code>=0xaa&&nonASCIIidentifierStart.test(String.fromCharCode(code)) -if(astral===false)return false -return isInAstralSet(code,astralIdentifierStartCodes)} -function isIdentifierChar(code,astral){if(code<48)return code===36 -if(code<58)return true -if(code<65)return false -if(code<91)return true -if(code<97)return code===95 -if(code<123)return true -if(code<=0xffff)return code>=0xaa&&nonASCIIidentifier.test(String.fromCharCode(code)) -if(astral===false)return false -return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)} -var TokenType=function TokenType(label,conf){if(conf===void 0)conf={};this.label=label -this.keyword=conf.keyword -this.beforeExpr=!!conf.beforeExpr -this.startsExpr=!!conf.startsExpr -this.isLoop=!!conf.isLoop -this.isAssign=!!conf.isAssign -this.prefix=!!conf.prefix -this.postfix=!!conf.postfix -this.binop=conf.binop||null -this.updateContext=null};function binop(name,prec){return new TokenType(name,{beforeExpr:true,binop:prec})} -var beforeExpr={beforeExpr:true};var startsExpr={startsExpr:true};var keywordTypes={} -function kw(name,options){if(options===void 0)options={};options.keyword=name -return keywordTypes[name]=new TokenType(name,options)} -var tt={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("prefix",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=",6),relational:binop("</>",7),bitShift:binop("<</>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class"),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import"),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})} -var lineBreak=/\r\n?|\n|\u2028|\u2029/ -var lineBreakG=new RegExp(lineBreak.source,"g") -function isNewLine(code){return code===10||code===13||code===0x2028||code===0x2029} -var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/ -var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g -function isArray(obj){return Object.prototype.toString.call(obj)==="[object Array]"} -function has(obj,propName){return Object.prototype.hasOwnProperty.call(obj,propName)} -var Position=function Position(line,col){this.line=line -this.column=col};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation(p,start,end){this.start=start -this.end=end -if(p.sourceFile!==null)this.source=p.sourceFile};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur -var match=lineBreakG.exec(input) -if(match&&match.index<offset){++line -cur=match.index+match[0].length}else{return new Position(line,offset-cur)}}} -var defaultOptions={ecmaVersion:7,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:false,allowImportExportEverywhere:false,allowHashBang:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false,plugins:{}} -function getOptions(opts){var options={} -for(var opt in defaultOptions) -options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt] -if(options.ecmaVersion>=2015) -options.ecmaVersion-=2009 -if(options.allowReserved==null) -options.allowReserved=options.ecmaVersion<5 -if(isArray(options.onToken)){var tokens=options.onToken -options.onToken=function(token){return tokens.push(token);}} -if(isArray(options.onComment)) -options.onComment=pushComment(options,options.onComment) -return options} -function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?'Block':'Line',value:text,start:start,end:end} -if(options.locations) -comment.loc=new SourceLocation(this,startLoc,endLoc) -if(options.ranges) -comment.range=[start,end] -array.push(comment)}} -var plugins={} -function keywordRegexp(words){return new RegExp("^("+words.replace(/ /g,"|")+")$")} -var Parser=function Parser(options,input,startPos){this.options=options=getOptions(options) -this.sourceFile=options.sourceFile -this.keywords=keywordRegexp(keywords[options.ecmaVersion>=6?6:5]) -var reserved="" -if(!options.allowReserved){for(var v=options.ecmaVersion;;v--) -if(reserved=reservedWords[v])break -if(options.sourceType=="module")reserved+=" await"} -this.reservedWords=keywordRegexp(reserved) -var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict -this.reservedWordsStrict=keywordRegexp(reservedStrict) -this.reservedWordsStrictBind=keywordRegexp(reservedStrict+" "+reservedWords.strictBind) -this.input=String(input) -this.containsEsc=false -this.loadPlugins(options.plugins) -if(startPos){this.pos=startPos -this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1 -this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length}else{this.pos=this.lineStart=0 -this.curLine=1} -this.type=tt.eof -this.value=null -this.start=this.end=this.pos -this.startLoc=this.endLoc=this.curPosition() -this.lastTokEndLoc=this.lastTokStartLoc=null -this.lastTokStart=this.lastTokEnd=this.pos -this.context=this.initialContext() -this.exprAllowed=true -this.strict=this.inModule=options.sourceType==="module" -this.potentialArrowAt=-1 -this.inFunction=this.inGenerator=this.inAsync=false -this.yieldPos=this.awaitPos=0 -this.labels=[] -if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==='#!') -this.skipLineComment(2)};Parser.prototype.isKeyword=function isKeyword(word){return this.keywords.test(word)};Parser.prototype.isReservedWord=function isReservedWord(word){return this.reservedWords.test(word)};Parser.prototype.extend=function extend(name,f){this[name]=f(this[name])};Parser.prototype.loadPlugins=function loadPlugins(pluginConfigs){var this$1=this;for(var name in pluginConfigs){var plugin=plugins[name] -if(!plugin)throw new Error("Plugin '"+name+"' not found") -plugin(this$1,pluginConfigs[name])}};Parser.prototype.parse=function parse(){var node=this.options.program||this.startNode() -this.nextToken() -return this.parseTopLevel(node)};var pp=Parser.prototype -pp.isUseStrict=function(stmt){return this.options.ecmaVersion>=5&&stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&stmt.expression.raw.slice(1,-1)==="use strict"} -pp.eat=function(type){if(this.type===type){this.next() -return true}else{return false}} -pp.isContextual=function(name){return this.type===tt.name&&this.value===name} -pp.eatContextual=function(name){return this.value===name&&this.eat(tt.name)} -pp.expectContextual=function(name){if(!this.eatContextual(name))this.unexpected()} -pp.canInsertSemicolon=function(){return this.type===tt.eof||this.type===tt.braceR||lineBreak.test(this.input.slice(this.lastTokEnd,this.start))} -pp.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon) -this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc) -return true}} -pp.semicolon=function(){if(!this.eat(tt.semi)&&!this.insertSemicolon())this.unexpected()} -pp.afterTrailingComma=function(tokType,notNext){if(this.type==tokType){if(this.options.onTrailingComma) -this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc) -if(!notNext) -this.next() -return true}} -pp.expect=function(type){this.eat(type)||this.unexpected()} -pp.unexpected=function(pos){this.raise(pos!=null?pos:this.start,"Unexpected token")} -var DestructuringErrors=function DestructuringErrors(){this.shorthandAssign=0 -this.trailingComma=0};pp.checkPatternErrors=function(refDestructuringErrors,andThrow){var trailing=refDestructuringErrors&&refDestructuringErrors.trailingComma -if(!andThrow)return!!trailing -if(trailing)this.raise(trailing,"Comma is not permitted after the rest element")} -pp.checkExpressionErrors=function(refDestructuringErrors,andThrow){var pos=refDestructuringErrors&&refDestructuringErrors.shorthandAssign -if(!andThrow)return!!pos -if(pos)this.raise(pos,"Shorthand property assignments are valid only in destructuring patterns")} -pp.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)) -this.raise(this.yieldPos,"Yield expression cannot be a default value") -if(this.awaitPos) -this.raise(this.awaitPos,"Await expression cannot be a default value")} -var pp$1=Parser.prototype -pp$1.parseTopLevel=function(node){var this$1=this;var first=true,exports={} -if(!node.body)node.body=[] -while(this.type!==tt.eof){var stmt=this$1.parseStatement(true,true,exports) -node.body.push(stmt) -if(first){if(this$1.isUseStrict(stmt))this$1.setStrict(true) -first=false}} -this.next() -if(this.options.ecmaVersion>=6){node.sourceType=this.options.sourceType} -return this.finishNode(node,"Program")} -var loopLabel={kind:"loop"};var switchLabel={kind:"switch"};pp$1.isLet=function(){if(this.type!==tt.name||this.options.ecmaVersion<6||this.value!="let")return false -skipWhiteSpace.lastIndex=this.pos -var skip=skipWhiteSpace.exec(this.input) -var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next) -if(nextCh===91||nextCh==123)return true -if(isIdentifierStart(nextCh,true)){for(var pos=next+1;isIdentifierChar(this.input.charCodeAt(pos),true);++pos){} -var ident=this.input.slice(next,pos) -if(!this.isKeyword(ident))return true} -return false} -pp$1.isAsyncFunction=function(){if(this.type!==tt.name||this.options.ecmaVersion<8||this.value!="async") -return false -skipWhiteSpace.lastIndex=this.pos -var skip=skipWhiteSpace.exec(this.input) -var next=this.pos+skip[0].length -return!lineBreak.test(this.input.slice(this.pos,next))&&this.input.slice(next,next+8)==="function"&&(next+8==this.input.length||!isIdentifierChar(this.input.charAt(next+8)))} -pp$1.parseStatement=function(declaration,topLevel,exports){var starttype=this.type,node=this.startNode(),kind -if(this.isLet()){starttype=tt._var -kind="let"} -switch(starttype){case tt._break:case tt._continue:return this.parseBreakContinueStatement(node,starttype.keyword) -case tt._debugger:return this.parseDebuggerStatement(node) -case tt._do:return this.parseDoStatement(node) -case tt._for:return this.parseForStatement(node) -case tt._function:if(!declaration&&this.options.ecmaVersion>=6)this.unexpected() -return this.parseFunctionStatement(node,false) -case tt._class:if(!declaration)this.unexpected() -return this.parseClass(node,true) -case tt._if:return this.parseIfStatement(node) -case tt._return:return this.parseReturnStatement(node) -case tt._switch:return this.parseSwitchStatement(node) -case tt._throw:return this.parseThrowStatement(node) -case tt._try:return this.parseTryStatement(node) -case tt._const:case tt._var:kind=kind||this.value -if(!declaration&&kind!="var")this.unexpected() -return this.parseVarStatement(node,kind) -case tt._while:return this.parseWhileStatement(node) -case tt._with:return this.parseWithStatement(node) -case tt.braceL:return this.parseBlock() -case tt.semi:return this.parseEmptyStatement(node) -case tt._export:case tt._import:if(!this.options.allowImportExportEverywhere){if(!topLevel) -this.raise(this.start,"'import' and 'export' may only appear at the top level") -if(!this.inModule) -this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")} -return starttype===tt._import?this.parseImport(node):this.parseExport(node,exports) -default:if(this.isAsyncFunction()&&declaration){this.next() -return this.parseFunctionStatement(node,true)} -var maybeName=this.value,expr=this.parseExpression() -if(starttype===tt.name&&expr.type==="Identifier"&&this.eat(tt.colon)) -return this.parseLabeledStatement(node,maybeName,expr) -else return this.parseExpressionStatement(node,expr)}} -pp$1.parseBreakContinueStatement=function(node,keyword){var this$1=this;var isBreak=keyword=="break" -this.next() -if(this.eat(tt.semi)||this.insertSemicolon())node.label=null -else if(this.type!==tt.name)this.unexpected() -else{node.label=this.parseIdent() -this.semicolon()} -for(var i=0;i<this.labels.length;++i){var lab=this$1.labels[i] -if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop"))break -if(node.label&&isBreak)break}} -if(i===this.labels.length)this.raise(node.start,"Unsyntactic "+keyword) -return this.finishNode(node,isBreak?"BreakStatement":"ContinueStatement")} -pp$1.parseDebuggerStatement=function(node){this.next() -this.semicolon() -return this.finishNode(node,"DebuggerStatement")} -pp$1.parseDoStatement=function(node){this.next() -this.labels.push(loopLabel) -node.body=this.parseStatement(false) -this.labels.pop() -this.expect(tt._while) -node.test=this.parseParenExpression() -if(this.options.ecmaVersion>=6) -this.eat(tt.semi) -else -this.semicolon() -return this.finishNode(node,"DoWhileStatement")} -pp$1.parseForStatement=function(node){this.next() -this.labels.push(loopLabel) -this.expect(tt.parenL) -if(this.type===tt.semi)return this.parseFor(node,null) -var isLet=this.isLet() -if(this.type===tt._var||this.type===tt._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value -this.next() -this.parseVar(init$1,true,kind) -this.finishNode(init$1,"VariableDeclaration") -if((this.type===tt._in||(this.options.ecmaVersion>=6&&this.isContextual("of")))&&init$1.declarations.length===1&&!(kind!=="var"&&init$1.declarations[0].init)) -return this.parseForIn(node,init$1) -return this.parseFor(node,init$1)} -var refDestructuringErrors=new DestructuringErrors -var init=this.parseExpression(true,refDestructuringErrors) -if(this.type===tt._in||(this.options.ecmaVersion>=6&&this.isContextual("of"))){this.checkPatternErrors(refDestructuringErrors,true) -this.toAssignable(init) -this.checkLVal(init) -return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true)} -return this.parseFor(node,init)} -pp$1.parseFunctionStatement=function(node,isAsync){this.next() -return this.parseFunction(node,true,false,isAsync)} -pp$1.isFunction=function(){return this.type===tt._function||this.isAsyncFunction()} -pp$1.parseIfStatement=function(node){this.next() -node.test=this.parseParenExpression() -node.consequent=this.parseStatement(!this.strict&&this.isFunction()) -node.alternate=this.eat(tt._else)?this.parseStatement(!this.strict&&this.isFunction()):null -return this.finishNode(node,"IfStatement")} -pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction) -this.raise(this.start,"'return' outside of function") -this.next() -if(this.eat(tt.semi)||this.insertSemicolon())node.argument=null -else{node.argument=this.parseExpression();this.semicolon()} -return this.finishNode(node,"ReturnStatement")} -pp$1.parseSwitchStatement=function(node){var this$1=this;this.next() -node.discriminant=this.parseParenExpression() -node.cases=[] -this.expect(tt.braceL) -this.labels.push(switchLabel) -for(var cur,sawDefault=false;this.type!=tt.braceR;){if(this$1.type===tt._case||this$1.type===tt._default){var isCase=this$1.type===tt._case -if(cur)this$1.finishNode(cur,"SwitchCase") -node.cases.push(cur=this$1.startNode()) -cur.consequent=[] -this$1.next() -if(isCase){cur.test=this$1.parseExpression()}else{if(sawDefault)this$1.raiseRecoverable(this$1.lastTokStart,"Multiple default clauses") -sawDefault=true -cur.test=null} -this$1.expect(tt.colon)}else{if(!cur)this$1.unexpected() -cur.consequent.push(this$1.parseStatement(true))}} -if(cur)this.finishNode(cur,"SwitchCase") -this.next() -this.labels.pop() -return this.finishNode(node,"SwitchStatement")} -pp$1.parseThrowStatement=function(node){this.next() -if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start))) -this.raise(this.lastTokEnd,"Illegal newline after throw") -node.argument=this.parseExpression() -this.semicolon() -return this.finishNode(node,"ThrowStatement")} -var empty=[] -pp$1.parseTryStatement=function(node){this.next() -node.block=this.parseBlock() -node.handler=null -if(this.type===tt._catch){var clause=this.startNode() -this.next() -this.expect(tt.parenL) -clause.param=this.parseBindingAtom() -this.checkLVal(clause.param,true) -this.expect(tt.parenR) -clause.body=this.parseBlock() -node.handler=this.finishNode(clause,"CatchClause")} -node.finalizer=this.eat(tt._finally)?this.parseBlock():null -if(!node.handler&&!node.finalizer) -this.raise(node.start,"Missing catch or finally clause") -return this.finishNode(node,"TryStatement")} -pp$1.parseVarStatement=function(node,kind){this.next() -this.parseVar(node,false,kind) -this.semicolon() -return this.finishNode(node,"VariableDeclaration")} -pp$1.parseWhileStatement=function(node){this.next() -node.test=this.parseParenExpression() -this.labels.push(loopLabel) -node.body=this.parseStatement(false) -this.labels.pop() -return this.finishNode(node,"WhileStatement")} -pp$1.parseWithStatement=function(node){if(this.strict)this.raise(this.start,"'with' in strict mode") -this.next() -node.object=this.parseParenExpression() -node.body=this.parseStatement(false) -return this.finishNode(node,"WithStatement")} -pp$1.parseEmptyStatement=function(node){this.next() -return this.finishNode(node,"EmptyStatement")} -pp$1.parseLabeledStatement=function(node,maybeName,expr){var this$1=this;for(var i=0;i<this.labels.length;++i) -if(this$1.labels[i].name===maybeName)this$1.raise(expr.start,"Label '"+maybeName+"' is already declared") -var kind=this.type.isLoop?"loop":this.type===tt._switch?"switch":null -for(var i$1=this.labels.length-1;i$1>=0;i$1--){var label=this$1.labels[i$1] -if(label.statementStart==node.start){label.statementStart=this$1.start -label.kind=kind}else break} -this.labels.push({name:maybeName,kind:kind,statementStart:this.start}) -node.body=this.parseStatement(true) -this.labels.pop() -node.label=expr -return this.finishNode(node,"LabeledStatement")} -pp$1.parseExpressionStatement=function(node,expr){node.expression=expr -this.semicolon() -return this.finishNode(node,"ExpressionStatement")} -pp$1.parseBlock=function(allowStrict){var this$1=this;var node=this.startNode(),first=true,oldStrict -node.body=[] -this.expect(tt.braceL) -while(!this.eat(tt.braceR)){var stmt=this$1.parseStatement(true) -node.body.push(stmt) -if(first&&allowStrict&&this$1.isUseStrict(stmt)){oldStrict=this$1.strict -this$1.setStrict(this$1.strict=true)} -first=false} -if(oldStrict===false)this.setStrict(false) -return this.finishNode(node,"BlockStatement")} -pp$1.parseFor=function(node,init){node.init=init -this.expect(tt.semi) -node.test=this.type===tt.semi?null:this.parseExpression() -this.expect(tt.semi) -node.update=this.type===tt.parenR?null:this.parseExpression() -this.expect(tt.parenR) -node.body=this.parseStatement(false) -this.labels.pop() -return this.finishNode(node,"ForStatement")} -pp$1.parseForIn=function(node,init){var type=this.type===tt._in?"ForInStatement":"ForOfStatement" -this.next() -node.left=init -node.right=this.parseExpression() -this.expect(tt.parenR) -node.body=this.parseStatement(false) -this.labels.pop() -return this.finishNode(node,type)} -pp$1.parseVar=function(node,isFor,kind){var this$1=this;node.declarations=[] -node.kind=kind -for(;;){var decl=this$1.startNode() -this$1.parseVarId(decl) -if(this$1.eat(tt.eq)){decl.init=this$1.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this$1.type===tt._in||(this$1.options.ecmaVersion>=6&&this$1.isContextual("of")))){this$1.unexpected()}else if(decl.id.type!="Identifier"&&!(isFor&&(this$1.type===tt._in||this$1.isContextual("of")))){this$1.raise(this$1.lastTokEnd,"Complex binding patterns require an initialization value")}else{decl.init=null} -node.declarations.push(this$1.finishNode(decl,"VariableDeclarator")) -if(!this$1.eat(tt.comma))break} -return node} -pp$1.parseVarId=function(decl){decl.id=this.parseBindingAtom() -this.checkLVal(decl.id,true)} -pp$1.parseFunction=function(node,isStatement,allowExpressionBody,isAsync){this.initFunction(node) -if(this.options.ecmaVersion>=6&&!isAsync) -node.generator=this.eat(tt.star) -if(this.options.ecmaVersion>=8) -node.async=!!isAsync -if(isStatement) -node.id=this.parseIdent() -var oldInGen=this.inGenerator,oldInAsync=this.inAsync,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos -this.inGenerator=node.generator -this.inAsync=node.async -this.yieldPos=0 -this.awaitPos=0 -if(!isStatement&&this.type===tt.name) -node.id=this.parseIdent() -this.parseFunctionParams(node) -this.parseFunctionBody(node,allowExpressionBody) -this.inGenerator=oldInGen -this.inAsync=oldInAsync -this.yieldPos=oldYieldPos -this.awaitPos=oldAwaitPos -return this.finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")} -pp$1.parseFunctionParams=function(node){this.expect(tt.parenL) -node.params=this.parseBindingList(tt.parenR,false,this.options.ecmaVersion>=8,true) -this.checkYieldAwaitInDefaultParams()} -pp$1.parseClass=function(node,isStatement){var this$1=this;this.next() -this.parseClassId(node,isStatement) -this.parseClassSuper(node) -var classBody=this.startNode() -var hadConstructor=false -classBody.body=[] -this.expect(tt.braceL) -while(!this.eat(tt.braceR)){if(this$1.eat(tt.semi))continue -var method=this$1.startNode() -var isGenerator=this$1.eat(tt.star) -var isAsync=false -var isMaybeStatic=this$1.type===tt.name&&this$1.value==="static" -this$1.parsePropertyName(method) -method.static=isMaybeStatic&&this$1.type!==tt.parenL -if(method.static){if(isGenerator)this$1.unexpected() -isGenerator=this$1.eat(tt.star) -this$1.parsePropertyName(method)} -if(this$1.options.ecmaVersion>=8&&!isGenerator&&!method.computed&&method.key.type==="Identifier"&&method.key.name==="async"&&this$1.type!==tt.parenL&&!this$1.canInsertSemicolon()){isAsync=true -this$1.parsePropertyName(method)} -method.kind="method" -var isGetSet=false -if(!method.computed){var key=method.key;if(!isGenerator&&!isAsync&&key.type==="Identifier"&&this$1.type!==tt.parenL&&(key.name==="get"||key.name==="set")){isGetSet=true -method.kind=key.name -key=this$1.parsePropertyName(method)} -if(!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(hadConstructor)this$1.raise(key.start,"Duplicate constructor in the same class") -if(isGetSet)this$1.raise(key.start,"Constructor can't have get/set modifier") -if(isGenerator)this$1.raise(key.start,"Constructor can't be a generator") -if(isAsync)this$1.raise(key.start,"Constructor can't be an async method") -method.kind="constructor" -hadConstructor=true}} -this$1.parseClassMethod(classBody,method,isGenerator,isAsync) -if(isGetSet){var paramCount=method.kind==="get"?0:1 -if(method.value.params.length!==paramCount){var start=method.value.start -if(method.kind==="get") -this$1.raiseRecoverable(start,"getter should have no params") -else -this$1.raiseRecoverable(start,"setter should have exactly one param")}else{if(method.kind==="set"&&method.value.params[0].type==="RestElement") -this$1.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params")}}} -node.body=this.finishNode(classBody,"ClassBody") -return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")} -pp$1.parseClassMethod=function(classBody,method,isGenerator,isAsync){method.value=this.parseMethod(isGenerator,isAsync) -classBody.body.push(this.finishNode(method,"MethodDefinition"))} -pp$1.parseClassId=function(node,isStatement){node.id=this.type===tt.name?this.parseIdent():isStatement?this.unexpected():null} -pp$1.parseClassSuper=function(node){node.superClass=this.eat(tt._extends)?this.parseExprSubscripts():null} -pp$1.parseExport=function(node,exports){var this$1=this;this.next() -if(this.eat(tt.star)){this.expectContextual("from") -node.source=this.type===tt.string?this.parseExprAtom():this.unexpected() -this.semicolon() -return this.finishNode(node,"ExportAllDeclaration")} -if(this.eat(tt._default)){this.checkExport(exports,"default",this.lastTokStart) -var parens=this.type==tt.parenL -var expr=this.parseMaybeAssign() -var needsSemi=true -if(!parens&&(expr.type=="FunctionExpression"||expr.type=="ClassExpression")){needsSemi=false -if(expr.id){expr.type=expr.type=="FunctionExpression"?"FunctionDeclaration":"ClassDeclaration"}} -node.declaration=expr -if(needsSemi)this.semicolon() -return this.finishNode(node,"ExportDefaultDeclaration")} -if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(true) -if(node.declaration.type==="VariableDeclaration") -this.checkVariableExport(exports,node.declaration.declarations) -else -this.checkExport(exports,node.declaration.id.name,node.declaration.id.start) -node.specifiers=[] -node.source=null}else{node.declaration=null -node.specifiers=this.parseExportSpecifiers(exports) -if(this.eatContextual("from")){node.source=this.type===tt.string?this.parseExprAtom():this.unexpected()}else{for(var i=0;i<node.specifiers.length;i++){if(this$1.keywords.test(node.specifiers[i].local.name)||this$1.reservedWords.test(node.specifiers[i].local.name)){this$1.unexpected(node.specifiers[i].local.start)}} -node.source=null} -this.semicolon()} -return this.finishNode(node,"ExportNamedDeclaration")} -pp$1.checkExport=function(exports,name,pos){if(!exports)return -if(Object.prototype.hasOwnProperty.call(exports,name)) -this.raiseRecoverable(pos,"Duplicate export '"+name+"'") -exports[name]=true} -pp$1.checkPatternExport=function(exports,pat){var this$1=this;var type=pat.type -if(type=="Identifier") -this.checkExport(exports,pat.name,pat.start) -else if(type=="ObjectPattern") -for(var i=0;i<pat.properties.length;++i) -this$1.checkPatternExport(exports,pat.properties[i].value) -else if(type=="ArrayPattern") -for(var i$1=0;i$1<pat.elements.length;++i$1){var elt=pat.elements[i$1] -if(elt)this$1.checkPatternExport(exports,elt)} -else if(type=="AssignmentPattern") -this.checkPatternExport(exports,pat.left) -else if(type=="ParenthesizedExpression") -this.checkPatternExport(exports,pat.expression)} -pp$1.checkVariableExport=function(exports,decls){var this$1=this;if(!exports)return -for(var i=0;i<decls.length;i++) -this$1.checkPatternExport(exports,decls[i].id)} -pp$1.shouldParseExportStatement=function(){return this.type.keyword||this.isLet()||this.isAsyncFunction()} -pp$1.parseExportSpecifiers=function(exports){var this$1=this;var nodes=[],first=true -this.expect(tt.braceL) -while(!this.eat(tt.braceR)){if(!first){this$1.expect(tt.comma) -if(this$1.afterTrailingComma(tt.braceR))break}else first=false -var node=this$1.startNode() -node.local=this$1.parseIdent(this$1.type===tt._default) -node.exported=this$1.eatContextual("as")?this$1.parseIdent(true):node.local -this$1.checkExport(exports,node.exported.name,node.exported.start) -nodes.push(this$1.finishNode(node,"ExportSpecifier"))} -return nodes} -pp$1.parseImport=function(node){this.next() -if(this.type===tt.string){node.specifiers=empty -node.source=this.parseExprAtom()}else{node.specifiers=this.parseImportSpecifiers() -this.expectContextual("from") -node.source=this.type===tt.string?this.parseExprAtom():this.unexpected()} -this.semicolon() -return this.finishNode(node,"ImportDeclaration")} -pp$1.parseImportSpecifiers=function(){var this$1=this;var nodes=[],first=true -if(this.type===tt.name){var node=this.startNode() -node.local=this.parseIdent() -this.checkLVal(node.local,true) -nodes.push(this.finishNode(node,"ImportDefaultSpecifier")) -if(!this.eat(tt.comma))return nodes} -if(this.type===tt.star){var node$1=this.startNode() -this.next() -this.expectContextual("as") -node$1.local=this.parseIdent() -this.checkLVal(node$1.local,true) -nodes.push(this.finishNode(node$1,"ImportNamespaceSpecifier")) -return nodes} -this.expect(tt.braceL) -while(!this.eat(tt.braceR)){if(!first){this$1.expect(tt.comma) -if(this$1.afterTrailingComma(tt.braceR))break}else first=false -var node$2=this$1.startNode() -node$2.imported=this$1.parseIdent(true) -if(this$1.eatContextual("as")){node$2.local=this$1.parseIdent()}else{node$2.local=node$2.imported -if(this$1.isKeyword(node$2.local.name))this$1.unexpected(node$2.local.start) -if(this$1.reservedWordsStrict.test(node$2.local.name))this$1.raiseRecoverable(node$2.local.start,"The keyword '"+node$2.local.name+"' is reserved")} -this$1.checkLVal(node$2.local,true) -nodes.push(this$1.finishNode(node$2,"ImportSpecifier"))} -return nodes} -var pp$2=Parser.prototype -pp$2.toAssignable=function(node,isBinding){var this$1=this;if(this.options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await") -this.raise(node.start,"Can not use 'await' as identifier inside an async function") -break -case"ObjectPattern":case"ArrayPattern":break -case"ObjectExpression":node.type="ObjectPattern" -for(var i=0;i<node.properties.length;i++){var prop=node.properties[i] -if(prop.kind!=="init")this$1.raise(prop.key.start,"Object pattern can't contain getter or setter") -this$1.toAssignable(prop.value,isBinding)} -break -case"ArrayExpression":node.type="ArrayPattern" -this.toAssignableList(node.elements,isBinding) -break -case"AssignmentExpression":if(node.operator==="="){node.type="AssignmentPattern" -delete node.operator -this.toAssignable(node.left,isBinding)}else{this.raise(node.left.end,"Only '=' operator can be used for specifying default value.") -break} -case"AssignmentPattern":break -case"ParenthesizedExpression":node.expression=this.toAssignable(node.expression,isBinding) -break -case"MemberExpression":if(!isBinding)break -default:this.raise(node.start,"Assigning to rvalue")}} -return node} -pp$2.toAssignableList=function(exprList,isBinding){var this$1=this;var end=exprList.length -if(end){var last=exprList[end-1] -if(last&&last.type=="RestElement"){--end}else if(last&&last.type=="SpreadElement"){last.type="RestElement" -var arg=last.argument -this.toAssignable(arg,isBinding) -if(arg.type!=="Identifier"&&arg.type!=="MemberExpression"&&arg.type!=="ArrayPattern") -this.unexpected(arg.start) ---end} -if(isBinding&&last&&last.type==="RestElement"&&last.argument.type!=="Identifier") -this.unexpected(last.argument.start)} -for(var i=0;i<end;i++){var elt=exprList[i] -if(elt)this$1.toAssignable(elt,isBinding)} -return exprList} -pp$2.parseSpread=function(refDestructuringErrors){var node=this.startNode() -this.next() -node.argument=this.parseMaybeAssign(false,refDestructuringErrors) -return this.finishNode(node,"SpreadElement")} -pp$2.parseRest=function(allowNonIdent){var node=this.startNode() -this.next() -if(allowNonIdent)node.argument=this.type===tt.name?this.parseIdent():this.unexpected() -else node.argument=this.type===tt.name||this.type===tt.bracketL?this.parseBindingAtom():this.unexpected() -return this.finishNode(node,"RestElement")} -pp$2.parseBindingAtom=function(){if(this.options.ecmaVersion<6)return this.parseIdent() -switch(this.type){case tt.name:return this.parseIdent() -case tt.bracketL:var node=this.startNode() -this.next() -node.elements=this.parseBindingList(tt.bracketR,true,true) -return this.finishNode(node,"ArrayPattern") -case tt.braceL:return this.parseObj(true) -default:this.unexpected()}} -pp$2.parseBindingList=function(close,allowEmpty,allowTrailingComma,allowNonIdent){var this$1=this;var elts=[],first=true -while(!this.eat(close)){if(first)first=false -else this$1.expect(tt.comma) -if(allowEmpty&&this$1.type===tt.comma){elts.push(null)}else if(allowTrailingComma&&this$1.afterTrailingComma(close)){break}else if(this$1.type===tt.ellipsis){var rest=this$1.parseRest(allowNonIdent) -this$1.parseBindingListItem(rest) -elts.push(rest) -if(this$1.type===tt.comma)this$1.raise(this$1.start,"Comma is not permitted after the rest element") -this$1.expect(close) -break}else{var elem=this$1.parseMaybeDefault(this$1.start,this$1.startLoc) -this$1.parseBindingListItem(elem) -elts.push(elem)}} -return elts} -pp$2.parseBindingListItem=function(param){return param} -pp$2.parseMaybeDefault=function(startPos,startLoc,left){left=left||this.parseBindingAtom() -if(this.options.ecmaVersion<6||!this.eat(tt.eq))return left -var node=this.startNodeAt(startPos,startLoc) -node.left=left -node.right=this.parseMaybeAssign() -return this.finishNode(node,"AssignmentPattern")} -pp$2.checkLVal=function(expr,isBinding,checkClashes){var this$1=this;switch(expr.type){case"Identifier":if(this.strict&&this.reservedWordsStrictBind.test(expr.name)) -this.raiseRecoverable(expr.start,(isBinding?"Binding ":"Assigning to ")+expr.name+" in strict mode") -if(checkClashes){if(has(checkClashes,expr.name)) -this.raiseRecoverable(expr.start,"Argument name clash") -checkClashes[expr.name]=true} -break -case"MemberExpression":if(isBinding)this.raiseRecoverable(expr.start,(isBinding?"Binding":"Assigning to")+" member expression") -break -case"ObjectPattern":for(var i=0;i<expr.properties.length;i++) -this$1.checkLVal(expr.properties[i].value,isBinding,checkClashes) -break -case"ArrayPattern":for(var i$1=0;i$1<expr.elements.length;i$1++){var elem=expr.elements[i$1] -if(elem)this$1.checkLVal(elem,isBinding,checkClashes)} -break -case"AssignmentPattern":this.checkLVal(expr.left,isBinding,checkClashes) -break -case"RestElement":this.checkLVal(expr.argument,isBinding,checkClashes) -break -case"ParenthesizedExpression":this.checkLVal(expr.expression,isBinding,checkClashes) -break -default:this.raise(expr.start,(isBinding?"Binding":"Assigning to")+" rvalue")}} -var pp$3=Parser.prototype -pp$3.checkPropClash=function(prop,propHash){if(this.options.ecmaVersion>=6&&(prop.computed||prop.method||prop.shorthand)) -return -var key=prop.key;var name -switch(key.type){case"Identifier":name=key.name;break -case"Literal":name=String(key.value);break -default:return} -var kind=prop.kind;if(this.options.ecmaVersion>=6){if(name==="__proto__"&&kind==="init"){if(propHash.proto)this.raiseRecoverable(key.start,"Redefinition of __proto__ property") -propHash.proto=true} -return} -name="$"+name -var other=propHash[name] -if(other){var isGetSet=kind!=="init" -if((this.strict||isGetSet)&&other[kind]||!(isGetSet^other.init)) -this.raiseRecoverable(key.start,"Redefinition of property")}else{other=propHash[name]={init:false,get:false,set:false}} -other[kind]=true} -pp$3.parseExpression=function(noIn,refDestructuringErrors){var this$1=this;var startPos=this.start,startLoc=this.startLoc -var expr=this.parseMaybeAssign(noIn,refDestructuringErrors) -if(this.type===tt.comma){var node=this.startNodeAt(startPos,startLoc) -node.expressions=[expr] -while(this.eat(tt.comma))node.expressions.push(this$1.parseMaybeAssign(noIn,refDestructuringErrors)) -return this.finishNode(node,"SequenceExpression")} -return expr} -pp$3.parseMaybeAssign=function(noIn,refDestructuringErrors,afterLeftParse){if(this.inGenerator&&this.isContextual("yield"))return this.parseYield() -var ownDestructuringErrors=false -if(!refDestructuringErrors){refDestructuringErrors=new DestructuringErrors -ownDestructuringErrors=true} -var startPos=this.start,startLoc=this.startLoc -if(this.type==tt.parenL||this.type==tt.name) -this.potentialArrowAt=this.start -var left=this.parseMaybeConditional(noIn,refDestructuringErrors) -if(afterLeftParse)left=afterLeftParse.call(this,left,startPos,startLoc) -if(this.type.isAssign){this.checkPatternErrors(refDestructuringErrors,true) -if(!ownDestructuringErrors)DestructuringErrors.call(refDestructuringErrors) -var node=this.startNodeAt(startPos,startLoc) -node.operator=this.value -node.left=this.type===tt.eq?this.toAssignable(left):left -refDestructuringErrors.shorthandAssign=0 -this.checkLVal(left) -this.next() -node.right=this.parseMaybeAssign(noIn) -return this.finishNode(node,"AssignmentExpression")}else{if(ownDestructuringErrors)this.checkExpressionErrors(refDestructuringErrors,true)} -return left} -pp$3.parseMaybeConditional=function(noIn,refDestructuringErrors){var startPos=this.start,startLoc=this.startLoc -var expr=this.parseExprOps(noIn,refDestructuringErrors) -if(this.checkExpressionErrors(refDestructuringErrors))return expr -if(this.eat(tt.question)){var node=this.startNodeAt(startPos,startLoc) -node.test=expr -node.consequent=this.parseMaybeAssign() -this.expect(tt.colon) -node.alternate=this.parseMaybeAssign(noIn) -return this.finishNode(node,"ConditionalExpression")} -return expr} -pp$3.parseExprOps=function(noIn,refDestructuringErrors){var startPos=this.start,startLoc=this.startLoc -var expr=this.parseMaybeUnary(refDestructuringErrors,false) -if(this.checkExpressionErrors(refDestructuringErrors))return expr -return this.parseExprOp(expr,startPos,startLoc,-1,noIn)} -pp$3.parseExprOp=function(left,leftStartPos,leftStartLoc,minPrec,noIn){var prec=this.type.binop -if(prec!=null&&(!noIn||this.type!==tt._in)){if(prec>minPrec){var logical=this.type===tt.logicalOR||this.type===tt.logicalAND -var op=this.value -this.next() -var startPos=this.start,startLoc=this.startLoc -var right=this.parseExprOp(this.parseMaybeUnary(null,false),startPos,startLoc,prec,noIn) -var node=this.buildBinary(leftStartPos,leftStartLoc,left,right,op,logical) -return this.parseExprOp(node,leftStartPos,leftStartLoc,minPrec,noIn)}} -return left} -pp$3.buildBinary=function(startPos,startLoc,left,right,op,logical){var node=this.startNodeAt(startPos,startLoc) -node.left=left -node.operator=op -node.right=right -return this.finishNode(node,logical?"LogicalExpression":"BinaryExpression")} -pp$3.parseMaybeUnary=function(refDestructuringErrors,sawUnary){var this$1=this;var startPos=this.start,startLoc=this.startLoc,expr -if(this.inAsync&&this.isContextual("await")){expr=this.parseAwait(refDestructuringErrors) -sawUnary=true}else if(this.type.prefix){var node=this.startNode(),update=this.type===tt.incDec -node.operator=this.value -node.prefix=true -this.next() -node.argument=this.parseMaybeUnary(null,true) -this.checkExpressionErrors(refDestructuringErrors,true) -if(update)this.checkLVal(node.argument) -else if(this.strict&&node.operator==="delete"&&node.argument.type==="Identifier") -this.raiseRecoverable(node.start,"Deleting local variable in strict mode") -else sawUnary=true -expr=this.finishNode(node,update?"UpdateExpression":"UnaryExpression")}else{expr=this.parseExprSubscripts(refDestructuringErrors) -if(this.checkExpressionErrors(refDestructuringErrors))return expr -while(this.type.postfix&&!this.canInsertSemicolon()){var node$1=this$1.startNodeAt(startPos,startLoc) -node$1.operator=this$1.value -node$1.prefix=false -node$1.argument=expr -this$1.checkLVal(expr) -this$1.next() -expr=this$1.finishNode(node$1,"UpdateExpression")}} -if(!sawUnary&&this.eat(tt.starstar)) -return this.buildBinary(startPos,startLoc,expr,this.parseMaybeUnary(null,false),"**",false) -else -return expr} -pp$3.parseExprSubscripts=function(refDestructuringErrors){var startPos=this.start,startLoc=this.startLoc -var expr=this.parseExprAtom(refDestructuringErrors) -var skipArrowSubscripts=expr.type==="ArrowFunctionExpression"&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==")" -if(this.checkExpressionErrors(refDestructuringErrors)||skipArrowSubscripts)return expr -return this.parseSubscripts(expr,startPos,startLoc)} -pp$3.parseSubscripts=function(base,startPos,startLoc,noCalls){var this$1=this;for(;;){var maybeAsyncArrow=this$1.options.ecmaVersion>=8&&base.type==="Identifier"&&base.name==="async"&&!this$1.canInsertSemicolon() -if(this$1.eat(tt.dot)){var node=this$1.startNodeAt(startPos,startLoc) -node.object=base -node.property=this$1.parseIdent(true) -node.computed=false -base=this$1.finishNode(node,"MemberExpression")}else if(this$1.eat(tt.bracketL)){var node$1=this$1.startNodeAt(startPos,startLoc) -node$1.object=base -node$1.property=this$1.parseExpression() -node$1.computed=true -this$1.expect(tt.bracketR) -base=this$1.finishNode(node$1,"MemberExpression")}else if(!noCalls&&this$1.eat(tt.parenL)){var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this$1.yieldPos,oldAwaitPos=this$1.awaitPos -this$1.yieldPos=0 -this$1.awaitPos=0 -var exprList=this$1.parseExprList(tt.parenR,this$1.options.ecmaVersion>=8,false,refDestructuringErrors) -if(maybeAsyncArrow&&!this$1.canInsertSemicolon()&&this$1.eat(tt.arrow)){this$1.checkPatternErrors(refDestructuringErrors,true) -this$1.checkYieldAwaitInDefaultParams() -this$1.yieldPos=oldYieldPos -this$1.awaitPos=oldAwaitPos -return this$1.parseArrowExpression(this$1.startNodeAt(startPos,startLoc),exprList,true)} -this$1.checkExpressionErrors(refDestructuringErrors,true) -this$1.yieldPos=oldYieldPos||this$1.yieldPos -this$1.awaitPos=oldAwaitPos||this$1.awaitPos -var node$2=this$1.startNodeAt(startPos,startLoc) -node$2.callee=base -node$2.arguments=exprList -base=this$1.finishNode(node$2,"CallExpression")}else if(this$1.type===tt.backQuote){var node$3=this$1.startNodeAt(startPos,startLoc) -node$3.tag=base -node$3.quasi=this$1.parseTemplate() -base=this$1.finishNode(node$3,"TaggedTemplateExpression")}else{return base}}} -pp$3.parseExprAtom=function(refDestructuringErrors){var node,canBeArrow=this.potentialArrowAt==this.start -switch(this.type){case tt._super:if(!this.inFunction) -this.raise(this.start,"'super' outside of function or class") -case tt._this:var type=this.type===tt._this?"ThisExpression":"Super" -node=this.startNode() -this.next() -return this.finishNode(node,type) -case tt.name:var startPos=this.start,startLoc=this.startLoc -var id=this.parseIdent(this.type!==tt.name) -if(this.options.ecmaVersion>=8&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(tt._function)) -return this.parseFunction(this.startNodeAt(startPos,startLoc),false,false,true) -if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(tt.arrow)) -return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false) -if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===tt.name){id=this.parseIdent() -if(this.canInsertSemicolon()||!this.eat(tt.arrow)) -this.unexpected() -return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}} -return id -case tt.regexp:var value=this.value -node=this.parseLiteral(value.value) -node.regex={pattern:value.pattern,flags:value.flags} -return node -case tt.num:case tt.string:return this.parseLiteral(this.value) -case tt._null:case tt._true:case tt._false:node=this.startNode() -node.value=this.type===tt._null?null:this.type===tt._true -node.raw=this.type.keyword -this.next() -return this.finishNode(node,"Literal") -case tt.parenL:return this.parseParenAndDistinguishExpression(canBeArrow) -case tt.bracketL:node=this.startNode() -this.next() -node.elements=this.parseExprList(tt.bracketR,true,true,refDestructuringErrors) -return this.finishNode(node,"ArrayExpression") -case tt.braceL:return this.parseObj(false,refDestructuringErrors) -case tt._function:node=this.startNode() -this.next() -return this.parseFunction(node,false) -case tt._class:return this.parseClass(this.startNode(),false) -case tt._new:return this.parseNew() -case tt.backQuote:return this.parseTemplate() -default:this.unexpected()}} -pp$3.parseLiteral=function(value){var node=this.startNode() -node.value=value -node.raw=this.input.slice(this.start,this.end) -this.next() -return this.finishNode(node,"Literal")} -pp$3.parseParenExpression=function(){this.expect(tt.parenL) -var val=this.parseExpression() -this.expect(tt.parenR) -return val} -pp$3.parseParenAndDistinguishExpression=function(canBeArrow){var this$1=this;var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8 -if(this.options.ecmaVersion>=6){this.next() -var innerStartPos=this.start,innerStartLoc=this.startLoc -var exprList=[],first=true,lastIsComma=false -var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart,innerParenStart -this.yieldPos=0 -this.awaitPos=0 -while(this.type!==tt.parenR){first?first=false:this$1.expect(tt.comma) -if(allowTrailingComma&&this$1.afterTrailingComma(tt.parenR,true)){lastIsComma=true -break}else if(this$1.type===tt.ellipsis){spreadStart=this$1.start -exprList.push(this$1.parseParenItem(this$1.parseRest())) -if(this$1.type===tt.comma)this$1.raise(this$1.start,"Comma is not permitted after the rest element") -break}else{if(this$1.type===tt.parenL&&!innerParenStart){innerParenStart=this$1.start} -exprList.push(this$1.parseMaybeAssign(false,refDestructuringErrors,this$1.parseParenItem))}} -var innerEndPos=this.start,innerEndLoc=this.startLoc -this.expect(tt.parenR) -if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(tt.arrow)){this.checkPatternErrors(refDestructuringErrors,true) -this.checkYieldAwaitInDefaultParams() -if(innerParenStart)this.unexpected(innerParenStart) -this.yieldPos=oldYieldPos -this.awaitPos=oldAwaitPos -return this.parseParenArrowList(startPos,startLoc,exprList)} -if(!exprList.length||lastIsComma)this.unexpected(this.lastTokStart) -if(spreadStart)this.unexpected(spreadStart) -this.checkExpressionErrors(refDestructuringErrors,true) -this.yieldPos=oldYieldPos||this.yieldPos -this.awaitPos=oldAwaitPos||this.awaitPos -if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc) -val.expressions=exprList -this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)}else{val=exprList[0]}}else{val=this.parseParenExpression()} -if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc) -par.expression=val -return this.finishNode(par,"ParenthesizedExpression")}else{return val}} -pp$3.parseParenItem=function(item){return item} -pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)} -var empty$1=[] -pp$3.parseNew=function(){var node=this.startNode() -var meta=this.parseIdent(true) -if(this.options.ecmaVersion>=6&&this.eat(tt.dot)){node.meta=meta -node.property=this.parseIdent(true) -if(node.property.name!=="target") -this.raiseRecoverable(node.property.start,"The only valid meta property for new is new.target") -if(!this.inFunction) -this.raiseRecoverable(node.start,"new.target can only be used in functions") -return this.finishNode(node,"MetaProperty")} -var startPos=this.start,startLoc=this.startLoc -node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true) -if(this.eat(tt.parenL))node.arguments=this.parseExprList(tt.parenR,this.options.ecmaVersion>=8,false) -else node.arguments=empty$1 -return this.finishNode(node,"NewExpression")} -pp$3.parseTemplateElement=function(){var elem=this.startNode() -elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,'\n'),cooked:this.value} -this.next() -elem.tail=this.type===tt.backQuote -return this.finishNode(elem,"TemplateElement")} -pp$3.parseTemplate=function(){var this$1=this;var node=this.startNode() -this.next() -node.expressions=[] -var curElt=this.parseTemplateElement() -node.quasis=[curElt] -while(!curElt.tail){this$1.expect(tt.dollarBraceL) -node.expressions.push(this$1.parseExpression()) -this$1.expect(tt.braceR) -node.quasis.push(curElt=this$1.parseTemplateElement())} -this.next() -return this.finishNode(node,"TemplateLiteral")} -pp$3.parseObj=function(isPattern,refDestructuringErrors){var this$1=this;var node=this.startNode(),first=true,propHash={} -node.properties=[] -this.next() -while(!this.eat(tt.braceR)){if(!first){this$1.expect(tt.comma) -if(this$1.afterTrailingComma(tt.braceR))break}else first=false -var prop=this$1.startNode(),isGenerator,isAsync,startPos,startLoc -if(this$1.options.ecmaVersion>=6){prop.method=false -prop.shorthand=false -if(isPattern||refDestructuringErrors){startPos=this$1.start -startLoc=this$1.startLoc} -if(!isPattern) -isGenerator=this$1.eat(tt.star)} -this$1.parsePropertyName(prop) -if(!isPattern&&this$1.options.ecmaVersion>=8&&!isGenerator&&!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&this$1.type!==tt.parenL&&this$1.type!==tt.colon&&!this$1.canInsertSemicolon()){isAsync=true -this$1.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false} -this$1.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors) -this$1.checkPropClash(prop,propHash) -node.properties.push(this$1.finishNode(prop,"Property"))} -return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")} -pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors){if((isGenerator||isAsync)&&this.type===tt.colon) -this.unexpected() -if(this.eat(tt.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors) -prop.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===tt.parenL){if(isPattern)this.unexpected() -prop.kind="init" -prop.method=true -prop.value=this.parseMethod(isGenerator,isAsync)}else if(this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!=tt.comma&&this.type!=tt.braceR)){if(isGenerator||isAsync||isPattern)this.unexpected() -prop.kind=prop.key.name -this.parsePropertyName(prop) -prop.value=this.parseMethod(false) -var paramCount=prop.kind==="get"?0:1 -if(prop.value.params.length!==paramCount){var start=prop.value.start -if(prop.kind==="get") -this.raiseRecoverable(start,"getter should have no params") -else -this.raiseRecoverable(start,"setter should have exactly one param")}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement") -this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){if(this.keywords.test(prop.key.name)||(this.strict?this.reservedWordsStrict:this.reservedWords).test(prop.key.name)||(this.inGenerator&&prop.key.name=="yield")||(this.inAsync&&prop.key.name=="await")) -this.raiseRecoverable(prop.key.start,"'"+prop.key.name+"' can not be used as shorthand property") -prop.kind="init" -if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else if(this.type===tt.eq&&refDestructuringErrors){if(!refDestructuringErrors.shorthandAssign) -refDestructuringErrors.shorthandAssign=this.start -prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else{prop.value=prop.key} -prop.shorthand=true}else this.unexpected()} -pp$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(tt.bracketL)){prop.computed=true -prop.key=this.parseMaybeAssign() -this.expect(tt.bracketR) -return prop.key}else{prop.computed=false}} -return prop.key=this.type===tt.num||this.type===tt.string?this.parseExprAtom():this.parseIdent(true)} -pp$3.initFunction=function(node){node.id=null -if(this.options.ecmaVersion>=6){node.generator=false -node.expression=false} -if(this.options.ecmaVersion>=8) -node.async=false} -pp$3.parseMethod=function(isGenerator,isAsync){var node=this.startNode(),oldInGen=this.inGenerator,oldInAsync=this.inAsync,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos -this.initFunction(node) -if(this.options.ecmaVersion>=6) -node.generator=isGenerator -if(this.options.ecmaVersion>=8) -node.async=!!isAsync -this.inGenerator=node.generator -this.inAsync=node.async -this.yieldPos=0 -this.awaitPos=0 -this.expect(tt.parenL) -node.params=this.parseBindingList(tt.parenR,false,this.options.ecmaVersion>=8) -this.checkYieldAwaitInDefaultParams() -this.parseFunctionBody(node,false) -this.inGenerator=oldInGen -this.inAsync=oldInAsync -this.yieldPos=oldYieldPos -this.awaitPos=oldAwaitPos -return this.finishNode(node,"FunctionExpression")} -pp$3.parseArrowExpression=function(node,params,isAsync){var oldInGen=this.inGenerator,oldInAsync=this.inAsync,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos -this.initFunction(node) -if(this.options.ecmaVersion>=8) -node.async=!!isAsync -this.inGenerator=false -this.inAsync=node.async -this.yieldPos=0 -this.awaitPos=0 -node.params=this.toAssignableList(params,true) -this.parseFunctionBody(node,true) -this.inGenerator=oldInGen -this.inAsync=oldInAsync -this.yieldPos=oldYieldPos -this.awaitPos=oldAwaitPos -return this.finishNode(node,"ArrowFunctionExpression")} -pp$3.parseFunctionBody=function(node,isArrowFunction){var isExpression=isArrowFunction&&this.type!==tt.braceL -if(isExpression){node.body=this.parseMaybeAssign() -node.expression=true}else{var oldInFunc=this.inFunction,oldLabels=this.labels -this.inFunction=true;this.labels=[] -node.body=this.parseBlock(true) -node.expression=false -this.inFunction=oldInFunc;this.labels=oldLabels} -var useStrict=(!isExpression&&node.body.body.length&&this.isUseStrict(node.body.body[0]))?node.body.body[0]:null -if(useStrict&&this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params)) -this.raiseRecoverable(useStrict.start,"Illegal 'use strict' directive in function with non-simple parameter list") -if(this.strict||useStrict){var oldStrict=this.strict -this.strict=true -if(node.id) -this.checkLVal(node.id,true) -this.checkParams(node) -this.strict=oldStrict}else if(isArrowFunction||!this.isSimpleParamList(node.params)){this.checkParams(node)}} -pp$3.isSimpleParamList=function(params){for(var i=0;i<params.length;i++) -if(params[i].type!=="Identifier")return false -return true} -pp$3.checkParams=function(node){var this$1=this;var nameHash={} -for(var i=0;i<node.params.length;i++)this$1.checkLVal(node.params[i],true,nameHash)} -pp$3.parseExprList=function(close,allowTrailingComma,allowEmpty,refDestructuringErrors){var this$1=this;var elts=[],first=true -while(!this.eat(close)){if(!first){this$1.expect(tt.comma) -if(allowTrailingComma&&this$1.afterTrailingComma(close))break}else first=false -var elt -if(allowEmpty&&this$1.type===tt.comma) -elt=null -else if(this$1.type===tt.ellipsis){elt=this$1.parseSpread(refDestructuringErrors) -if(this$1.type===tt.comma&&refDestructuringErrors&&!refDestructuringErrors.trailingComma){refDestructuringErrors.trailingComma=this$1.start}}else -elt=this$1.parseMaybeAssign(false,refDestructuringErrors) -elts.push(elt)} -return elts} -pp$3.parseIdent=function(liberal){var node=this.startNode() -if(liberal&&this.options.allowReserved=="never")liberal=false -if(this.type===tt.name){if(!liberal&&(this.strict?this.reservedWordsStrict:this.reservedWords).test(this.value)&&(this.options.ecmaVersion>=6||this.input.slice(this.start,this.end).indexOf("\\")==-1)) -this.raiseRecoverable(this.start,"The keyword '"+this.value+"' is reserved") -if(this.inGenerator&&this.value==="yield") -this.raiseRecoverable(this.start,"Can not use 'yield' as identifier inside a generator") -if(this.inAsync&&this.value==="await") -this.raiseRecoverable(this.start,"Can not use 'await' as identifier inside an async function") -node.name=this.value}else if(liberal&&this.type.keyword){node.name=this.type.keyword}else{this.unexpected()} -this.next() -return this.finishNode(node,"Identifier")} -pp$3.parseYield=function(){if(!this.yieldPos)this.yieldPos=this.start -var node=this.startNode() -this.next() -if(this.type==tt.semi||this.canInsertSemicolon()||(this.type!=tt.star&&!this.type.startsExpr)){node.delegate=false -node.argument=null}else{node.delegate=this.eat(tt.star) -node.argument=this.parseMaybeAssign()} -return this.finishNode(node,"YieldExpression")} -pp$3.parseAwait=function(){if(!this.awaitPos)this.awaitPos=this.start -var node=this.startNode() -this.next() -node.argument=this.parseMaybeUnary(null,true) -return this.finishNode(node,"AwaitExpression")} -var pp$4=Parser.prototype -pp$4.raise=function(pos,message){var loc=getLineInfo(this.input,pos) -message+=" ("+loc.line+":"+loc.column+")" -var err=new SyntaxError(message) -err.pos=pos;err.loc=loc;err.raisedAt=this.pos -throw err} -pp$4.raiseRecoverable=pp$4.raise -pp$4.curPosition=function(){if(this.options.locations){return new Position(this.curLine,this.pos-this.lineStart)}} -var Node=function Node(parser,pos,loc){this.type="" -this.start=pos -this.end=0 -if(parser.options.locations) -this.loc=new SourceLocation(parser,loc) -if(parser.options.directSourceFile) -this.sourceFile=parser.options.directSourceFile -if(parser.options.ranges) -this.range=[pos,0]};var pp$5=Parser.prototype -pp$5.startNode=function(){return new Node(this,this.start,this.startLoc)} -pp$5.startNodeAt=function(pos,loc){return new Node(this,pos,loc)} -function finishNodeAt(node,type,pos,loc){node.type=type -node.end=pos -if(this.options.locations) -node.loc.end=loc -if(this.options.ranges) -node.range[1]=pos -return node} -pp$5.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)} -pp$5.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)} -var TokContext=function TokContext(token,isExpr,preserveSpace,override){this.token=token -this.isExpr=!!isExpr -this.preserveSpace=!!preserveSpace -this.override=override};var types={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",true),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,function(p){return p.readTmplToken();}),f_expr:new TokContext("function",true)} -var pp$6=Parser.prototype -pp$6.initialContext=function(){return[types.b_stat]} -pp$6.braceIsBlock=function(prevType){if(prevType===tt.colon){var parent=this.curContext() -if(parent===types.b_stat||parent===types.b_expr) -return!parent.isExpr} -if(prevType===tt._return) -return lineBreak.test(this.input.slice(this.lastTokEnd,this.start)) -if(prevType===tt._else||prevType===tt.semi||prevType===tt.eof||prevType===tt.parenR) -return true -if(prevType==tt.braceL) -return this.curContext()===types.b_stat -return!this.exprAllowed} -pp$6.updateContext=function(prevType){var update,type=this.type -if(type.keyword&&prevType==tt.dot) -this.exprAllowed=false -else if(update=type.updateContext) -update.call(this,prevType) -else -this.exprAllowed=type.beforeExpr} -tt.parenR.updateContext=tt.braceR.updateContext=function(){if(this.context.length==1){this.exprAllowed=true -return} -var out=this.context.pop() -if(out===types.b_stat&&this.curContext()===types.f_expr){this.context.pop() -this.exprAllowed=false}else if(out===types.b_tmpl){this.exprAllowed=true}else{this.exprAllowed=!out.isExpr}} -tt.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types.b_stat:types.b_expr) -this.exprAllowed=true} -tt.dollarBraceL.updateContext=function(){this.context.push(types.b_tmpl) -this.exprAllowed=true} -tt.parenL.updateContext=function(prevType){var statementParens=prevType===tt._if||prevType===tt._for||prevType===tt._with||prevType===tt._while -this.context.push(statementParens?types.p_stat:types.p_expr) -this.exprAllowed=true} -tt.incDec.updateContext=function(){} -tt._function.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==tt.semi&&prevType!==tt._else&&!((prevType===tt.colon||prevType===tt.braceL)&&this.curContext()===types.b_stat)) -this.context.push(types.f_expr) -this.exprAllowed=false} -tt.backQuote.updateContext=function(){if(this.curContext()===types.q_tmpl) -this.context.pop() -else -this.context.push(types.q_tmpl) -this.exprAllowed=false} -var Token=function Token(p){this.type=p.type -this.value=p.value -this.start=p.start -this.end=p.end -if(p.options.locations) -this.loc=new SourceLocation(p,p.startLoc,p.endLoc) -if(p.options.ranges) -this.range=[p.start,p.end]};var pp$7=Parser.prototype -var isRhino=typeof Packages=="object"&&Object.prototype.toString.call(Packages)=="[object JavaPackage]" -pp$7.next=function(){if(this.options.onToken) -this.options.onToken(new Token(this)) -this.lastTokEnd=this.end -this.lastTokStart=this.start -this.lastTokEndLoc=this.endLoc -this.lastTokStartLoc=this.startLoc -this.nextToken()} -pp$7.getToken=function(){this.next() -return new Token(this)} -if(typeof Symbol!=="undefined") -pp$7[Symbol.iterator]=function(){var self=this -return{next:function(){var token=self.getToken() -return{done:token.type===tt.eof,value:token}}}} -pp$7.setStrict=function(strict){var this$1=this;this.strict=strict -if(this.type!==tt.num&&this.type!==tt.string)return -this.pos=this.start -if(this.options.locations){while(this.pos<this.lineStart){this$1.lineStart=this$1.input.lastIndexOf("\n",this$1.lineStart-2)+1 ---this$1.curLine}} -this.nextToken()} -pp$7.curContext=function(){return this.context[this.context.length-1]} -pp$7.nextToken=function(){var curContext=this.curContext() -if(!curContext||!curContext.preserveSpace)this.skipSpace() -this.start=this.pos -if(this.options.locations)this.startLoc=this.curPosition() -if(this.pos>=this.input.length)return this.finishToken(tt.eof) -if(curContext.override)return curContext.override(this) -else this.readToken(this.fullCharCodeAtPos())} -pp$7.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92) -return this.readWord() -return this.getTokenFromCode(code)} -pp$7.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos) -if(code<=0xd7ff||code>=0xe000)return code -var next=this.input.charCodeAt(this.pos+1) -return(code<<10)+next-0x35fdc00} -pp$7.skipBlockComment=function(){var this$1=this;var startLoc=this.options.onComment&&this.curPosition() -var start=this.pos,end=this.input.indexOf("*/",this.pos+=2) -if(end===-1)this.raise(this.pos-2,"Unterminated comment") -this.pos=end+2 -if(this.options.locations){lineBreakG.lastIndex=start -var match -while((match=lineBreakG.exec(this.input))&&match.index<this.pos){++this$1.curLine -this$1.lineStart=match.index+match[0].length}} -if(this.options.onComment) -this.options.onComment(true,this.input.slice(start+2,end),start,this.pos,startLoc,this.curPosition())} -pp$7.skipLineComment=function(startSkip){var this$1=this;var start=this.pos -var startLoc=this.options.onComment&&this.curPosition() -var ch=this.input.charCodeAt(this.pos+=startSkip) -while(this.pos<this.input.length&&ch!==10&&ch!==13&&ch!==8232&&ch!==8233){++this$1.pos -ch=this$1.input.charCodeAt(this$1.pos)} -if(this.options.onComment) -this.options.onComment(false,this.input.slice(start+startSkip,this.pos),start,this.pos,startLoc,this.curPosition())} -pp$7.skipSpace=function(){var this$1=this;loop:while(this.pos<this.input.length){var ch=this$1.input.charCodeAt(this$1.pos) -switch(ch){case 32:case 160:++this$1.pos -break -case 13:if(this$1.input.charCodeAt(this$1.pos+1)===10){++this$1.pos} -case 10:case 8232:case 8233:++this$1.pos -if(this$1.options.locations){++this$1.curLine -this$1.lineStart=this$1.pos} -break -case 47:switch(this$1.input.charCodeAt(this$1.pos+1)){case 42:this$1.skipBlockComment() -break -case 47:this$1.skipLineComment(2) -break -default:break loop} -break -default:if(ch>8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this$1.pos}else{break loop}}}} -pp$7.finishToken=function(type,val){this.end=this.pos -if(this.options.locations)this.endLoc=this.curPosition() -var prevType=this.type -this.type=type -this.value=val -this.updateContext(prevType)} -pp$7.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1) -if(next>=48&&next<=57)return this.readNumber(true) -var next2=this.input.charCodeAt(this.pos+2) -if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3 -return this.finishToken(tt.ellipsis)}else{++this.pos -return this.finishToken(tt.dot)}} -pp$7.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1) -if(this.exprAllowed){++this.pos;return this.readRegexp()} -if(next===61)return this.finishOp(tt.assign,2) -return this.finishOp(tt.slash,1)} -pp$7.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1) -var size=1 -var tokentype=code===42?tt.star:tt.modulo -if(this.options.ecmaVersion>=7&&next===42){++size -tokentype=tt.starstar -next=this.input.charCodeAt(this.pos+2)} -if(next===61)return this.finishOp(tt.assign,size+1) -return this.finishOp(tokentype,size)} -pp$7.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1) -if(next===code)return this.finishOp(code===124?tt.logicalOR:tt.logicalAND,2) -if(next===61)return this.finishOp(tt.assign,2) -return this.finishOp(code===124?tt.bitwiseOR:tt.bitwiseAND,1)} -pp$7.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1) -if(next===61)return this.finishOp(tt.assign,2) -return this.finishOp(tt.bitwiseXOR,1)} -pp$7.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1) -if(next===code){if(next==45&&this.input.charCodeAt(this.pos+2)==62&&lineBreak.test(this.input.slice(this.lastTokEnd,this.pos))){this.skipLineComment(3) -this.skipSpace() -return this.nextToken()} -return this.finishOp(tt.incDec,2)} -if(next===61)return this.finishOp(tt.assign,2) -return this.finishOp(tt.plusMin,1)} -pp$7.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1) -var size=1 -if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2 -if(this.input.charCodeAt(this.pos+size)===61)return this.finishOp(tt.assign,size+1) -return this.finishOp(tt.bitShift,size)} -if(next==33&&code==60&&this.input.charCodeAt(this.pos+2)==45&&this.input.charCodeAt(this.pos+3)==45){if(this.inModule)this.unexpected() -this.skipLineComment(4) -this.skipSpace() -return this.nextToken()} -if(next===61)size=2 -return this.finishOp(tt.relational,size)} -pp$7.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1) -if(next===61)return this.finishOp(tt.equality,this.input.charCodeAt(this.pos+2)===61?3:2) -if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2 -return this.finishToken(tt.arrow)} -return this.finishOp(code===61?tt.eq:tt.prefix,1)} -pp$7.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot() -case 40:++this.pos;return this.finishToken(tt.parenL) -case 41:++this.pos;return this.finishToken(tt.parenR) -case 59:++this.pos;return this.finishToken(tt.semi) -case 44:++this.pos;return this.finishToken(tt.comma) -case 91:++this.pos;return this.finishToken(tt.bracketL) -case 93:++this.pos;return this.finishToken(tt.bracketR) -case 123:++this.pos;return this.finishToken(tt.braceL) -case 125:++this.pos;return this.finishToken(tt.braceR) -case 58:++this.pos;return this.finishToken(tt.colon) -case 63:++this.pos;return this.finishToken(tt.question) -case 96:if(this.options.ecmaVersion<6)break -++this.pos -return this.finishToken(tt.backQuote) -case 48:var next=this.input.charCodeAt(this.pos+1) -if(next===120||next===88)return this.readRadixNumber(16) -if(this.options.ecmaVersion>=6){if(next===111||next===79)return this.readRadixNumber(8) -if(next===98||next===66)return this.readRadixNumber(2)} -case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false) -case 34:case 39:return this.readString(code) -case 47:return this.readToken_slash() -case 37:case 42:return this.readToken_mult_modulo_exp(code) -case 124:case 38:return this.readToken_pipe_amp(code) -case 94:return this.readToken_caret() -case 43:case 45:return this.readToken_plus_min(code) -case 60:case 62:return this.readToken_lt_gt(code) -case 61:case 33:return this.readToken_eq_excl(code) -case 126:return this.finishOp(tt.prefix,1)} -this.raise(this.pos,"Unexpected character '"+codePointToString(code)+"'")} -pp$7.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size) -this.pos+=size -return this.finishToken(type,str)} -function tryCreateRegexp(src,flags,throwErrorAt,parser){try{return new RegExp(src,flags)}catch(e){if(throwErrorAt!==undefined){if(e instanceof SyntaxError)parser.raise(throwErrorAt,"Error parsing regular expression: "+e.message) -throw e}}} -var regexpUnicodeSupport=!!tryCreateRegexp("\uffff","u") -pp$7.readRegexp=function(){var this$1=this;var escaped,inClass,start=this.pos -for(;;){if(this$1.pos>=this$1.input.length)this$1.raise(start,"Unterminated regular expression") -var ch=this$1.input.charAt(this$1.pos) -if(lineBreak.test(ch))this$1.raise(start,"Unterminated regular expression") -if(!escaped){if(ch==="[")inClass=true -else if(ch==="]"&&inClass)inClass=false -else if(ch==="/"&&!inClass)break -escaped=ch==="\\"}else escaped=false -++this$1.pos} -var content=this.input.slice(start,this.pos) -++this.pos -var mods=this.readWord1() -var tmp=content,tmpFlags="" -if(mods){var validFlags=/^[gim]*$/ -if(this.options.ecmaVersion>=6)validFlags=/^[gimuy]*$/ -if(!validFlags.test(mods))this.raise(start,"Invalid regular expression flag") -if(mods.indexOf("u")>=0){if(regexpUnicodeSupport){tmpFlags="u"}else{tmp=tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g,function(_match,code,offset){code=Number("0x"+code) -if(code>0x10FFFF)this$1.raise(start+offset+3,"Code point out of bounds") -return"x"}) -tmp=tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x") -tmpFlags=tmpFlags.replace("u","")}}} -var value=null -if(!isRhino){tryCreateRegexp(tmp,tmpFlags,start,this) -value=tryCreateRegexp(content,mods)} -return this.finishToken(tt.regexp,{pattern:content,flags:mods,value:value})} -pp$7.readInt=function(radix,len){var this$1=this;var start=this.pos,total=0 -for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=this$1.input.charCodeAt(this$1.pos),val -if(code>=97)val=code-97+10 -else if(code>=65)val=code-65+10 -else if(code>=48&&code<=57)val=code-48 -else val=Infinity -if(val>=radix)break -++this$1.pos -total=total*radix+val} -if(this.pos===start||len!=null&&this.pos-start!==len)return null -return total} -pp$7.readRadixNumber=function(radix){this.pos+=2 -var val=this.readInt(radix) -if(val==null)this.raise(this.start+2,"Expected number in radix "+radix) -if(isIdentifierStart(this.fullCharCodeAtPos()))this.raise(this.pos,"Identifier directly after number") -return this.finishToken(tt.num,val)} -pp$7.readNumber=function(startsWithDot){var start=this.pos,isFloat=false,octal=this.input.charCodeAt(this.pos)===48 -if(!startsWithDot&&this.readInt(10)===null)this.raise(start,"Invalid number") -if(octal&&this.pos==start+1)octal=false -var next=this.input.charCodeAt(this.pos) -if(next===46&&!octal){++this.pos -this.readInt(10) -isFloat=true -next=this.input.charCodeAt(this.pos)} -if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos) -if(next===43||next===45)++this.pos -if(this.readInt(10)===null)this.raise(start,"Invalid number") -isFloat=true} -if(isIdentifierStart(this.fullCharCodeAtPos()))this.raise(this.pos,"Identifier directly after number") -var str=this.input.slice(start,this.pos),val -if(isFloat)val=parseFloat(str) -else if(!octal||str.length===1)val=parseInt(str,10) -else if(/[89]/.test(str)||this.strict)this.raise(start,"Invalid number") -else val=parseInt(str,8) -return this.finishToken(tt.num,val)} -pp$7.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code -if(ch===123){if(this.options.ecmaVersion<6)this.unexpected() -var codePos=++this.pos -code=this.readHexChar(this.input.indexOf('}',this.pos)-this.pos) -++this.pos -if(code>0x10FFFF)this.raise(codePos,"Code point out of bounds")}else{code=this.readHexChar(4)} -return code} -function codePointToString(code){if(code<=0xFFFF)return String.fromCharCode(code) -code-=0x10000 -return String.fromCharCode((code>>10)+0xD800,(code&1023)+0xDC00)} -pp$7.readString=function(quote){var this$1=this;var out="",chunkStart=++this.pos -for(;;){if(this$1.pos>=this$1.input.length)this$1.raise(this$1.start,"Unterminated string constant") -var ch=this$1.input.charCodeAt(this$1.pos) -if(ch===quote)break -if(ch===92){out+=this$1.input.slice(chunkStart,this$1.pos) -out+=this$1.readEscapedChar(false) -chunkStart=this$1.pos}else{if(isNewLine(ch))this$1.raise(this$1.start,"Unterminated string constant") -++this$1.pos}} -out+=this.input.slice(chunkStart,this.pos++) -return this.finishToken(tt.string,out)} -pp$7.readTmplToken=function(){var this$1=this;var out="",chunkStart=this.pos -for(;;){if(this$1.pos>=this$1.input.length)this$1.raise(this$1.start,"Unterminated template") -var ch=this$1.input.charCodeAt(this$1.pos) -if(ch===96||ch===36&&this$1.input.charCodeAt(this$1.pos+1)===123){if(this$1.pos===this$1.start&&this$1.type===tt.template){if(ch===36){this$1.pos+=2 -return this$1.finishToken(tt.dollarBraceL)}else{++this$1.pos -return this$1.finishToken(tt.backQuote)}} -out+=this$1.input.slice(chunkStart,this$1.pos) -return this$1.finishToken(tt.template,out)} -if(ch===92){out+=this$1.input.slice(chunkStart,this$1.pos) -out+=this$1.readEscapedChar(true) -chunkStart=this$1.pos}else if(isNewLine(ch)){out+=this$1.input.slice(chunkStart,this$1.pos) -++this$1.pos -switch(ch){case 13:if(this$1.input.charCodeAt(this$1.pos)===10)++this$1.pos -case 10:out+="\n" -break -default:out+=String.fromCharCode(ch) -break} -if(this$1.options.locations){++this$1.curLine -this$1.lineStart=this$1.pos} -chunkStart=this$1.pos}else{++this$1.pos}}} -pp$7.readEscapedChar=function(inTemplate){var ch=this.input.charCodeAt(++this.pos) -++this.pos -switch(ch){case 110:return"\n" -case 114:return"\r" -case 120:return String.fromCharCode(this.readHexChar(2)) -case 117:return codePointToString(this.readCodePoint()) -case 116:return"\t" -case 98:return"\b" -case 118:return"\u000b" -case 102:return"\f" -case 13:if(this.input.charCodeAt(this.pos)===10)++this.pos -case 10:if(this.options.locations){this.lineStart=this.pos;++this.curLine} -return"" -default:if(ch>=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0] -var octal=parseInt(octalStr,8) -if(octal>255){octalStr=octalStr.slice(0,-1) -octal=parseInt(octalStr,8)} -if(octalStr!=="0"&&(this.strict||inTemplate)){this.raise(this.pos-2,"Octal literal in strict mode")} -this.pos+=octalStr.length-1 -return String.fromCharCode(octal)} -return String.fromCharCode(ch)}} -pp$7.readHexChar=function(len){var codePos=this.pos -var n=this.readInt(16,len) -if(n===null)this.raise(codePos,"Bad character escape sequence") -return n} -pp$7.readWord1=function(){var this$1=this;this.containsEsc=false -var word="",first=true,chunkStart=this.pos -var astral=this.options.ecmaVersion>=6 -while(this.pos<this.input.length){var ch=this$1.fullCharCodeAtPos() -if(isIdentifierChar(ch,astral)){this$1.pos+=ch<=0xffff?1:2}else if(ch===92){this$1.containsEsc=true -word+=this$1.input.slice(chunkStart,this$1.pos) -var escStart=this$1.pos -if(this$1.input.charCodeAt(++this$1.pos)!=117) -this$1.raise(this$1.pos,"Expecting Unicode escape sequence \\uXXXX") -++this$1.pos -var esc=this$1.readCodePoint() -if(!(first?isIdentifierStart:isIdentifierChar)(esc,astral)) -this$1.raise(escStart,"Invalid Unicode escape") -word+=codePointToString(esc) -chunkStart=this$1.pos}else{break} -first=false} -return word+this.input.slice(chunkStart,this.pos)} -pp$7.readWord=function(){var word=this.readWord1() -var type=tt.name -if((this.options.ecmaVersion>=6||!this.containsEsc)&&this.keywords.test(word)) -type=keywordTypes[word] -return this.finishToken(type,word)} -var version="4.0.3" -function parse(input,options){return new Parser(options,input).parse()} -function parseExpressionAt(input,pos,options){var p=new Parser(options,input,pos) -p.nextToken() -return p.parseExpression()} -function tokenizer(input,options){return new Parser(options,input)} -function addLooseExports(parse,Parser,plugins){exports.parse_dammit=parse -exports.LooseParser=Parser -exports.pluginsLoose=plugins} -exports.version=version;exports.parse=parse;exports.parseExpressionAt=parseExpressionAt;exports.tokenizer=tokenizer;exports.addLooseExports=addLooseExports;exports.Parser=Parser;exports.plugins=plugins;exports.defaultOptions=defaultOptions;exports.Position=Position;exports.SourceLocation=SourceLocation;exports.getLineInfo=getLineInfo;exports.Node=Node;exports.TokenType=TokenType;exports.tokTypes=tt;exports.TokContext=TokContext;exports.tokContexts=types;exports.isIdentifierChar=isIdentifierChar;exports.isIdentifierStart=isIdentifierStart;exports.Token=Token;exports.isNewLine=isNewLine;exports.lineBreak=lineBreak;exports.lineBreakG=lineBreakG;Object.defineProperty(exports,'__esModule',{value:true});})));;(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?factory(exports,require('./acorn')):typeof define==='function'&&define.amd?define(['exports','./acorn'],factory):(factory((global.acorn=global.acorn||{},global.acorn.loose=global.acorn.loose||{}),global.acorn));}(this,(function(exports,__acorn){'use strict';var pluginsLoose={} -var LooseParser=function LooseParser(input,options){if(options===void 0)options={};this.toks=__acorn.tokenizer(input,options) -this.options=this.toks.options -this.input=this.toks.input -this.tok=this.last={type:__acorn.tokTypes.eof,start:0,end:0} -if(this.options.locations){var here=this.toks.curPosition() -this.tok.loc=new __acorn.SourceLocation(this.toks,here,here)} -this.ahead=[] -this.context=[] -this.curIndent=0 -this.curLineStart=0 -this.nextLineStart=this.lineEnd(this.curLineStart)+1 -this.inAsync=false -this.options.pluginsLoose=options.pluginsLoose||{} -this.loadPlugins(this.options.pluginsLoose)};LooseParser.prototype.startNode=function startNode(){return new __acorn.Node(this.toks,this.tok.start,this.options.locations?this.tok.loc.start:null)};LooseParser.prototype.storeCurrentPos=function storeCurrentPos(){return this.options.locations?[this.tok.start,this.tok.loc.start]:this.tok.start};LooseParser.prototype.startNodeAt=function startNodeAt(pos){if(this.options.locations){return new __acorn.Node(this.toks,pos[0],pos[1])}else{return new __acorn.Node(this.toks,pos)}};LooseParser.prototype.finishNode=function finishNode(node,type){node.type=type -node.end=this.last.end -if(this.options.locations) -node.loc.end=this.last.loc.end -if(this.options.ranges) -node.range[1]=this.last.end -return node};LooseParser.prototype.dummyNode=function dummyNode(type){var dummy=this.startNode() -dummy.type=type -dummy.end=dummy.start -if(this.options.locations) -dummy.loc.end=dummy.loc.start -if(this.options.ranges) -dummy.range[1]=dummy.start -this.last={type:__acorn.tokTypes.name,start:dummy.start,end:dummy.start,loc:dummy.loc} -return dummy};LooseParser.prototype.dummyIdent=function dummyIdent(){var dummy=this.dummyNode("Identifier") -dummy.name="✖" -return dummy};LooseParser.prototype.dummyString=function dummyString(){var dummy=this.dummyNode("Literal") -dummy.value=dummy.raw="✖" -return dummy};LooseParser.prototype.eat=function eat(type){if(this.tok.type===type){this.next() -return true}else{return false}};LooseParser.prototype.isContextual=function isContextual(name){return this.tok.type===__acorn.tokTypes.name&&this.tok.value===name};LooseParser.prototype.eatContextual=function eatContextual(name){return this.tok.value===name&&this.eat(__acorn.tokTypes.name)};LooseParser.prototype.canInsertSemicolon=function canInsertSemicolon(){return this.tok.type===__acorn.tokTypes.eof||this.tok.type===__acorn.tokTypes.braceR||__acorn.lineBreak.test(this.input.slice(this.last.end,this.tok.start))};LooseParser.prototype.semicolon=function semicolon(){return this.eat(__acorn.tokTypes.semi)};LooseParser.prototype.expect=function expect(type){var this$1=this;if(this.eat(type))return true -for(var i=1;i<=2;i++){if(this$1.lookAhead(i).type==type){for(var j=0;j<i;j++)this$1.next() -return true}}};LooseParser.prototype.pushCx=function pushCx(){this.context.push(this.curIndent)};LooseParser.prototype.popCx=function popCx(){this.curIndent=this.context.pop()};LooseParser.prototype.lineEnd=function lineEnd(pos){while(pos<this.input.length&&!__acorn.isNewLine(this.input.charCodeAt(pos)))++pos -return pos};LooseParser.prototype.indentationAfter=function indentationAfter(pos){var this$1=this;for(var count=0;;++pos){var ch=this$1.input.charCodeAt(pos) -if(ch===32)++count -else if(ch===9)count+=this$1.options.tabSize -else return count}};LooseParser.prototype.closes=function closes(closeTok,indent,line,blockHeuristic){if(this.tok.type===closeTok||this.tok.type===__acorn.tokTypes.eof)return true -return line!=this.curLineStart&&this.curIndent<indent&&this.tokenStartsLine()&&(!blockHeuristic||this.nextLineStart>=this.input.length||this.indentationAfter(this.nextLineStart)<indent)};LooseParser.prototype.tokenStartsLine=function tokenStartsLine(){var this$1=this;for(var p=this.tok.start-1;p>=this.curLineStart;--p){var ch=this$1.input.charCodeAt(p) -if(ch!==9&&ch!==32)return false} -return true};LooseParser.prototype.extend=function extend(name,f){this[name]=f(this[name])};LooseParser.prototype.loadPlugins=function loadPlugins(pluginConfigs){var this$1=this;for(var name in pluginConfigs){var plugin=pluginsLoose[name] -if(!plugin)throw new Error("Plugin '"+name+"' not found") -plugin(this$1,pluginConfigs[name])}};var lp=LooseParser.prototype -function isSpace(ch){return(ch<14&&ch>8)||ch===32||ch===160||__acorn.isNewLine(ch)} -lp.next=function(){var this$1=this;this.last=this.tok -if(this.ahead.length) -this.tok=this.ahead.shift() -else -this.tok=this.readToken() -if(this.tok.start>=this.nextLineStart){while(this.tok.start>=this.nextLineStart){this$1.curLineStart=this$1.nextLineStart -this$1.nextLineStart=this$1.lineEnd(this$1.curLineStart)+1} -this.curIndent=this.indentationAfter(this.curLineStart)}} -lp.readToken=function(){var this$1=this;for(;;){try{this$1.toks.next() -if(this$1.toks.type===__acorn.tokTypes.dot&&this$1.input.substr(this$1.toks.end,1)==="."&&this$1.options.ecmaVersion>=6){this$1.toks.end++ -this$1.toks.type=__acorn.tokTypes.ellipsis} -return new __acorn.Token(this$1.toks)}catch(e){if(!(e instanceof SyntaxError))throw e -var msg=e.message,pos=e.raisedAt,replace=true -if(/unterminated/i.test(msg)){pos=this$1.lineEnd(e.pos+1) -if(/string/.test(msg)){replace={start:e.pos,end:pos,type:__acorn.tokTypes.string,value:this$1.input.slice(e.pos+1,pos)}}else if(/regular expr/i.test(msg)){var re=this$1.input.slice(e.pos,pos) -try{re=new RegExp(re)}catch(e){} -replace={start:e.pos,end:pos,type:__acorn.tokTypes.regexp,value:re}}else if(/template/.test(msg)){replace={start:e.pos,end:pos,type:__acorn.tokTypes.template,value:this$1.input.slice(e.pos,pos)}}else{replace=false}}else if(/invalid (unicode|regexp|number)|expecting unicode|octal literal|is reserved|directly after number|expected number in radix/i.test(msg)){while(pos<this.input.length&&!isSpace(this.input.charCodeAt(pos)))++pos}else if(/character escape|expected hexadecimal/i.test(msg)){while(pos<this.input.length){var ch=this$1.input.charCodeAt(pos++) -if(ch===34||ch===39||__acorn.isNewLine(ch))break}}else if(/unexpected character/i.test(msg)){pos++ -replace=false}else if(/regular expression/i.test(msg)){replace=true}else{throw e} -this$1.resetTo(pos) -if(replace===true)replace={start:pos,end:pos,type:__acorn.tokTypes.name,value:"✖"} -if(replace){if(this$1.options.locations) -replace.loc=new __acorn.SourceLocation(this$1.toks,__acorn.getLineInfo(this$1.input,replace.start),__acorn.getLineInfo(this$1.input,replace.end)) -return replace}}}} -lp.resetTo=function(pos){var this$1=this;this.toks.pos=pos -var ch=this.input.charAt(pos-1) -this.toks.exprAllowed=!ch||/[[{(,;:?/*=+\-~!|&%^<>]/.test(ch)||/[enwfd]/.test(ch)&&/\b(keywords|case|else|return|throw|new|in|(instance|type)of|delete|void)$/.test(this.input.slice(pos-10,pos)) -if(this.options.locations){this.toks.curLine=1 -this.toks.lineStart=__acorn.lineBreakG.lastIndex=0 -var match -while((match=__acorn.lineBreakG.exec(this.input))&&match.index<pos){++this$1.toks.curLine -this$1.toks.lineStart=match.index+match[0].length}}} -lp.lookAhead=function(n){var this$1=this;while(n>this.ahead.length) -this$1.ahead.push(this$1.readToken()) -return this.ahead[n-1]} -function isDummy(node){return node.name=="✖"} -var lp$1=LooseParser.prototype -lp$1.parseTopLevel=function(){var this$1=this;var node=this.startNodeAt(this.options.locations?[0,__acorn.getLineInfo(this.input,0)]:0) -node.body=[] -while(this.tok.type!==__acorn.tokTypes.eof)node.body.push(this$1.parseStatement()) -this.last=this.tok -if(this.options.ecmaVersion>=6){node.sourceType=this.options.sourceType} -return this.finishNode(node,"Program")} -lp$1.parseStatement=function(){var this$1=this;var starttype=this.tok.type,node=this.startNode(),kind -if(this.toks.isLet()){starttype=__acorn.tokTypes._var -kind="let"} -switch(starttype){case __acorn.tokTypes._break:case __acorn.tokTypes._continue:this.next() -var isBreak=starttype===__acorn.tokTypes._break -if(this.semicolon()||this.canInsertSemicolon()){node.label=null}else{node.label=this.tok.type===__acorn.tokTypes.name?this.parseIdent():null -this.semicolon()} -return this.finishNode(node,isBreak?"BreakStatement":"ContinueStatement") -case __acorn.tokTypes._debugger:this.next() -this.semicolon() -return this.finishNode(node,"DebuggerStatement") -case __acorn.tokTypes._do:this.next() -node.body=this.parseStatement() -node.test=this.eat(__acorn.tokTypes._while)?this.parseParenExpression():this.dummyIdent() -this.semicolon() -return this.finishNode(node,"DoWhileStatement") -case __acorn.tokTypes._for:this.next() -this.pushCx() -this.expect(__acorn.tokTypes.parenL) -if(this.tok.type===__acorn.tokTypes.semi)return this.parseFor(node,null) -var isLet=this.toks.isLet() -if(isLet||this.tok.type===__acorn.tokTypes._var||this.tok.type===__acorn.tokTypes._const){var init$1=this.parseVar(true,isLet?"let":this.tok.value) -if(init$1.declarations.length===1&&(this.tok.type===__acorn.tokTypes._in||this.isContextual("of"))){return this.parseForIn(node,init$1)} -return this.parseFor(node,init$1)} -var init=this.parseExpression(true) -if(this.tok.type===__acorn.tokTypes._in||this.isContextual("of")) -return this.parseForIn(node,this.toAssignable(init)) -return this.parseFor(node,init) -case __acorn.tokTypes._function:this.next() -return this.parseFunction(node,true) -case __acorn.tokTypes._if:this.next() -node.test=this.parseParenExpression() -node.consequent=this.parseStatement() -node.alternate=this.eat(__acorn.tokTypes._else)?this.parseStatement():null -return this.finishNode(node,"IfStatement") -case __acorn.tokTypes._return:this.next() -if(this.eat(__acorn.tokTypes.semi)||this.canInsertSemicolon())node.argument=null -else{node.argument=this.parseExpression();this.semicolon()} -return this.finishNode(node,"ReturnStatement") -case __acorn.tokTypes._switch:var blockIndent=this.curIndent,line=this.curLineStart -this.next() -node.discriminant=this.parseParenExpression() -node.cases=[] -this.pushCx() -this.expect(__acorn.tokTypes.braceL) -var cur -while(!this.closes(__acorn.tokTypes.braceR,blockIndent,line,true)){if(this$1.tok.type===__acorn.tokTypes._case||this$1.tok.type===__acorn.tokTypes._default){var isCase=this$1.tok.type===__acorn.tokTypes._case -if(cur)this$1.finishNode(cur,"SwitchCase") -node.cases.push(cur=this$1.startNode()) -cur.consequent=[] -this$1.next() -if(isCase)cur.test=this$1.parseExpression() -else cur.test=null -this$1.expect(__acorn.tokTypes.colon)}else{if(!cur){node.cases.push(cur=this$1.startNode()) -cur.consequent=[] -cur.test=null} -cur.consequent.push(this$1.parseStatement())}} -if(cur)this.finishNode(cur,"SwitchCase") -this.popCx() -this.eat(__acorn.tokTypes.braceR) -return this.finishNode(node,"SwitchStatement") -case __acorn.tokTypes._throw:this.next() -node.argument=this.parseExpression() -this.semicolon() -return this.finishNode(node,"ThrowStatement") -case __acorn.tokTypes._try:this.next() -node.block=this.parseBlock() -node.handler=null -if(this.tok.type===__acorn.tokTypes._catch){var clause=this.startNode() -this.next() -this.expect(__acorn.tokTypes.parenL) -clause.param=this.toAssignable(this.parseExprAtom(),true) -this.expect(__acorn.tokTypes.parenR) -clause.body=this.parseBlock() -node.handler=this.finishNode(clause,"CatchClause")} -node.finalizer=this.eat(__acorn.tokTypes._finally)?this.parseBlock():null -if(!node.handler&&!node.finalizer)return node.block -return this.finishNode(node,"TryStatement") -case __acorn.tokTypes._var:case __acorn.tokTypes._const:return this.parseVar(false,kind||this.tok.value) -case __acorn.tokTypes._while:this.next() -node.test=this.parseParenExpression() -node.body=this.parseStatement() -return this.finishNode(node,"WhileStatement") -case __acorn.tokTypes._with:this.next() -node.object=this.parseParenExpression() -node.body=this.parseStatement() -return this.finishNode(node,"WithStatement") -case __acorn.tokTypes.braceL:return this.parseBlock() -case __acorn.tokTypes.semi:this.next() -return this.finishNode(node,"EmptyStatement") -case __acorn.tokTypes._class:return this.parseClass(true) -case __acorn.tokTypes._import:return this.parseImport() -case __acorn.tokTypes._export:return this.parseExport() -default:if(this.toks.isAsyncFunction()){this.next() -this.next() -return this.parseFunction(node,true,true)} -var expr=this.parseExpression() -if(isDummy(expr)){this.next() -if(this.tok.type===__acorn.tokTypes.eof)return this.finishNode(node,"EmptyStatement") -return this.parseStatement()}else if(starttype===__acorn.tokTypes.name&&expr.type==="Identifier"&&this.eat(__acorn.tokTypes.colon)){node.body=this.parseStatement() -node.label=expr -return this.finishNode(node,"LabeledStatement")}else{node.expression=expr -this.semicolon() -return this.finishNode(node,"ExpressionStatement")}}} -lp$1.parseBlock=function(){var this$1=this;var node=this.startNode() -this.pushCx() -this.expect(__acorn.tokTypes.braceL) -var blockIndent=this.curIndent,line=this.curLineStart -node.body=[] -while(!this.closes(__acorn.tokTypes.braceR,blockIndent,line,true)) -node.body.push(this$1.parseStatement()) -this.popCx() -this.eat(__acorn.tokTypes.braceR) -return this.finishNode(node,"BlockStatement")} -lp$1.parseFor=function(node,init){node.init=init -node.test=node.update=null -if(this.eat(__acorn.tokTypes.semi)&&this.tok.type!==__acorn.tokTypes.semi)node.test=this.parseExpression() -if(this.eat(__acorn.tokTypes.semi)&&this.tok.type!==__acorn.tokTypes.parenR)node.update=this.parseExpression() -this.popCx() -this.expect(__acorn.tokTypes.parenR) -node.body=this.parseStatement() -return this.finishNode(node,"ForStatement")} -lp$1.parseForIn=function(node,init){var type=this.tok.type===__acorn.tokTypes._in?"ForInStatement":"ForOfStatement" -this.next() -node.left=init -node.right=this.parseExpression() -this.popCx() -this.expect(__acorn.tokTypes.parenR) -node.body=this.parseStatement() -return this.finishNode(node,type)} -lp$1.parseVar=function(noIn,kind){var this$1=this;var node=this.startNode() -node.kind=kind -this.next() -node.declarations=[] -do{var decl=this$1.startNode() -decl.id=this$1.options.ecmaVersion>=6?this$1.toAssignable(this$1.parseExprAtom(),true):this$1.parseIdent() -decl.init=this$1.eat(__acorn.tokTypes.eq)?this$1.parseMaybeAssign(noIn):null -node.declarations.push(this$1.finishNode(decl,"VariableDeclarator"))}while(this.eat(__acorn.tokTypes.comma)) -if(!node.declarations.length){var decl$1=this.startNode() -decl$1.id=this.dummyIdent() -node.declarations.push(this.finishNode(decl$1,"VariableDeclarator"))} -if(!noIn)this.semicolon() -return this.finishNode(node,"VariableDeclaration")} -lp$1.parseClass=function(isStatement){var this$1=this;var node=this.startNode() -this.next() -if(this.tok.type===__acorn.tokTypes.name)node.id=this.parseIdent() -else if(isStatement===true)node.id=this.dummyIdent() -else node.id=null -node.superClass=this.eat(__acorn.tokTypes._extends)?this.parseExpression():null -node.body=this.startNode() -node.body.body=[] -this.pushCx() -var indent=this.curIndent+1,line=this.curLineStart -this.eat(__acorn.tokTypes.braceL) -if(this.curIndent+1<indent){indent=this.curIndent;line=this.curLineStart} -while(!this.closes(__acorn.tokTypes.braceR,indent,line)){if(this$1.semicolon())continue -var method=this$1.startNode(),isGenerator,isAsync -if(this$1.options.ecmaVersion>=6){method.static=false -isGenerator=this$1.eat(__acorn.tokTypes.star)} -this$1.parsePropertyName(method) -if(isDummy(method.key)){if(isDummy(this$1.parseMaybeAssign()))this$1.next();this$1.eat(__acorn.tokTypes.comma);continue} -if(method.key.type==="Identifier"&&!method.computed&&method.key.name==="static"&&(this$1.tok.type!=__acorn.tokTypes.parenL&&this$1.tok.type!=__acorn.tokTypes.braceL)){method.static=true -isGenerator=this$1.eat(__acorn.tokTypes.star) -this$1.parsePropertyName(method)}else{method.static=false} -if(!method.computed&&method.key.type==="Identifier"&&method.key.name==="async"&&this$1.tok.type!==__acorn.tokTypes.parenL&&!this$1.canInsertSemicolon()){this$1.parsePropertyName(method) -isAsync=true}else{isAsync=false} -if(this$1.options.ecmaVersion>=5&&method.key.type==="Identifier"&&!method.computed&&(method.key.name==="get"||method.key.name==="set")&&this$1.tok.type!==__acorn.tokTypes.parenL&&this$1.tok.type!==__acorn.tokTypes.braceL){method.kind=method.key.name -this$1.parsePropertyName(method) -method.value=this$1.parseMethod(false)}else{if(!method.computed&&!method.static&&!isGenerator&&!isAsync&&(method.key.type==="Identifier"&&method.key.name==="constructor"||method.key.type==="Literal"&&method.key.value==="constructor")){method.kind="constructor"}else{method.kind="method"} -method.value=this$1.parseMethod(isGenerator,isAsync)} -node.body.body.push(this$1.finishNode(method,"MethodDefinition"))} -this.popCx() -if(!this.eat(__acorn.tokTypes.braceR)){this.last.end=this.tok.start -if(this.options.locations)this.last.loc.end=this.tok.loc.start} -this.semicolon() -this.finishNode(node.body,"ClassBody") -return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")} -lp$1.parseFunction=function(node,isStatement,isAsync){var oldInAsync=this.inAsync -this.initFunction(node) -if(this.options.ecmaVersion>=6){node.generator=this.eat(__acorn.tokTypes.star)} -if(this.options.ecmaVersion>=8){node.async=!!isAsync} -if(this.tok.type===__acorn.tokTypes.name)node.id=this.parseIdent() -else if(isStatement===true)node.id=this.dummyIdent() -this.inAsync=node.async -node.params=this.parseFunctionParams() -node.body=this.parseBlock() -this.inAsync=oldInAsync -return this.finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")} -lp$1.parseExport=function(){var node=this.startNode() -this.next() -if(this.eat(__acorn.tokTypes.star)){node.source=this.eatContextual("from")?this.parseExprAtom():this.dummyString() -return this.finishNode(node,"ExportAllDeclaration")} -if(this.eat(__acorn.tokTypes._default)){var isAsync -if(this.tok.type===__acorn.tokTypes._function||(isAsync=this.toks.isAsyncFunction())){var fNode=this.startNode() -this.next() -if(isAsync)this.next() -node.declaration=this.parseFunction(fNode,"nullableID",isAsync)}else if(this.tok.type===__acorn.tokTypes._class){node.declaration=this.parseClass("nullableID")}else{node.declaration=this.parseMaybeAssign() -this.semicolon()} -return this.finishNode(node,"ExportDefaultDeclaration")} -if(this.tok.type.keyword||this.toks.isLet()||this.toks.isAsyncFunction()){node.declaration=this.parseStatement() -node.specifiers=[] -node.source=null}else{node.declaration=null -node.specifiers=this.parseExportSpecifierList() -node.source=this.eatContextual("from")?this.parseExprAtom():null -this.semicolon()} -return this.finishNode(node,"ExportNamedDeclaration")} -lp$1.parseImport=function(){var node=this.startNode() -this.next() -if(this.tok.type===__acorn.tokTypes.string){node.specifiers=[] -node.source=this.parseExprAtom() -node.kind=""}else{var elt -if(this.tok.type===__acorn.tokTypes.name&&this.tok.value!=="from"){elt=this.startNode() -elt.local=this.parseIdent() -this.finishNode(elt,"ImportDefaultSpecifier") -this.eat(__acorn.tokTypes.comma)} -node.specifiers=this.parseImportSpecifierList() -node.source=this.eatContextual("from")&&this.tok.type==__acorn.tokTypes.string?this.parseExprAtom():this.dummyString() -if(elt)node.specifiers.unshift(elt)} -this.semicolon() -return this.finishNode(node,"ImportDeclaration")} -lp$1.parseImportSpecifierList=function(){var this$1=this;var elts=[] -if(this.tok.type===__acorn.tokTypes.star){var elt=this.startNode() -this.next() -elt.local=this.eatContextual("as")?this.parseIdent():this.dummyIdent() -elts.push(this.finishNode(elt,"ImportNamespaceSpecifier"))}else{var indent=this.curIndent,line=this.curLineStart,continuedLine=this.nextLineStart -this.pushCx() -this.eat(__acorn.tokTypes.braceL) -if(this.curLineStart>continuedLine)continuedLine=this.curLineStart -while(!this.closes(__acorn.tokTypes.braceR,indent+(this.curLineStart<=continuedLine?1:0),line)){var elt$1=this$1.startNode() -if(this$1.eat(__acorn.tokTypes.star)){elt$1.local=this$1.eatContextual("as")?this$1.parseIdent():this$1.dummyIdent() -this$1.finishNode(elt$1,"ImportNamespaceSpecifier")}else{if(this$1.isContextual("from"))break -elt$1.imported=this$1.parseIdent() -if(isDummy(elt$1.imported))break -elt$1.local=this$1.eatContextual("as")?this$1.parseIdent():elt$1.imported -this$1.finishNode(elt$1,"ImportSpecifier")} -elts.push(elt$1) -this$1.eat(__acorn.tokTypes.comma)} -this.eat(__acorn.tokTypes.braceR) -this.popCx()} -return elts} -lp$1.parseExportSpecifierList=function(){var this$1=this;var elts=[] -var indent=this.curIndent,line=this.curLineStart,continuedLine=this.nextLineStart -this.pushCx() -this.eat(__acorn.tokTypes.braceL) -if(this.curLineStart>continuedLine)continuedLine=this.curLineStart -while(!this.closes(__acorn.tokTypes.braceR,indent+(this.curLineStart<=continuedLine?1:0),line)){if(this$1.isContextual("from"))break -var elt=this$1.startNode() -elt.local=this$1.parseIdent() -if(isDummy(elt.local))break -elt.exported=this$1.eatContextual("as")?this$1.parseIdent():elt.local -this$1.finishNode(elt,"ExportSpecifier") -elts.push(elt) -this$1.eat(__acorn.tokTypes.comma)} -this.eat(__acorn.tokTypes.braceR) -this.popCx() -return elts} -var lp$2=LooseParser.prototype -lp$2.checkLVal=function(expr){if(!expr)return expr -switch(expr.type){case"Identifier":case"MemberExpression":return expr -case"ParenthesizedExpression":expr.expression=this.checkLVal(expr.expression) -return expr -default:return this.dummyIdent()}} -lp$2.parseExpression=function(noIn){var this$1=this;var start=this.storeCurrentPos() -var expr=this.parseMaybeAssign(noIn) -if(this.tok.type===__acorn.tokTypes.comma){var node=this.startNodeAt(start) -node.expressions=[expr] -while(this.eat(__acorn.tokTypes.comma))node.expressions.push(this$1.parseMaybeAssign(noIn)) -return this.finishNode(node,"SequenceExpression")} -return expr} -lp$2.parseParenExpression=function(){this.pushCx() -this.expect(__acorn.tokTypes.parenL) -var val=this.parseExpression() -this.popCx() -this.expect(__acorn.tokTypes.parenR) -return val} -lp$2.parseMaybeAssign=function(noIn){if(this.toks.isContextual("yield")){var node=this.startNode() -this.next() -if(this.semicolon()||this.canInsertSemicolon()||(this.tok.type!=__acorn.tokTypes.star&&!this.tok.type.startsExpr)){node.delegate=false -node.argument=null}else{node.delegate=this.eat(__acorn.tokTypes.star) -node.argument=this.parseMaybeAssign()} -return this.finishNode(node,"YieldExpression")} -var start=this.storeCurrentPos() -var left=this.parseMaybeConditional(noIn) -if(this.tok.type.isAssign){var node$1=this.startNodeAt(start) -node$1.operator=this.tok.value -node$1.left=this.tok.type===__acorn.tokTypes.eq?this.toAssignable(left):this.checkLVal(left) -this.next() -node$1.right=this.parseMaybeAssign(noIn) -return this.finishNode(node$1,"AssignmentExpression")} -return left} -lp$2.parseMaybeConditional=function(noIn){var start=this.storeCurrentPos() -var expr=this.parseExprOps(noIn) -if(this.eat(__acorn.tokTypes.question)){var node=this.startNodeAt(start) -node.test=expr -node.consequent=this.parseMaybeAssign() -node.alternate=this.expect(__acorn.tokTypes.colon)?this.parseMaybeAssign(noIn):this.dummyIdent() -return this.finishNode(node,"ConditionalExpression")} -return expr} -lp$2.parseExprOps=function(noIn){var start=this.storeCurrentPos() -var indent=this.curIndent,line=this.curLineStart -return this.parseExprOp(this.parseMaybeUnary(false),start,-1,noIn,indent,line)} -lp$2.parseExprOp=function(left,start,minPrec,noIn,indent,line){if(this.curLineStart!=line&&this.curIndent<indent&&this.tokenStartsLine())return left -var prec=this.tok.type.binop -if(prec!=null&&(!noIn||this.tok.type!==__acorn.tokTypes._in)){if(prec>minPrec){var node=this.startNodeAt(start) -node.left=left -node.operator=this.tok.value -this.next() -if(this.curLineStart!=line&&this.curIndent<indent&&this.tokenStartsLine()){node.right=this.dummyIdent()}else{var rightStart=this.storeCurrentPos() -node.right=this.parseExprOp(this.parseMaybeUnary(false),rightStart,prec,noIn,indent,line)} -this.finishNode(node,/&&|\|\|/.test(node.operator)?"LogicalExpression":"BinaryExpression") -return this.parseExprOp(node,start,minPrec,noIn,indent,line)}} -return left} -lp$2.parseMaybeUnary=function(sawUnary){var this$1=this;var start=this.storeCurrentPos(),expr -if(this.options.ecmaVersion>=8&&this.inAsync&&this.toks.isContextual("await")){expr=this.parseAwait() -sawUnary=true}else if(this.tok.type.prefix){var node=this.startNode(),update=this.tok.type===__acorn.tokTypes.incDec -if(!update)sawUnary=true -node.operator=this.tok.value -node.prefix=true -this.next() -node.argument=this.parseMaybeUnary(true) -if(update)node.argument=this.checkLVal(node.argument) -expr=this.finishNode(node,update?"UpdateExpression":"UnaryExpression")}else if(this.tok.type===__acorn.tokTypes.ellipsis){var node$1=this.startNode() -this.next() -node$1.argument=this.parseMaybeUnary(sawUnary) -expr=this.finishNode(node$1,"SpreadElement")}else{expr=this.parseExprSubscripts() -while(this.tok.type.postfix&&!this.canInsertSemicolon()){var node$2=this$1.startNodeAt(start) -node$2.operator=this$1.tok.value -node$2.prefix=false -node$2.argument=this$1.checkLVal(expr) -this$1.next() -expr=this$1.finishNode(node$2,"UpdateExpression")}} -if(!sawUnary&&this.eat(__acorn.tokTypes.starstar)){var node$3=this.startNodeAt(start) -node$3.operator="**" -node$3.left=expr -node$3.right=this.parseMaybeUnary(false) -return this.finishNode(node$3,"BinaryExpression")} -return expr} -lp$2.parseExprSubscripts=function(){var start=this.storeCurrentPos() -return this.parseSubscripts(this.parseExprAtom(),start,false,this.curIndent,this.curLineStart)} -lp$2.parseSubscripts=function(base,start,noCalls,startIndent,line){var this$1=this;for(;;){if(this$1.curLineStart!=line&&this$1.curIndent<=startIndent&&this$1.tokenStartsLine()){if(this$1.tok.type==__acorn.tokTypes.dot&&this$1.curIndent==startIndent) ---startIndent -else -return base} -var maybeAsyncArrow=base.type==="Identifier"&&base.name==="async"&&!this$1.canInsertSemicolon() -if(this$1.eat(__acorn.tokTypes.dot)){var node=this$1.startNodeAt(start) -node.object=base -if(this$1.curLineStart!=line&&this$1.curIndent<=startIndent&&this$1.tokenStartsLine()) -node.property=this$1.dummyIdent() -else -node.property=this$1.parsePropertyAccessor()||this$1.dummyIdent() -node.computed=false -base=this$1.finishNode(node,"MemberExpression")}else if(this$1.tok.type==__acorn.tokTypes.bracketL){this$1.pushCx() -this$1.next() -var node$1=this$1.startNodeAt(start) -node$1.object=base -node$1.property=this$1.parseExpression() -node$1.computed=true -this$1.popCx() -this$1.expect(__acorn.tokTypes.bracketR) -base=this$1.finishNode(node$1,"MemberExpression")}else if(!noCalls&&this$1.tok.type==__acorn.tokTypes.parenL){var exprList=this$1.parseExprList(__acorn.tokTypes.parenR) -if(maybeAsyncArrow&&this$1.eat(__acorn.tokTypes.arrow)) -return this$1.parseArrowExpression(this$1.startNodeAt(start),exprList,true) -var node$2=this$1.startNodeAt(start) -node$2.callee=base -node$2.arguments=exprList -base=this$1.finishNode(node$2,"CallExpression")}else if(this$1.tok.type==__acorn.tokTypes.backQuote){var node$3=this$1.startNodeAt(start) -node$3.tag=base -node$3.quasi=this$1.parseTemplate() -base=this$1.finishNode(node$3,"TaggedTemplateExpression")}else{return base}}} -lp$2.parseExprAtom=function(){var node -switch(this.tok.type){case __acorn.tokTypes._this:case __acorn.tokTypes._super:var type=this.tok.type===__acorn.tokTypes._this?"ThisExpression":"Super" -node=this.startNode() -this.next() -return this.finishNode(node,type) -case __acorn.tokTypes.name:var start=this.storeCurrentPos() -var id=this.parseIdent() -var isAsync=false -if(id.name==="async"&&!this.canInsertSemicolon()){if(this.eat(__acorn.tokTypes._function)) -return this.parseFunction(this.startNodeAt(start),false,true) -if(this.tok.type===__acorn.tokTypes.name){id=this.parseIdent() -isAsync=true}} -return this.eat(__acorn.tokTypes.arrow)?this.parseArrowExpression(this.startNodeAt(start),[id],isAsync):id -case __acorn.tokTypes.regexp:node=this.startNode() -var val=this.tok.value -node.regex={pattern:val.pattern,flags:val.flags} -node.value=val.value -node.raw=this.input.slice(this.tok.start,this.tok.end) -this.next() -return this.finishNode(node,"Literal") -case __acorn.tokTypes.num:case __acorn.tokTypes.string:node=this.startNode() -node.value=this.tok.value -node.raw=this.input.slice(this.tok.start,this.tok.end) -this.next() -return this.finishNode(node,"Literal") -case __acorn.tokTypes._null:case __acorn.tokTypes._true:case __acorn.tokTypes._false:node=this.startNode() -node.value=this.tok.type===__acorn.tokTypes._null?null:this.tok.type===__acorn.tokTypes._true -node.raw=this.tok.type.keyword -this.next() -return this.finishNode(node,"Literal") -case __acorn.tokTypes.parenL:var parenStart=this.storeCurrentPos() -this.next() -var inner=this.parseExpression() -this.expect(__acorn.tokTypes.parenR) -if(this.eat(__acorn.tokTypes.arrow)){var params=inner.expressions||[inner] -if(params.length&&isDummy(params[params.length-1])) -params.pop() -return this.parseArrowExpression(this.startNodeAt(parenStart),params)} -if(this.options.preserveParens){var par=this.startNodeAt(parenStart) -par.expression=inner -inner=this.finishNode(par,"ParenthesizedExpression")} -return inner -case __acorn.tokTypes.bracketL:node=this.startNode() -node.elements=this.parseExprList(__acorn.tokTypes.bracketR,true) -return this.finishNode(node,"ArrayExpression") -case __acorn.tokTypes.braceL:return this.parseObj() -case __acorn.tokTypes._class:return this.parseClass(false) -case __acorn.tokTypes._function:node=this.startNode() -this.next() -return this.parseFunction(node,false) -case __acorn.tokTypes._new:return this.parseNew() -case __acorn.tokTypes.backQuote:return this.parseTemplate() -default:return this.dummyIdent()}} -lp$2.parseNew=function(){var node=this.startNode(),startIndent=this.curIndent,line=this.curLineStart -var meta=this.parseIdent(true) -if(this.options.ecmaVersion>=6&&this.eat(__acorn.tokTypes.dot)){node.meta=meta -node.property=this.parseIdent(true) -return this.finishNode(node,"MetaProperty")} -var start=this.storeCurrentPos() -node.callee=this.parseSubscripts(this.parseExprAtom(),start,true,startIndent,line) -if(this.tok.type==__acorn.tokTypes.parenL){node.arguments=this.parseExprList(__acorn.tokTypes.parenR)}else{node.arguments=[]} -return this.finishNode(node,"NewExpression")} -lp$2.parseTemplateElement=function(){var elem=this.startNode() -elem.value={raw:this.input.slice(this.tok.start,this.tok.end).replace(/\r\n?/g,"\n"),cooked:this.tok.value} -this.next() -elem.tail=this.tok.type===__acorn.tokTypes.backQuote -return this.finishNode(elem,"TemplateElement")} -lp$2.parseTemplate=function(){var this$1=this;var node=this.startNode() -this.next() -node.expressions=[] -var curElt=this.parseTemplateElement() -node.quasis=[curElt] -while(!curElt.tail){this$1.next() -node.expressions.push(this$1.parseExpression()) -if(this$1.expect(__acorn.tokTypes.braceR)){curElt=this$1.parseTemplateElement()}else{curElt=this$1.startNode() -curElt.value={cooked:"",raw:""} -curElt.tail=true -this$1.finishNode(curElt,"TemplateElement")} -node.quasis.push(curElt)} -this.expect(__acorn.tokTypes.backQuote) -return this.finishNode(node,"TemplateLiteral")} -lp$2.parseObj=function(){var this$1=this;var node=this.startNode() -node.properties=[] -this.pushCx() -var indent=this.curIndent+1,line=this.curLineStart -this.eat(__acorn.tokTypes.braceL) -if(this.curIndent+1<indent){indent=this.curIndent;line=this.curLineStart} -while(!this.closes(__acorn.tokTypes.braceR,indent,line)){var prop=this$1.startNode(),isGenerator,isAsync,start -if(this$1.options.ecmaVersion>=6){start=this$1.storeCurrentPos() -prop.method=false -prop.shorthand=false -isGenerator=this$1.eat(__acorn.tokTypes.star)} -this$1.parsePropertyName(prop) -if(!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&this$1.tok.type!==__acorn.tokTypes.parenL&&this$1.tok.type!==__acorn.tokTypes.colon&&!this$1.canInsertSemicolon()){this$1.parsePropertyName(prop) -isAsync=true}else{isAsync=false} -if(isDummy(prop.key)){if(isDummy(this$1.parseMaybeAssign()))this$1.next();this$1.eat(__acorn.tokTypes.comma);continue} -if(this$1.eat(__acorn.tokTypes.colon)){prop.kind="init" -prop.value=this$1.parseMaybeAssign()}else if(this$1.options.ecmaVersion>=6&&(this$1.tok.type===__acorn.tokTypes.parenL||this$1.tok.type===__acorn.tokTypes.braceL)){prop.kind="init" -prop.method=true -prop.value=this$1.parseMethod(isGenerator,isAsync)}else if(this$1.options.ecmaVersion>=5&&prop.key.type==="Identifier"&&!prop.computed&&(prop.key.name==="get"||prop.key.name==="set")&&(this$1.tok.type!=__acorn.tokTypes.comma&&this$1.tok.type!=__acorn.tokTypes.braceR)){prop.kind=prop.key.name -this$1.parsePropertyName(prop) -prop.value=this$1.parseMethod(false)}else{prop.kind="init" -if(this$1.options.ecmaVersion>=6){if(this$1.eat(__acorn.tokTypes.eq)){var assign=this$1.startNodeAt(start) -assign.operator="=" -assign.left=prop.key -assign.right=this$1.parseMaybeAssign() -prop.value=this$1.finishNode(assign,"AssignmentExpression")}else{prop.value=prop.key}}else{prop.value=this$1.dummyIdent()} -prop.shorthand=true} -node.properties.push(this$1.finishNode(prop,"Property")) -this$1.eat(__acorn.tokTypes.comma)} -this.popCx() -if(!this.eat(__acorn.tokTypes.braceR)){this.last.end=this.tok.start -if(this.options.locations)this.last.loc.end=this.tok.loc.start} -return this.finishNode(node,"ObjectExpression")} -lp$2.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(__acorn.tokTypes.bracketL)){prop.computed=true -prop.key=this.parseExpression() -this.expect(__acorn.tokTypes.bracketR) -return}else{prop.computed=false}} -var key=(this.tok.type===__acorn.tokTypes.num||this.tok.type===__acorn.tokTypes.string)?this.parseExprAtom():this.parseIdent() -prop.key=key||this.dummyIdent()} -lp$2.parsePropertyAccessor=function(){if(this.tok.type===__acorn.tokTypes.name||this.tok.type.keyword)return this.parseIdent()} -lp$2.parseIdent=function(){var name=this.tok.type===__acorn.tokTypes.name?this.tok.value:this.tok.type.keyword -if(!name)return this.dummyIdent() -var node=this.startNode() -this.next() -node.name=name -return this.finishNode(node,"Identifier")} -lp$2.initFunction=function(node){node.id=null -node.params=[] -if(this.options.ecmaVersion>=6){node.generator=false -node.expression=false} -if(this.options.ecmaVersion>=8) -node.async=false} -lp$2.toAssignable=function(node,binding){var this$1=this;if(!node||node.type=="Identifier"||(node.type=="MemberExpression"&&!binding)){}else if(node.type=="ParenthesizedExpression"){node.expression=this.toAssignable(node.expression,binding)}else if(this.options.ecmaVersion<6){return this.dummyIdent()}else if(node.type=="ObjectExpression"){node.type="ObjectPattern" -var props=node.properties -for(var i=0;i<props.length;i++) -props[i].value=this$1.toAssignable(props[i].value,binding)}else if(node.type=="ArrayExpression"){node.type="ArrayPattern" -this.toAssignableList(node.elements,binding)}else if(node.type=="SpreadElement"){node.type="RestElement" -node.argument=this.toAssignable(node.argument,binding)}else if(node.type=="AssignmentExpression"){node.type="AssignmentPattern" -delete node.operator}else{return this.dummyIdent()} -return node} -lp$2.toAssignableList=function(exprList,binding){var this$1=this;for(var i=0;i<exprList.length;i++) -exprList[i]=this$1.toAssignable(exprList[i],binding) -return exprList} -lp$2.parseFunctionParams=function(params){params=this.parseExprList(__acorn.tokTypes.parenR) -return this.toAssignableList(params,true)} -lp$2.parseMethod=function(isGenerator,isAsync){var node=this.startNode(),oldInAsync=this.inAsync -this.initFunction(node) -if(this.options.ecmaVersion>=6) -node.generator=!!isGenerator -if(this.options.ecmaVersion>=8) -node.async=!!isAsync -this.inAsync=node.async -node.params=this.parseFunctionParams() -node.expression=this.options.ecmaVersion>=6&&this.tok.type!==__acorn.tokTypes.braceL -node.body=node.expression?this.parseMaybeAssign():this.parseBlock() -this.inAsync=oldInAsync -return this.finishNode(node,"FunctionExpression")} -lp$2.parseArrowExpression=function(node,params,isAsync){var oldInAsync=this.inAsync -this.initFunction(node) -if(this.options.ecmaVersion>=8) -node.async=!!isAsync -this.inAsync=node.async -node.params=this.toAssignableList(params,true) -node.expression=this.tok.type!==__acorn.tokTypes.braceL -node.body=node.expression?this.parseMaybeAssign():this.parseBlock() -this.inAsync=oldInAsync -return this.finishNode(node,"ArrowFunctionExpression")} -lp$2.parseExprList=function(close,allowEmpty){var this$1=this;this.pushCx() -var indent=this.curIndent,line=this.curLineStart,elts=[] -this.next() -while(!this.closes(close,indent+1,line)){if(this$1.eat(__acorn.tokTypes.comma)){elts.push(allowEmpty?null:this$1.dummyIdent()) -continue} -var elt=this$1.parseMaybeAssign() -if(isDummy(elt)){if(this$1.closes(close,indent,line))break -this$1.next()}else{elts.push(elt)} -this$1.eat(__acorn.tokTypes.comma)} -this.popCx() -if(!this.eat(close)){this.last.end=this.tok.start -if(this.options.locations)this.last.loc.end=this.tok.loc.start} -return elts} -lp$2.parseAwait=function(){var node=this.startNode() -this.next() -node.argument=this.parseMaybeUnary() -return this.finishNode(node,"AwaitExpression")} -__acorn.defaultOptions.tabSize=4 -function parse_dammit(input,options){var p=new LooseParser(input,options) -p.next() -return p.parseTopLevel()} -__acorn.addLooseExports(parse_dammit,LooseParser,pluginsLoose) -exports.parse_dammit=parse_dammit;exports.LooseParser=LooseParser;exports.pluginsLoose=pluginsLoose;Object.defineProperty(exports,'__esModule',{value:true});})));;FormatterWorker.CSSFormatter=class{constructor(builder){this._builder=builder;} -format(text,lineEndings,fromOffset,toOffset){this._lineEndings=lineEndings;this._fromOffset=fromOffset;this._toOffset=toOffset;this._lastLine=-1;this._state={};var tokenize=FormatterWorker.createTokenizer('text/css');var oldEnforce=this._builder.setEnforceSpaceBetweenWords(false);tokenize(text.substring(this._fromOffset,this._toOffset),this._tokenCallback.bind(this));this._builder.setEnforceSpaceBetweenWords(oldEnforce);} -_tokenCallback(token,type,startPosition){startPosition+=this._fromOffset;var startLine=this._lineEndings.lowerBound(startPosition);if(startLine!==this._lastLine) -this._state.eatWhitespace=true;if(/^property/.test(type)&&!this._state.inPropertyValue) -this._state.seenProperty=true;this._lastLine=startLine;var isWhitespace=/^\s+$/.test(token);if(isWhitespace){if(!this._state.eatWhitespace) -this._builder.addSoftSpace();return;} -this._state.eatWhitespace=false;if(token==='\n') -return;if(token!=='}'){if(this._state.afterClosingBrace) -this._builder.addNewLine(true);this._state.afterClosingBrace=false;} -if(token==='}'){if(this._state.inPropertyValue) -this._builder.addNewLine();this._builder.decreaseNestingLevel();this._state.afterClosingBrace=true;this._state.inPropertyValue=false;}else if(token===':'&&!this._state.inPropertyValue&&this._state.seenProperty){this._builder.addToken(token,startPosition);this._builder.addSoftSpace();this._state.eatWhitespace=true;this._state.inPropertyValue=true;this._state.seenProperty=false;return;}else if(token==='{'){this._builder.addSoftSpace();this._builder.addToken(token,startPosition);this._builder.addNewLine();this._builder.increaseNestingLevel();return;} -this._builder.addToken(token,startPosition);if(type==='comment'&&!this._state.inPropertyValue&&!this._state.seenProperty) -this._builder.addNewLine();if(token===';'&&this._state.inPropertyValue){this._state.inPropertyValue=false;this._builder.addNewLine();}else if(token==='}'){this._builder.addNewLine();}}};;FormatterWorker.AcornTokenizer=class{constructor(content){this._content=content;this._comments=[];this._tokenizer=acorn.tokenizer(this._content,{ecmaVersion:8,onComment:this._comments});this._textCursor=new TextUtils.TextCursor(this._content.computeLineEndings());this._tokenLineStart=0;this._tokenLineEnd=0;this._nextTokenInternal();} -static punctuator(token,values){return token.type!==acorn.tokTypes.num&&token.type!==acorn.tokTypes.regexp&&token.type!==acorn.tokTypes.string&&token.type!==acorn.tokTypes.name&&!token.type.keyword&&(!values||(token.type.label.length===1&&values.indexOf(token.type.label)!==-1));} -static keyword(token,keyword){return!!token.type.keyword&&token.type!==acorn.tokTypes._true&&token.type!==acorn.tokTypes._false&&token.type!==acorn.tokTypes._null&&(!keyword||token.type.keyword===keyword);} -static identifier(token,identifier){return token.type===acorn.tokTypes.name&&(!identifier||token.value===identifier);} -static lineComment(token){return token.type==='Line';} -static blockComment(token){return token.type==='Block';} -_nextTokenInternal(){if(this._comments.length) -return this._comments.shift();var token=this._bufferedToken;this._bufferedToken=this._tokenizer.getToken();return token;} -nextToken(){var token=this._nextTokenInternal();if(token.type===acorn.tokTypes.eof) -return null;this._textCursor.advance(token.start);this._tokenLineStart=this._textCursor.lineNumber();this._tokenColumnStart=this._textCursor.columnNumber();this._textCursor.advance(token.end);this._tokenLineEnd=this._textCursor.lineNumber();return token;} -peekToken(){if(this._comments.length) -return this._comments[0];return this._bufferedToken.type!==acorn.tokTypes.eof?this._bufferedToken:null;} -tokenLineStart(){return this._tokenLineStart;} -tokenLineEnd(){return this._tokenLineEnd;} -tokenColumnStart(){return this._tokenColumnStart;}};;FormatterWorker.JavaScriptFormatter=class{constructor(builder){this._builder=builder;} -format(text,lineEndings,fromOffset,toOffset){this._fromOffset=fromOffset;this._toOffset=toOffset;this._content=text.substring(this._fromOffset,this._toOffset);this._lastLineNumber=0;this._tokenizer=new FormatterWorker.AcornTokenizer(this._content);var ast=acorn.parse(this._content,{ranges:false,ecmaVersion:8,preserveParens:true});var walker=new FormatterWorker.ESTreeWalker(this._beforeVisit.bind(this),this._afterVisit.bind(this));walker.walk(ast);} -_push(token,format){for(var i=0;i<format.length;++i){if(format[i]==='s'){this._builder.addSoftSpace();}else if(format[i]==='S'){this._builder.addHardSpace();}else if(format[i]==='n'){this._builder.addNewLine();}else if(format[i]==='>'){this._builder.increaseNestingLevel();}else if(format[i]==='<'){this._builder.decreaseNestingLevel();}else if(format[i]==='t'){if(this._tokenizer.tokenLineStart()-this._lastLineNumber>1) -this._builder.addNewLine(true);this._lastLineNumber=this._tokenizer.tokenLineEnd();this._builder.addToken(this._content.substring(token.start,token.end),this._fromOffset+token.start);}}} -_beforeVisit(node){if(!node.parent) -return;while(this._tokenizer.peekToken()&&this._tokenizer.peekToken().start<node.start){var token=(this._tokenizer.nextToken());var format=this._formatToken(node.parent,token);this._push(token,format);}} -_afterVisit(node){while(this._tokenizer.peekToken()&&this._tokenizer.peekToken().start<node.end){var token=(this._tokenizer.nextToken());var format=this._formatToken(node,token);this._push(token,format);} -this._push(null,this._finishNode(node));} -_inForLoopHeader(node){var parent=node.parent;if(!parent) -return false;if(parent.type==='ForStatement') -return node===parent.init||node===parent.test||node===parent.update;if(parent.type==='ForInStatement'||parent.type==='ForOfStatement') -return node===parent.left||parent.right;return false;} -_formatToken(node,token){var AT=FormatterWorker.AcornTokenizer;if(AT.lineComment(token)) -return'tn';if(AT.blockComment(token)) -return'tn';if(node.type==='ContinueStatement'||node.type==='BreakStatement'){return node.label&&AT.keyword(token)?'ts':'t';}else if(node.type==='Identifier'){return't';}else if(node.type==='ReturnStatement'){if(AT.punctuator(token,';')) -return't';return node.argument?'ts':'t';}else if(node.type==='Property'){if(AT.punctuator(token,':')) -return'ts';return't';}else if(node.type==='ArrayExpression'){if(AT.punctuator(token,',')) -return'ts';return't';}else if(node.type==='LabeledStatement'){if(AT.punctuator(token,':')) -return'ts';}else if(node.type==='LogicalExpression'||node.type==='AssignmentExpression'||node.type==='BinaryExpression'){if(AT.punctuator(token)&&!AT.punctuator(token,'()')) -return'sts';}else if(node.type==='ConditionalExpression'){if(AT.punctuator(token,'?:')) -return'sts';}else if(node.type==='VariableDeclarator'){if(AT.punctuator(token,'=')) -return'sts';}else if(node.type==='ObjectPattern'){if(node.parent&&node.parent.type==='VariableDeclarator'&&AT.punctuator(token,'{')) -return'st';if(AT.punctuator(token,',')) -return'ts';}else if(node.type==='FunctionDeclaration'){if(AT.punctuator(token,',)')) -return'ts';}else if(node.type==='FunctionExpression'){if(AT.punctuator(token,',)')) -return'ts';if(AT.keyword(token,'function')) -return node.id?'ts':'t';}else if(node.type==='WithStatement'){if(AT.punctuator(token,')')) -return node.body&&node.body.type==='BlockStatement'?'ts':'tn>';}else if(node.type==='SwitchStatement'){if(AT.punctuator(token,'{')) -return'tn>';if(AT.punctuator(token,'}')) -return'n<tn';if(AT.punctuator(token,')')) -return'ts';}else if(node.type==='SwitchCase'){if(AT.keyword(token,'case')) -return'n<ts';if(AT.keyword(token,'default')) -return'n<t';if(AT.punctuator(token,':')) -return'tn>';}else if(node.type==='VariableDeclaration'){if(AT.punctuator(token,',')){var allVariablesInitialized=true;var declarations=(node.declarations);for(var i=0;i<declarations.length;++i) -allVariablesInitialized=allVariablesInitialized&&!!declarations[i].init;return!this._inForLoopHeader(node)&&allVariablesInitialized?'nSSts':'ts';}}else if(node.type==='BlockStatement'){if(AT.punctuator(token,'{')) -return node.body.length?'tn>':'t';if(AT.punctuator(token,'}')) -return node.body.length?'n<t':'t';}else if(node.type==='CatchClause'){if(AT.punctuator(token,')')) -return'ts';}else if(node.type==='ObjectExpression'){if(!node.properties.length) -return't';if(AT.punctuator(token,'{')) -return'tn>';if(AT.punctuator(token,'}')) -return'n<t';if(AT.punctuator(token,',')) -return'tn';}else if(node.type==='IfStatement'){if(AT.punctuator(token,')')) -return node.consequent&&node.consequent.type==='BlockStatement'?'ts':'tn>';if(AT.keyword(token,'else')){var preFormat=node.consequent&&node.consequent.type==='BlockStatement'?'st':'n<t';var postFormat='n>';if(node.alternate&&(node.alternate.type==='BlockStatement'||node.alternate.type==='IfStatement')) -postFormat='s';return preFormat+postFormat;}}else if(node.type==='CallExpression'){if(AT.punctuator(token,',')) -return'ts';}else if(node.type==='SequenceExpression'&&AT.punctuator(token,',')){return node.parent&&node.parent.type==='SwitchCase'?'ts':'tn';}else if(node.type==='ForStatement'||node.type==='ForOfStatement'||node.type==='ForInStatement'){if(AT.punctuator(token,';')) -return'ts';if(AT.keyword(token,'in')||AT.identifier(token,'of')) -return'sts';if(AT.punctuator(token,')')) -return node.body&&node.body.type==='BlockStatement'?'ts':'tn>';}else if(node.type==='WhileStatement'){if(AT.punctuator(token,')')) -return node.body&&node.body.type==='BlockStatement'?'ts':'tn>';}else if(node.type==='DoWhileStatement'){var blockBody=node.body&&node.body.type==='BlockStatement';if(AT.keyword(token,'do')) -return blockBody?'ts':'tn>';if(AT.keyword(token,'while')) -return blockBody?'sts':'n<ts';}else if(node.type==='ClassBody'){if(AT.punctuator(token,'{')) -return'stn>';if(AT.punctuator(token,'}')) -return'<ntn';return't';}else if(node.type==='YieldExpression'){return't';}else if(node.type==='Super'){return't';} -return AT.keyword(token)&&!AT.keyword(token,'this')?'ts':'t';} -_finishNode(node){if(node.type==='WithStatement'){if(node.body&&node.body.type!=='BlockStatement') -return'n<';}else if(node.type==='VariableDeclaration'){if(!this._inForLoopHeader(node)) -return'n';}else if(node.type==='ForStatement'||node.type==='ForOfStatement'||node.type==='ForInStatement'){if(node.body&&node.body.type!=='BlockStatement') -return'n<';}else if(node.type==='BlockStatement'){if(node.parent&&node.parent.type==='IfStatement'&&node.parent.alternate&&node.parent.consequent===node) -return'';if(node.parent&&node.parent.type==='FunctionExpression'&&node.parent.parent&&node.parent.parent.type==='Property') -return'';if(node.parent&&node.parent.type==='FunctionExpression'&&node.parent.parent&&node.parent.parent.type==='VariableDeclarator') -return'';if(node.parent&&node.parent.type==='FunctionExpression'&&node.parent.parent&&node.parent.parent.type==='CallExpression') -return'';if(node.parent&&node.parent.type==='DoWhileStatement') -return'';if(node.parent&&node.parent.type==='TryStatement'&&node.parent.block===node) -return's';if(node.parent&&node.parent.type==='CatchClause'&&node.parent.parent.finalizer) -return's';return'n';}else if(node.type==='WhileStatement'){if(node.body&&node.body.type!=='BlockStatement') -return'n<';}else if(node.type==='IfStatement'){if(node.alternate){if(node.alternate.type!=='BlockStatement'&&node.alternate.type!=='IfStatement') -return'<';}else if(node.consequent){if(node.consequent.type!=='BlockStatement') -return'<';}}else if(node.type==='BreakStatement'||node.type==='ContinueStatement'||node.type==='ThrowStatement'||node.type==='ReturnStatement'||node.type==='ExpressionStatement'){return'n';} -return'';}};;FormatterWorker.FormattedContentBuilder=class{constructor(indentString){this._lastOriginalPosition=0;this._formattedContent=[];this._formattedContentLength=0;this._lastFormattedPosition=0;this._mapping={original:[0],formatted:[0]};this._nestingLevel=0;this._indentString=indentString;this._cachedIndents=new Map();this._newLines=0;this._softSpace=false;this._hardSpaces=0;this._enforceSpaceBetweenWords=true;} -setEnforceSpaceBetweenWords(value){var oldValue=this._enforceSpaceBetweenWords;this._enforceSpaceBetweenWords=value;return oldValue;} -addToken(token,offset){var last=this._formattedContent.peekLast();if(this._enforceSpaceBetweenWords&&last&&/\w/.test(last[last.length-1])&&/\w/.test(token)) -this.addSoftSpace();this._appendFormatting();this._addMappingIfNeeded(offset);this._addText(token);} -addSoftSpace(){if(!this._hardSpaces) -this._softSpace=true;} -addHardSpace(){this._softSpace=false;++this._hardSpaces;} -addNewLine(noSquash){if(!this._formattedContentLength) -return;if(noSquash) -++this._newLines;else -this._newLines=this._newLines||1;} -increaseNestingLevel(){this._nestingLevel+=1;} -decreaseNestingLevel(){if(this._nestingLevel>0) -this._nestingLevel-=1;} -_appendFormatting(){if(this._newLines){for(var i=0;i<this._newLines;++i) -this._addText('\n');this._addText(this._indent());}else if(this._softSpace){this._addText(' ');} -if(this._hardSpaces){for(var i=0;i<this._hardSpaces;++i) -this._addText(' ');} -this._newLines=0;this._softSpace=false;this._hardSpaces=0;} -content(){return this._formattedContent.join('')+(this._newLines?'\n':'');} -mapping(){return this._mapping;} -_indent(){var cachedValue=this._cachedIndents.get(this._nestingLevel);if(cachedValue) -return cachedValue;var fullIndent='';for(var i=0;i<this._nestingLevel;++i) -fullIndent+=this._indentString;if(this._nestingLevel<=20) -this._cachedIndents.set(this._nestingLevel,fullIndent);return fullIndent;} -_addText(text){this._formattedContent.push(text);this._formattedContentLength+=text.length;} -_addMappingIfNeeded(originalPosition){if(originalPosition-this._lastOriginalPosition===this._formattedContentLength-this._lastFormattedPosition) -return;this._mapping.original.push(originalPosition);this._lastOriginalPosition=originalPosition;this._mapping.formatted.push(this._formattedContentLength);this._lastFormattedPosition=this._formattedContentLength;}};;FormatterWorker.CSSParserStates={Initial:'Initial',Selector:'Selector',Style:'Style',PropertyName:'PropertyName',PropertyValue:'PropertyValue',AtRule:'AtRule'};FormatterWorker.parseCSS=function(text){FormatterWorker._innerParseCSS(text,postMessage);};FormatterWorker._innerParseCSS=function(text,chunkCallback){var chunkSize=100000;var lines=text.split('\n');var rules=[];var processedChunkCharacters=0;var state=FormatterWorker.CSSParserStates.Initial;var rule;var property;var UndefTokenType=new Set();var disabledRules=[];function disabledRulesCallback(chunk){disabledRules=disabledRules.concat(chunk.chunk);} -function processToken(tokenValue,tokenTypes,column,newColumn){var tokenType=tokenTypes?new Set(tokenTypes.split(' ')):UndefTokenType;switch(state){case FormatterWorker.CSSParserStates.Initial:if(tokenType.has('qualifier')||tokenType.has('builtin')||tokenType.has('tag')){rule={selectorText:tokenValue,lineNumber:lineNumber,columnNumber:column,properties:[],};state=FormatterWorker.CSSParserStates.Selector;}else if(tokenType.has('def')){rule={atRule:tokenValue,lineNumber:lineNumber,columnNumber:column,};state=FormatterWorker.CSSParserStates.AtRule;} -break;case FormatterWorker.CSSParserStates.Selector:if(tokenValue==='{'&&tokenType===UndefTokenType){rule.selectorText=rule.selectorText.trim();rule.styleRange=createRange(lineNumber,newColumn);state=FormatterWorker.CSSParserStates.Style;}else{rule.selectorText+=tokenValue;} -break;case FormatterWorker.CSSParserStates.AtRule:if((tokenValue===';'||tokenValue==='{')&&tokenType===UndefTokenType){rule.atRule=rule.atRule.trim();rules.push(rule);state=FormatterWorker.CSSParserStates.Initial;}else{rule.atRule+=tokenValue;} -break;case FormatterWorker.CSSParserStates.Style:if(tokenType.has('meta')||tokenType.has('property')){property={name:tokenValue,value:'',range:createRange(lineNumber,column),nameRange:createRange(lineNumber,column)};state=FormatterWorker.CSSParserStates.PropertyName;}else if(tokenValue==='}'&&tokenType===UndefTokenType){rule.styleRange.endLine=lineNumber;rule.styleRange.endColumn=column;rules.push(rule);state=FormatterWorker.CSSParserStates.Initial;}else if(tokenType.has('comment')){if(tokenValue.substring(0,2)!=='/*'||tokenValue.substring(tokenValue.length-2)!=='*/') -break;var uncommentedText=tokenValue.substring(2,tokenValue.length-2);var fakeRule='a{\n'+uncommentedText+'}';disabledRules=[];FormatterWorker._innerParseCSS(fakeRule,disabledRulesCallback);if(disabledRules.length===1&&disabledRules[0].properties.length===1){var disabledProperty=disabledRules[0].properties[0];disabledProperty.disabled=true;disabledProperty.range=createRange(lineNumber,column);disabledProperty.range.endColumn=newColumn;var lineOffset=lineNumber-1;var columnOffset=column+2;disabledProperty.nameRange.startLine+=lineOffset;disabledProperty.nameRange.startColumn+=columnOffset;disabledProperty.nameRange.endLine+=lineOffset;disabledProperty.nameRange.endColumn+=columnOffset;disabledProperty.valueRange.startLine+=lineOffset;disabledProperty.valueRange.startColumn+=columnOffset;disabledProperty.valueRange.endLine+=lineOffset;disabledProperty.valueRange.endColumn+=columnOffset;rule.properties.push(disabledProperty);}} -break;case FormatterWorker.CSSParserStates.PropertyName:if(tokenValue===':'&&tokenType===UndefTokenType){property.name=property.name;property.nameRange.endLine=lineNumber;property.nameRange.endColumn=column;property.valueRange=createRange(lineNumber,newColumn);state=FormatterWorker.CSSParserStates.PropertyValue;}else if(tokenType.has('property')){property.name+=tokenValue;} -break;case FormatterWorker.CSSParserStates.PropertyValue:if((tokenValue===';'||tokenValue==='}')&&tokenType===UndefTokenType){property.value=property.value;property.valueRange.endLine=lineNumber;property.valueRange.endColumn=column;property.range.endLine=lineNumber;property.range.endColumn=tokenValue===';'?newColumn:column;rule.properties.push(property);if(tokenValue==='}'){rule.styleRange.endLine=lineNumber;rule.styleRange.endColumn=column;rules.push(rule);state=FormatterWorker.CSSParserStates.Initial;}else{state=FormatterWorker.CSSParserStates.Style;}}else if(!tokenType.has('comment')){property.value+=tokenValue;} -break;default:console.assert(false,'Unknown CSS parser state.');} -processedChunkCharacters+=newColumn-column;if(processedChunkCharacters>chunkSize){chunkCallback({chunk:rules,isLastChunk:false});rules=[];processedChunkCharacters=0;}} -var tokenizer=FormatterWorker.createTokenizer('text/css');var lineNumber;for(lineNumber=0;lineNumber<lines.length;++lineNumber){var line=lines[lineNumber];tokenizer(line,processToken);processToken('\n',null,line.length,line.length+1);} -chunkCallback({chunk:rules,isLastChunk:true});function createRange(lineNumber,columnNumber){return{startLine:lineNumber,startColumn:columnNumber,endLine:lineNumber,endColumn:columnNumber};}};;FormatterWorker.HTMLFormatter=class{constructor(builder){this._builder=builder;this._jsFormatter=new FormatterWorker.JavaScriptFormatter(builder);this._cssFormatter=new FormatterWorker.CSSFormatter(builder);} -format(text,lineEndings){this._text=text;this._lineEndings=lineEndings;this._model=new FormatterWorker.HTMLModel(text);this._walk(this._model.document());} -_formatTokensTill(element,offset){while(this._model.peekToken()&&this._model.peekToken().startOffset<offset){var token=this._model.nextToken();this._formatToken(element,token);}} -_walk(element){if(element.parent) -this._formatTokensTill(element.parent,element.openTag.startOffset);this._beforeOpenTag(element);this._formatTokensTill(element,element.openTag.endOffset);this._afterOpenTag(element);for(var i=0;i<element.children.length;++i) -this._walk(element.children[i]);this._formatTokensTill(element,element.closeTag.startOffset);this._beforeCloseTag(element);this._formatTokensTill(element,element.closeTag.endOffset);this._afterCloseTag(element);} -_beforeOpenTag(element){if(!element.children.length||element===this._model.document()) -return;this._builder.addNewLine();} -_afterOpenTag(element){if(!element.children.length||element===this._model.document()) -return;this._builder.increaseNestingLevel();this._builder.addNewLine();} -_beforeCloseTag(element){if(!element.children.length||element===this._model.document()) -return;this._builder.decreaseNestingLevel();this._builder.addNewLine();} -_afterCloseTag(element){this._builder.addNewLine();} -_formatToken(element,token){if(token.value.isWhitespace()) -return;if(token.type.has('comment')||token.type.has('meta')){this._builder.addNewLine();this._builder.addToken(token.value.trim(),token.startOffset);this._builder.addNewLine();return;} -var isBodyToken=element.openTag.endOffset<=token.startOffset&&token.startOffset<element.closeTag.startOffset;if(isBodyToken&&element.name==='style'){this._builder.addNewLine();this._builder.increaseNestingLevel();this._cssFormatter.format(this._text,this._lineEndings,token.startOffset,token.endOffset);this._builder.decreaseNestingLevel();return;} -if(isBodyToken&&element.name==='script'){this._builder.addNewLine();this._builder.increaseNestingLevel();var mimeType=element.openTag.attributes.has('type')?element.openTag.attributes.get('type').toLowerCase():null;if(!mimeType||FormatterWorker.HTMLFormatter.SupportedJavaScriptMimeTypes.has(mimeType)){this._jsFormatter.format(this._text,this._lineEndings,token.startOffset,token.endOffset);}else{this._builder.addToken(token.value,token.startOffset);this._builder.addNewLine();} -this._builder.decreaseNestingLevel();return;} -if(!isBodyToken&&token.type.has('attribute')) -this._builder.addSoftSpace();this._builder.addToken(token.value,token.startOffset);}};FormatterWorker.HTMLFormatter.SupportedJavaScriptMimeTypes=new Set(['text/javascript','text/ecmascript','application/javascript','application/ecmascript']);FormatterWorker.HTMLModel=class{constructor(text){this._state=FormatterWorker.HTMLModel.ParseState.Initial;this._document=new FormatterWorker.HTMLModel.Element('document');this._document.openTag=new FormatterWorker.HTMLModel.Tag('document',0,0,new Map(),true,false);this._document.closeTag=new FormatterWorker.HTMLModel.Tag('document',text.length,text.length,new Map(),false,false);this._stack=[this._document];this._tokens=[];this._tokenIndex=0;this._build(text);} -_build(text){var tokenizer=FormatterWorker.createTokenizer('text/html');var lastOffset=0;var lowerCaseText=text.toLowerCase();while(true){tokenizer(text.substring(lastOffset),processToken.bind(this,lastOffset));if(lastOffset>=text.length) -break;var element=this._stack.peekLast();lastOffset=lowerCaseText.indexOf('</'+element.name,lastOffset);if(lastOffset===-1) -lastOffset=text.length;var tokenStart=element.openTag.endOffset;var tokenEnd=lastOffset;var tokenValue=text.substring(tokenStart,tokenEnd);this._tokens.push(new FormatterWorker.HTMLModel.Token(tokenValue,new Set(),tokenStart,tokenEnd));} -while(this._stack.length>1){var element=this._stack.peekLast();this._popElement(new FormatterWorker.HTMLModel.Tag(element.name,text.length,text.length,new Map(),false,false));} -function processToken(baseOffset,tokenValue,type,tokenStart,tokenEnd){tokenStart+=baseOffset;tokenEnd+=baseOffset;lastOffset=tokenEnd;var tokenType=type?new Set(type.split(' ')):new Set();var token=new FormatterWorker.HTMLModel.Token(tokenValue,tokenType,tokenStart,tokenEnd);this._tokens.push(token);this._updateDOM(token);var element=this._stack.peekLast();if(element&&(element.name==='script'||element.name==='style')&&element.openTag.endOffset===lastOffset) -return FormatterWorker.AbortTokenization;}} -_updateDOM(token){var S=FormatterWorker.HTMLModel.ParseState;var value=token.value;var type=token.type;switch(this._state){case S.Initial:if(type.has('bracket')&&(value==='<'||value==='</')){this._onStartTag(token);this._state=S.Tag;} -return;case S.Tag:if(type.has('tag')&&!type.has('bracket')){this._tagName=value.trim().toLowerCase();}else if(type.has('attribute')){this._attributeName=value.trim().toLowerCase();this._attributes.set(this._attributeName,'');this._state=S.AttributeName;}else if(type.has('bracket')&&(value==='>'||value==='/>')){this._onEndTag(token);this._state=S.Initial;} -return;case S.AttributeName:if(!type.size&&value==='='){this._state=S.AttributeValue;}else if(type.has('bracket')&&(value==='>'||value==='/>')){this._onEndTag(token);this._state=S.Initial;} -return;case S.AttributeValue:if(type.has('string')){this._attributes.set(this._attributeName,value);this._state=S.Tag;}else if(type.has('bracket')&&(value==='>'||value==='/>')){this._onEndTag(token);this._state=S.Initial;} -return;}} -_onStartTag(token){this._tagName='';this._tagStartOffset=token.startOffset;this._tagEndOffset=null;this._attributes=new Map();this._attributeName='';this._isOpenTag=token.value==='<';} -_onEndTag(token){this._tagEndOffset=token.endOffset;var selfClosingTag=token.value==='/>'||FormatterWorker.HTMLModel.SelfClosingTags.has(this._tagName);var tag=new FormatterWorker.HTMLModel.Tag(this._tagName,this._tagStartOffset,this._tagEndOffset,this._attributes,this._isOpenTag,selfClosingTag);this._onTagComplete(tag);} -_onTagComplete(tag){if(tag.isOpenTag){var topElement=this._stack.peekLast();if(topElement!==this._document&&topElement.openTag.selfClosingTag) -this._popElement(autocloseTag(topElement,topElement.openTag.endOffset));else if((topElement.name in FormatterWorker.HTMLModel.AutoClosingTags)&&FormatterWorker.HTMLModel.AutoClosingTags[topElement.name].has(tag.name)) -this._popElement(autocloseTag(topElement,tag.startOffset));this._pushElement(tag);return;} -while(this._stack.length>1&&this._stack.peekLast().name!==tag.name) -this._popElement(autocloseTag(this._stack.peekLast(),tag.startOffset));if(this._stack.length===1) -return;this._popElement(tag);function autocloseTag(element,offset){return new FormatterWorker.HTMLModel.Tag(element.name,offset,offset,new Map(),false,false);}} -_popElement(closeTag){var element=this._stack.pop();element.closeTag=closeTag;} -_pushElement(openTag){var topElement=this._stack.peekLast();var newElement=new FormatterWorker.HTMLModel.Element(openTag.name);newElement.parent=topElement;topElement.children.push(newElement);newElement.openTag=openTag;this._stack.push(newElement);} -peekToken(){return this._tokenIndex<this._tokens.length?this._tokens[this._tokenIndex]:null;} -nextToken(){return this._tokens[this._tokenIndex++];} -document(){return this._document;}};FormatterWorker.HTMLModel.SelfClosingTags=new Set(['area','base','br','col','command','embed','hr','img','input','keygen','link','meta','param','source','track','wbr']);FormatterWorker.HTMLModel.AutoClosingTags={'head':new Set(['body']),'li':new Set(['li']),'dt':new Set(['dt','dd']),'dd':new Set(['dt','dd']),'p':new Set(['address','article','aside','blockquote','div','dl','fieldset','footer','form','h1','h2','h3','h4','h5','h6','header','hgroup','hr','main','nav','ol','p','pre','section','table','ul']),'rb':new Set(['rb','rt','rtc','rp']),'rt':new Set(['rb','rt','rtc','rp']),'rtc':new Set(['rb','rtc','rp']),'rp':new Set(['rb','rt','rtc','rp']),'optgroup':new Set(['optgroup']),'option':new Set(['option','optgroup']),'colgroup':new Set(['colgroup']),'thead':new Set(['tbody','tfoot']),'tbody':new Set(['tbody','tfoot']),'tfoot':new Set(['tbody']),'tr':new Set(['tr']),'td':new Set(['td','th']),'th':new Set(['td','th']),};FormatterWorker.HTMLModel.ParseState={Initial:'Initial',Tag:'Tag',AttributeName:'AttributeName',AttributeValue:'AttributeValue'};FormatterWorker.HTMLModel.Token=class{constructor(value,type,startOffset,endOffset){this.value=value;this.type=type;this.startOffset=startOffset;this.endOffset=endOffset;}};FormatterWorker.HTMLModel.Tag=class{constructor(name,startOffset,endOffset,attributes,isOpenTag,selfClosingTag){this.name=name;this.startOffset=startOffset;this.endOffset=endOffset;this.attributes=attributes;this.isOpenTag=isOpenTag;this.selfClosingTag=selfClosingTag;}};FormatterWorker.HTMLModel.Element=class{constructor(name){this.name=name;this.children=[];this.parent=null;this.openTag=null;this.closeTag=null;}};;FormatterWorker.IdentityFormatter=class{constructor(builder){this._builder=builder;} -format(text,lineEndings,fromOffset,toOffset){var content=text.substring(fromOffset,toOffset);this._builder.addToken(content,fromOffset);}};;FormatterWorker.javaScriptOutline=function(content){var chunkSize=100000;var outlineChunk=[];var lastReportedOffset=0;var ast;try{ast=acorn.parse(content,{ranges:false,ecmaVersion:8});}catch(e){ast=acorn.parse_dammit(content,{ranges:false,ecmaVersion:8});} -var textCursor=new TextUtils.TextCursor(content.computeLineEndings());var walker=new FormatterWorker.ESTreeWalker(beforeVisit);walker.walk(ast);postMessage({chunk:outlineChunk,isLastChunk:true});function beforeVisit(node){if(node.type==='ClassDeclaration'){reportClass((node.id));}else if(node.type==='VariableDeclarator'&&isClassNode(node.init)){reportClass((node.id));}else if(node.type==='AssignmentExpression'&&isNameNode(node.left)&&isClassNode(node.right)){reportClass((node.left));}else if(node.type==='Property'&&isNameNode(node.key)&&isClassNode(node.value)){reportClass((node.key));}else if(node.type==='FunctionDeclaration'){reportFunction((node.id),node);}else if(node.type==='VariableDeclarator'&&isFunctionNode(node.init)){reportFunction((node.id),(node.init));}else if(node.type==='AssignmentExpression'&&isNameNode(node.left)&&isFunctionNode(node.right)){reportFunction((node.left),(node.right));}else if((node.type==='MethodDefinition'||node.type==='Property')&&isNameNode(node.key)&&isFunctionNode(node.value)){var namePrefix=[];if(node.kind==='get'||node.kind==='set') -namePrefix.push(node.kind);if(node.static) -namePrefix.push('static');reportFunction(node.key,node.value,namePrefix.join(' '));}} -function reportClass(nameNode){var name='class '+stringifyNameNode(nameNode);textCursor.advance(nameNode.start);addOutlineItem({name:name,line:textCursor.lineNumber(),column:textCursor.columnNumber(),});} -function reportFunction(nameNode,functionNode,namePrefix){var name=stringifyNameNode(nameNode);if(functionNode.generator) -name='*'+name;if(namePrefix) -name=namePrefix+' '+name;if(functionNode.async) -name='async '+name;textCursor.advance(nameNode.start);addOutlineItem({name:name,line:textCursor.lineNumber(),column:textCursor.columnNumber(),arguments:stringifyArguments((functionNode.params))});} -function isNameNode(node){if(!node) -return false;if(node.type==='MemberExpression') -return!node.computed&&node.property.type==='Identifier';return node.type==='Identifier';} -function isFunctionNode(node){if(!node) -return false;return node.type==='FunctionExpression'||node.type==='ArrowFunctionExpression';} -function isClassNode(node){return!!node&&node.type==='ClassExpression';} -function stringifyNameNode(node){if(node.type==='MemberExpression') -node=(node.property);console.assert(node.type==='Identifier','Cannot extract identifier from unknown type: '+node.type);return(node.name);} -function stringifyArguments(params){var result=[];for(var param of params){if(param.type==='Identifier') -result.push(param.name);else if(param.type==='RestElement'&¶m.argument.type==='Identifier') -result.push('...'+param.argument.name);else -console.error('Error: unexpected function parameter type: '+param.type);} -return'('+result.join(', ')+')';} -function addOutlineItem(item){outlineChunk.push(item);if(textCursor.offset()-lastReportedOffset<chunkSize) -return;postMessage({chunk:outlineChunk,isLastChunk:false});outlineChunk=[];lastReportedOffset=textCursor.offset();}};;FormatterWorker.RelaxedJSONParser={};FormatterWorker.RelaxedJSONParser.States={ExpectKey:'ExpectKey',ExpectValue:'ExpectValue'};FormatterWorker.RelaxedJSONParser.Keywords={'NaN':NaN,'true':true,'false':false,'Infinity':Infinity,'undefined':undefined,'null':null};FormatterWorker.RelaxedJSONParser.parse=function(content){var Keywords=FormatterWorker.RelaxedJSONParser.Keywords;var States=FormatterWorker.RelaxedJSONParser.States;content='('+content+')';try{var root=acorn.parse(content,{});}catch(e){return null;} -var walker=new FormatterWorker.ESTreeWalker(beforeVisit,afterVisit);var rootTip=[];var stack=[];var stackData=({key:0,tip:rootTip,state:States.ExpectValue,parentIsArray:true});walker.setWalkNulls(true);var hasExpression=false;walker.walk(root);if(hasExpression) -return null;return rootTip.length?rootTip[0]:null;function pushStack(newStack){stack.push(stackData);stackData=newStack;} -function popStack(){stackData=stack.pop();} -function applyValue(value){stackData.tip[stackData.key]=value;if(stackData.parentIsArray) -stackData.key++;else -stackData.state=null;} -function beforeVisit(node){switch(node.type){case'ObjectExpression':var newTip={};applyValue(newTip);pushStack(({key:null,tip:newTip,state:null,parentIsArray:false}));break;case'ArrayExpression':var newTip=[];applyValue(newTip);pushStack(({key:0,tip:newTip,state:States.ExpectValue,parentIsArray:true}));break;case'Property':stackData.state=States.ExpectKey;break;case'Literal':if(stackData.state===States.ExpectKey){stackData.key=node.value;stackData.state=States.ExpectValue;}else if(stackData.state===States.ExpectValue){applyValue(extractValue(node));return FormatterWorker.ESTreeWalker.SkipSubtree;} -break;case'Identifier':if(stackData.state===States.ExpectKey){stackData.key=(node.name);stackData.state=States.ExpectValue;}else if(stackData.state===States.ExpectValue){applyValue(extractValue(node));return FormatterWorker.ESTreeWalker.SkipSubtree;} -break;case'UnaryExpression':if(stackData.state===States.ExpectValue){applyValue(extractValue(node));return FormatterWorker.ESTreeWalker.SkipSubtree;} -break;case'Program':case'ExpressionStatement':break;default:if(stackData.state===States.ExpectValue) -applyValue(extractValue(node));return FormatterWorker.ESTreeWalker.SkipSubtree;}} -function afterVisit(node){if(node.type==='ObjectExpression'||node.type==='ArrayExpression') -popStack();} -function extractValue(node){var isNegative=false;var originalNode=node;var value;if(node.type==='UnaryExpression'&&(node.operator==='-'||node.operator==='+')){if(node.operator==='-') -isNegative=true;node=(node.argument);} -if(node.type==='Literal'){value=node.value;}else if(node.type==='Identifier'&&Keywords.hasOwnProperty(node.name)){value=Keywords[node.name];}else{hasExpression=true;return content.substring(originalNode.start,originalNode.end);} -if(isNegative){if(typeof value!=='number'){hasExpression=true;return content.substring(originalNode.start,originalNode.end);} -value=-(value);} -return value;}};FormatterWorker.RelaxedJSONParser.Context;;applicationDescriptor={"has_html":false,"modules":[{"type":"remote","name":"gonzales"},{"type":"autostart","name":"formatter_worker"},{"type":"autostart","name":"text_utils"},{"type":"autostart","name":"cm_headless"},{"type":"autostart","name":"platform"}]};if(!self.Runtime) -self.importScripts('Runtime.js');Runtime.startWorker('formatter_worker'); \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/har_importer/har_importer_module.js b/src/cobalt/debug/content/devtools/har_importer/har_importer_module.js deleted file mode 100644 index dbe288e..0000000 --- a/src/cobalt/debug/content/devtools/har_importer/har_importer_module.js +++ /dev/null
@@ -1,31 +0,0 @@ -HARImporter.HARBase=class{constructor(data){if(!data||typeof data!=='object') -throw'First parameter is expected to be an object';} -static _safeDate(data){var date=new Date(data);if(!Number.isNaN(date.getTime())) -return date;throw'Invalid date format';} -static _safeNumber(data){var result=Number(data);if(!Number.isNaN(result)) -return result;throw'Casting to number results in NaN';} -static _optionalNumber(data){return data!==undefined?HARImporter.HARBase._safeNumber(data):undefined;} -static _optionalString(data){return data!==undefined?String(data):undefined;} -customAsString(name){var value=(this)['_'+name];return value!==undefined?String(value):undefined;} -customAsNumber(name){var value=(this)['_'+name];if(value===undefined) -return;value=Number(value);if(Number.isNaN(value)) -return;return value;}};HARImporter.HARRoot=class extends HARImporter.HARBase{constructor(data){super(data);this.log=new HARImporter.HARLog(data['log']);}};HARImporter.HARLog=class extends HARImporter.HARBase{constructor(data){super(data);this.version=String(data['version']);this.creator=new HARImporter.HARCreator(data['creator']);this.browser=data['browser']?new HARImporter.HARCreator(data['browser']):undefined;this.pages=Array.isArray(data['pages'])?data['pages'].map(page=>new HARImporter.HARPage(page)):[];if(!Array.isArray(data['entries'])) -throw'log.entries is expected to be an array';this.entries=data['entries'].map(entry=>new HARImporter.HAREntry(entry));this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARCreator=class extends HARImporter.HARBase{constructor(data){super(data);this.name=String(data['name']);this.version=String(data['version']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARPage=class extends HARImporter.HARBase{constructor(data){super(data);this.startedDateTime=HARImporter.HARBase._safeDate(data['startedDateTime']);this.id=String(data['id']);this.title=String(data['title']);this.pageTimings=new HARImporter.HARPageTimings(data['pageTimings']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARPageTimings=class extends HARImporter.HARBase{constructor(data){super(data);this.onContentLoad=HARImporter.HARBase._optionalNumber(data['onContentLoad']);this.onLoad=HARImporter.HARBase._optionalNumber(data['onLoad']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HAREntry=class extends HARImporter.HARBase{constructor(data){super(data);this.pageref=HARImporter.HARBase._optionalString(data['pageref']);this.startedDateTime=HARImporter.HARBase._safeDate(data['startedDateTime']);this.time=HARImporter.HARBase._safeNumber(data['time']);this.request=new HARImporter.HARRequest(data['request']);this.response=new HARImporter.HARResponse(data['response']);this.cache={};this.timings=new HARImporter.HARTimings(data['timings']);this.serverIPAddress=HARImporter.HARBase._optionalString(data['serverIPAddress']);this.connection=HARImporter.HARBase._optionalString(data['connection']);this.comment=HARImporter.HARBase._optionalString(data['comment']);this._fromCache=HARImporter.HARBase._optionalString(data['_fromCache']);}};HARImporter.HARRequest=class extends HARImporter.HARBase{constructor(data){super(data);this.method=String(data['method']);this.url=String(data['url']);this.httpVersion=String(data['httpVersion']);this.cookies=Array.isArray(data['cookies'])?data['cookies'].map(cookie=>new HARImporter.HARCookie(cookie)):[];this.headers=Array.isArray(data['headers'])?data['headers'].map(header=>new HARImporter.HARHeader(header)):[];this.queryString=Array.isArray(data['queryString'])?data['queryString'].map(qs=>new HARImporter.HARQueryString(qs)):[];this.postData=data['postData']?new HARImporter.HARPostData(data['postData']):undefined;this.headersSize=HARImporter.HARBase._safeNumber(data['headersSize']);this.bodySize=HARImporter.HARBase._safeNumber(data['bodySize']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARResponse=class extends HARImporter.HARBase{constructor(data){super(data);this.status=HARImporter.HARBase._safeNumber(data['status']);this.statusText=String(data['statusText']);this.httpVersion=String(data['httpVersion']);this.cookies=Array.isArray(data['cookies'])?data['cookies'].map(cookie=>new HARImporter.HARCookie(cookie)):[];this.headers=Array.isArray(data['headers'])?data['headers'].map(header=>new HARImporter.HARHeader(header)):[];this.content=new HARImporter.HARContent(data['content']);this.redirectURL=String(data['redirectURL']);this.headersSize=HARImporter.HARBase._safeNumber(data['headersSize']);this.bodySize=HARImporter.HARBase._safeNumber(data['bodySize']);this.comment=HARImporter.HARBase._optionalString(data['comment']);this._transferSize=HARImporter.HARBase._optionalNumber(data['_transferSize']);this._error=HARImporter.HARBase._optionalString(data['_error']);}};HARImporter.HARCookie=class extends HARImporter.HARBase{constructor(data){super(data);this.name=String(data['name']);this.value=String(data['value']);this.path=HARImporter.HARBase._optionalString(data['path']);this.domain=HARImporter.HARBase._optionalString(data['domain']);this.expires=data['expires']?HARImporter.HARBase._safeDate(data['expires']):undefined;this.httpOnly=data['httpOnly']!==undefined?!!data['httpOnly']:undefined;this.secure=data['secure']!==undefined?!!data['secure']:undefined;this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARHeader=class extends HARImporter.HARBase{constructor(data){super(data);this.name=String(data['name']);this.value=String(data['value']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARQueryString=class extends HARImporter.HARBase{constructor(data){super(data);this.name=String(data['name']);this.value=String(data['value']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARPostData=class extends HARImporter.HARBase{constructor(data){super(data);this.mimeType=String(data['mimeType']);this.params=Array.isArray(data['params'])?data['params'].map(param=>new HARImporter.HARParam(param)):[];this.text=String(data['text']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARParam=class extends HARImporter.HARBase{constructor(data){super(data);this.name=String(data['name']);this.value=HARImporter.HARBase._optionalString(data['value']);this.fileName=HARImporter.HARBase._optionalString(data['fileName']);this.contentType=HARImporter.HARBase._optionalString(data['contentType']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARContent=class extends HARImporter.HARBase{constructor(data){super(data);this.size=HARImporter.HARBase._safeNumber(data['size']);this.compression=HARImporter.HARBase._optionalNumber(data['compression']);this.mimeType=String(data['mimeType']);this.text=HARImporter.HARBase._optionalString(data['text']);this.encoding=HARImporter.HARBase._optionalString(data['encoding']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARTimings=class extends HARImporter.HARBase{constructor(data){super(data);this.blocked=HARImporter.HARBase._optionalNumber(data['blocked']);this.dns=HARImporter.HARBase._optionalNumber(data['dns']);this.connect=HARImporter.HARBase._optionalNumber(data['connect']);this.send=HARImporter.HARBase._safeNumber(data['send']);this.wait=HARImporter.HARBase._safeNumber(data['wait']);this.receive=HARImporter.HARBase._safeNumber(data['receive']);this.ssl=HARImporter.HARBase._optionalNumber(data['ssl']);this.comment=HARImporter.HARBase._optionalString(data['comment']);this._blocked_queueing=HARImporter.HARBase._optionalNumber(data['_blocked_queueing']);this._blocked_proxy=HARImporter.HARBase._optionalNumber(data['_blocked_proxy']);}};;HARImporter.Importer=class{static requestsFromHARLog(log){var pages=new Map();for(var page of log.pages) -pages.set(page.id,page);log.entries.sort((a,b)=>a.startedDateTime-b.startedDateTime);var pageLoads=new Map();var requests=[];for(var entry of log.entries){var pageLoad=pageLoads.get(entry.pageref);var documentURL=pageLoad?pageLoad.mainRequest.url():entry.request.url;var request=new SDK.NetworkRequest('har-'+requests.length,entry.request.url,documentURL,'','',null);var page=pages.get(entry.pageref);if(!pageLoad&&page){pageLoad=HARImporter.Importer._buildPageLoad(page,request);pageLoads.set(entry.pageref,pageLoad);} -HARImporter.Importer._fillRequestFromHAREntry(request,entry,pageLoad);if(pageLoad) -pageLoad.bindRequest(request);requests.push(request);} -return requests;} -static _buildPageLoad(page,mainRequest){var pageLoad=new NetworkLog.PageLoad(mainRequest);pageLoad.startTime=page.startedDateTime;pageLoad.contentLoadTime=page.pageTimings.onContentLoad*1000;pageLoad.loadTime=page.pageTimings.onLoad*1000;return pageLoad;} -static _fillRequestFromHAREntry(request,entry,pageLoad){if(entry.request.postData) -request.requestFormData=entry.request.postData.text;request.connectionId=entry.connection||'';request.requestMethod=entry.request.method;request.setRequestHeaders(entry.request.headers);if(entry.response.content.mimeType&&entry.response.content.mimeType!=='x-unknown') -request.mimeType=entry.response.content.mimeType;request.responseHeaders=entry.response.headers;request.statusCode=entry.response.status;request.statusText=entry.response.statusText;var protocol=entry.response.httpVersion.toLowerCase();if(protocol==='http/2.0') -protocol='h2';request.protocol=protocol.replace(/^http\/2\.0?\+quic/,'http/2+quic');var issueTime=entry.startedDateTime.getTime()/1000;request.setIssueTime(issueTime,issueTime);var contentSize=entry.response.content.size>0?entry.response.content.size:0;var headersSize=entry.response.headersSize>0?entry.response.headersSize:0;var bodySize=entry.response.bodySize>0?entry.response.bodySize:0;request.resourceSize=contentSize||(headersSize+bodySize);var transferSize=entry.response.customAsNumber('transferSize');if(transferSize===undefined) -transferSize=entry.response.headersSize+entry.response.bodySize;request.setTransferSize(transferSize>=0?transferSize:0);var fromCache=entry.customAsString('fromCache');if(fromCache==='memory') -request.setFromMemoryCache();else if(fromCache==='disk') -request.setFromDiskCache();var contentData={error:null,content:null,encoded:entry.response.content.encoding==='base64'};if(entry.response.content.text!==undefined) -contentData.content=entry.response.content.text;request.setContentDataProvider(async()=>contentData);HARImporter.Importer._setupTiming(request,issueTime,entry.time,entry.timings);request.setRemoteAddress(entry.serverIPAddress||'',80);var resourceType=(pageLoad&&pageLoad.mainRequest===request)?Common.resourceTypes.Document:Common.ResourceType.fromMimeType(entry.response.content.mimeType);if(!resourceType) -resourceType=Common.ResourceType.fromURL(entry.request.url)||Common.resourceTypes.Other;request.setResourceType(resourceType);request.finished=true;} -static _setupTiming(request,issueTime,entryTotalDuration,timings){function accumulateTime(timing){if(timing===undefined||timing<0) -return-1;lastEntry+=timing;return lastEntry;} -var lastEntry=timings.blocked>=0?timings.blocked:0;var proxy=timings.customAsNumber('blocked_proxy')||-1;var queueing=timings.customAsNumber('blocked_queueing')||-1;var ssl=timings.ssl>=0?timings.ssl:0;if(timings.connect>0) -timings.connect-=ssl;var timing={proxyStart:proxy>0?lastEntry-proxy:-1,proxyEnd:proxy>0?lastEntry:-1,requestTime:issueTime+(queueing>0?queueing:0)/1000,dnsStart:timings.dns>=0?lastEntry:-1,dnsEnd:accumulateTime(timings.dns),connectStart:timings.connect>=0?lastEntry:-1,connectEnd:accumulateTime(timings.connect)+ssl,sslStart:timings.ssl>=0?lastEntry:-1,sslEnd:accumulateTime(timings.ssl),workerStart:-1,workerReady:-1,sendStart:timings.send>=0?lastEntry:-1,sendEnd:accumulateTime(timings.send),pushStart:0,pushEnd:0,receiveHeadersEnd:accumulateTime(timings.wait)};accumulateTime(timings.receive);request.timing=timing;request.endTime=issueTime+Math.max(entryTotalDuration,lastEntry)/1000;}};; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/heap_snapshot_model/heap_snapshot_model_module.js b/src/cobalt/debug/content/devtools/heap_snapshot_model/heap_snapshot_model_module.js deleted file mode 100644 index 03a8785..0000000 --- a/src/cobalt/debug/content/devtools/heap_snapshot_model/heap_snapshot_model_module.js +++ /dev/null
@@ -1,2 +0,0 @@ -HeapSnapshotModel.HeapSnapshotProgressEvent={Update:'ProgressUpdate',BrokenSnapshot:'BrokenSnapshot'};HeapSnapshotModel.baseSystemDistance=100000000;HeapSnapshotModel.AllocationNodeCallers=class{constructor(nodesWithSingleCaller,branchingCallers){this.nodesWithSingleCaller=nodesWithSingleCaller;this.branchingCallers=branchingCallers;}};HeapSnapshotModel.SerializedAllocationNode=class{constructor(nodeId,functionName,scriptName,scriptId,line,column,count,size,liveCount,liveSize,hasChildren){this.id=nodeId;this.name=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;this.count=count;this.size=size;this.liveCount=liveCount;this.liveSize=liveSize;this.hasChildren=hasChildren;}};HeapSnapshotModel.AllocationStackFrame=class{constructor(functionName,scriptName,scriptId,line,column){this.functionName=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;}};HeapSnapshotModel.Node=class{constructor(id,name,distance,nodeIndex,retainedSize,selfSize,type){this.id=id;this.name=name;this.distance=distance;this.nodeIndex=nodeIndex;this.retainedSize=retainedSize;this.selfSize=selfSize;this.type=type;this.canBeQueried=false;this.detachedDOMTreeNode=false;}};HeapSnapshotModel.Edge=class{constructor(name,node,type,edgeIndex){this.name=name;this.node=node;this.type=type;this.edgeIndex=edgeIndex;}};HeapSnapshotModel.Aggregate=class{constructor(){this.count;this.distance;this.self;this.maxRet;this.type;this.name;this.idxs;}};HeapSnapshotModel.AggregateForDiff=class{constructor(){this.indexes=[];this.ids=[];this.selfSizes=[];}};HeapSnapshotModel.Diff=class{constructor(){this.addedCount=0;this.removedCount=0;this.addedSize=0;this.removedSize=0;this.deletedIndexes=[];this.addedIndexes=[];}};HeapSnapshotModel.DiffForClass=class{constructor(){this.addedCount;this.removedCount;this.addedSize;this.removedSize;this.deletedIndexes;this.addedIndexes;this.countDelta;this.sizeDelta;}};HeapSnapshotModel.ComparatorConfig=class{constructor(){this.fieldName1;this.ascending1;this.fieldName2;this.ascending2;}};HeapSnapshotModel.WorkerCommand=class{constructor(){this.callId;this.disposition;this.objectId;this.newObjectId;this.methodName;this.methodArguments;this.source;}};HeapSnapshotModel.ItemsRange=class{constructor(startPosition,endPosition,totalLength,items){this.startPosition=startPosition;this.endPosition=endPosition;this.totalLength=totalLength;this.items=items;}};HeapSnapshotModel.StaticData=class{constructor(nodeCount,rootNodeIndex,totalSize,maxJSObjectId){this.nodeCount=nodeCount;this.rootNodeIndex=rootNodeIndex;this.totalSize=totalSize;this.maxJSObjectId=maxJSObjectId;}};HeapSnapshotModel.Statistics=class{constructor(){this.total;this.v8heap;this.native;this.code;this.jsArrays;this.strings;this.system;}};HeapSnapshotModel.NodeFilter=class{constructor(minNodeId,maxNodeId){this.minNodeId=minNodeId;this.maxNodeId=maxNodeId;this.allocationNodeId;} -equals(o){return this.minNodeId===o.minNodeId&&this.maxNodeId===o.maxNodeId&&this.allocationNodeId===o.allocationNodeId;}};HeapSnapshotModel.SearchConfig=class{constructor(query,caseSensitive,isRegex,shouldJump,jumpBackward){this.query=query;this.caseSensitive=caseSensitive;this.isRegex=isRegex;this.shouldJump=shouldJump;this.jumpBackward=jumpBackward;}};HeapSnapshotModel.Samples=class{constructor(timestamps,lastAssignedIds,sizes){this.timestamps=timestamps;this.lastAssignedIds=lastAssignedIds;this.sizes=sizes;}};; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/heap_snapshot_worker.js b/src/cobalt/debug/content/devtools/heap_snapshot_worker.js deleted file mode 100644 index 9fc1683..0000000 --- a/src/cobalt/debug/content/devtools/heap_snapshot_worker.js +++ /dev/null
@@ -1,1257 +0,0 @@ -var allDescriptors=[{"dependencies":[],"name":"heap_snapshot_model"},{"dependencies":[],"name":"platform"},{"dependencies":["heap_snapshot_model","platform","common"],"name":"heap_snapshot_worker"},{"dependencies":["platform"],"name":"text_utils"},{"dependencies":["text_utils","platform"],"name":"common"}];var applicationDescriptor;var _loadedScripts={};for(var k of[]){} -(function(){var baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();var Runtime=class{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(var i=0;i<descriptors.length;++i) -this._registerModule(descriptors[i]);} -static loadResourcePromise(url){return new Promise(load);function load(fulfill,reject){var xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE) -return;if([0,200,304].indexOf(xhr.status)===-1) -reject(new Error('While loading from url '+url+' server responded with a status of '+xhr.status));else -fulfill(e.target.response);} -xhr.send(null);}} -static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1) -return path;var normalizedSegments=[];var segments=path.split('/');for(var i=0;i<segments.length;i++){var segment=segments[i];if(segment==='.') -continue;else if(segment==='..') -normalizedSegments.pop();else if(segment) -normalizedSegments.push(segment);} -var normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/') -return normalizedPath;if(path[0]==='/'&&normalizedPath) -normalizedPath='/'+normalizedPath;if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..')) -normalizedPath=normalizedPath+'/';return normalizedPath;} -static _loadScriptsPromise(scriptNames,base){var promises=[];var urls=[];var sources=new Array(scriptNames.length);var scriptToEval=0;for(var i=0;i<scriptNames.length;++i){var scriptName=scriptNames[i];var sourceURL=(base||self._importScriptPathPrefix)+scriptName;var schemaIndex=sourceURL.indexOf('://')+3;var pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1) -pathIndex=sourceURL.length;sourceURL=sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));if(_loadedScripts[sourceURL]) -continue;urls.push(sourceURL);promises.push(Runtime.loadResourcePromise(sourceURL).then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));} -return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}} -function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;} -self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}} -static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;} -var sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}} -static startApplication(appName){console.timeStamp('Runtime.startApplication');var allDescriptorsByName={};for(var i=0;i<allDescriptors.length;++i){var d=allDescriptors[i];allDescriptorsByName[d['name']]=d;} -var applicationPromise;if(applicationDescriptor) -applicationPromise=Promise.resolve(applicationDescriptor);else -applicationPromise=Runtime.loadResourcePromise(appName+'.json').then(JSON.parse.bind(JSON));return applicationPromise.then(parseModuleDescriptors);function parseModuleDescriptors(appDescriptor){var configuration=appDescriptor.modules;var moduleJSONPromises=[];var coreModuleNames=[];for(var i=0;i<configuration.length;++i){var descriptor=configuration[i];var name=descriptor['name'];var moduleJSON=allDescriptorsByName[name];if(moduleJSON) -moduleJSONPromises.push(Promise.resolve(moduleJSON));else -moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));if(descriptor['type']==='autostart') -coreModuleNames.push(name);} -return Promise.all(moduleJSONPromises).then(instantiateRuntime);function instantiateRuntime(moduleDescriptors){for(var i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';} -self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames) -return(self.runtime._loadAutoStartModules(coreModuleNames));return Promise.resolve();}}} -static startWorker(appName){return Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}} -static queryParam(name){return Runtime._queryParamsObject[name]||null;} -static queryParamsString(){return location.search;} -static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}} -static _assert(value,message){if(value) -return;Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);} -static setPlatform(platform){Runtime._platform=platform;} -static _isDescriptorEnabled(descriptor){var activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*') -return Runtime.experiments.supportEnabled();if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1))) -return false;if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment)) -return false;var condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition)) -return false;if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1))) -return false;return true;} -static resolveSourceURL(path){var sourceURL=self.location.href;if(self.location.search) -sourceURL=sourceURL.replace(self.location.search,'');sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';} -useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend')) -Runtime._remoteBase+='debug/';} -_registerModule(descriptor){var module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;} -loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();} -_loadAutoStartModules(moduleNames){var promises=[];for(var i=0;i<moduleNames.length;++i) -promises.push(this.loadModulePromise(moduleNames[i]));return Promise.all(promises);} -_checkExtensionApplicability(extension,predicate){if(!predicate) -return false;var contextTypes=extension.descriptor().contextTypes;if(!contextTypes) -return true;for(var i=0;i<contextTypes.length;++i){var contextType=this._resolve(contextTypes[i]);var isMatching=!!contextType&&predicate(contextType);if(isMatching) -return true;} -return false;} -isExtensionApplicableToContext(extension,context){if(!context) -return true;return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}} -isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes) -return true;return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}} -extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type) -return false;if(!extension.enabled()) -return false;return!context||extension.isApplicable(context);} -function orderComparator(extension1,extension2){var order1=extension1.descriptor()['order']||0;var order2=extension2.descriptor()['order']||0;return order1-order2;} -function titleComparator(extension1,extension2){var title1=extension1.title()||'';var title2=extension2.title()||'';return title1.localeCompare(title2);}} -extension(type,context){return this.extensions(type,context)[0]||null;} -allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));} -_resolve(typeName){if(!this._cachedTypeClasses[typeName]){var path=typeName.split('.');var object=self;for(var i=0;object&&(i<path.length);++i) -object=object[path[i]];if(object) -this._cachedTypeClasses[typeName]=(object);} -return this._cachedTypeClasses[typeName]||null;} -sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction) -return constructorFunction[Runtime._instanceSymbol];var instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}};Runtime._queryParamsObject={__proto__:null};Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';Runtime.ModuleDescriptor=class{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.condition;this.remote;}};Runtime.ExtensionDescriptor=class{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}};Runtime.Module=class{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();var extensions=(descriptor.extensions);for(var i=0;extensions&&i<extensions.length;++i){var extension=new Runtime.Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);} -this._loadedForTest=false;} -name(){return this._name;} -enabled(){return Runtime._isDescriptorEnabled(this._descriptor);} -resource(name){var fullName=this._name+'/'+name;var content=Runtime.cachedResources[fullName];if(!content) -throw new Error(fullName+' not preloaded. Check module.json');return content;} -_loadPromise(){if(!this.enabled()) -return Promise.reject(new Error('Module '+this._name+' is not enabled'));if(this._pendingLoadPromise) -return this._pendingLoadPromise;var dependencies=this._descriptor.dependencies;var dependencyPromises=[];for(var i=0;dependencies&&i<dependencies.length;++i) -dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;} -_loadResources(){var resources=this._descriptor['resources'];if(!resources||!resources.length) -return Promise.resolve();var promises=[];for(var i=0;i<resources.length;++i){var url=this._modularizeURL(resources[i]);promises.push(Runtime._loadResourceIntoCache(url,true));} -return Promise.all(promises).then(undefined);} -_loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length) -return Promise.resolve();const specialCases={'sdk':'SDK','ui':'UI','object_ui':'ObjectUI','perf_ui':'PerfUI','har_importer':'HARImporter','sass_test_runner':'SASSTestRunner','sdk_test_runner':'SDKTestRunner'};var namespace=specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());} -_modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);} -_remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;} -substituteURL(value){var base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}};Runtime.Extension=class{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;} -descriptor(){return this._descriptor;} -module(){return this._module;} -enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());} -_typeClass(){if(!this._hasTypeClass) -return null;return this._module._manager._resolve(this._type.substring(1));} -isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);} -instance(){return this._module._loadPromise().then(this._createInstance.bind(this));} -_createInstance(){var className=this._className||this._factoryName;if(!className) -throw new Error('Could not instantiate extension with no class');var constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function)) -throw new Error('Could not instantiate: '+className);if(this._className) -return this._module._manager.sharedInstance(constructorFunction);return new constructorFunction(this);} -title(){return this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];} -hasContextType(contextType){var contextTypes=this.descriptor().contextTypes;if(!contextTypes) -return false;for(var i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i])) -return true;} -return false;}};Runtime.ExperimentsSupport=class{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};} -allConfigurableExperiments(){var result=[];for(var i=0;i<this._experiments.length;i++){var experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name]) -result.push(experiment);} -return result;} -supportEnabled(){return this._supportEnabled;} -_setExperimentsSetting(value){if(!self.localStorage) -return;self.localStorage['experiments']=JSON.stringify(value);} -register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));} -isEnabled(experimentName){this._checkExperiment(experimentName);if(this._enabledTransiently[experimentName]) -return true;if(!this.supportEnabled()) -return false;return!!Runtime._experimentsSetting()[experimentName];} -setEnabled(experimentName,enabled){this._checkExperiment(experimentName);var experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);} -setDefaultExperiments(experimentNames){for(var i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}} -enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;} -clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};} -cleanUpStaleExperiments(){var experimentsSetting=Runtime._experimentsSetting();var cleanedUpExperimentSetting={};for(var i=0;i<this._experiments.length;++i){var experimentName=this._experiments[i].name;if(experimentsSetting[experimentName]) -cleanedUpExperimentSetting[experimentName]=true;} -this._setExperimentsSetting(cleanedUpExperimentSetting);} -_checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}};Runtime.Experiment=class{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;} -isEnabled(){return this._experiments.isEnabled(this.name);} -setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}};{(function parseQueryParameters(){var queryParams=Runtime.queryParamsString();if(!queryParams) -return;var params=queryParams.substring(1).split('&');for(var i=0;i<params.length;++i){var pair=params[i].split('=');var name=pair.shift();Runtime._queryParamsObject[name]=pair.join('=');}})();} -Runtime.experiments=new Runtime.ExperimentsSupport();Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('chrome-devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){var versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch) -Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}})();function ServicePort(){} -ServicePort.prototype={setHandlers(messageHandler,closeHandler){},send(message){},close(){}};var runtime;self['HeapSnapshotModel']=self['HeapSnapshotModel']||{};HeapSnapshotModel.HeapSnapshotProgressEvent={Update:'ProgressUpdate',BrokenSnapshot:'BrokenSnapshot'};HeapSnapshotModel.baseSystemDistance=100000000;HeapSnapshotModel.AllocationNodeCallers=class{constructor(nodesWithSingleCaller,branchingCallers){this.nodesWithSingleCaller=nodesWithSingleCaller;this.branchingCallers=branchingCallers;}};HeapSnapshotModel.SerializedAllocationNode=class{constructor(nodeId,functionName,scriptName,scriptId,line,column,count,size,liveCount,liveSize,hasChildren){this.id=nodeId;this.name=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;this.count=count;this.size=size;this.liveCount=liveCount;this.liveSize=liveSize;this.hasChildren=hasChildren;}};HeapSnapshotModel.AllocationStackFrame=class{constructor(functionName,scriptName,scriptId,line,column){this.functionName=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;}};HeapSnapshotModel.Node=class{constructor(id,name,distance,nodeIndex,retainedSize,selfSize,type){this.id=id;this.name=name;this.distance=distance;this.nodeIndex=nodeIndex;this.retainedSize=retainedSize;this.selfSize=selfSize;this.type=type;this.canBeQueried=false;this.detachedDOMTreeNode=false;}};HeapSnapshotModel.Edge=class{constructor(name,node,type,edgeIndex){this.name=name;this.node=node;this.type=type;this.edgeIndex=edgeIndex;}};HeapSnapshotModel.Aggregate=class{constructor(){this.count;this.distance;this.self;this.maxRet;this.type;this.name;this.idxs;}};HeapSnapshotModel.AggregateForDiff=class{constructor(){this.indexes=[];this.ids=[];this.selfSizes=[];}};HeapSnapshotModel.Diff=class{constructor(){this.addedCount=0;this.removedCount=0;this.addedSize=0;this.removedSize=0;this.deletedIndexes=[];this.addedIndexes=[];}};HeapSnapshotModel.DiffForClass=class{constructor(){this.addedCount;this.removedCount;this.addedSize;this.removedSize;this.deletedIndexes;this.addedIndexes;this.countDelta;this.sizeDelta;}};HeapSnapshotModel.ComparatorConfig=class{constructor(){this.fieldName1;this.ascending1;this.fieldName2;this.ascending2;}};HeapSnapshotModel.WorkerCommand=class{constructor(){this.callId;this.disposition;this.objectId;this.newObjectId;this.methodName;this.methodArguments;this.source;}};HeapSnapshotModel.ItemsRange=class{constructor(startPosition,endPosition,totalLength,items){this.startPosition=startPosition;this.endPosition=endPosition;this.totalLength=totalLength;this.items=items;}};HeapSnapshotModel.StaticData=class{constructor(nodeCount,rootNodeIndex,totalSize,maxJSObjectId){this.nodeCount=nodeCount;this.rootNodeIndex=rootNodeIndex;this.totalSize=totalSize;this.maxJSObjectId=maxJSObjectId;}};HeapSnapshotModel.Statistics=class{constructor(){this.total;this.v8heap;this.native;this.code;this.jsArrays;this.strings;this.system;}};HeapSnapshotModel.NodeFilter=class{constructor(minNodeId,maxNodeId){this.minNodeId=minNodeId;this.maxNodeId=maxNodeId;this.allocationNodeId;} -equals(o){return this.minNodeId===o.minNodeId&&this.maxNodeId===o.maxNodeId&&this.allocationNodeId===o.allocationNodeId;}};HeapSnapshotModel.SearchConfig=class{constructor(query,caseSensitive,isRegex,shouldJump,jumpBackward){this.query=query;this.caseSensitive=caseSensitive;this.isRegex=isRegex;this.shouldJump=shouldJump;this.jumpBackward=jumpBackward;}};HeapSnapshotModel.Samples=class{constructor(timestamps,lastAssignedIds,sizes){this.timestamps=timestamps;this.lastAssignedIds=lastAssignedIds;this.sizes=sizes;}};;self['Platform']=self['Platform']||{};var ArrayLike;function mod(m,n){return((m%n)+n)%n;} -String.prototype.findAll=function(string){var matches=[];var i=this.indexOf(string);while(i!==-1){matches.push(i);i=this.indexOf(string,i+string.length);} -return matches;};String.prototype.reverse=function(){return this.split('').reverse().join('');};String.prototype.replaceControlCharacters=function(){return this.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u0080-\u009f]/g,'�');};String.prototype.isWhitespace=function(){return/^\s*$/.test(this);};String.prototype.computeLineEndings=function(){var endings=this.findAll('\n');endings.push(this.length);return endings;};String.prototype.escapeCharacters=function(chars){var foundChar=false;for(var i=0;i<chars.length;++i){if(this.indexOf(chars.charAt(i))!==-1){foundChar=true;break;}} -if(!foundChar) -return String(this);var result='';for(var i=0;i<this.length;++i){if(chars.indexOf(this.charAt(i))!==-1) -result+='\\';result+=this.charAt(i);} -return result;};String.regexSpecialCharacters=function(){return'^[]{}()\\.^$*+?|-,';};String.prototype.escapeForRegExp=function(){return this.escapeCharacters(String.regexSpecialCharacters());};String.prototype.escapeHTML=function(){return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');};String.prototype.unescapeHTML=function(){return this.replace(/</g,'<').replace(/>/g,'>').replace(/:/g,':').replace(/"/g,'"').replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');};String.prototype.collapseWhitespace=function(){return this.replace(/[\s\xA0]+/g,' ');};String.prototype.trimMiddle=function(maxLength){if(this.length<=maxLength) -return String(this);var leftHalf=maxLength>>1;var rightHalf=maxLength-leftHalf-1;if(this.codePointAt(this.length-rightHalf-1)>=0x10000){--rightHalf;++leftHalf;} -if(leftHalf>0&&this.codePointAt(leftHalf-1)>=0x10000) ---leftHalf;return this.substr(0,leftHalf)+'\u2026'+this.substr(this.length-rightHalf,rightHalf);};String.prototype.trimEnd=function(maxLength){if(this.length<=maxLength) -return String(this);return this.substr(0,maxLength-1)+'\u2026';};String.prototype.trimURL=function(baseURLDomain){var result=this.replace(/^(https|http|file):\/\//i,'');if(baseURLDomain){if(result.toLowerCase().startsWith(baseURLDomain.toLowerCase())) -result=result.substr(baseURLDomain.length);} -return result;};String.prototype.toTitleCase=function(){return this.substring(0,1).toUpperCase()+this.substring(1);};String.prototype.compareTo=function(other){if(this>other) -return 1;if(this<other) -return-1;return 0;};String.prototype.removeURLFragment=function(){var fragmentIndex=this.indexOf('#');if(fragmentIndex===-1) -fragmentIndex=this.length;return this.substring(0,fragmentIndex);};String.hashCode=function(string){if(!string) -return 0;var p=((1<<30)*4-5);var z=0x5033d967;var z2=0x59d2f15d;var s=0;var zi=1;for(var i=0;i<string.length;i++){var xi=string.charCodeAt(i)*z2;s=(s+zi*xi)%p;zi=(zi*z)%p;} -s=(s+zi*(p-1))%p;return Math.abs(s|0);};String.isDigitAt=function(string,index){var c=string.charCodeAt(index);return(48<=c&&c<=57);};String.prototype.toBase64=function(){function encodeBits(b){return b<26?b+65:b<52?b+71:b<62?b-4:b===62?43:b===63?47:65;} -var encoder=new TextEncoder();var data=encoder.encode(this.toString());var n=data.length;var encoded='';if(n===0) -return encoded;var shift;var v=0;for(var i=0;i<n;i++){shift=i%3;v|=data[i]<<(16>>>shift&24);if(shift===2){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),encodeBits(v&63));v=0;}} -if(shift===0) -encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),61,61);else if(shift===1) -encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),61);return encoded;};String.naturalOrderComparator=function(a,b){var chunk=/^\d+|^\D+/;var chunka,chunkb,anum,bnum;while(1){if(a){if(!b) -return 1;}else{if(b) -return-1;else -return 0;} -chunka=a.match(chunk)[0];chunkb=b.match(chunk)[0];anum=!isNaN(chunka);bnum=!isNaN(chunkb);if(anum&&!bnum) -return-1;if(bnum&&!anum) -return 1;if(anum&&bnum){var diff=chunka-chunkb;if(diff) -return diff;if(chunka.length!==chunkb.length){if(!+chunka&&!+chunkb) -return chunka.length-chunkb.length;else -return chunkb.length-chunka.length;}}else if(chunka!==chunkb){return(chunka<chunkb)?-1:1;} -a=a.substring(chunka.length);b=b.substring(chunkb.length);}};String.caseInsensetiveComparator=function(a,b){a=a.toUpperCase();b=b.toUpperCase();if(a===b) -return 0;return a>b?1:-1;};Number.constrain=function(num,min,max){if(num<min) -num=min;else if(num>max) -num=max;return num;};Number.gcd=function(a,b){if(b===0) -return a;else -return Number.gcd(b,a%b);};Number.toFixedIfFloating=function(value){if(!value||isNaN(value)) -return value;var number=Number(value);return number%1?number.toFixed(3):String(number);};Date.prototype.isValid=function(){return!isNaN(this.getTime());};Date.prototype.toISO8601Compact=function(){function leadZero(x){return(x>9?'':'0')+x;} -return this.getFullYear()+leadZero(this.getMonth()+1)+leadZero(this.getDate())+'T'+ -leadZero(this.getHours())+leadZero(this.getMinutes())+leadZero(this.getSeconds());};Object.defineProperty(Array.prototype,'remove',{value:function(value,firstOnly){var index=this.indexOf(value);if(index===-1) -return false;if(firstOnly){this.splice(index,1);return true;} -for(var i=index+1,n=this.length;i<n;++i){if(this[i]!==value) -this[index++]=this[i];} -this.length=index;return true;}});Object.defineProperty(Array.prototype,'pushAll',{value:function(array){for(var i=0;i<array.length;++i) -this.push(array[i]);}});Object.defineProperty(Array.prototype,'rotate',{value:function(index){var result=[];for(var i=index;i<index+this.length;++i) -result.push(this[i%this.length]);return result;}});Object.defineProperty(Array.prototype,'sortNumbers',{value:function(){function numericComparator(a,b){return a-b;} -this.sort(numericComparator);}});Object.defineProperty(Uint32Array.prototype,'sort',{value:Array.prototype.sort});(function(){var partition={value:function(comparator,left,right,pivotIndex){function swap(array,i1,i2){var temp=array[i1];array[i1]=array[i2];array[i2]=temp;} -var pivotValue=this[pivotIndex];swap(this,right,pivotIndex);var storeIndex=left;for(var i=left;i<right;++i){if(comparator(this[i],pivotValue)<0){swap(this,storeIndex,i);++storeIndex;}} -swap(this,right,storeIndex);return storeIndex;}};Object.defineProperty(Array.prototype,'partition',partition);Object.defineProperty(Uint32Array.prototype,'partition',partition);var sortRange={value:function(comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight){function quickSortRange(array,comparator,left,right,sortWindowLeft,sortWindowRight){if(right<=left) -return;var pivotIndex=Math.floor(Math.random()*(right-left))+left;var pivotNewIndex=array.partition(comparator,left,right,pivotIndex);if(sortWindowLeft<pivotNewIndex) -quickSortRange(array,comparator,left,pivotNewIndex-1,sortWindowLeft,sortWindowRight);if(pivotNewIndex<sortWindowRight) -quickSortRange(array,comparator,pivotNewIndex+1,right,sortWindowLeft,sortWindowRight);} -if(leftBound===0&&rightBound===(this.length-1)&&sortWindowLeft===0&&sortWindowRight>=rightBound) -this.sort(comparator);else -quickSortRange(this,comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight);return this;}};Object.defineProperty(Array.prototype,'sortRange',sortRange);Object.defineProperty(Uint32Array.prototype,'sortRange',sortRange);})();Object.defineProperty(Array.prototype,'stableSort',{value:function(comparator){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);} -comparator=comparator||defaultComparator;var indices=new Array(this.length);for(var i=0;i<this.length;++i) -indices[i]=i;var self=this;function indexComparator(a,b){var result=comparator(self[a],self[b]);return result?result:a-b;} -indices.sort(indexComparator);for(var i=0;i<this.length;++i){if(indices[i]<0||i===indices[i]) -continue;var cyclical=i;var saved=this[i];while(true){var next=indices[cyclical];indices[cyclical]=-1;if(next===i){this[cyclical]=saved;break;}else{this[cyclical]=this[next];cyclical=next;}}} -return this;}});Object.defineProperty(Array.prototype,'qselect',{value:function(k,comparator){if(k<0||k>=this.length) -return;if(!comparator){comparator=function(a,b){return a-b;};} -var low=0;var high=this.length-1;for(;;){var pivotPosition=this.partition(comparator,low,high,Math.floor((high+low)/2));if(pivotPosition===k) -return this[k];else if(pivotPosition>k) -high=pivotPosition-1;else -low=pivotPosition+1;}}});Object.defineProperty(Array.prototype,'lowerBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);} -comparator=comparator||defaultComparator;var l=left||0;var r=right!==undefined?right:this.length;while(l<r){var m=(l+r)>>1;if(comparator(object,this[m])>0) -l=m+1;else -r=m;} -return r;}});Object.defineProperty(Array.prototype,'upperBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);} -comparator=comparator||defaultComparator;var l=left||0;var r=right!==undefined?right:this.length;while(l<r){var m=(l+r)>>1;if(comparator(object,this[m])>=0) -l=m+1;else -r=m;} -return r;}});Object.defineProperty(Uint32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Uint32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Int32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Int32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Float64Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Array.prototype,'binaryIndexOf',{value:function(value,comparator){var index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,'select',{value:function(field){var result=new Array(this.length);for(var i=0;i<this.length;++i) -result[i]=this[i][field];return result;}});Object.defineProperty(Array.prototype,'peekLast',{value:function(){return this[this.length-1];}});(function(){function mergeOrIntersect(array1,array2,comparator,mergeNotIntersect){var result=[];var i=0;var j=0;while(i<array1.length&&j<array2.length){var compareValue=comparator(array1[i],array2[j]);if(mergeNotIntersect||!compareValue) -result.push(compareValue<=0?array1[i]:array2[j]);if(compareValue<=0) -i++;if(compareValue>=0) -j++;} -if(mergeNotIntersect){while(i<array1.length) -result.push(array1[i++]);while(j<array2.length) -result.push(array2[j++]);} -return result;} -Object.defineProperty(Array.prototype,'intersectOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,false);}});Object.defineProperty(Array.prototype,'mergeOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,true);}});})();String.sprintf=function(format,var_arg){return String.vsprintf(format,Array.prototype.slice.call(arguments,1));};String.tokenizeFormatString=function(format,formatters){var tokens=[];var substitutionIndex=0;function addStringToken(str){if(tokens.length&&tokens[tokens.length-1].type==='string') -tokens[tokens.length-1].value+=str;else -tokens.push({type:'string',value:str});} -function addSpecifierToken(specifier,precision,substitutionIndex){tokens.push({type:'specifier',specifier:specifier,precision:precision,substitutionIndex:substitutionIndex});} -var index=0;for(var precentIndex=format.indexOf('%',index);precentIndex!==-1;precentIndex=format.indexOf('%',index)){if(format.length===index) -break;addStringToken(format.substring(index,precentIndex));index=precentIndex+1;if(format[index]==='%'){addStringToken('%');++index;continue;} -if(String.isDigitAt(format,index)){var number=parseInt(format.substring(index),10);while(String.isDigitAt(format,index)) -++index;if(number>0&&format[index]==='$'){substitutionIndex=(number-1);++index;}} -var precision=-1;if(format[index]==='.'){++index;precision=parseInt(format.substring(index),10);if(isNaN(precision)) -precision=0;while(String.isDigitAt(format,index)) -++index;} -if(!(format[index]in formatters)){addStringToken(format.substring(precentIndex,index+1));++index;continue;} -addSpecifierToken(format[index],precision,substitutionIndex);++substitutionIndex;++index;} -addStringToken(format.substring(index));return tokens;};String.standardFormatters={d:function(substitution){return!isNaN(substitution)?substitution:0;},f:function(substitution,token){if(substitution&&token.precision>-1) -substitution=substitution.toFixed(token.precision);return!isNaN(substitution)?substitution:(token.precision>-1?Number(0).toFixed(token.precision):0);},s:function(substitution){return substitution;}};String.vsprintf=function(format,substitutions){return String.format(format,substitutions,String.standardFormatters,'',function(a,b){return a+b;}).formattedResult;};String.format=function(format,substitutions,formatters,initialValue,append,tokenizedFormat){if(!format||!substitutions||!substitutions.length) -return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName(){return'String.format("'+format+'", "'+Array.prototype.join.call(substitutions,'", "')+'")';} -function warn(msg){console.warn(prettyFunctionName()+': '+msg);} -function error(msg){console.error(prettyFunctionName()+': '+msg);} -var result=initialValue;var tokens=tokenizedFormat||String.tokenizeFormatString(format,formatters);var usedSubstitutionIndexes={};for(var i=0;i<tokens.length;++i){var token=tokens[i];if(token.type==='string'){result=append(result,token.value);continue;} -if(token.type!=='specifier'){error('Unknown token type "'+token.type+'" found.');continue;} -if(token.substitutionIndex>=substitutions.length){error('not enough substitution arguments. Had '+substitutions.length+' but needed '+ -(token.substitutionIndex+1)+', so substitution was skipped.');result=append(result,'%'+(token.precision>-1?token.precision:'')+token.specifier);continue;} -usedSubstitutionIndexes[token.substitutionIndex]=true;if(!(token.specifier in formatters)){warn('unsupported format character \u201C'+token.specifier+'\u201D. Treating as a string.');result=append(result,substitutions[token.substitutionIndex]);continue;} -result=append(result,formatters[token.specifier](substitutions[token.substitutionIndex],token));} -var unusedSubstitutions=[];for(var i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes) -continue;unusedSubstitutions.push(substitutions[i]);} -return{formattedResult:result,unusedSubstitutions:unusedSubstitutions};};function createSearchRegex(query,caseSensitive,isRegex){var regexFlags=caseSensitive?'g':'gi';var regexObject;if(isRegex){try{regexObject=new RegExp(query,regexFlags);}catch(e){}} -if(!regexObject) -regexObject=createPlainTextSearchRegex(query,regexFlags);return regexObject;} -function createPlainTextSearchRegex(query,flags){var regexSpecialCharacters=String.regexSpecialCharacters();var regex='';for(var i=0;i<query.length;++i){var c=query.charAt(i);if(regexSpecialCharacters.indexOf(c)!==-1) -regex+='\\';regex+=c;} -return new RegExp(regex,flags||'');} -function countRegexMatches(regex,content){var text=content;var result=0;var match;while(text&&(match=regex.exec(text))){if(match[0].length>0) -++result;text=text.substring(match.index+1);} -return result;} -function spacesPadding(spacesCount){return'\u00a0'.repeat(spacesCount);} -function numberToStringWithSpacesPadding(value,symbolsCount){var numberString=value.toString();var paddingLength=Math.max(0,symbolsCount-numberString.length);return spacesPadding(paddingLength)+numberString;} -Set.prototype.valuesArray=function(){return Array.from(this.values());};Set.prototype.firstValue=function(){if(!this.size) -return null;return this.values().next().value;};Set.prototype.addAll=function(iterable){for(var e of iterable) -this.add(e);};Set.prototype.containsAll=function(iterable){for(var e of iterable){if(!this.has(e)) -return false;} -return true;};Map.prototype.remove=function(key){var value=this.get(key);this.delete(key);return value;};Map.prototype.valuesArray=function(){return Array.from(this.values());};Map.prototype.keysArray=function(){return Array.from(this.keys());};Map.prototype.inverse=function(){var result=new Multimap();for(var key of this.keys()){var value=this.get(key);result.set(value,key);} -return result;};var Multimap=function(){this._map=new Map();};Multimap.prototype={set:function(key,value){var set=this._map.get(key);if(!set){set=new Set();this._map.set(key,set);} -set.add(value);},get:function(key){var result=this._map.get(key);if(!result) -result=new Set();return result;},has:function(key){return this._map.has(key);},hasValue:function(key,value){var set=this._map.get(key);if(!set) -return false;return set.has(value);},get size(){return this._map.size;},delete:function(key,value){var values=this.get(key);if(!values) -return false;var result=values.delete(value);if(!values.size) -this._map.delete(key);return result;},deleteAll:function(key){this._map.delete(key);},keysArray:function(){return this._map.keysArray();},valuesArray:function(){var result=[];var keys=this.keysArray();for(var i=0;i<keys.length;++i) -result.pushAll(this.get(keys[i]).valuesArray());return result;},clear:function(){this._map.clear();}};function loadXHR(url){return new Promise(load);function load(successCallback,failureCallback){function onReadyStateChanged(){if(xhr.readyState!==XMLHttpRequest.DONE) -return;if(xhr.status!==200){xhr.onreadystatechange=null;failureCallback(new Error(xhr.status));return;} -xhr.onreadystatechange=null;successCallback(xhr.responseText);} -var xhr=new XMLHttpRequest();xhr.withCredentials=false;xhr.open('GET',url,true);xhr.onreadystatechange=onReadyStateChanged;xhr.send(null);}} -function suppressUnused(value){} -self.setImmediate=function(callback){const args=[...arguments].slice(1);Promise.resolve().then(()=>callback(...args));return 0;};Promise.prototype.spread=function(callback){return this.then(spreadPromise);function spreadPromise(arg){return callback.apply(null,arg);}};Promise.prototype.catchException=function(defaultValue){return this.catch(function(error){console.error(error);return defaultValue;});};Map.prototype.diff=function(other,isEqual){var leftKeys=this.keysArray();var rightKeys=other.keysArray();leftKeys.sort((a,b)=>a-b);rightKeys.sort((a,b)=>a-b);var removed=[];var added=[];var equal=[];var leftIndex=0;var rightIndex=0;while(leftIndex<leftKeys.length&&rightIndex<rightKeys.length){var leftKey=leftKeys[leftIndex];var rightKey=rightKeys[rightIndex];if(leftKey===rightKey&&isEqual(this.get(leftKey),other.get(rightKey))){equal.push(this.get(leftKey));++leftIndex;++rightIndex;continue;} -if(leftKey<=rightKey){removed.push(this.get(leftKey));++leftIndex;continue;} -added.push(other.get(rightKey));++rightIndex;} -while(leftIndex<leftKeys.length){var leftKey=leftKeys[leftIndex++];removed.push(this.get(leftKey));} -while(rightIndex<rightKeys.length){var rightKey=rightKeys[rightIndex++];added.push(other.get(rightKey));} -return{added:added,removed:removed,equal:equal};};function runOnWindowLoad(callback){function windowLoaded(){self.removeEventListener('DOMContentLoaded',windowLoaded,false);callback();} -if(document.readyState==='complete'||document.readyState==='interactive') -callback();else -self.addEventListener('DOMContentLoaded',windowLoaded,false);} -var _singletonSymbol=Symbol('singleton');function singleton(constructorFunction){if(_singletonSymbol in constructorFunction) -return constructorFunction[_singletonSymbol];var instance=new constructorFunction();constructorFunction[_singletonSymbol]=instance;return instance;};self['TextUtils']=self['TextUtils']||{};TextUtils.Text=class{constructor(value){this._value=value;} -lineEndings(){if(!this._lineEndings) -this._lineEndings=this._value.computeLineEndings();return this._lineEndings;} -value(){return this._value;} -lineCount(){var lineEndings=this.lineEndings();return lineEndings.length;} -offsetFromPosition(lineNumber,columnNumber){return(lineNumber?this.lineEndings()[lineNumber-1]+1:0)+columnNumber;} -positionFromOffset(offset){var lineEndings=this.lineEndings();var lineNumber=lineEndings.lowerBound(offset);return{lineNumber:lineNumber,columnNumber:offset-(lineNumber&&(lineEndings[lineNumber-1]+1))};} -lineAt(lineNumber){var lineEndings=this.lineEndings();var lineStart=lineNumber>0?lineEndings[lineNumber-1]+1:0;var lineEnd=lineEndings[lineNumber];var lineContent=this._value.substring(lineStart,lineEnd);if(lineContent.length>0&&lineContent.charAt(lineContent.length-1)==='\r') -lineContent=lineContent.substring(0,lineContent.length-1);return lineContent;} -toSourceRange(range){var start=this.offsetFromPosition(range.startLine,range.startColumn);var end=this.offsetFromPosition(range.endLine,range.endColumn);return new TextUtils.SourceRange(start,end-start);} -toTextRange(sourceRange){var cursor=new TextUtils.TextCursor(this.lineEndings());var result=TextUtils.TextRange.createFromLocation(0,0);cursor.resetTo(sourceRange.offset);result.startLine=cursor.lineNumber();result.startColumn=cursor.columnNumber();cursor.advance(sourceRange.offset+sourceRange.length);result.endLine=cursor.lineNumber();result.endColumn=cursor.columnNumber();return result;} -replaceRange(range,replacement){var sourceRange=this.toSourceRange(range);return this._value.substring(0,sourceRange.offset)+replacement+ -this._value.substring(sourceRange.offset+sourceRange.length);} -extract(range){var sourceRange=this.toSourceRange(range);return this._value.substr(sourceRange.offset,sourceRange.length);}};TextUtils.Text.Position;TextUtils.TextCursor=class{constructor(lineEndings){this._lineEndings=lineEndings;this._offset=0;this._lineNumber=0;this._columnNumber=0;} -advance(offset){this._offset=offset;while(this._lineNumber<this._lineEndings.length&&this._lineEndings[this._lineNumber]<this._offset) -++this._lineNumber;this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;} -offset(){return this._offset;} -resetTo(offset){this._offset=offset;this._lineNumber=this._lineEndings.lowerBound(offset);this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;} -lineNumber(){return this._lineNumber;} -columnNumber(){return this._columnNumber;}};;TextUtils.TextUtils={isStopChar:function(char){return(char>' '&&char<'0')||(char>'9'&&char<'A')||(char>'Z'&&char<'_')||(char>'_'&&char<'a')||(char>'z'&&char<='~');},isWordChar:function(char){return!TextUtils.TextUtils.isStopChar(char)&&!TextUtils.TextUtils.isSpaceChar(char);},isSpaceChar:function(char){return TextUtils.TextUtils._SpaceCharRegex.test(char);},isWord:function(word){for(var i=0;i<word.length;++i){if(!TextUtils.TextUtils.isWordChar(word.charAt(i))) -return false;} -return true;},isOpeningBraceChar:function(char){return char==='('||char==='{';},isClosingBraceChar:function(char){return char===')'||char==='}';},isBraceChar:function(char){return TextUtils.TextUtils.isOpeningBraceChar(char)||TextUtils.TextUtils.isClosingBraceChar(char);},textToWords:function(text,isWordChar,wordCallback){var startWord=-1;for(var i=0;i<text.length;++i){if(!isWordChar(text.charAt(i))){if(startWord!==-1) -wordCallback(text.substring(startWord,i));startWord=-1;}else if(startWord===-1){startWord=i;}} -if(startWord!==-1) -wordCallback(text.substring(startWord));},lineIndent:function(line){var indentation=0;while(indentation<line.length&&TextUtils.TextUtils.isSpaceChar(line.charAt(indentation))) -++indentation;return line.substr(0,indentation);},isUpperCase:function(text){return text===text.toUpperCase();},isLowerCase:function(text){return text===text.toLowerCase();},splitStringByRegexes(text,regexes){var matches=[];var globalRegexes=[];for(var i=0;i<regexes.length;i++){var regex=regexes[i];if(!regex.global) -globalRegexes.push(new RegExp(regex.source,regex.flags?regex.flags+'g':'g'));else -globalRegexes.push(regex);} -doSplit(text,0,0);return matches;function doSplit(text,regexIndex,startIndex){if(regexIndex>=globalRegexes.length){matches.push({value:text,position:startIndex,regexIndex:-1,captureGroups:[]});return;} -var regex=globalRegexes[regexIndex];var currentIndex=0;var result;regex.lastIndex=0;while((result=regex.exec(text))!==null){var stringBeforeMatch=text.substring(currentIndex,result.index);if(stringBeforeMatch) -doSplit(stringBeforeMatch,regexIndex+1,startIndex+currentIndex);var match=result[0];matches.push({value:match,position:startIndex+result.index,regexIndex:regexIndex,captureGroups:result.slice(1)});currentIndex=result.index+match.length;} -var stringAfterMatches=text.substring(currentIndex);if(stringAfterMatches) -doSplit(stringAfterMatches,regexIndex+1,startIndex+currentIndex);}}};TextUtils.FilterParser=class{constructor(keys){this._keys=keys;} -static cloneFilter(filter){return{key:filter.key,text:filter.text,regex:filter.regex,negative:filter.negative};} -parse(query){var splitResult=TextUtils.TextUtils.splitStringByRegexes(query,[TextUtils.TextUtils._keyValueFilterRegex,TextUtils.TextUtils._regexFilterRegex,TextUtils.TextUtils._textFilterRegex]);var filters=[];for(var i=0;i<splitResult.length;i++){var regexIndex=splitResult[i].regexIndex;if(regexIndex===-1) -continue;var result=splitResult[i].captureGroups;if(regexIndex===0){if(this._keys.indexOf((result[1]))!==-1) -filters.push({key:result[1],text:result[2],negative:!!result[0]});else -filters.push({text:result[1]+':'+result[2],negative:!!result[0]});}else if(regexIndex===1){try{filters.push({regex:new RegExp(result[1],'i'),negative:!!result[0]});}catch(e){filters.push({text:'/'+result[1]+'/',negative:!!result[0]});}}else if(regexIndex===2){filters.push({text:result[1],negative:!!result[0]});}} -return filters;}};TextUtils.FilterParser.ParsedFilter;TextUtils.TextUtils._keyValueFilterRegex=/(?:^|\s)(\-)?([\w\-]+):([^\s]+)/;TextUtils.TextUtils._regexFilterRegex=/(?:^|\s)(\-)?\/([^\s]+)\//;TextUtils.TextUtils._textFilterRegex=/(?:^|\s)(\-)?([^\s]+)/;TextUtils.TextUtils._SpaceCharRegex=/\s/;TextUtils.TextUtils.Indent={TwoSpaces:' ',FourSpaces:' ',EightSpaces:' ',TabCharacter:'\t'};TextUtils.TextUtils.BalancedJSONTokenizer=class{constructor(callback,findMultiple){this._callback=callback;this._index=0;this._balance=0;this._buffer='';this._findMultiple=findMultiple||false;this._closingDoubleQuoteRegex=/[^\\](?:\\\\)*"/g;} -write(chunk){this._buffer+=chunk;var lastIndex=this._buffer.length;var buffer=this._buffer;for(var index=this._index;index<lastIndex;++index){var character=buffer[index];if(character==='"'){this._closingDoubleQuoteRegex.lastIndex=index;if(!this._closingDoubleQuoteRegex.test(buffer)) -break;index=this._closingDoubleQuoteRegex.lastIndex-1;}else if(character==='{'){++this._balance;}else if(character==='}'){--this._balance;if(this._balance<0){this._reportBalanced();return false;} -if(!this._balance){this._lastBalancedIndex=index+1;if(!this._findMultiple) -break;}}else if(character===']'&&!this._balance){this._reportBalanced();return false;}} -this._index=index;this._reportBalanced();return true;} -_reportBalanced(){if(!this._lastBalancedIndex) -return;this._callback(this._buffer.slice(0,this._lastBalancedIndex));this._buffer=this._buffer.slice(this._lastBalancedIndex);this._index-=this._lastBalancedIndex;this._lastBalancedIndex=0;} -remainder(){return this._buffer;}};TextUtils.TokenizerFactory=function(){};TextUtils.TokenizerFactory.prototype={createTokenizer(mimeType){}};TextUtils.isMinified=function(text){var kMaxNonMinifiedLength=500;var linesToCheck=10;var lastPosition=0;do{var eolIndex=text.indexOf('\n',lastPosition);if(eolIndex<0) -eolIndex=text.length;if(eolIndex-lastPosition>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#') -return true;lastPosition=eolIndex+1;}while(--linesToCheck>=0&&lastPosition<text.length);return false;};;TextUtils.TextRange=class{constructor(startLine,startColumn,endLine,endColumn){this.startLine=startLine;this.startColumn=startColumn;this.endLine=endLine;this.endColumn=endColumn;} -static createFromLocation(line,column){return new TextUtils.TextRange(line,column,line,column);} -static fromObject(serializedTextRange){return new TextUtils.TextRange(serializedTextRange.startLine,serializedTextRange.startColumn,serializedTextRange.endLine,serializedTextRange.endColumn);} -static comparator(range1,range2){return range1.compareTo(range2);} -static fromEdit(oldRange,newText){var endLine=oldRange.startLine;var endColumn=oldRange.startColumn+newText.length;var lineEndings=newText.computeLineEndings();if(lineEndings.length>1){endLine=oldRange.startLine+lineEndings.length-1;var len=lineEndings.length;endColumn=lineEndings[len-1]-lineEndings[len-2]-1;} -return new TextUtils.TextRange(oldRange.startLine,oldRange.startColumn,endLine,endColumn);} -isEmpty(){return this.startLine===this.endLine&&this.startColumn===this.endColumn;} -immediatelyPrecedes(range){if(!range) -return false;return this.endLine===range.startLine&&this.endColumn===range.startColumn;} -immediatelyFollows(range){if(!range) -return false;return range.immediatelyPrecedes(this);} -follows(range){return(range.endLine===this.startLine&&range.endColumn<=this.startColumn)||range.endLine<this.startLine;} -get linesCount(){return this.endLine-this.startLine;} -collapseToEnd(){return new TextUtils.TextRange(this.endLine,this.endColumn,this.endLine,this.endColumn);} -collapseToStart(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.startLine,this.startColumn);} -normalize(){if(this.startLine>this.endLine||(this.startLine===this.endLine&&this.startColumn>this.endColumn)) -return new TextUtils.TextRange(this.endLine,this.endColumn,this.startLine,this.startColumn);else -return this.clone();} -clone(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.endLine,this.endColumn);} -serializeToObject(){var serializedTextRange={};serializedTextRange.startLine=this.startLine;serializedTextRange.startColumn=this.startColumn;serializedTextRange.endLine=this.endLine;serializedTextRange.endColumn=this.endColumn;return serializedTextRange;} -compareTo(other){if(this.startLine>other.startLine) -return 1;if(this.startLine<other.startLine) -return-1;if(this.startColumn>other.startColumn) -return 1;if(this.startColumn<other.startColumn) -return-1;return 0;} -compareToPosition(lineNumber,columnNumber){if(lineNumber<this.startLine||(lineNumber===this.startLine&&columnNumber<this.startColumn)) -return-1;if(lineNumber>this.endLine||(lineNumber===this.endLine&&columnNumber>this.endColumn)) -return 1;return 0;} -equal(other){return this.startLine===other.startLine&&this.endLine===other.endLine&&this.startColumn===other.startColumn&&this.endColumn===other.endColumn;} -relativeTo(line,column){var relative=this.clone();if(this.startLine===line) -relative.startColumn-=column;if(this.endLine===line) -relative.endColumn-=column;relative.startLine-=line;relative.endLine-=line;return relative;} -rebaseAfterTextEdit(originalRange,editedRange){console.assert(originalRange.startLine===editedRange.startLine);console.assert(originalRange.startColumn===editedRange.startColumn);var rebase=this.clone();if(!this.follows(originalRange)) -return rebase;var lineDelta=editedRange.endLine-originalRange.endLine;var columnDelta=editedRange.endColumn-originalRange.endColumn;rebase.startLine+=lineDelta;rebase.endLine+=lineDelta;if(rebase.startLine===editedRange.endLine) -rebase.startColumn+=columnDelta;if(rebase.endLine===editedRange.endLine) -rebase.endColumn+=columnDelta;return rebase;} -toString(){return JSON.stringify(this);} -containsLocation(lineNumber,columnNumber){if(this.startLine===this.endLine) -return this.startLine===lineNumber&&this.startColumn<=columnNumber&&columnNumber<=this.endColumn;if(this.startLine===lineNumber) -return this.startColumn<=columnNumber;if(this.endLine===lineNumber) -return columnNumber<=this.endColumn;return this.startLine<lineNumber&&lineNumber<this.endLine;}};TextUtils.SourceRange=class{constructor(offset,length){this.offset=offset;this.length=length;}};TextUtils.SourceEdit=class{constructor(sourceURL,oldRange,newText){this.sourceURL=sourceURL;this.oldRange=oldRange;this.newText=newText;} -static comparator(edit1,edit2){return TextUtils.TextRange.comparator(edit1.oldRange,edit2.oldRange);} -newRange(){return TextUtils.TextRange.fromEdit(this.oldRange,this.newText);}};;self['Common']=self['Common']||{};Common.Worker=class{constructor(appName){var url=appName+'.js';url+=Runtime.queryParamsString();this._workerPromise=new Promise(fulfill=>{this._worker=new Worker(url);this._worker.onmessage=onMessage.bind(this);function onMessage(event){console.assert(event.data==='workerReady');this._worker.onmessage=null;fulfill(this._worker);this._worker=null;}});} -postMessage(message){this._workerPromise.then(worker=>{if(!this._disposed) -worker.postMessage(message);});} -dispose(){this._disposed=true;this._workerPromise.then(worker=>worker.terminate());} -terminate(){this.dispose();} -set onmessage(listener){this._workerPromise.then(worker=>worker.onmessage=listener);} -set onerror(listener){this._workerPromise.then(worker=>worker.onerror=listener);}};;Common.TextDictionary=class{constructor(){this._words=new Map();this._index=new Common.Trie();} -addWord(word){var count=this._words.get(word)||0;++count;this._words.set(word,count);this._index.add(word);} -removeWord(word){var count=this._words.get(word)||0;if(!count) -return;if(count===1){this._words.delete(word);this._index.remove(word);return;} ---count;this._words.set(word,count);} -wordsWithPrefix(prefix){return this._index.words(prefix);} -hasWord(word){return this._words.has(word);} -wordCount(word){return this._words.get(word)||0;} -reset(){this._words.clear();this._index.clear();}};;Common.Object=class{constructor(){this._listeners;} -addEventListener(eventType,listener,thisObject){if(!listener) -console.assert(false);if(!this._listeners) -this._listeners=new Map();if(!this._listeners.has(eventType)) -this._listeners.set(eventType,[]);this._listeners.get(eventType).push({thisObject:thisObject,listener:listener});return{eventTarget:this,eventType:eventType,thisObject:thisObject,listener:listener};} -once(eventType){return new Promise(resolve=>{var descriptor=this.addEventListener(eventType,event=>{this.removeEventListener(eventType,descriptor.listener);resolve(event.data);});});} -removeEventListener(eventType,listener,thisObject){console.assert(listener);if(!this._listeners||!this._listeners.has(eventType)) -return;var listeners=this._listeners.get(eventType);for(var i=0;i<listeners.length;++i){if(listeners[i].listener===listener&&listeners[i].thisObject===thisObject) -listeners.splice(i--,1);} -if(!listeners.length) -this._listeners.delete(eventType);} -hasEventListeners(eventType){return!!(this._listeners&&this._listeners.has(eventType));} -dispatchEventToListeners(eventType,eventData){if(!this._listeners||!this._listeners.has(eventType)) -return;var event=({data:eventData});var listeners=this._listeners.get(eventType).slice(0);for(var i=0;i<listeners.length;++i) -listeners[i].listener.call(listeners[i].thisObject,event);}};Common.Event;Common.Object._listenerCallbackTuple;Common.EventTarget=function(){};Common.EventTarget.EventDescriptor;Common.EventTarget.removeEventListeners=function(eventList){for(var i=0;i<eventList.length;++i){var eventInfo=eventList[i];eventInfo.eventTarget.removeEventListener(eventInfo.eventType,eventInfo.listener,eventInfo.thisObject);} -eventList.splice(0,eventList.length);};Common.EventTarget.prototype={addEventListener(eventType,listener,thisObject){},once(eventType){},removeEventListener(eventType,listener,thisObject){},hasEventListeners(eventType){},dispatchEventToListeners(eventType,eventData){},};;Common.Color=class{constructor(rgba,format,originalText){this._rgba=rgba;this._originalText=originalText||null;this._originalTextIsValid=!!this._originalText;this._format=format;if(typeof this._rgba[3]==='undefined') -this._rgba[3]=1;for(var i=0;i<4;++i){if(this._rgba[i]<0){this._rgba[i]=0;this._originalTextIsValid=false;} -if(this._rgba[i]>1){this._rgba[i]=1;this._originalTextIsValid=false;}}} -static parse(text){var value=text.toLowerCase().replace(/\s+/g,'');var simple=/^(?:#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgb\(((?:-?\d+%?,){2}-?\d+%?)\)|(\w+)|hsl\((-?\d+\.?\d*(?:,-?\d+\.?\d*%){2})\))$/i;var match=value.match(simple);if(match){if(match[1]){var hex=match[1].toLowerCase();var format;if(hex.length===3){format=Common.Color.Format.ShortHEX;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2);}else if(hex.length===4){format=Common.Color.Format.ShortHEXA;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2)+ -hex.charAt(3)+hex.charAt(3);}else if(hex.length===6){format=Common.Color.Format.HEX;}else{format=Common.Color.Format.HEXA;} -var r=parseInt(hex.substring(0,2),16);var g=parseInt(hex.substring(2,4),16);var b=parseInt(hex.substring(4,6),16);var a=1;if(hex.length===8) -a=parseInt(hex.substring(6,8),16)/255;return new Common.Color([r/255,g/255,b/255,a],format,text);} -if(match[2]){var rgbString=match[2].split(/\s*,\s*/);var rgba=[Common.Color._parseRgbNumeric(rgbString[0]),Common.Color._parseRgbNumeric(rgbString[1]),Common.Color._parseRgbNumeric(rgbString[2]),1];return new Common.Color(rgba,Common.Color.Format.RGB,text);} -if(match[3]){var nickname=match[3].toLowerCase();if(nickname in Common.Color.Nicknames){var rgba=Common.Color.Nicknames[nickname];var color=Common.Color.fromRGBA(rgba);color._format=Common.Color.Format.Nickname;color._originalText=text;return color;} -return null;} -if(match[4]){var hslString=match[4].replace(/%/g,'').split(/\s*,\s*/);var hsla=[Common.Color._parseHueNumeric(hslString[0]),Common.Color._parseSatLightNumeric(hslString[1]),Common.Color._parseSatLightNumeric(hslString[2]),1];var rgba=[];Common.Color.hsl2rgb(hsla,rgba);return new Common.Color(rgba,Common.Color.Format.HSL,text);} -return null;} -var advanced=/^(?:rgba\(((?:-?\d+%?,){3}-?(?:\d+|\d*\.\d+))\)|hsla\((-?(?:\d+|\d*\.\d+)(?:,-?(?:\d+|\d*\.\d+)*%){2},-?(?:\d+|\d*\.\d+))\))$/;match=value.match(advanced);if(match){if(match[1]){var rgbaString=match[1].split(/\s*,\s*/);var rgba=[Common.Color._parseRgbNumeric(rgbaString[0]),Common.Color._parseRgbNumeric(rgbaString[1]),Common.Color._parseRgbNumeric(rgbaString[2]),Common.Color._parseAlphaNumeric(rgbaString[3])];return new Common.Color(rgba,Common.Color.Format.RGBA,text);} -if(match[2]){var hslaString=match[2].replace(/%/g,'').split(/\s*,\s*/);var hsla=[Common.Color._parseHueNumeric(hslaString[0]),Common.Color._parseSatLightNumeric(hslaString[1]),Common.Color._parseSatLightNumeric(hslaString[2]),Common.Color._parseAlphaNumeric(hslaString[3])];var rgba=[];Common.Color.hsl2rgb(hsla,rgba);return new Common.Color(rgba,Common.Color.Format.HSLA,text);}} -return null;} -static fromRGBA(rgba){return new Common.Color([rgba[0]/255,rgba[1]/255,rgba[2]/255,rgba[3]],Common.Color.Format.RGBA);} -static fromHSVA(hsva){var rgba=[];Common.Color.hsva2rgba(hsva,rgba);return new Common.Color(rgba,Common.Color.Format.HSLA);} -static _parseRgbNumeric(value){var parsed=parseInt(value,10);if(value.indexOf('%')!==-1) -parsed/=100;else -parsed/=255;return parsed;} -static _parseHueNumeric(value){return isNaN(value)?0:(parseFloat(value)/360)%1;} -static _parseSatLightNumeric(value){return Math.min(1,parseFloat(value)/100);} -static _parseAlphaNumeric(value){return isNaN(value)?0:parseFloat(value);} -static _hsva2hsla(hsva,out_hsla){var h=hsva[0];var s=hsva[1];var v=hsva[2];var t=(2-s)*v;if(v===0||s===0) -s=0;else -s*=v/(t<1?t:2-t);out_hsla[0]=h;out_hsla[1]=s;out_hsla[2]=t/2;out_hsla[3]=hsva[3];} -static hsl2rgb(hsl,out_rgb){var h=hsl[0];var s=hsl[1];var l=hsl[2];function hue2rgb(p,q,h){if(h<0) -h+=1;else if(h>1) -h-=1;if((h*6)<1) -return p+(q-p)*h*6;else if((h*2)<1) -return q;else if((h*3)<2) -return p+(q-p)*((2/3)-h)*6;else -return p;} -if(s<0) -s=0;if(l<=0.5) -var q=l*(1+s);else -var q=l+s-(l*s);var p=2*l-q;var tr=h+(1/3);var tg=h;var tb=h-(1/3);out_rgb[0]=hue2rgb(p,q,tr);out_rgb[1]=hue2rgb(p,q,tg);out_rgb[2]=hue2rgb(p,q,tb);out_rgb[3]=hsl[3];} -static hsva2rgba(hsva,out_rgba){Common.Color._hsva2hsla(hsva,Common.Color.hsva2rgba._tmpHSLA);Common.Color.hsl2rgb(Common.Color.hsva2rgba._tmpHSLA,out_rgba);for(var i=0;i<Common.Color.hsva2rgba._tmpHSLA.length;i++) -Common.Color.hsva2rgba._tmpHSLA[i]=0;} -static luminance(rgba){var rSRGB=rgba[0];var gSRGB=rgba[1];var bSRGB=rgba[2];var r=rSRGB<=0.03928?rSRGB/12.92:Math.pow(((rSRGB+0.055)/1.055),2.4);var g=gSRGB<=0.03928?gSRGB/12.92:Math.pow(((gSRGB+0.055)/1.055),2.4);var b=bSRGB<=0.03928?bSRGB/12.92:Math.pow(((bSRGB+0.055)/1.055),2.4);return 0.2126*r+0.7152*g+0.0722*b;} -static blendColors(fgRGBA,bgRGBA,out_blended){var alpha=fgRGBA[3];out_blended[0]=((1-alpha)*bgRGBA[0])+(alpha*fgRGBA[0]);out_blended[1]=((1-alpha)*bgRGBA[1])+(alpha*fgRGBA[1]);out_blended[2]=((1-alpha)*bgRGBA[2])+(alpha*fgRGBA[2]);out_blended[3]=alpha+(bgRGBA[3]*(1-alpha));} -static calculateContrastRatio(fgRGBA,bgRGBA){Common.Color.blendColors(fgRGBA,bgRGBA,Common.Color.calculateContrastRatio._blendedFg);var fgLuminance=Common.Color.luminance(Common.Color.calculateContrastRatio._blendedFg);var bgLuminance=Common.Color.luminance(bgRGBA);var contrastRatio=(Math.max(fgLuminance,bgLuminance)+0.05)/(Math.min(fgLuminance,bgLuminance)+0.05);for(var i=0;i<Common.Color.calculateContrastRatio._blendedFg.length;i++) -Common.Color.calculateContrastRatio._blendedFg[i]=0;return contrastRatio;} -static desiredLuminance(luminance,contrast,lighter){function computeLuminance(){if(lighter) -return(luminance+0.05)*contrast-0.05;else -return(luminance+0.05)/contrast-0.05;} -var desiredLuminance=computeLuminance();if(desiredLuminance<0||desiredLuminance>1){lighter=!lighter;desiredLuminance=computeLuminance();} -return desiredLuminance;} -static detectColorFormat(color){const cf=Common.Color.Format;var format;var formatSetting=Common.moduleSetting('colorFormat').get();if(formatSetting===cf.Original) -format=cf.Original;else if(formatSetting===cf.RGB) -format=(color.hasAlpha()?cf.RGBA:cf.RGB);else if(formatSetting===cf.HSL) -format=(color.hasAlpha()?cf.HSLA:cf.HSL);else if(formatSetting===cf.HEX) -format=color.detectHEXFormat();else -format=cf.RGBA;return format;} -format(){return this._format;} -hsla(){if(this._hsla) -return this._hsla;var r=this._rgba[0];var g=this._rgba[1];var b=this._rgba[2];var max=Math.max(r,g,b);var min=Math.min(r,g,b);var diff=max-min;var add=max+min;if(min===max) -var h=0;else if(r===max) -var h=((1/6*(g-b)/diff)+1)%1;else if(g===max) -var h=(1/6*(b-r)/diff)+1/3;else -var h=(1/6*(r-g)/diff)+2/3;var l=0.5*add;if(l===0) -var s=0;else if(l===1) -var s=0;else if(l<=0.5) -var s=diff/add;else -var s=diff/(2-add);this._hsla=[h,s,l,this._rgba[3]];return this._hsla;} -canonicalHSLA(){var hsla=this.hsla();return[Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]];} -hsva(){var hsla=this.hsla();var h=hsla[0];var s=hsla[1];var l=hsla[2];s*=l<0.5?l:1-l;return[h,s!==0?2*s/(l+s):0,(l+s),hsla[3]];} -hasAlpha(){return this._rgba[3]!==1;} -detectHEXFormat(){var canBeShort=true;for(var i=0;i<4;++i){var c=Math.round(this._rgba[i]*255);if(c%17){canBeShort=false;break;}} -var hasAlpha=this.hasAlpha();var cf=Common.Color.Format;if(canBeShort) -return hasAlpha?cf.ShortHEXA:cf.ShortHEX;return hasAlpha?cf.HEXA:cf.HEX;} -asString(format){if(format===this._format&&this._originalTextIsValid) -return this._originalText;if(!format) -format=this._format;function toRgbValue(value){return Math.round(value*255);} -function toHexValue(value){var hex=Math.round(value*255).toString(16);return hex.length===1?'0'+hex:hex;} -function toShortHexValue(value){return(Math.round(value*255)/17).toString(16);} -switch(format){case Common.Color.Format.Original:return this._originalText;case Common.Color.Format.RGB:if(this.hasAlpha()) -return null;return String.sprintf('rgb(%d, %d, %d)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]));case Common.Color.Format.RGBA:return String.sprintf('rgba(%d, %d, %d, %f)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]),this._rgba[3]);case Common.Color.Format.HSL:if(this.hasAlpha()) -return null;var hsl=this.hsla();return String.sprintf('hsl(%d, %d%, %d%)',Math.round(hsl[0]*360),Math.round(hsl[1]*100),Math.round(hsl[2]*100));case Common.Color.Format.HSLA:var hsla=this.hsla();return String.sprintf('hsla(%d, %d%, %d%, %f)',Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]);case Common.Color.Format.HEXA:return String.sprintf('#%s%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2]),toHexValue(this._rgba[3])).toLowerCase();case Common.Color.Format.HEX:if(this.hasAlpha()) -return null;return String.sprintf('#%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2])).toLowerCase();case Common.Color.Format.ShortHEXA:var hexFormat=this.detectHEXFormat();if(hexFormat!==Common.Color.Format.ShortHEXA&&hexFormat!==Common.Color.Format.ShortHEX) -return null;return String.sprintf('#%s%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2]),toShortHexValue(this._rgba[3])).toLowerCase();case Common.Color.Format.ShortHEX:if(this.hasAlpha()) -return null;if(this.detectHEXFormat()!==Common.Color.Format.ShortHEX) -return null;return String.sprintf('#%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2])).toLowerCase();case Common.Color.Format.Nickname:return this.nickname();} -return this._originalText;} -rgba(){return this._rgba.slice();} -canonicalRGBA(){var rgba=new Array(4);for(var i=0;i<3;++i) -rgba[i]=Math.round(this._rgba[i]*255);rgba[3]=this._rgba[3];return rgba;} -nickname(){if(!Common.Color._rgbaToNickname){Common.Color._rgbaToNickname={};for(var nickname in Common.Color.Nicknames){var rgba=Common.Color.Nicknames[nickname];if(rgba.length!==4) -rgba=rgba.concat(1);Common.Color._rgbaToNickname[rgba]=nickname;}} -return Common.Color._rgbaToNickname[this.canonicalRGBA()]||null;} -toProtocolRGBA(){var rgba=this.canonicalRGBA();var result={r:rgba[0],g:rgba[1],b:rgba[2]};if(rgba[3]!==1) -result.a=rgba[3];return result;} -invert(){var rgba=[];rgba[0]=1-this._rgba[0];rgba[1]=1-this._rgba[1];rgba[2]=1-this._rgba[2];rgba[3]=this._rgba[3];return new Common.Color(rgba,Common.Color.Format.RGBA);} -setAlpha(alpha){var rgba=this._rgba.slice();rgba[3]=alpha;return new Common.Color(rgba,Common.Color.Format.RGBA);} -blendWith(fgColor){var rgba=[];Common.Color.blendColors(fgColor._rgba,this._rgba,rgba);return new Common.Color(rgba,Common.Color.Format.RGBA);}};Common.Color.Regex=/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b[a-zA-Z]+\b(?!-))/g;Common.Color.Format={Original:'original',Nickname:'nickname',HEX:'hex',ShortHEX:'shorthex',HEXA:'hexa',ShortHEXA:'shorthexa',RGB:'rgb',RGBA:'rgba',HSL:'hsl',HSLA:'hsla'};Common.Color.hsva2rgba._tmpHSLA=[0,0,0,0];Common.Color.calculateContrastRatio._blendedFg=[0,0,0,0];Common.Color.Nicknames={'aliceblue':[240,248,255],'antiquewhite':[250,235,215],'aqua':[0,255,255],'aquamarine':[127,255,212],'azure':[240,255,255],'beige':[245,245,220],'bisque':[255,228,196],'black':[0,0,0],'blanchedalmond':[255,235,205],'blue':[0,0,255],'blueviolet':[138,43,226],'brown':[165,42,42],'burlywood':[222,184,135],'cadetblue':[95,158,160],'chartreuse':[127,255,0],'chocolate':[210,105,30],'coral':[255,127,80],'cornflowerblue':[100,149,237],'cornsilk':[255,248,220],'crimson':[237,20,61],'cyan':[0,255,255],'darkblue':[0,0,139],'darkcyan':[0,139,139],'darkgoldenrod':[184,134,11],'darkgray':[169,169,169],'darkgrey':[169,169,169],'darkgreen':[0,100,0],'darkkhaki':[189,183,107],'darkmagenta':[139,0,139],'darkolivegreen':[85,107,47],'darkorange':[255,140,0],'darkorchid':[153,50,204],'darkred':[139,0,0],'darksalmon':[233,150,122],'darkseagreen':[143,188,143],'darkslateblue':[72,61,139],'darkslategray':[47,79,79],'darkslategrey':[47,79,79],'darkturquoise':[0,206,209],'darkviolet':[148,0,211],'deeppink':[255,20,147],'deepskyblue':[0,191,255],'dimgray':[105,105,105],'dimgrey':[105,105,105],'dodgerblue':[30,144,255],'firebrick':[178,34,34],'floralwhite':[255,250,240],'forestgreen':[34,139,34],'fuchsia':[255,0,255],'gainsboro':[220,220,220],'ghostwhite':[248,248,255],'gold':[255,215,0],'goldenrod':[218,165,32],'gray':[128,128,128],'grey':[128,128,128],'green':[0,128,0],'greenyellow':[173,255,47],'honeydew':[240,255,240],'hotpink':[255,105,180],'indianred':[205,92,92],'indigo':[75,0,130],'ivory':[255,255,240],'khaki':[240,230,140],'lavender':[230,230,250],'lavenderblush':[255,240,245],'lawngreen':[124,252,0],'lemonchiffon':[255,250,205],'lightblue':[173,216,230],'lightcoral':[240,128,128],'lightcyan':[224,255,255],'lightgoldenrodyellow':[250,250,210],'lightgreen':[144,238,144],'lightgray':[211,211,211],'lightgrey':[211,211,211],'lightpink':[255,182,193],'lightsalmon':[255,160,122],'lightseagreen':[32,178,170],'lightskyblue':[135,206,250],'lightslategray':[119,136,153],'lightslategrey':[119,136,153],'lightsteelblue':[176,196,222],'lightyellow':[255,255,224],'lime':[0,255,0],'limegreen':[50,205,50],'linen':[250,240,230],'magenta':[255,0,255],'maroon':[128,0,0],'mediumaquamarine':[102,205,170],'mediumblue':[0,0,205],'mediumorchid':[186,85,211],'mediumpurple':[147,112,219],'mediumseagreen':[60,179,113],'mediumslateblue':[123,104,238],'mediumspringgreen':[0,250,154],'mediumturquoise':[72,209,204],'mediumvioletred':[199,21,133],'midnightblue':[25,25,112],'mintcream':[245,255,250],'mistyrose':[255,228,225],'moccasin':[255,228,181],'navajowhite':[255,222,173],'navy':[0,0,128],'oldlace':[253,245,230],'olive':[128,128,0],'olivedrab':[107,142,35],'orange':[255,165,0],'orangered':[255,69,0],'orchid':[218,112,214],'palegoldenrod':[238,232,170],'palegreen':[152,251,152],'paleturquoise':[175,238,238],'palevioletred':[219,112,147],'papayawhip':[255,239,213],'peachpuff':[255,218,185],'peru':[205,133,63],'pink':[255,192,203],'plum':[221,160,221],'powderblue':[176,224,230],'purple':[128,0,128],'rebeccapurple':[102,51,153],'red':[255,0,0],'rosybrown':[188,143,143],'royalblue':[65,105,225],'saddlebrown':[139,69,19],'salmon':[250,128,114],'sandybrown':[244,164,96],'seagreen':[46,139,87],'seashell':[255,245,238],'sienna':[160,82,45],'silver':[192,192,192],'skyblue':[135,206,235],'slateblue':[106,90,205],'slategray':[112,128,144],'slategrey':[112,128,144],'snow':[255,250,250],'springgreen':[0,255,127],'steelblue':[70,130,180],'tan':[210,180,140],'teal':[0,128,128],'thistle':[216,191,216],'tomato':[255,99,71],'turquoise':[64,224,208],'violet':[238,130,238],'wheat':[245,222,179],'white':[255,255,255],'whitesmoke':[245,245,245],'yellow':[255,255,0],'yellowgreen':[154,205,50],'transparent':[0,0,0,0],};Common.Color.PageHighlight={Content:Common.Color.fromRGBA([111,168,220,.66]),ContentLight:Common.Color.fromRGBA([111,168,220,.5]),ContentOutline:Common.Color.fromRGBA([9,83,148]),Padding:Common.Color.fromRGBA([147,196,125,.55]),PaddingLight:Common.Color.fromRGBA([147,196,125,.4]),Border:Common.Color.fromRGBA([255,229,153,.66]),BorderLight:Common.Color.fromRGBA([255,229,153,.5]),Margin:Common.Color.fromRGBA([246,178,107,.66]),MarginLight:Common.Color.fromRGBA([246,178,107,.5]),EventTarget:Common.Color.fromRGBA([255,196,196,.66]),Shape:Common.Color.fromRGBA([96,82,177,0.8]),ShapeMargin:Common.Color.fromRGBA([96,82,127,.6]),CssGrid:Common.Color.fromRGBA([0x4b,0,0x82,1])};Common.Color.Generator=class{constructor(hueSpace,satSpace,lightnessSpace,alphaSpace){this._hueSpace=hueSpace||{min:0,max:360};this._satSpace=satSpace||67;this._lightnessSpace=lightnessSpace||80;this._alphaSpace=alphaSpace||1;this._colors=new Map();} -setColorForID(id,color){this._colors.set(id,color);} -colorForID(id){var color=this._colors.get(id);if(!color){color=this._generateColorForID(id);this._colors.set(id,color);} -return color;} -_generateColorForID(id){var hash=String.hashCode(id);var h=this._indexToValueInSpace(hash,this._hueSpace);var s=this._indexToValueInSpace(hash>>8,this._satSpace);var l=this._indexToValueInSpace(hash>>16,this._lightnessSpace);var a=this._indexToValueInSpace(hash>>24,this._alphaSpace);return`hsla(${h}, ${s}%, ${l}%, ${a})`;} -_indexToValueInSpace(index,space){if(typeof space==='number') -return space;var count=space.count||space.max-space.min;index%=count;return space.min+Math.floor(index/(count-1)*(space.max-space.min));}};;Common.Console=class extends Common.Object{constructor(){super();this._messages=[];} -addMessage(text,level,show){var message=new Common.Console.Message(text,level||Common.Console.MessageLevel.Info,Date.now(),show||false);this._messages.push(message);this.dispatchEventToListeners(Common.Console.Events.MessageAdded,message);} -log(text){this.addMessage(text,Common.Console.MessageLevel.Info);} -warn(text){this.addMessage(text,Common.Console.MessageLevel.Warning);} -error(text){this.addMessage(text,Common.Console.MessageLevel.Error,true);} -messages(){return this._messages;} -show(){this.showPromise();} -showPromise(){return Common.Revealer.revealPromise(this);}};Common.Console.Events={MessageAdded:Symbol('messageAdded')};Common.Console.MessageLevel={Info:'info',Warning:'warning',Error:'error'};Common.Console.Message=class{constructor(text,level,timestamp,show){this.text=text;this.level=level;this.timestamp=(typeof timestamp==='number')?timestamp:Date.now();this.show=show;}};Common.console=new Common.Console();;Common.ContentProvider=function(){};Common.ContentProvider.prototype={contentURL(){},contentType(){},contentEncoded(){},requestContent(){},searchInContent(query,caseSensitive,isRegex){}};Common.ContentProvider.SearchMatch=class{constructor(lineNumber,lineContent){this.lineNumber=lineNumber;this.lineContent=lineContent;}};Common.ContentProvider.performSearchInContent=function(content,query,caseSensitive,isRegex){var regex=createSearchRegex(query,caseSensitive,isRegex);var text=new TextUtils.Text(content);var result=[];for(var i=0;i<text.lineCount();++i){var lineContent=text.lineAt(i);regex.lastIndex=0;if(regex.exec(lineContent)) -result.push(new Common.ContentProvider.SearchMatch(i,lineContent));} -return result;};Common.ContentProvider.contentAsDataURL=function(content,mimeType,contentEncoded,charset){const maxDataUrlSize=1024*1024;if(content===null||content.length>maxDataUrlSize) -return null;return'data:'+mimeType+(charset?';charset='+charset:'')+(contentEncoded?';base64':'')+','+ -content;};;Common.ParsedURL=class{constructor(url){this.isValid=false;this.url=url;this.scheme='';this.user='';this.host='';this.port='';this.path='';this.queryParams='';this.fragment='';this.folderPathComponents='';this.lastPathComponent='';var match=url.match(Common.ParsedURL._urlRegex());if(match){this.isValid=true;this.scheme=match[2].toLowerCase();this.user=match[3];this.host=match[4];this.port=match[5];this.path=match[6]||'/';this.queryParams=match[7]||'';this.fragment=match[8];}else{if(this.url.startsWith('data:')){this.scheme='data';return;} -if(this.url==='about:blank'){this.scheme='about';return;} -this.path=this.url;} -var lastSlashIndex=this.path.lastIndexOf('/');if(lastSlashIndex!==-1){this.folderPathComponents=this.path.substring(0,lastSlashIndex);this.lastPathComponent=this.path.substring(lastSlashIndex+1);}else{this.lastPathComponent=this.path;}} -static platformPathToURL(fileSystemPath){fileSystemPath=fileSystemPath.replace(/\\/g,'/');if(!fileSystemPath.startsWith('file://')){if(fileSystemPath.startsWith('/')) -fileSystemPath='file://'+fileSystemPath;else -fileSystemPath='file:///'+fileSystemPath;} -return fileSystemPath;} -static _urlRegex(){if(Common.ParsedURL._urlRegexInstance) -return Common.ParsedURL._urlRegexInstance;var schemeRegex=/([A-Za-z][A-Za-z0-9+.-]*):\/\//;var userRegex=/(?:([A-Za-z0-9\-._~%!$&'()*+,;=:]*)@)?/;var hostRegex=/([^\s\/:]*)/;var portRegex=/(?::([\d]+))?/;var pathRegex=/(\/[^#?]*)?/;var queryRegex=/(?:\?([^#]*))?/;var fragmentRegex=/(?:#(.*))?/;Common.ParsedURL._urlRegexInstance=new RegExp('^('+schemeRegex.source+userRegex.source+hostRegex.source+portRegex.source+')'+pathRegex.source+ -queryRegex.source+fragmentRegex.source+'$');return Common.ParsedURL._urlRegexInstance;} -static extractPath(url){var parsedURL=url.asParsedURL();return parsedURL?parsedURL.path:'';} -static extractOrigin(url){var parsedURL=url.asParsedURL();return parsedURL?parsedURL.securityOrigin():'';} -static extractExtension(url){var lastIndexOfDot=url.lastIndexOf('.');var extension=lastIndexOfDot!==-1?url.substr(lastIndexOfDot+1):'';var indexOfQuestionMark=extension.indexOf('?');if(indexOfQuestionMark!==-1) -extension=extension.substr(0,indexOfQuestionMark);return extension;} -static extractName(url){var index=url.lastIndexOf('/');return index!==-1?url.substr(index+1):url;} -static completeURL(baseURL,href){var trimmedHref=href.trim();if(trimmedHref.startsWith('data:')||trimmedHref.startsWith('blob:')||trimmedHref.startsWith('javascript:')) -return href;var parsedHref=trimmedHref.asParsedURL();if(parsedHref&&parsedHref.scheme) -return trimmedHref;var parsedURL=baseURL.asParsedURL();if(!parsedURL) -return null;if(parsedURL.isDataURL()) -return href;if(href.length>1&&href.charAt(0)==='/'&&href.charAt(1)==='/'){return parsedURL.scheme+':'+href;} -var securityOrigin=parsedURL.securityOrigin();var pathText=parsedURL.path;var queryText=parsedURL.queryParams?'?'+parsedURL.queryParams:'';if(!href.length) -return securityOrigin+pathText+queryText;if(href.charAt(0)==='#') -return securityOrigin+pathText+queryText+href;if(href.charAt(0)==='?') -return securityOrigin+pathText+href;var hrefPath=href.match(/^[^#?]*/)[0];var hrefSuffix=href.substring(hrefPath.length);if(hrefPath.charAt(0)!=='/') -hrefPath=parsedURL.folderPathComponents+'/'+hrefPath;return securityOrigin+Runtime.normalizePath(hrefPath)+hrefSuffix;} -static splitLineAndColumn(string){var beforePathMatch=string.match(Common.ParsedURL._urlRegex());var beforePath='';var pathAndAfter=string;if(beforePathMatch){beforePath=beforePathMatch[1];pathAndAfter=string.substring(beforePathMatch[1].length);} -var lineColumnRegEx=/(?::(\d+))?(?::(\d+))?$/;var lineColumnMatch=lineColumnRegEx.exec(pathAndAfter);var lineNumber;var columnNumber;console.assert(lineColumnMatch);if(typeof(lineColumnMatch[1])==='string'){lineNumber=parseInt(lineColumnMatch[1],10);lineNumber=isNaN(lineNumber)?undefined:lineNumber-1;} -if(typeof(lineColumnMatch[2])==='string'){columnNumber=parseInt(lineColumnMatch[2],10);columnNumber=isNaN(columnNumber)?undefined:columnNumber-1;} -return{url:beforePath+pathAndAfter.substring(0,pathAndAfter.length-lineColumnMatch[0].length),lineNumber:lineNumber,columnNumber:columnNumber};} -static isRelativeURL(url){return!(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(url));} -get displayName(){if(this._displayName) -return this._displayName;if(this.isDataURL()) -return this.dataURLDisplayName();if(this.isAboutBlank()) -return this.url;this._displayName=this.lastPathComponent;if(!this._displayName) -this._displayName=(this.host||'')+'/';if(this._displayName==='/') -this._displayName=this.url;return this._displayName;} -dataURLDisplayName(){if(this._dataURLDisplayName) -return this._dataURLDisplayName;if(!this.isDataURL()) -return'';this._dataURLDisplayName=this.url.trimEnd(20);return this._dataURLDisplayName;} -isAboutBlank(){return this.url==='about:blank';} -isDataURL(){return this.scheme==='data';} -lastPathComponentWithFragment(){return this.lastPathComponent+(this.fragment?'#'+this.fragment:'');} -domain(){if(this.isDataURL()) -return'data:';return this.host+(this.port?':'+this.port:'');} -securityOrigin(){if(this.isDataURL()) -return'data:';return this.scheme+'://'+this.domain();} -urlWithoutScheme(){if(this.scheme&&this.url.startsWith(this.scheme+'://')) -return this.url.substring(this.scheme.length+3);return this.url;}};String.prototype.asParsedURL=function(){var parsedURL=new Common.ParsedURL(this.toString());if(parsedURL.isValid) -return parsedURL;return null;};;Common.Progress=function(){};Common.Progress.prototype={setTotalWork(totalWork){},setTitle(title){},setWorked(worked,title){},worked(worked){},done(){},isCanceled(){return false;},};Common.CompositeProgress=class{constructor(parent){this._parent=parent;this._children=[];this._childrenDone=0;this._parent.setTotalWork(1);this._parent.setWorked(0);} -_childDone(){if(++this._childrenDone!==this._children.length) -return;this._parent.done();} -createSubProgress(weight){var child=new Common.SubProgress(this,weight);this._children.push(child);return child;} -_update(){var totalWeights=0;var done=0;for(var i=0;i<this._children.length;++i){var child=this._children[i];if(child._totalWork) -done+=child._weight*child._worked/child._totalWork;totalWeights+=child._weight;} -this._parent.setWorked(done/totalWeights);}};Common.SubProgress=class{constructor(composite,weight){this._composite=composite;this._weight=weight||1;this._worked=0;} -isCanceled(){return this._composite._parent.isCanceled();} -setTitle(title){this._composite._parent.setTitle(title);} -done(){this.setWorked(this._totalWork);this._composite._childDone();} -setTotalWork(totalWork){this._totalWork=totalWork;this._composite._update();} -setWorked(worked,title){this._worked=worked;if(typeof title!=='undefined') -this.setTitle(title);this._composite._update();} -worked(worked){this.setWorked(this._worked+(worked||1));}};Common.ProgressProxy=class{constructor(delegate,doneCallback){this._delegate=delegate;this._doneCallback=doneCallback;} -isCanceled(){return this._delegate?this._delegate.isCanceled():false;} -setTitle(title){if(this._delegate) -this._delegate.setTitle(title);} -done(){if(this._delegate) -this._delegate.done();if(this._doneCallback) -this._doneCallback();} -setTotalWork(totalWork){if(this._delegate) -this._delegate.setTotalWork(totalWork);} -setWorked(worked,title){if(this._delegate) -this._delegate.setWorked(worked,title);} -worked(worked){if(this._delegate) -this._delegate.worked(worked);}};;Common.ResourceType=class{constructor(name,title,category,isTextType){this._name=name;this._title=title;this._category=category;this._isTextType=isTextType;} -static fromMimeType(mimeType){if(mimeType.startsWith('text/html')) -return Common.resourceTypes.Document;if(mimeType.startsWith('text/css')) -return Common.resourceTypes.Stylesheet;if(mimeType.startsWith('image/')) -return Common.resourceTypes.Image;if(mimeType.startsWith('text/')) -return Common.resourceTypes.Script;if(mimeType.includes('font')) -return Common.resourceTypes.Font;if(mimeType.includes('script')) -return Common.resourceTypes.Script;if(mimeType.includes('octet')) -return Common.resourceTypes.Other;if(mimeType.includes('application')) -return Common.resourceTypes.Script;return Common.resourceTypes.Other;} -static fromURL(url){return Common.ResourceType._resourceTypeByExtension.get(Common.ParsedURL.extractExtension(url))||null;} -static mimeFromURL(url){var name=Common.ParsedURL.extractName(url);if(Common.ResourceType._mimeTypeByName.has(name)) -return Common.ResourceType._mimeTypeByName.get(name);var ext=Common.ParsedURL.extractExtension(url).toLowerCase();return Common.ResourceType._mimeTypeByExtension.get(ext);} -name(){return this._name;} -title(){return this._title;} -category(){return this._category;} -isTextType(){return this._isTextType;} -isScript(){return this._name==='script'||this._name==='sm-script'||this._name==='snippet';} -hasScripts(){return this.isScript()||this.isDocument();} -isStyleSheet(){return this._name==='stylesheet'||this._name==='sm-stylesheet';} -isDocument(){return this._name==='document';} -isDocumentOrScriptOrStyleSheet(){return this.isDocument()||this.isScript()||this.isStyleSheet();} -isFromSourceMap(){return this._name.startsWith('sm-');} -toString(){return this._name;} -canonicalMimeType(){if(this.isDocument()) -return'text/html';if(this.isScript()) -return'text/javascript';if(this.isStyleSheet()) -return'text/css';return'';}};Common.ResourceCategory=class{constructor(title,shortTitle){this.title=title;this.shortTitle=shortTitle;}};Common.resourceCategories={XHR:new Common.ResourceCategory('XHR and Fetch','XHR'),Script:new Common.ResourceCategory('Scripts','JS'),Stylesheet:new Common.ResourceCategory('Stylesheets','CSS'),Image:new Common.ResourceCategory('Images','Img'),Media:new Common.ResourceCategory('Media','Media'),Font:new Common.ResourceCategory('Fonts','Font'),Document:new Common.ResourceCategory('Documents','Doc'),WebSocket:new Common.ResourceCategory('WebSockets','WS'),Manifest:new Common.ResourceCategory('Manifest','Manifest'),Other:new Common.ResourceCategory('Other','Other')};Common.resourceTypes={XHR:new Common.ResourceType('xhr','XHR',Common.resourceCategories.XHR,true),Fetch:new Common.ResourceType('fetch','Fetch',Common.resourceCategories.XHR,true),EventSource:new Common.ResourceType('eventsource','EventSource',Common.resourceCategories.XHR,true),Script:new Common.ResourceType('script','Script',Common.resourceCategories.Script,true),Snippet:new Common.ResourceType('snippet','Snippet',Common.resourceCategories.Script,true),Stylesheet:new Common.ResourceType('stylesheet','Stylesheet',Common.resourceCategories.Stylesheet,true),Image:new Common.ResourceType('image','Image',Common.resourceCategories.Image,false),Media:new Common.ResourceType('media','Media',Common.resourceCategories.Media,false),Font:new Common.ResourceType('font','Font',Common.resourceCategories.Font,false),Document:new Common.ResourceType('document','Document',Common.resourceCategories.Document,true),TextTrack:new Common.ResourceType('texttrack','TextTrack',Common.resourceCategories.Other,true),WebSocket:new Common.ResourceType('websocket','WebSocket',Common.resourceCategories.WebSocket,false),Other:new Common.ResourceType('other','Other',Common.resourceCategories.Other,false),SourceMapScript:new Common.ResourceType('sm-script','Script',Common.resourceCategories.Script,false),SourceMapStyleSheet:new Common.ResourceType('sm-stylesheet','Stylesheet',Common.resourceCategories.Stylesheet,false),Manifest:new Common.ResourceType('manifest','Manifest',Common.resourceCategories.Manifest,true),};Common.ResourceType._mimeTypeByName=new Map([['Cakefile','text/x-coffeescript']]);Common.ResourceType._resourceTypeByExtension=new Map([['js',Common.resourceTypes.Script],['css',Common.resourceTypes.Stylesheet],['xsl',Common.resourceTypes.Stylesheet],['jpeg',Common.resourceTypes.Image],['jpg',Common.resourceTypes.Image],['svg',Common.resourceTypes.Image],['gif',Common.resourceTypes.Image],['png',Common.resourceTypes.Image],['ico',Common.resourceTypes.Image],['tiff',Common.resourceTypes.Image],['tif',Common.resourceTypes.Image],['bmp',Common.resourceTypes.Image],['webp',Common.resourceTypes.Media],['ttf',Common.resourceTypes.Font],['otf',Common.resourceTypes.Font],['ttc',Common.resourceTypes.Font],['woff',Common.resourceTypes.Font]]);Common.ResourceType._mimeTypeByExtension=new Map([['js','text/javascript'],['css','text/css'],['html','text/html'],['htm','text/html'],['xml','application/xml'],['xsl','application/xml'],['asp','application/x-aspx'],['aspx','application/x-aspx'],['jsp','application/x-jsp'],['c','text/x-c++src'],['cc','text/x-c++src'],['cpp','text/x-c++src'],['h','text/x-c++src'],['m','text/x-c++src'],['mm','text/x-c++src'],['coffee','text/x-coffeescript'],['dart','text/javascript'],['ts','text/typescript'],['tsx','text/typescript'],['json','application/json'],['gyp','application/json'],['gypi','application/json'],['cs','text/x-csharp'],['java','text/x-java'],['less','text/x-less'],['php','text/x-php'],['phtml','application/x-httpd-php'],['py','text/x-python'],['sh','text/x-sh'],['scss','text/x-scss'],['vtt','text/vtt'],['ls','text/x-livescript'],['cljs','text/x-clojure'],['cljc','text/x-clojure'],['cljx','text/x-clojure'],['styl','text/x-styl'],['jsx','text/jsx'],['jpeg','image/jpeg'],['jpg','image/jpeg'],['svg','image/svg+xml'],['gif','image/gif'],['webp','image/webp'],['png','image/png'],['ico','image/ico'],['tiff','image/tiff'],['tif','image/tif'],['bmp','image/bmp'],['ttf','font/opentype'],['otf','font/opentype'],['ttc','font/opentype'],['woff','application/font-woff']]);;Common.Settings=class{constructor(globalStorage,localStorage){this._globalStorage=globalStorage;this._localStorage=localStorage;this._sessionStorage=new Common.SettingsStorage({});this._eventSupport=new Common.Object();this._registry=new Map();this._moduleSettings=new Map();self.runtime.extensions('setting').forEach(this._registerModuleSetting.bind(this));} -_registerModuleSetting(extension){var descriptor=extension.descriptor();var settingName=descriptor['settingName'];var isRegex=descriptor['settingType']==='regex';var defaultValue=descriptor['defaultValue'];var storageType;switch(descriptor['storageType']){case('local'):storageType=Common.SettingStorageType.Local;break;case('session'):storageType=Common.SettingStorageType.Session;break;case('global'):storageType=Common.SettingStorageType.Global;break;default:storageType=Common.SettingStorageType.Global;} -var setting=isRegex?this.createRegExpSetting(settingName,defaultValue,undefined,storageType):this.createSetting(settingName,defaultValue,storageType);if(descriptor['title']) -setting.setTitle(descriptor['title']);if(descriptor['userActionCondition']) -setting.setRequiresUserAction(!!Runtime.queryParam(descriptor['userActionCondition']));setting._extension=extension;this._moduleSettings.set(settingName,setting);} -moduleSetting(settingName){var setting=this._moduleSettings.get(settingName);if(!setting) -throw new Error('No setting registered: '+settingName);return setting;} -settingForTest(settingName){var setting=this._registry.get(settingName);if(!setting) -throw new Error('No setting registered: '+settingName);return setting;} -createSetting(key,defaultValue,storageType){var storage=this._storageFromType(storageType);if(!this._registry.get(key)) -this._registry.set(key,new Common.Setting(this,key,defaultValue,this._eventSupport,storage));return(this._registry.get(key));} -createLocalSetting(key,defaultValue){return this.createSetting(key,defaultValue,Common.SettingStorageType.Local);} -createRegExpSetting(key,defaultValue,regexFlags,storageType){if(!this._registry.get(key)){this._registry.set(key,new Common.RegExpSetting(this,key,defaultValue,this._eventSupport,this._storageFromType(storageType),regexFlags));} -return(this._registry.get(key));} -clearAll(){this._globalStorage.removeAll();this._localStorage.removeAll();var versionSetting=Common.settings.createSetting(Common.VersionController._currentVersionName,0);versionSetting.set(Common.VersionController.currentVersion);} -_storageFromType(storageType){switch(storageType){case(Common.SettingStorageType.Local):return this._localStorage;case(Common.SettingStorageType.Session):return this._sessionStorage;case(Common.SettingStorageType.Global):return this._globalStorage;} -return this._globalStorage;}};Common.SettingsStorage=class{constructor(object,setCallback,removeCallback,removeAllCallback,storagePrefix){this._object=object;this._setCallback=setCallback||function(){};this._removeCallback=removeCallback||function(){};this._removeAllCallback=removeAllCallback||function(){};this._storagePrefix=storagePrefix||'';} -set(name,value){name=this._storagePrefix+name;this._object[name]=value;this._setCallback(name,value);} -has(name){name=this._storagePrefix+name;return name in this._object;} -get(name){name=this._storagePrefix+name;return this._object[name];} -remove(name){name=this._storagePrefix+name;delete this._object[name];this._removeCallback(name);} -removeAll(){this._object={};this._removeAllCallback();} -_dumpSizes(){Common.console.log('Ten largest settings: ');var sizes={__proto__:null};for(var key in this._object) -sizes[key]=this._object[key].length;var keys=Object.keys(sizes);function comparator(key1,key2){return sizes[key2]-sizes[key1];} -keys.sort(comparator);for(var i=0;i<10&&i<keys.length;++i) -Common.console.log('Setting: \''+keys[i]+'\', size: '+sizes[keys[i]]);}};Common.Setting=class{constructor(settings,name,defaultValue,eventSupport,storage){this._settings=settings;this._name=name;this._defaultValue=defaultValue;this._eventSupport=eventSupport;this._storage=storage;this._title='';this._extension=null;} -addChangeListener(listener,thisObject){this._eventSupport.addEventListener(this._name,listener,thisObject);} -removeChangeListener(listener,thisObject){this._eventSupport.removeEventListener(this._name,listener,thisObject);} -get name(){return this._name;} -title(){return this._title;} -setTitle(title){this._title=title;} -setRequiresUserAction(requiresUserAction){this._requiresUserAction=requiresUserAction;} -get(){if(this._requiresUserAction&&!this._hadUserAction) -return this._defaultValue;if(typeof this._value!=='undefined') -return this._value;this._value=this._defaultValue;if(this._storage.has(this._name)){try{this._value=JSON.parse(this._storage.get(this._name));}catch(e){this._storage.remove(this._name);}} -return this._value;} -set(value){this._hadUserAction=true;this._value=value;try{var settingString=JSON.stringify(value);try{this._storage.set(this._name,settingString);}catch(e){this._printSettingsSavingError(e.message,this._name,settingString);}}catch(e){Common.console.error('Cannot stringify setting with name: '+this._name+', error: '+e.message);} -this._eventSupport.dispatchEventToListeners(this._name,value);} -remove(){this._settings._registry.delete(this._name);this._settings._moduleSettings.delete(this._name);this._storage.remove(this._name);} -extension(){return this._extension;} -_printSettingsSavingError(message,name,value){var errorMessage='Error saving setting with name: '+this._name+', value length: '+value.length+'. Error: '+message;console.error(errorMessage);Common.console.error(errorMessage);this._storage._dumpSizes();}};Common.RegExpSetting=class extends Common.Setting{constructor(settings,name,defaultValue,eventSupport,storage,regexFlags){super(settings,name,defaultValue?[{pattern:defaultValue}]:[],eventSupport,storage);this._regexFlags=regexFlags;} -get(){var result=[];var items=this.getAsArray();for(var i=0;i<items.length;++i){var item=items[i];if(item.pattern&&!item.disabled) -result.push(item.pattern);} -return result.join('|');} -getAsArray(){return super.get();} -set(value){this.setAsArray([{pattern:value}]);} -setAsArray(value){delete this._regex;super.set(value);} -asRegExp(){if(typeof this._regex!=='undefined') -return this._regex;this._regex=null;try{var pattern=this.get();if(pattern) -this._regex=new RegExp(pattern,this._regexFlags||'');}catch(e){} -return this._regex;}};Common.VersionController=class{updateVersion(){var localStorageVersion=window.localStorage?window.localStorage[Common.VersionController._currentVersionName]:0;var versionSetting=Common.settings.createSetting(Common.VersionController._currentVersionName,0);var currentVersion=Common.VersionController.currentVersion;var oldVersion=versionSetting.get()||parseInt(localStorageVersion||'0',10);if(oldVersion===0){versionSetting.set(currentVersion);return;} -var methodsToRun=this._methodsToRunToUpdateVersion(oldVersion,currentVersion);for(var i=0;i<methodsToRun.length;++i) -this[methodsToRun[i]].call(this);versionSetting.set(currentVersion);} -_methodsToRunToUpdateVersion(oldVersion,currentVersion){var result=[];for(var i=oldVersion;i<currentVersion;++i) -result.push('_updateVersionFrom'+i+'To'+(i+1));return result;} -_updateVersionFrom0To1(){this._clearBreakpointsWhenTooMany(Common.settings.createLocalSetting('breakpoints',[]),500000);} -_updateVersionFrom1To2(){Common.settings.createSetting('previouslyViewedFiles',[]).set([]);} -_updateVersionFrom2To3(){Common.settings.createSetting('fileSystemMapping',{}).set({});Common.settings.createSetting('fileMappingEntries',[]).remove();} -_updateVersionFrom3To4(){var advancedMode=Common.settings.createSetting('showHeaSnapshotObjectsHiddenProperties',false);Common.moduleSetting('showAdvancedHeapSnapshotProperties').set(advancedMode.get());advancedMode.remove();} -_updateVersionFrom4To5(){var settingNames={'FileSystemViewSidebarWidth':'fileSystemViewSplitViewState','elementsSidebarWidth':'elementsPanelSplitViewState','StylesPaneSplitRatio':'stylesPaneSplitViewState','heapSnapshotRetainersViewSize':'heapSnapshotSplitViewState','InspectorView.splitView':'InspectorView.splitViewState','InspectorView.screencastSplitView':'InspectorView.screencastSplitViewState','Inspector.drawerSplitView':'Inspector.drawerSplitViewState','layerDetailsSplitView':'layerDetailsSplitViewState','networkSidebarWidth':'networkPanelSplitViewState','sourcesSidebarWidth':'sourcesPanelSplitViewState','scriptsPanelNavigatorSidebarWidth':'sourcesPanelNavigatorSplitViewState','sourcesPanelSplitSidebarRatio':'sourcesPanelDebuggerSidebarSplitViewState','timeline-details':'timelinePanelDetailsSplitViewState','timeline-split':'timelinePanelRecorsSplitViewState','timeline-view':'timelinePanelTimelineStackSplitViewState','auditsSidebarWidth':'auditsPanelSplitViewState','layersSidebarWidth':'layersPanelSplitViewState','profilesSidebarWidth':'profilesPanelSplitViewState','resourcesSidebarWidth':'resourcesPanelSplitViewState'};var empty={};for(var oldName in settingNames){var newName=settingNames[oldName];var oldNameH=oldName+'H';var newValue=null;var oldSetting=Common.settings.createSetting(oldName,empty);if(oldSetting.get()!==empty){newValue=newValue||{};newValue.vertical={};newValue.vertical.size=oldSetting.get();oldSetting.remove();} -var oldSettingH=Common.settings.createSetting(oldNameH,empty);if(oldSettingH.get()!==empty){newValue=newValue||{};newValue.horizontal={};newValue.horizontal.size=oldSettingH.get();oldSettingH.remove();} -if(newValue) -Common.settings.createSetting(newName,{}).set(newValue);}} -_updateVersionFrom5To6(){var settingNames={'debuggerSidebarHidden':'sourcesPanelSplitViewState','navigatorHidden':'sourcesPanelNavigatorSplitViewState','WebInspector.Drawer.showOnLoad':'Inspector.drawerSplitViewState'};for(var oldName in settingNames){var oldSetting=Common.settings.createSetting(oldName,null);if(oldSetting.get()===null){oldSetting.remove();continue;} -var newName=settingNames[oldName];var invert=oldName==='WebInspector.Drawer.showOnLoad';var hidden=oldSetting.get()!==invert;oldSetting.remove();var showMode=hidden?'OnlyMain':'Both';var newSetting=Common.settings.createSetting(newName,{});var newValue=newSetting.get()||{};newValue.vertical=newValue.vertical||{};newValue.vertical.showMode=showMode;newValue.horizontal=newValue.horizontal||{};newValue.horizontal.showMode=showMode;newSetting.set(newValue);}} -_updateVersionFrom6To7(){var settingNames={'sourcesPanelNavigatorSplitViewState':'sourcesPanelNavigatorSplitViewState','elementsPanelSplitViewState':'elementsPanelSplitViewState','stylesPaneSplitViewState':'stylesPaneSplitViewState','sourcesPanelDebuggerSidebarSplitViewState':'sourcesPanelDebuggerSidebarSplitViewState'};var empty={};for(var name in settingNames){var setting=Common.settings.createSetting(name,empty);var value=setting.get();if(value===empty) -continue;if(value.vertical&&value.vertical.size&&value.vertical.size<1) -value.vertical.size=0;if(value.horizontal&&value.horizontal.size&&value.horizontal.size<1) -value.horizontal.size=0;setting.set(value);}} -_updateVersionFrom7To8(){} -_updateVersionFrom8To9(){var settingNames=['skipStackFramesPattern','workspaceFolderExcludePattern'];for(var i=0;i<settingNames.length;++i){var setting=Common.settings.createSetting(settingNames[i],'');var value=setting.get();if(!value) -return;if(typeof value==='string') -value=[value];for(var j=0;j<value.length;++j){if(typeof value[j]==='string') -value[j]={pattern:value[j]};} -setting.set(value);}} -_updateVersionFrom9To10(){if(!window.localStorage) -return;for(var key in window.localStorage){if(key.startsWith('revision-history')) -window.localStorage.removeItem(key);}} -_updateVersionFrom10To11(){var oldSettingName='customDevicePresets';var newSettingName='customEmulatedDeviceList';var oldSetting=Common.settings.createSetting(oldSettingName,undefined);var list=oldSetting.get();if(!Array.isArray(list)) -return;var newList=[];for(var i=0;i<list.length;++i){var value=list[i];var device={};device['title']=value['title'];device['type']='unknown';device['user-agent']=value['userAgent'];device['capabilities']=[];if(value['touch']) -device['capabilities'].push('touch');if(value['mobile']) -device['capabilities'].push('mobile');device['screen']={};device['screen']['vertical']={width:value['width'],height:value['height']};device['screen']['horizontal']={width:value['height'],height:value['width']};device['screen']['device-pixel-ratio']=value['deviceScaleFactor'];device['modes']=[];device['show-by-default']=true;device['show']='Default';newList.push(device);} -if(newList.length) -Common.settings.createSetting(newSettingName,[]).set(newList);oldSetting.remove();} -_updateVersionFrom11To12(){this._migrateSettingsFromLocalStorage();} -_updateVersionFrom12To13(){this._migrateSettingsFromLocalStorage();Common.settings.createSetting('timelineOverviewMode','').remove();} -_updateVersionFrom13To14(){var defaultValue={'throughput':-1,'latency':0};Common.settings.createSetting('networkConditions',defaultValue).set(defaultValue);} -_updateVersionFrom14To15(){var setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});var oldValue=setting.get();var newValue={};for(var fileSystemPath in oldValue){newValue[fileSystemPath]=[];for(var entry of oldValue[fileSystemPath]) -newValue[fileSystemPath].push(entry.path);} -setting.set(newValue);} -_updateVersionFrom15To16(){var setting=Common.settings.createSetting('InspectorView.panelOrder',{});var tabOrders=setting.get();for(var key of Object.keys(tabOrders)) -tabOrders[key]=(tabOrders[key]+1)*10;setting.set(tabOrders);} -_updateVersionFrom16To17(){var setting=Common.settings.createSetting('networkConditionsCustomProfiles',[]);var oldValue=setting.get();var newValue=[];if(Array.isArray(oldValue)){for(var preset of oldValue){if(typeof preset.title==='string'&&typeof preset.value==='object'&&typeof preset.value.throughput==='number'&&typeof preset.value.latency==='number'){newValue.push({title:preset.title,value:{download:preset.value.throughput,upload:preset.value.throughput,latency:preset.value.latency}});}}} -setting.set(newValue);} -_updateVersionFrom17To18(){var setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});var oldValue=setting.get();var newValue={};for(var oldKey in oldValue){var newKey=oldKey.replace(/\\/g,'/');if(!newKey.startsWith('file://')){if(newKey.startsWith('/')) -newKey='file://'+newKey;else -newKey='file:///'+newKey;} -newValue[newKey]=oldValue[oldKey];} -setting.set(newValue);} -_updateVersionFrom18To19(){var defaultColumns={status:true,type:true,initiator:true,size:true,time:true};var visibleColumnSettings=Common.settings.createSetting('networkLogColumnsVisibility',defaultColumns);var visibleColumns=visibleColumnSettings.get();visibleColumns.name=true;visibleColumns.timeline=true;var configs={};for(var columnId in visibleColumns){if(!visibleColumns.hasOwnProperty(columnId)) -continue;configs[columnId.toLowerCase()]={visible:visibleColumns[columnId]};} -var newSetting=Common.settings.createSetting('networkLogColumns',{});newSetting.set(configs);visibleColumnSettings.remove();} -_updateVersionFrom19To20(){var oldSetting=Common.settings.createSetting('InspectorView.panelOrder',{});var newSetting=Common.settings.createSetting('panel-tabOrder',{});newSetting.set(oldSetting.get());oldSetting.remove();} -_updateVersionFrom20To21(){var networkColumns=Common.settings.createSetting('networkLogColumns',{});var columns=(networkColumns.get());delete columns['timeline'];delete columns['waterfall'];networkColumns.set(columns);} -_updateVersionFrom21To22(){var breakpointsSetting=Common.settings.createLocalSetting('breakpoints',[]);var breakpoints=breakpointsSetting.get();for(var breakpoint of breakpoints){breakpoint['url']=breakpoint['sourceFileId'];delete breakpoint['sourceFileId'];} -breakpointsSetting.set(breakpoints);} -_updateVersionFrom22To23(){} -_updateVersionFrom23To24(){var oldSetting=Common.settings.createSetting('searchInContentScripts',false);var newSetting=Common.settings.createSetting('searchInAnonymousAndContentScripts',false);newSetting.set(oldSetting.get());oldSetting.remove();} -_updateVersionFrom24To25(){var defaultColumns={status:true,type:true,initiator:true,size:true,time:true};var networkLogColumnsSetting=Common.settings.createSetting('networkLogColumns',defaultColumns);var columns=networkLogColumnsSetting.get();delete columns.product;networkLogColumnsSetting.set(columns);} -_migrateSettingsFromLocalStorage(){var localSettings=new Set(['advancedSearchConfig','breakpoints','consoleHistory','domBreakpoints','eventListenerBreakpoints','fileSystemMapping','lastSelectedSourcesSidebarPaneTab','previouslyViewedFiles','savedURLs','watchExpressions','workspaceExcludedFolders','xhrBreakpoints']);if(!window.localStorage) -return;for(var key in window.localStorage){if(localSettings.has(key)) -continue;var value=window.localStorage[key];window.localStorage.removeItem(key);Common.settings._globalStorage[key]=value;}} -_clearBreakpointsWhenTooMany(breakpointsSetting,maxBreakpointsCount){if(breakpointsSetting.get().length>maxBreakpointsCount) -breakpointsSetting.set([]);}};Common.VersionController._currentVersionName='inspectorVersion';Common.VersionController.currentVersion=25;Common.settings;Common.SettingStorageType={Global:Symbol('Global'),Local:Symbol('Local'),Session:Symbol('Session')};Common.moduleSetting=function(settingName){return Common.settings.moduleSetting(settingName);};Common.settingForTest=function(settingName){return Common.settings.settingForTest(settingName);};;Common.StaticContentProvider=class{constructor(contentURL,contentType,lazyContent){this._contentURL=contentURL;this._contentType=contentType;this._lazyContent=lazyContent;} -static fromString(contentURL,contentType,content){var lazyContent=()=>Promise.resolve(content);return new Common.StaticContentProvider(contentURL,contentType,lazyContent);} -contentURL(){return this._contentURL;} -contentType(){return this._contentType;} -contentEncoded(){return Promise.resolve(false);} -requestContent(){return this._lazyContent();} -async searchInContent(query,caseSensitive,isRegex){var content=await this._lazyContent();return content?Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex):[];}};;Common.OutputStream=function(){};Common.OutputStream.prototype={write(data){},close(){}};Common.StringOutputStream=class{constructor(){this._data='';} -async write(chunk){this._data+=chunk;} -close(){} -data(){return this._data;}};;Common.Segment=class{constructor(begin,end,data){if(begin>end) -console.assert(false,'Invalid segment');this.begin=begin;this.end=end;this.data=data;} -intersects(that){return this.begin<that.end&&that.begin<this.end;}};Common.SegmentedRange=class{constructor(mergeCallback){this._segments=[];this._mergeCallback=mergeCallback;} -append(newSegment){var startIndex=this._segments.lowerBound(newSegment,(a,b)=>a.begin-b.begin);var endIndex=startIndex;var merged=null;if(startIndex>0){var precedingSegment=this._segments[startIndex-1];merged=this._tryMerge(precedingSegment,newSegment);if(merged){--startIndex;newSegment=merged;}else if(this._segments[startIndex-1].end>=newSegment.begin){if(newSegment.end<precedingSegment.end){this._segments.splice(startIndex,0,new Common.Segment(newSegment.end,precedingSegment.end,precedingSegment.data));} -precedingSegment.end=newSegment.begin;}} -while(endIndex<this._segments.length&&this._segments[endIndex].end<=newSegment.end) -++endIndex;if(endIndex<this._segments.length){merged=this._tryMerge(newSegment,this._segments[endIndex]);if(merged){endIndex++;newSegment=merged;}else if(newSegment.intersects(this._segments[endIndex])){this._segments[endIndex].begin=newSegment.end;}} -this._segments.splice(startIndex,endIndex-startIndex,newSegment);} -appendRange(that){that.segments().forEach(segment=>this.append(segment));} -segments(){return this._segments;} -_tryMerge(first,second){var merged=this._mergeCallback&&this._mergeCallback(first,second);if(!merged) -return null;merged.begin=first.begin;merged.end=Math.max(first.end,second.end);return merged;}};;Common.Throttler=class{constructor(timeout){this._timeout=timeout;this._isRunningProcess=false;this._asSoonAsPossible=false;this._process=null;this._lastCompleteTime=0;} -_processCompleted(){this._lastCompleteTime=window.performance.now();this._isRunningProcess=false;if(this._process) -this._innerSchedule(false);this._processCompletedForTests();} -_processCompletedForTests(){} -_onTimeout(){delete this._processTimeout;this._asSoonAsPossible=false;this._isRunningProcess=true;Promise.resolve().then(this._process).catch(console.error.bind(console)).then(this._processCompleted.bind(this));this._process=null;} -schedule(process,asSoonAsPossible){this._process=process;var hasScheduledTasks=!!this._processTimeout||this._isRunningProcess;var okToFire=window.performance.now()-this._lastCompleteTime>this._timeout;asSoonAsPossible=!!asSoonAsPossible||(!hasScheduledTasks&&okToFire);var forceTimerUpdate=asSoonAsPossible&&!this._asSoonAsPossible;this._asSoonAsPossible=this._asSoonAsPossible||asSoonAsPossible;this._innerSchedule(forceTimerUpdate);} -_innerSchedule(forceTimerUpdate){if(this._isRunningProcess) -return;if(this._processTimeout&&!forceTimerUpdate) -return;if(this._processTimeout) -this._clearTimeout(this._processTimeout);var timeout=this._asSoonAsPossible?0:this._timeout;this._processTimeout=this._setTimeout(this._onTimeout.bind(this),timeout);} -_clearTimeout(timeoutId){clearTimeout(timeoutId);} -_setTimeout(operation,timeout){return setTimeout(operation,timeout);}};Common.Throttler.FinishCallback;;Common.Trie=class{constructor(){this.clear();} -add(word){var node=this._root;++this._wordsInSubtree[this._root];for(var i=0;i<word.length;++i){var edge=word[i];var next=this._edges[node][edge];if(!next){if(this._freeNodes.length){next=this._freeNodes.pop();}else{next=this._size++;this._isWord.push(false);this._wordsInSubtree.push(0);this._edges.push({__proto__:null});} -this._edges[node][edge]=next;} -++this._wordsInSubtree[next];node=next;} -this._isWord[node]=true;} -remove(word){if(!this.has(word)) -return false;var node=this._root;--this._wordsInSubtree[this._root];for(var i=0;i<word.length;++i){var edge=word[i];var next=this._edges[node][edge];if(!--this._wordsInSubtree[next]){delete this._edges[node][edge];this._freeNodes.push(next);} -node=next;} -this._isWord[node]=false;return true;} -has(word){var node=this._root;for(var i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node) -return false;} -return this._isWord[node];} -words(prefix){prefix=prefix||'';var node=this._root;for(var i=0;i<prefix.length;++i){node=this._edges[node][prefix[i]];if(!node) -return[];} -var results=[];this._dfs(node,prefix,results);return results;} -_dfs(node,prefix,results){if(this._isWord[node]) -results.push(prefix);var edges=this._edges[node];for(var edge in edges) -this._dfs(edges[edge],prefix+edge,results);} -longestPrefix(word,fullWordOnly){var node=this._root;var wordIndex=0;for(var i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node) -break;if(!fullWordOnly||this._isWord[node]) -wordIndex=i+1;} -return word.substring(0,wordIndex);} -clear(){this._size=1;this._root=0;this._edges=[{__proto__:null}];this._isWord=[false];this._wordsInSubtree=[0];this._freeNodes=[];}};;self['Common']=self['Common']||{};Common.UIString=function(string,vararg){return String.vsprintf(Common.localize(string),Array.prototype.slice.call(arguments,1));};Common.localize=function(string){return string;};Common.UIStringFormat=class{constructor(format){this._localizedFormat=Common.localize(format);this._tokenizedFormat=String.tokenizeFormatString(this._localizedFormat,String.standardFormatters);} -static _append(a,b){return a+b;} -format(vararg){return String.format(this._localizedFormat,arguments,String.standardFormatters,'',Common.UIStringFormat._append,this._tokenizedFormat).formattedResult;}};;Common.Renderer=function(){};Common.Renderer.prototype={render(object,options){}};Common.Renderer.renderPromise=function(object,options){if(!object) -return Promise.reject(new Error('Can\'t render '+object));return self.runtime.extension(Common.Renderer,object).instance().then(render);function render(renderer){return renderer.render(object,options||{});}};Common.Renderer.Options;Common.Revealer=function(){};Common.Revealer.reveal=function(revealable,omitFocus){Common.Revealer.revealPromise(revealable,omitFocus);};Common.Revealer.revealPromise=function(revealable,omitFocus){if(!revealable) -return Promise.reject(new Error('Can\'t reveal '+revealable));return self.runtime.allInstances(Common.Revealer,revealable).then(reveal);function reveal(revealers){var promises=[];for(var i=0;i<revealers.length;++i) -promises.push(revealers[i].reveal((revealable),omitFocus));return Promise.race(promises);}};Common.Revealer.prototype={reveal(object,omitFocus){}};Common.App=function(){};Common.App.prototype={presentUI(document){}};Common.AppProvider=function(){};Common.AppProvider.prototype={createApp(){}};Common.QueryParamHandler=function(){};Common.QueryParamHandler.prototype={handleQueryParam(value){}};;Common.CharacterIdMap=class{constructor(){this._elementToCharacter=new Map();this._characterToElement=new Map();this._charCode=33;} -toChar(object){var character=this._elementToCharacter.get(object);if(!character){if(this._charCode>=0xFFFF) -throw new Error('CharacterIdMap ran out of capacity!');character=String.fromCharCode(this._charCode++);this._elementToCharacter.set(object,character);this._characterToElement.set(character,object);} -return character;} -fromChar(character){var object=this._characterToElement.get(character);if(object===undefined) -return null;return object;}};;self['HeapSnapshotWorker']=self['HeapSnapshotWorker']||{};HeapSnapshotWorker.AllocationProfile=class{constructor(profile,liveObjectStats){this._strings=profile.strings;this._liveObjectStats=liveObjectStats;this._nextNodeId=1;this._functionInfos=[];this._idToNode={};this._idToTopDownNode={};this._collapsedTopNodeIdToFunctionInfo={};this._traceTops=null;this._buildFunctionAllocationInfos(profile);this._traceTree=this._buildAllocationTree(profile,liveObjectStats);} -_buildFunctionAllocationInfos(profile){var strings=this._strings;var functionInfoFields=profile.snapshot.meta.trace_function_info_fields;var functionNameOffset=functionInfoFields.indexOf('name');var scriptNameOffset=functionInfoFields.indexOf('script_name');var scriptIdOffset=functionInfoFields.indexOf('script_id');var lineOffset=functionInfoFields.indexOf('line');var columnOffset=functionInfoFields.indexOf('column');var functionInfoFieldCount=functionInfoFields.length;var rawInfos=profile.trace_function_infos;var infoLength=rawInfos.length;var functionInfos=this._functionInfos=new Array(infoLength/functionInfoFieldCount);var index=0;for(var i=0;i<infoLength;i+=functionInfoFieldCount){functionInfos[index++]=new HeapSnapshotWorker.FunctionAllocationInfo(strings[rawInfos[i+functionNameOffset]],strings[rawInfos[i+scriptNameOffset]],rawInfos[i+scriptIdOffset],rawInfos[i+lineOffset],rawInfos[i+columnOffset]);}} -_buildAllocationTree(profile,liveObjectStats){var traceTreeRaw=profile.trace_tree;var functionInfos=this._functionInfos;var idToTopDownNode=this._idToTopDownNode;var traceNodeFields=profile.snapshot.meta.trace_node_fields;var nodeIdOffset=traceNodeFields.indexOf('id');var functionInfoIndexOffset=traceNodeFields.indexOf('function_info_index');var allocationCountOffset=traceNodeFields.indexOf('count');var allocationSizeOffset=traceNodeFields.indexOf('size');var childrenOffset=traceNodeFields.indexOf('children');var nodeFieldCount=traceNodeFields.length;function traverseNode(rawNodeArray,nodeOffset,parent){var functionInfo=functionInfos[rawNodeArray[nodeOffset+functionInfoIndexOffset]];var id=rawNodeArray[nodeOffset+nodeIdOffset];var stats=liveObjectStats[id];var liveCount=stats?stats.count:0;var liveSize=stats?stats.size:0;var result=new HeapSnapshotWorker.TopDownAllocationNode(id,functionInfo,rawNodeArray[nodeOffset+allocationCountOffset],rawNodeArray[nodeOffset+allocationSizeOffset],liveCount,liveSize,parent);idToTopDownNode[id]=result;functionInfo.addTraceTopNode(result);var rawChildren=rawNodeArray[nodeOffset+childrenOffset];for(var i=0;i<rawChildren.length;i+=nodeFieldCount) -result.children.push(traverseNode(rawChildren,i,result));return result;} -return traverseNode(traceTreeRaw,0,null);} -serializeTraceTops(){if(this._traceTops) -return this._traceTops;var result=this._traceTops=[];var functionInfos=this._functionInfos;for(var i=0;i<functionInfos.length;i++){var info=functionInfos[i];if(info.totalCount===0) -continue;var nodeId=this._nextNodeId++;var isRoot=i===0;result.push(this._serializeNode(nodeId,info,info.totalCount,info.totalSize,info.totalLiveCount,info.totalLiveSize,!isRoot));this._collapsedTopNodeIdToFunctionInfo[nodeId]=info;} -result.sort(function(a,b){return b.size-a.size;});return result;} -serializeCallers(nodeId){var node=this._ensureBottomUpNode(nodeId);var nodesWithSingleCaller=[];while(node.callers().length===1){node=node.callers()[0];nodesWithSingleCaller.push(this._serializeCaller(node));} -var branchingCallers=[];var callers=node.callers();for(var i=0;i<callers.length;i++) -branchingCallers.push(this._serializeCaller(callers[i]));return new HeapSnapshotModel.AllocationNodeCallers(nodesWithSingleCaller,branchingCallers);} -serializeAllocationStack(traceNodeId){var node=this._idToTopDownNode[traceNodeId];var result=[];while(node){var functionInfo=node.functionInfo;result.push(new HeapSnapshotModel.AllocationStackFrame(functionInfo.functionName,functionInfo.scriptName,functionInfo.scriptId,functionInfo.line,functionInfo.column));node=node.parent;} -return result;} -traceIds(allocationNodeId){return this._ensureBottomUpNode(allocationNodeId).traceTopIds;} -_ensureBottomUpNode(nodeId){var node=this._idToNode[nodeId];if(!node){var functionInfo=this._collapsedTopNodeIdToFunctionInfo[nodeId];node=functionInfo.bottomUpRoot();delete this._collapsedTopNodeIdToFunctionInfo[nodeId];this._idToNode[nodeId]=node;} -return node;} -_serializeCaller(node){var callerId=this._nextNodeId++;this._idToNode[callerId]=node;return this._serializeNode(callerId,node.functionInfo,node.allocationCount,node.allocationSize,node.liveCount,node.liveSize,node.hasCallers());} -_serializeNode(nodeId,functionInfo,count,size,liveCount,liveSize,hasChildren){return new HeapSnapshotModel.SerializedAllocationNode(nodeId,functionInfo.functionName,functionInfo.scriptName,functionInfo.scriptId,functionInfo.line,functionInfo.column,count,size,liveCount,liveSize,hasChildren);}};HeapSnapshotWorker.TopDownAllocationNode=class{constructor(id,functionInfo,count,size,liveCount,liveSize,parent){this.id=id;this.functionInfo=functionInfo;this.allocationCount=count;this.allocationSize=size;this.liveCount=liveCount;this.liveSize=liveSize;this.parent=parent;this.children=[];}};HeapSnapshotWorker.BottomUpAllocationNode=class{constructor(functionInfo){this.functionInfo=functionInfo;this.allocationCount=0;this.allocationSize=0;this.liveCount=0;this.liveSize=0;this.traceTopIds=[];this._callers=[];} -addCaller(traceNode){var functionInfo=traceNode.functionInfo;var result;for(var i=0;i<this._callers.length;i++){var caller=this._callers[i];if(caller.functionInfo===functionInfo){result=caller;break;}} -if(!result){result=new HeapSnapshotWorker.BottomUpAllocationNode(functionInfo);this._callers.push(result);} -return result;} -callers(){return this._callers;} -hasCallers(){return this._callers.length>0;}};HeapSnapshotWorker.FunctionAllocationInfo=class{constructor(functionName,scriptName,scriptId,line,column){this.functionName=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;this.totalCount=0;this.totalSize=0;this.totalLiveCount=0;this.totalLiveSize=0;this._traceTops=[];} -addTraceTopNode(node){if(node.allocationCount===0) -return;this._traceTops.push(node);this.totalCount+=node.allocationCount;this.totalSize+=node.allocationSize;this.totalLiveCount+=node.liveCount;this.totalLiveSize+=node.liveSize;} -bottomUpRoot(){if(!this._traceTops.length) -return null;if(!this._bottomUpTree) -this._buildAllocationTraceTree();return this._bottomUpTree;} -_buildAllocationTraceTree(){this._bottomUpTree=new HeapSnapshotWorker.BottomUpAllocationNode(this);for(var i=0;i<this._traceTops.length;i++){var node=this._traceTops[i];var bottomUpNode=this._bottomUpTree;var count=node.allocationCount;var size=node.allocationSize;var liveCount=node.liveCount;var liveSize=node.liveSize;var traceId=node.id;while(true){bottomUpNode.allocationCount+=count;bottomUpNode.allocationSize+=size;bottomUpNode.liveCount+=liveCount;bottomUpNode.liveSize+=liveSize;bottomUpNode.traceTopIds.push(traceId);node=node.parent;if(node===null) -break;bottomUpNode=bottomUpNode.addCaller(node);}}}};;HeapSnapshotWorker.HeapSnapshotItem=function(){};HeapSnapshotWorker.HeapSnapshotItem.prototype={itemIndex(){},serialize(){}};HeapSnapshotWorker.HeapSnapshotEdge=class{constructor(snapshot,edgeIndex){this._snapshot=snapshot;this._edges=snapshot.containmentEdges;this.edgeIndex=edgeIndex||0;} -clone(){return new HeapSnapshotWorker.HeapSnapshotEdge(this._snapshot,this.edgeIndex);} -hasStringName(){throw new Error('Not implemented');} -name(){throw new Error('Not implemented');} -node(){return this._snapshot.createNode(this.nodeIndex());} -nodeIndex(){return this._edges[this.edgeIndex+this._snapshot._edgeToNodeOffset];} -toString(){return'HeapSnapshotEdge: '+this.name();} -type(){return this._snapshot._edgeTypes[this.rawType()];} -itemIndex(){return this.edgeIndex;} -serialize(){return new HeapSnapshotModel.Edge(this.name(),this.node().serialize(),this.type(),this.edgeIndex);} -rawType(){return this._edges[this.edgeIndex+this._snapshot._edgeTypeOffset];}};HeapSnapshotWorker.HeapSnapshotItemIterator=function(){};HeapSnapshotWorker.HeapSnapshotItemIterator.prototype={hasNext(){},item(){},next(){}};HeapSnapshotWorker.HeapSnapshotItemIndexProvider=function(){};HeapSnapshotWorker.HeapSnapshotItemIndexProvider.prototype={itemForIndex(newIndex){},};HeapSnapshotWorker.HeapSnapshotNodeIndexProvider=class{constructor(snapshot){this._node=snapshot.createNode();} -itemForIndex(index){this._node.nodeIndex=index;return this._node;}};HeapSnapshotWorker.HeapSnapshotEdgeIndexProvider=class{constructor(snapshot){this._edge=snapshot.createEdge(0);} -itemForIndex(index){this._edge.edgeIndex=index;return this._edge;}};HeapSnapshotWorker.HeapSnapshotRetainerEdgeIndexProvider=class{constructor(snapshot){this._retainerEdge=snapshot.createRetainingEdge(0);} -itemForIndex(index){this._retainerEdge.setRetainerIndex(index);return this._retainerEdge;}};HeapSnapshotWorker.HeapSnapshotEdgeIterator=class{constructor(node){this._sourceNode=node;this.edge=node._snapshot.createEdge(node.edgeIndexesStart());} -hasNext(){return this.edge.edgeIndex<this._sourceNode.edgeIndexesEnd();} -item(){return this.edge;} -next(){this.edge.edgeIndex+=this.edge._snapshot._edgeFieldsCount;}};HeapSnapshotWorker.HeapSnapshotRetainerEdge=class{constructor(snapshot,retainerIndex){this._snapshot=snapshot;this.setRetainerIndex(retainerIndex);} -clone(){return new HeapSnapshotWorker.HeapSnapshotRetainerEdge(this._snapshot,this.retainerIndex());} -hasStringName(){return this._edge().hasStringName();} -name(){return this._edge().name();} -node(){return this._node();} -nodeIndex(){return this._retainingNodeIndex;} -retainerIndex(){return this._retainerIndex;} -setRetainerIndex(retainerIndex){if(retainerIndex===this._retainerIndex) -return;this._retainerIndex=retainerIndex;this._globalEdgeIndex=this._snapshot._retainingEdges[retainerIndex];this._retainingNodeIndex=this._snapshot._retainingNodes[retainerIndex];this._edgeInstance=null;this._nodeInstance=null;} -set edgeIndex(edgeIndex){this.setRetainerIndex(edgeIndex);} -_node(){if(!this._nodeInstance) -this._nodeInstance=this._snapshot.createNode(this._retainingNodeIndex);return this._nodeInstance;} -_edge(){if(!this._edgeInstance) -this._edgeInstance=this._snapshot.createEdge(this._globalEdgeIndex);return this._edgeInstance;} -toString(){return this._edge().toString();} -itemIndex(){return this._retainerIndex;} -serialize(){return new HeapSnapshotModel.Edge(this.name(),this.node().serialize(),this.type(),this._globalEdgeIndex);} -type(){return this._edge().type();}};HeapSnapshotWorker.HeapSnapshotRetainerEdgeIterator=class{constructor(retainedNode){var snapshot=retainedNode._snapshot;var retainedNodeOrdinal=retainedNode.ordinal();var retainerIndex=snapshot._firstRetainerIndex[retainedNodeOrdinal];this._retainersEnd=snapshot._firstRetainerIndex[retainedNodeOrdinal+1];this.retainer=snapshot.createRetainingEdge(retainerIndex);} -hasNext(){return this.retainer.retainerIndex()<this._retainersEnd;} -item(){return this.retainer;} -next(){this.retainer.setRetainerIndex(this.retainer.retainerIndex()+1);}};HeapSnapshotWorker.HeapSnapshotNode=class{constructor(snapshot,nodeIndex){this._snapshot=snapshot;this.nodeIndex=nodeIndex||0;} -distance(){return this._snapshot._nodeDistances[this.nodeIndex/this._snapshot._nodeFieldCount];} -className(){throw new Error('Not implemented');} -classIndex(){throw new Error('Not implemented');} -dominatorIndex(){var nodeFieldCount=this._snapshot._nodeFieldCount;return this._snapshot._dominatorsTree[this.nodeIndex/this._snapshot._nodeFieldCount]*nodeFieldCount;} -edges(){return new HeapSnapshotWorker.HeapSnapshotEdgeIterator(this);} -edgesCount(){return(this.edgeIndexesEnd()-this.edgeIndexesStart())/this._snapshot._edgeFieldsCount;} -id(){throw new Error('Not implemented');} -isRoot(){return this.nodeIndex===this._snapshot._rootNodeIndex;} -name(){return this._snapshot.strings[this._name()];} -retainedSize(){return this._snapshot._retainedSizes[this.ordinal()];} -retainers(){return new HeapSnapshotWorker.HeapSnapshotRetainerEdgeIterator(this);} -retainersCount(){var snapshot=this._snapshot;var ordinal=this.ordinal();return snapshot._firstRetainerIndex[ordinal+1]-snapshot._firstRetainerIndex[ordinal];} -selfSize(){var snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeSelfSizeOffset];} -type(){return this._snapshot._nodeTypes[this.rawType()];} -traceNodeId(){var snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeTraceNodeIdOffset];} -itemIndex(){return this.nodeIndex;} -serialize(){return new HeapSnapshotModel.Node(this.id(),this.name(),this.distance(),this.nodeIndex,this.retainedSize(),this.selfSize(),this.type());} -_name(){var snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeNameOffset];} -edgeIndexesStart(){return this._snapshot._firstEdgeIndexes[this.ordinal()];} -edgeIndexesEnd(){return this._snapshot._firstEdgeIndexes[this.ordinal()+1];} -ordinal(){return this.nodeIndex/this._snapshot._nodeFieldCount;} -_nextNodeIndex(){return this.nodeIndex+this._snapshot._nodeFieldCount;} -rawType(){var snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeTypeOffset];}};HeapSnapshotWorker.HeapSnapshotNodeIterator=class{constructor(node){this.node=node;this._nodesLength=node._snapshot.nodes.length;} -hasNext(){return this.node.nodeIndex<this._nodesLength;} -item(){return this.node;} -next(){this.node.nodeIndex=this.node._nextNodeIndex();}};HeapSnapshotWorker.HeapSnapshotIndexRangeIterator=class{constructor(itemProvider,indexes){this._itemProvider=itemProvider;this._indexes=indexes;this._position=0;} -hasNext(){return this._position<this._indexes.length;} -item(){var index=this._indexes[this._position];return this._itemProvider.itemForIndex(index);} -next(){++this._position;}};HeapSnapshotWorker.HeapSnapshotFilteredIterator=class{constructor(iterator,filter){this._iterator=iterator;this._filter=filter;this._skipFilteredItems();} -hasNext(){return this._iterator.hasNext();} -item(){return this._iterator.item();} -next(){this._iterator.next();this._skipFilteredItems();} -_skipFilteredItems(){while(this._iterator.hasNext()&&!this._filter(this._iterator.item())) -this._iterator.next();}};HeapSnapshotWorker.HeapSnapshotProgress=class{constructor(dispatcher){this._dispatcher=dispatcher;} -updateStatus(status){this._sendUpdateEvent(Common.UIString(status));} -updateProgress(title,value,total){var percentValue=((total?(value/total):0)*100).toFixed(0);this._sendUpdateEvent(Common.UIString(title,percentValue));} -reportProblem(error){if(this._dispatcher) -this._dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotProgressEvent.BrokenSnapshot,error);} -_sendUpdateEvent(text){if(this._dispatcher) -this._dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotProgressEvent.Update,text);}};HeapSnapshotWorker.HeapSnapshotProblemReport=class{constructor(title){this._errors=[title];} -addError(error){if(this._errors.length>100) -return;this._errors.push(error);} -toString(){return this._errors.join('\n ');}};HeapSnapshotWorker.HeapSnapshot=class{constructor(profile,progress){this.nodes=profile.nodes;this.containmentEdges=profile.edges;this._metaNode=profile.snapshot.meta;this._rawSamples=profile.samples;this._samples=null;this.strings=profile.strings;this._progress=progress;this._noDistance=-5;this._rootNodeIndex=0;if(profile.snapshot.root_index) -this._rootNodeIndex=profile.snapshot.root_index;this._snapshotDiffs={};this._aggregatesForDiff=null;this._aggregates={};this._aggregatesSortedFlags={};this._profile=profile;} -initialize(){var meta=this._metaNode;this._nodeTypeOffset=meta.node_fields.indexOf('type');this._nodeNameOffset=meta.node_fields.indexOf('name');this._nodeIdOffset=meta.node_fields.indexOf('id');this._nodeSelfSizeOffset=meta.node_fields.indexOf('self_size');this._nodeEdgeCountOffset=meta.node_fields.indexOf('edge_count');this._nodeTraceNodeIdOffset=meta.node_fields.indexOf('trace_node_id');this._nodeFieldCount=meta.node_fields.length;this._nodeTypes=meta.node_types[this._nodeTypeOffset];this._nodeArrayType=this._nodeTypes.indexOf('array');this._nodeHiddenType=this._nodeTypes.indexOf('hidden');this._nodeObjectType=this._nodeTypes.indexOf('object');this._nodeNativeType=this._nodeTypes.indexOf('native');this._nodeConsStringType=this._nodeTypes.indexOf('concatenated string');this._nodeSlicedStringType=this._nodeTypes.indexOf('sliced string');this._nodeCodeType=this._nodeTypes.indexOf('code');this._nodeSyntheticType=this._nodeTypes.indexOf('synthetic');this._edgeFieldsCount=meta.edge_fields.length;this._edgeTypeOffset=meta.edge_fields.indexOf('type');this._edgeNameOffset=meta.edge_fields.indexOf('name_or_index');this._edgeToNodeOffset=meta.edge_fields.indexOf('to_node');this._edgeTypes=meta.edge_types[this._edgeTypeOffset];this._edgeTypes.push('invisible');this._edgeElementType=this._edgeTypes.indexOf('element');this._edgeHiddenType=this._edgeTypes.indexOf('hidden');this._edgeInternalType=this._edgeTypes.indexOf('internal');this._edgeShortcutType=this._edgeTypes.indexOf('shortcut');this._edgeWeakType=this._edgeTypes.indexOf('weak');this._edgeInvisibleType=this._edgeTypes.indexOf('invisible');this.nodeCount=this.nodes.length/this._nodeFieldCount;this._edgeCount=this.containmentEdges.length/this._edgeFieldsCount;this._retainedSizes=new Float64Array(this.nodeCount);this._firstEdgeIndexes=new Uint32Array(this.nodeCount+1);this._retainingNodes=new Uint32Array(this._edgeCount);this._retainingEdges=new Uint32Array(this._edgeCount);this._firstRetainerIndex=new Uint32Array(this.nodeCount+1);this._nodeDistances=new Int32Array(this.nodeCount);this._firstDominatedNodeIndex=new Uint32Array(this.nodeCount+1);this._dominatedNodes=new Uint32Array(this.nodeCount-1);this._progress.updateStatus('Building edge indexes\u2026');this._buildEdgeIndexes();this._progress.updateStatus('Building retainers\u2026');this._buildRetainers();this._progress.updateStatus('Calculating node flags\u2026');this.calculateFlags();this._progress.updateStatus('Calculating distances\u2026');this.calculateDistances();this._progress.updateStatus('Building postorder index\u2026');var result=this._buildPostOrderIndex();this._progress.updateStatus('Building dominator tree\u2026');this._dominatorsTree=this._buildDominatorTree(result.postOrderIndex2NodeOrdinal,result.nodeOrdinal2PostOrderIndex);this._progress.updateStatus('Calculating retained sizes\u2026');this._calculateRetainedSizes(result.postOrderIndex2NodeOrdinal);this._progress.updateStatus('Building dominated nodes\u2026');this._buildDominatedNodes();this._progress.updateStatus('Calculating statistics\u2026');this.calculateStatistics();this._progress.updateStatus('Calculating samples\u2026');this._buildSamples();this._progress.updateStatus('Finished processing.');if(this._profile.snapshot.trace_function_count){this._progress.updateStatus('Building allocation statistics\u2026');var nodes=this.nodes;var nodesLength=nodes.length;var nodeFieldCount=this._nodeFieldCount;var node=this.rootNode();var liveObjects={};for(var nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;var traceNodeId=node.traceNodeId();var stats=liveObjects[traceNodeId];if(!stats) -liveObjects[traceNodeId]=stats={count:0,size:0,ids:[]};stats.count++;stats.size+=node.selfSize();stats.ids.push(node.id());} -this._allocationProfile=new HeapSnapshotWorker.AllocationProfile(this._profile,liveObjects);this._progress.updateStatus('Done');}} -_buildEdgeIndexes(){var nodes=this.nodes;var nodeCount=this.nodeCount;var firstEdgeIndexes=this._firstEdgeIndexes;var nodeFieldCount=this._nodeFieldCount;var edgeFieldsCount=this._edgeFieldsCount;var nodeEdgeCountOffset=this._nodeEdgeCountOffset;firstEdgeIndexes[nodeCount]=this.containmentEdges.length;for(var nodeOrdinal=0,edgeIndex=0;nodeOrdinal<nodeCount;++nodeOrdinal){firstEdgeIndexes[nodeOrdinal]=edgeIndex;edgeIndex+=nodes[nodeOrdinal*nodeFieldCount+nodeEdgeCountOffset]*edgeFieldsCount;}} -_buildRetainers(){var retainingNodes=this._retainingNodes;var retainingEdges=this._retainingEdges;var firstRetainerIndex=this._firstRetainerIndex;var containmentEdges=this.containmentEdges;var edgeFieldsCount=this._edgeFieldsCount;var nodeFieldCount=this._nodeFieldCount;var edgeToNodeOffset=this._edgeToNodeOffset;var firstEdgeIndexes=this._firstEdgeIndexes;var nodeCount=this.nodeCount;for(var toNodeFieldIndex=edgeToNodeOffset,l=containmentEdges.length;toNodeFieldIndex<l;toNodeFieldIndex+=edgeFieldsCount){var toNodeIndex=containmentEdges[toNodeFieldIndex];if(toNodeIndex%nodeFieldCount) -throw new Error('Invalid toNodeIndex '+toNodeIndex);++firstRetainerIndex[toNodeIndex/nodeFieldCount];} -for(var i=0,firstUnusedRetainerSlot=0;i<nodeCount;i++){var retainersCount=firstRetainerIndex[i];firstRetainerIndex[i]=firstUnusedRetainerSlot;retainingNodes[firstUnusedRetainerSlot]=retainersCount;firstUnusedRetainerSlot+=retainersCount;} -firstRetainerIndex[nodeCount]=retainingNodes.length;var nextNodeFirstEdgeIndex=firstEdgeIndexes[0];for(var srcNodeOrdinal=0;srcNodeOrdinal<nodeCount;++srcNodeOrdinal){var firstEdgeIndex=nextNodeFirstEdgeIndex;nextNodeFirstEdgeIndex=firstEdgeIndexes[srcNodeOrdinal+1];var srcNodeIndex=srcNodeOrdinal*nodeFieldCount;for(var edgeIndex=firstEdgeIndex;edgeIndex<nextNodeFirstEdgeIndex;edgeIndex+=edgeFieldsCount){var toNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];if(toNodeIndex%nodeFieldCount) -throw new Error('Invalid toNodeIndex '+toNodeIndex);var firstRetainerSlotIndex=firstRetainerIndex[toNodeIndex/nodeFieldCount];var nextUnusedRetainerSlotIndex=firstRetainerSlotIndex+(--retainingNodes[firstRetainerSlotIndex]);retainingNodes[nextUnusedRetainerSlotIndex]=srcNodeIndex;retainingEdges[nextUnusedRetainerSlotIndex]=edgeIndex;}}} -createNode(nodeIndex){throw new Error('Not implemented');} -createEdge(edgeIndex){throw new Error('Not implemented');} -createRetainingEdge(retainerIndex){throw new Error('Not implemented');} -_allNodes(){return new HeapSnapshotWorker.HeapSnapshotNodeIterator(this.rootNode());} -rootNode(){return this.createNode(this._rootNodeIndex);} -get rootNodeIndex(){return this._rootNodeIndex;} -get totalSize(){return this.rootNode().retainedSize();} -_getDominatedIndex(nodeIndex){if(nodeIndex%this._nodeFieldCount) -throw new Error('Invalid nodeIndex: '+nodeIndex);return this._firstDominatedNodeIndex[nodeIndex/this._nodeFieldCount];} -_createFilter(nodeFilter){var minNodeId=nodeFilter.minNodeId;var maxNodeId=nodeFilter.maxNodeId;var allocationNodeId=nodeFilter.allocationNodeId;var filter;if(typeof allocationNodeId==='number'){filter=this._createAllocationStackFilter(allocationNodeId);filter.key='AllocationNodeId: '+allocationNodeId;}else if(typeof minNodeId==='number'&&typeof maxNodeId==='number'){filter=this._createNodeIdFilter(minNodeId,maxNodeId);filter.key='NodeIdRange: '+minNodeId+'..'+maxNodeId;} -return filter;} -search(searchConfig,nodeFilter){var query=searchConfig.query;function filterString(matchedStringIndexes,string,index){if(string.indexOf(query)!==-1) -matchedStringIndexes.add(index);return matchedStringIndexes;} -var regexp=searchConfig.isRegex?new RegExp(query):createPlainTextSearchRegex(query,'i');function filterRegexp(matchedStringIndexes,string,index){if(regexp.test(string)) -matchedStringIndexes.add(index);return matchedStringIndexes;} -var stringFilter=(searchConfig.isRegex||!searchConfig.caseSensitive)?filterRegexp:filterString;var stringIndexes=this.strings.reduce(stringFilter,new Set());if(!stringIndexes.size) -return[];var filter=this._createFilter(nodeFilter);var nodeIds=[];var nodesLength=this.nodes.length;var nodes=this.nodes;var nodeNameOffset=this._nodeNameOffset;var nodeIdOffset=this._nodeIdOffset;var nodeFieldCount=this._nodeFieldCount;var node=this.rootNode();for(var nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;if(filter&&!filter(node)) -continue;if(stringIndexes.has(nodes[nodeIndex+nodeNameOffset])) -nodeIds.push(nodes[nodeIndex+nodeIdOffset]);} -return nodeIds;} -aggregatesWithFilter(nodeFilter){var filter=this._createFilter(nodeFilter);var key=filter?filter.key:'allObjects';return this.aggregates(false,key,filter);} -_createNodeIdFilter(minNodeId,maxNodeId){function nodeIdFilter(node){var id=node.id();return id>minNodeId&&id<=maxNodeId;} -return nodeIdFilter;} -_createAllocationStackFilter(bottomUpAllocationNodeId){var traceIds=this._allocationProfile.traceIds(bottomUpAllocationNodeId);if(!traceIds.length) -return undefined;var set={};for(var i=0;i<traceIds.length;i++) -set[traceIds[i]]=true;function traceIdFilter(node){return!!set[node.traceNodeId()];} -return traceIdFilter;} -aggregates(sortedIndexes,key,filter){var aggregatesByClassName=key&&this._aggregates[key];if(!aggregatesByClassName){var aggregates=this._buildAggregates(filter);this._calculateClassesRetainedSize(aggregates.aggregatesByClassIndex,filter);aggregatesByClassName=aggregates.aggregatesByClassName;if(key) -this._aggregates[key]=aggregatesByClassName;} -if(sortedIndexes&&(!key||!this._aggregatesSortedFlags[key])){this._sortAggregateIndexes(aggregatesByClassName);if(key) -this._aggregatesSortedFlags[key]=sortedIndexes;} -return aggregatesByClassName;} -allocationTracesTops(){return this._allocationProfile.serializeTraceTops();} -allocationNodeCallers(nodeId){return this._allocationProfile.serializeCallers(nodeId);} -allocationStack(nodeIndex){var node=this.createNode(nodeIndex);var allocationNodeId=node.traceNodeId();if(!allocationNodeId) -return null;return this._allocationProfile.serializeAllocationStack(allocationNodeId);} -aggregatesForDiff(){if(this._aggregatesForDiff) -return this._aggregatesForDiff;var aggregatesByClassName=this.aggregates(true,'allObjects');this._aggregatesForDiff={};var node=this.createNode();for(var className in aggregatesByClassName){var aggregate=aggregatesByClassName[className];var indexes=aggregate.idxs;var ids=new Array(indexes.length);var selfSizes=new Array(indexes.length);for(var i=0;i<indexes.length;i++){node.nodeIndex=indexes[i];ids[i]=node.id();selfSizes[i]=node.selfSize();} -this._aggregatesForDiff[className]={indexes:indexes,ids:ids,selfSizes:selfSizes};} -return this._aggregatesForDiff;} -isUserRoot(node){return true;} -forEachRoot(action,userRootsOnly){for(var iter=this.rootNode().edges();iter.hasNext();iter.next()){var node=iter.edge.node();if(!userRootsOnly||this.isUserRoot(node)) -action(node);}} -calculateDistances(filter){var nodeCount=this.nodeCount;var distances=this._nodeDistances;var noDistance=this._noDistance;for(var i=0;i<nodeCount;++i) -distances[i]=noDistance;var nodesToVisit=new Uint32Array(this.nodeCount);var nodesToVisitLength=0;function enqueueNode(distance,node){var ordinal=node.ordinal();if(distances[ordinal]!==noDistance) -return;distances[ordinal]=distance;nodesToVisit[nodesToVisitLength++]=node.nodeIndex;} -this.forEachRoot(enqueueNode.bind(null,1),true);this._bfs(nodesToVisit,nodesToVisitLength,distances,filter);nodesToVisitLength=0;this.forEachRoot(enqueueNode.bind(null,HeapSnapshotModel.baseSystemDistance),false);this._bfs(nodesToVisit,nodesToVisitLength,distances,filter);} -_bfs(nodesToVisit,nodesToVisitLength,distances,filter){var edgeFieldsCount=this._edgeFieldsCount;var nodeFieldCount=this._nodeFieldCount;var containmentEdges=this.containmentEdges;var firstEdgeIndexes=this._firstEdgeIndexes;var edgeToNodeOffset=this._edgeToNodeOffset;var edgeTypeOffset=this._edgeTypeOffset;var nodeCount=this.nodeCount;var edgeWeakType=this._edgeWeakType;var noDistance=this._noDistance;var index=0;var edge=this.createEdge(0);var node=this.createNode(0);while(index<nodesToVisitLength){var nodeIndex=nodesToVisit[index++];var nodeOrdinal=nodeIndex/nodeFieldCount;var distance=distances[nodeOrdinal]+1;var firstEdgeIndex=firstEdgeIndexes[nodeOrdinal];var edgesEnd=firstEdgeIndexes[nodeOrdinal+1];node.nodeIndex=nodeIndex;for(var edgeIndex=firstEdgeIndex;edgeIndex<edgesEnd;edgeIndex+=edgeFieldsCount){var edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(edgeType===edgeWeakType) -continue;var childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];var childNodeOrdinal=childNodeIndex/nodeFieldCount;if(distances[childNodeOrdinal]!==noDistance) -continue;edge.edgeIndex=edgeIndex;if(filter&&!filter(node,edge)) -continue;distances[childNodeOrdinal]=distance;nodesToVisit[nodesToVisitLength++]=childNodeIndex;}} -if(nodesToVisitLength>nodeCount){throw new Error('BFS failed. Nodes to visit ('+nodesToVisitLength+') is more than nodes count ('+nodeCount+')');}} -_buildAggregates(filter){var aggregates={};var aggregatesByClassName={};var classIndexes=[];var nodes=this.nodes;var nodesLength=nodes.length;var nodeNativeType=this._nodeNativeType;var nodeFieldCount=this._nodeFieldCount;var selfSizeOffset=this._nodeSelfSizeOffset;var nodeTypeOffset=this._nodeTypeOffset;var node=this.rootNode();var nodeDistances=this._nodeDistances;for(var nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;if(filter&&!filter(node)) -continue;var selfSize=nodes[nodeIndex+selfSizeOffset];if(!selfSize&&nodes[nodeIndex+nodeTypeOffset]!==nodeNativeType) -continue;var classIndex=node.classIndex();var nodeOrdinal=nodeIndex/nodeFieldCount;var distance=nodeDistances[nodeOrdinal];if(!(classIndex in aggregates)){var nodeType=node.type();var nameMatters=nodeType==='object'||nodeType==='native';var value={count:1,distance:distance,self:selfSize,maxRet:0,type:nodeType,name:nameMatters?node.name():null,idxs:[nodeIndex]};aggregates[classIndex]=value;classIndexes.push(classIndex);aggregatesByClassName[node.className()]=value;}else{var clss=aggregates[classIndex];clss.distance=Math.min(clss.distance,distance);++clss.count;clss.self+=selfSize;clss.idxs.push(nodeIndex);}} -for(var i=0,l=classIndexes.length;i<l;++i){var classIndex=classIndexes[i];aggregates[classIndex].idxs=aggregates[classIndex].idxs.slice();} -return{aggregatesByClassName:aggregatesByClassName,aggregatesByClassIndex:aggregates};} -_calculateClassesRetainedSize(aggregates,filter){var rootNodeIndex=this._rootNodeIndex;var node=this.createNode(rootNodeIndex);var list=[rootNodeIndex];var sizes=[-1];var classes=[];var seenClassNameIndexes={};var nodeFieldCount=this._nodeFieldCount;var nodeTypeOffset=this._nodeTypeOffset;var nodeNativeType=this._nodeNativeType;var dominatedNodes=this._dominatedNodes;var nodes=this.nodes;var firstDominatedNodeIndex=this._firstDominatedNodeIndex;while(list.length){var nodeIndex=list.pop();node.nodeIndex=nodeIndex;var classIndex=node.classIndex();var seen=!!seenClassNameIndexes[classIndex];var nodeOrdinal=nodeIndex/nodeFieldCount;var dominatedIndexFrom=firstDominatedNodeIndex[nodeOrdinal];var dominatedIndexTo=firstDominatedNodeIndex[nodeOrdinal+1];if(!seen&&(!filter||filter(node))&&(node.selfSize()||nodes[nodeIndex+nodeTypeOffset]===nodeNativeType)){aggregates[classIndex].maxRet+=node.retainedSize();if(dominatedIndexFrom!==dominatedIndexTo){seenClassNameIndexes[classIndex]=true;sizes.push(list.length);classes.push(classIndex);}} -for(var i=dominatedIndexFrom;i<dominatedIndexTo;i++) -list.push(dominatedNodes[i]);var l=list.length;while(sizes[sizes.length-1]===l){sizes.pop();classIndex=classes.pop();seenClassNameIndexes[classIndex]=false;}}} -_sortAggregateIndexes(aggregates){var nodeA=this.createNode();var nodeB=this.createNode();for(var clss in aggregates){aggregates[clss].idxs.sort((idxA,idxB)=>{nodeA.nodeIndex=idxA;nodeB.nodeIndex=idxB;return nodeA.id()<nodeB.id()?-1:1;});}} -_isEssentialEdge(nodeIndex,edgeType){return edgeType!==this._edgeWeakType&&(edgeType!==this._edgeShortcutType||nodeIndex===this._rootNodeIndex);} -_buildPostOrderIndex(){var nodeFieldCount=this._nodeFieldCount;var nodeCount=this.nodeCount;var rootNodeOrdinal=this._rootNodeIndex/nodeFieldCount;var edgeFieldsCount=this._edgeFieldsCount;var edgeTypeOffset=this._edgeTypeOffset;var edgeToNodeOffset=this._edgeToNodeOffset;var firstEdgeIndexes=this._firstEdgeIndexes;var containmentEdges=this.containmentEdges;var mapAndFlag=this.userObjectsMapAndFlag();var flags=mapAndFlag?mapAndFlag.map:null;var flag=mapAndFlag?mapAndFlag.flag:0;var stackNodes=new Uint32Array(nodeCount);var stackCurrentEdge=new Uint32Array(nodeCount);var postOrderIndex2NodeOrdinal=new Uint32Array(nodeCount);var nodeOrdinal2PostOrderIndex=new Uint32Array(nodeCount);var visited=new Uint8Array(nodeCount);var postOrderIndex=0;var stackTop=0;stackNodes[0]=rootNodeOrdinal;stackCurrentEdge[0]=firstEdgeIndexes[rootNodeOrdinal];visited[rootNodeOrdinal]=1;var iteration=0;while(true){++iteration;while(stackTop>=0){var nodeOrdinal=stackNodes[stackTop];var edgeIndex=stackCurrentEdge[stackTop];var edgesEnd=firstEdgeIndexes[nodeOrdinal+1];if(edgeIndex<edgesEnd){stackCurrentEdge[stackTop]+=edgeFieldsCount;var edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(!this._isEssentialEdge(nodeOrdinal*nodeFieldCount,edgeType)) -continue;var childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];var childNodeOrdinal=childNodeIndex/nodeFieldCount;if(visited[childNodeOrdinal]) -continue;var nodeFlag=!flags||(flags[nodeOrdinal]&flag);var childNodeFlag=!flags||(flags[childNodeOrdinal]&flag);if(nodeOrdinal!==rootNodeOrdinal&&childNodeFlag&&!nodeFlag) -continue;++stackTop;stackNodes[stackTop]=childNodeOrdinal;stackCurrentEdge[stackTop]=firstEdgeIndexes[childNodeOrdinal];visited[childNodeOrdinal]=1;}else{nodeOrdinal2PostOrderIndex[nodeOrdinal]=postOrderIndex;postOrderIndex2NodeOrdinal[postOrderIndex++]=nodeOrdinal;--stackTop;}} -if(postOrderIndex===nodeCount||iteration>1) -break;var errors=new HeapSnapshotWorker.HeapSnapshotProblemReport(`Heap snapshot: ${nodeCount - - postOrderIndex} nodes are unreachable from the root. Following nodes have only weak retainers:`);var dumpNode=this.rootNode();--postOrderIndex;stackTop=0;stackNodes[0]=rootNodeOrdinal;stackCurrentEdge[0]=firstEdgeIndexes[rootNodeOrdinal+1];for(var i=0;i<nodeCount;++i){if(visited[i]||!this._hasOnlyWeakRetainers(i)) -continue;stackNodes[++stackTop]=i;stackCurrentEdge[stackTop]=firstEdgeIndexes[i];visited[i]=1;dumpNode.nodeIndex=i*nodeFieldCount;var retainers=[];for(var it=dumpNode.retainers();it.hasNext();it.next()) -retainers.push(`${it.item().node().name()}@${it.item().node().id()}.${it.item().name()}`);errors.addError(`${dumpNode.name()} @${dumpNode.id()} weak retainers: ${retainers.join(', ')}`);} -console.warn(errors.toString());} -if(postOrderIndex!==nodeCount){var errors=new HeapSnapshotWorker.HeapSnapshotProblemReport('Still found '+(nodeCount-postOrderIndex)+' unreachable nodes in heap snapshot:');var dumpNode=this.rootNode();--postOrderIndex;for(var i=0;i<nodeCount;++i){if(visited[i]) -continue;dumpNode.nodeIndex=i*nodeFieldCount;errors.addError(dumpNode.name()+' @'+dumpNode.id());nodeOrdinal2PostOrderIndex[i]=postOrderIndex;postOrderIndex2NodeOrdinal[postOrderIndex++]=i;} -nodeOrdinal2PostOrderIndex[rootNodeOrdinal]=postOrderIndex;postOrderIndex2NodeOrdinal[postOrderIndex++]=rootNodeOrdinal;console.warn(errors.toString());} -return{postOrderIndex2NodeOrdinal:postOrderIndex2NodeOrdinal,nodeOrdinal2PostOrderIndex:nodeOrdinal2PostOrderIndex};} -_hasOnlyWeakRetainers(nodeOrdinal){var edgeTypeOffset=this._edgeTypeOffset;var edgeWeakType=this._edgeWeakType;var edgeShortcutType=this._edgeShortcutType;var containmentEdges=this.containmentEdges;var retainingEdges=this._retainingEdges;var beginRetainerIndex=this._firstRetainerIndex[nodeOrdinal];var endRetainerIndex=this._firstRetainerIndex[nodeOrdinal+1];for(var retainerIndex=beginRetainerIndex;retainerIndex<endRetainerIndex;++retainerIndex){var retainerEdgeIndex=retainingEdges[retainerIndex];var retainerEdgeType=containmentEdges[retainerEdgeIndex+edgeTypeOffset];if(retainerEdgeType!==edgeWeakType&&retainerEdgeType!==edgeShortcutType) -return false;} -return true;} -_buildDominatorTree(postOrderIndex2NodeOrdinal,nodeOrdinal2PostOrderIndex){var nodeFieldCount=this._nodeFieldCount;var firstRetainerIndex=this._firstRetainerIndex;var retainingNodes=this._retainingNodes;var retainingEdges=this._retainingEdges;var edgeFieldsCount=this._edgeFieldsCount;var edgeTypeOffset=this._edgeTypeOffset;var edgeToNodeOffset=this._edgeToNodeOffset;var firstEdgeIndexes=this._firstEdgeIndexes;var containmentEdges=this.containmentEdges;var rootNodeIndex=this._rootNodeIndex;var mapAndFlag=this.userObjectsMapAndFlag();var flags=mapAndFlag?mapAndFlag.map:null;var flag=mapAndFlag?mapAndFlag.flag:0;var nodesCount=postOrderIndex2NodeOrdinal.length;var rootPostOrderedIndex=nodesCount-1;var noEntry=nodesCount;var dominators=new Uint32Array(nodesCount);for(var i=0;i<rootPostOrderedIndex;++i) -dominators[i]=noEntry;dominators[rootPostOrderedIndex]=rootPostOrderedIndex;var affected=new Uint8Array(nodesCount);var nodeOrdinal;{nodeOrdinal=this._rootNodeIndex/nodeFieldCount;var endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];for(var edgeIndex=firstEdgeIndexes[nodeOrdinal];edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){var edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(!this._isEssentialEdge(this._rootNodeIndex,edgeType)) -continue;var childNodeOrdinal=containmentEdges[edgeIndex+edgeToNodeOffset]/nodeFieldCount;affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]]=1;}} -var changed=true;while(changed){changed=false;for(var postOrderIndex=rootPostOrderedIndex-1;postOrderIndex>=0;--postOrderIndex){if(affected[postOrderIndex]===0) -continue;affected[postOrderIndex]=0;if(dominators[postOrderIndex]===rootPostOrderedIndex) -continue;nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];var nodeFlag=!flags||(flags[nodeOrdinal]&flag);var newDominatorIndex=noEntry;var beginRetainerIndex=firstRetainerIndex[nodeOrdinal];var endRetainerIndex=firstRetainerIndex[nodeOrdinal+1];var orphanNode=true;for(var retainerIndex=beginRetainerIndex;retainerIndex<endRetainerIndex;++retainerIndex){var retainerEdgeIndex=retainingEdges[retainerIndex];var retainerEdgeType=containmentEdges[retainerEdgeIndex+edgeTypeOffset];var retainerNodeIndex=retainingNodes[retainerIndex];if(!this._isEssentialEdge(retainerNodeIndex,retainerEdgeType)) -continue;orphanNode=false;var retainerNodeOrdinal=retainerNodeIndex/nodeFieldCount;var retainerNodeFlag=!flags||(flags[retainerNodeOrdinal]&flag);if(retainerNodeIndex!==rootNodeIndex&&nodeFlag&&!retainerNodeFlag) -continue;var retanerPostOrderIndex=nodeOrdinal2PostOrderIndex[retainerNodeOrdinal];if(dominators[retanerPostOrderIndex]!==noEntry){if(newDominatorIndex===noEntry){newDominatorIndex=retanerPostOrderIndex;}else{while(retanerPostOrderIndex!==newDominatorIndex){while(retanerPostOrderIndex<newDominatorIndex) -retanerPostOrderIndex=dominators[retanerPostOrderIndex];while(newDominatorIndex<retanerPostOrderIndex) -newDominatorIndex=dominators[newDominatorIndex];}} -if(newDominatorIndex===rootPostOrderedIndex) -break;}} -if(orphanNode) -newDominatorIndex=rootPostOrderedIndex;if(newDominatorIndex!==noEntry&&dominators[postOrderIndex]!==newDominatorIndex){dominators[postOrderIndex]=newDominatorIndex;changed=true;nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];var beginEdgeToNodeFieldIndex=firstEdgeIndexes[nodeOrdinal]+edgeToNodeOffset;var endEdgeToNodeFieldIndex=firstEdgeIndexes[nodeOrdinal+1];for(var toNodeFieldIndex=beginEdgeToNodeFieldIndex;toNodeFieldIndex<endEdgeToNodeFieldIndex;toNodeFieldIndex+=edgeFieldsCount){var childNodeOrdinal=containmentEdges[toNodeFieldIndex]/nodeFieldCount;affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]]=1;}}}} -var dominatorsTree=new Uint32Array(nodesCount);for(var postOrderIndex=0,l=dominators.length;postOrderIndex<l;++postOrderIndex){nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];dominatorsTree[nodeOrdinal]=postOrderIndex2NodeOrdinal[dominators[postOrderIndex]];} -return dominatorsTree;} -_calculateRetainedSizes(postOrderIndex2NodeOrdinal){var nodeCount=this.nodeCount;var nodes=this.nodes;var nodeSelfSizeOffset=this._nodeSelfSizeOffset;var nodeFieldCount=this._nodeFieldCount;var dominatorsTree=this._dominatorsTree;var retainedSizes=this._retainedSizes;for(var nodeOrdinal=0;nodeOrdinal<nodeCount;++nodeOrdinal) -retainedSizes[nodeOrdinal]=nodes[nodeOrdinal*nodeFieldCount+nodeSelfSizeOffset];for(var postOrderIndex=0;postOrderIndex<nodeCount-1;++postOrderIndex){var nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];var dominatorOrdinal=dominatorsTree[nodeOrdinal];retainedSizes[dominatorOrdinal]+=retainedSizes[nodeOrdinal];}} -_buildDominatedNodes(){var indexArray=this._firstDominatedNodeIndex;var dominatedNodes=this._dominatedNodes;var nodeFieldCount=this._nodeFieldCount;var dominatorsTree=this._dominatorsTree;var fromNodeOrdinal=0;var toNodeOrdinal=this.nodeCount;var rootNodeOrdinal=this._rootNodeIndex/nodeFieldCount;if(rootNodeOrdinal===fromNodeOrdinal) -fromNodeOrdinal=1;else if(rootNodeOrdinal===toNodeOrdinal-1) -toNodeOrdinal=toNodeOrdinal-1;else -throw new Error('Root node is expected to be either first or last');for(var nodeOrdinal=fromNodeOrdinal;nodeOrdinal<toNodeOrdinal;++nodeOrdinal) -++indexArray[dominatorsTree[nodeOrdinal]];var firstDominatedNodeIndex=0;for(var i=0,l=this.nodeCount;i<l;++i){var dominatedCount=dominatedNodes[firstDominatedNodeIndex]=indexArray[i];indexArray[i]=firstDominatedNodeIndex;firstDominatedNodeIndex+=dominatedCount;} -indexArray[this.nodeCount]=dominatedNodes.length;for(var nodeOrdinal=fromNodeOrdinal;nodeOrdinal<toNodeOrdinal;++nodeOrdinal){var dominatorOrdinal=dominatorsTree[nodeOrdinal];var dominatedRefIndex=indexArray[dominatorOrdinal];dominatedRefIndex+=(--dominatedNodes[dominatedRefIndex]);dominatedNodes[dominatedRefIndex]=nodeOrdinal*nodeFieldCount;}} -_buildSamples(){var samples=this._rawSamples;if(!samples||!samples.length) -return;var sampleCount=samples.length/2;var sizeForRange=new Array(sampleCount);var timestamps=new Array(sampleCount);var lastAssignedIds=new Array(sampleCount);var timestampOffset=this._metaNode.sample_fields.indexOf('timestamp_us');var lastAssignedIdOffset=this._metaNode.sample_fields.indexOf('last_assigned_id');for(var i=0;i<sampleCount;i++){sizeForRange[i]=0;timestamps[i]=(samples[2*i+timestampOffset])/1000;lastAssignedIds[i]=samples[2*i+lastAssignedIdOffset];} -var nodes=this.nodes;var nodesLength=nodes.length;var nodeFieldCount=this._nodeFieldCount;var node=this.rootNode();for(var nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;var nodeId=node.id();if(nodeId%2===0) -continue;var rangeIndex=lastAssignedIds.lowerBound(nodeId);if(rangeIndex===sampleCount){continue;} -sizeForRange[rangeIndex]+=node.selfSize();} -this._samples=new HeapSnapshotModel.Samples(timestamps,lastAssignedIds,sizeForRange);} -getSamples(){return this._samples;} -calculateFlags(){throw new Error('Not implemented');} -calculateStatistics(){throw new Error('Not implemented');} -userObjectsMapAndFlag(){throw new Error('Not implemented');} -calculateSnapshotDiff(baseSnapshotId,baseSnapshotAggregates){var snapshotDiff=this._snapshotDiffs[baseSnapshotId];if(snapshotDiff) -return snapshotDiff;snapshotDiff={};var aggregates=this.aggregates(true,'allObjects');for(var className in baseSnapshotAggregates){var baseAggregate=baseSnapshotAggregates[className];var diff=this._calculateDiffForClass(baseAggregate,aggregates[className]);if(diff) -snapshotDiff[className]=diff;} -var emptyBaseAggregate=new HeapSnapshotModel.AggregateForDiff();for(var className in aggregates){if(className in baseSnapshotAggregates) -continue;snapshotDiff[className]=this._calculateDiffForClass(emptyBaseAggregate,aggregates[className]);} -this._snapshotDiffs[baseSnapshotId]=snapshotDiff;return snapshotDiff;} -_calculateDiffForClass(baseAggregate,aggregate){var baseIds=baseAggregate.ids;var baseIndexes=baseAggregate.indexes;var baseSelfSizes=baseAggregate.selfSizes;var indexes=aggregate?aggregate.idxs:[];var i=0,l=baseIds.length;var j=0,m=indexes.length;var diff=new HeapSnapshotModel.Diff();var nodeB=this.createNode(indexes[j]);while(i<l&&j<m){var nodeAId=baseIds[i];if(nodeAId<nodeB.id()){diff.deletedIndexes.push(baseIndexes[i]);diff.removedCount++;diff.removedSize+=baseSelfSizes[i];++i;}else if(nodeAId>nodeB.id()){diff.addedIndexes.push(indexes[j]);diff.addedCount++;diff.addedSize+=nodeB.selfSize();nodeB.nodeIndex=indexes[++j];}else{++i;nodeB.nodeIndex=indexes[++j];}} -while(i<l){diff.deletedIndexes.push(baseIndexes[i]);diff.removedCount++;diff.removedSize+=baseSelfSizes[i];++i;} -while(j<m){diff.addedIndexes.push(indexes[j]);diff.addedCount++;diff.addedSize+=nodeB.selfSize();nodeB.nodeIndex=indexes[++j];} -diff.countDelta=diff.addedCount-diff.removedCount;diff.sizeDelta=diff.addedSize-diff.removedSize;if(!diff.addedCount&&!diff.removedCount) -return null;return diff;} -_nodeForSnapshotObjectId(snapshotObjectId){for(var it=this._allNodes();it.hasNext();it.next()){if(it.node.id()===snapshotObjectId) -return it.node;} -return null;} -nodeClassName(snapshotObjectId){var node=this._nodeForSnapshotObjectId(snapshotObjectId);if(node) -return node.className();return null;} -idsOfObjectsWithName(name){var ids=[];for(var it=this._allNodes();it.hasNext();it.next()){if(it.item().name()===name) -ids.push(it.item().id());} -return ids;} -createEdgesProvider(nodeIndex){var node=this.createNode(nodeIndex);var filter=this.containmentEdgesFilter();var indexProvider=new HeapSnapshotWorker.HeapSnapshotEdgeIndexProvider(this);return new HeapSnapshotWorker.HeapSnapshotEdgesProvider(this,filter,node.edges(),indexProvider);} -createEdgesProviderForTest(nodeIndex,filter){var node=this.createNode(nodeIndex);var indexProvider=new HeapSnapshotWorker.HeapSnapshotEdgeIndexProvider(this);return new HeapSnapshotWorker.HeapSnapshotEdgesProvider(this,filter,node.edges(),indexProvider);} -retainingEdgesFilter(){return null;} -containmentEdgesFilter(){return null;} -createRetainingEdgesProvider(nodeIndex){var node=this.createNode(nodeIndex);var filter=this.retainingEdgesFilter();var indexProvider=new HeapSnapshotWorker.HeapSnapshotRetainerEdgeIndexProvider(this);return new HeapSnapshotWorker.HeapSnapshotEdgesProvider(this,filter,node.retainers(),indexProvider);} -createAddedNodesProvider(baseSnapshotId,className){var snapshotDiff=this._snapshotDiffs[baseSnapshotId];var diffForClass=snapshotDiff[className];return new HeapSnapshotWorker.HeapSnapshotNodesProvider(this,diffForClass.addedIndexes);} -createDeletedNodesProvider(nodeIndexes){return new HeapSnapshotWorker.HeapSnapshotNodesProvider(this,nodeIndexes);} -createNodesProviderForClass(className,nodeFilter){return new HeapSnapshotWorker.HeapSnapshotNodesProvider(this,this.aggregatesWithFilter(nodeFilter)[className].idxs);} -_maxJsNodeId(){var nodeFieldCount=this._nodeFieldCount;var nodes=this.nodes;var nodesLength=nodes.length;var id=0;for(var nodeIndex=this._nodeIdOffset;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){var nextId=nodes[nodeIndex];if(nextId%2===0) -continue;if(id<nextId) -id=nextId;} -return id;} -updateStaticData(){return new HeapSnapshotModel.StaticData(this.nodeCount,this._rootNodeIndex,this.totalSize,this._maxJsNodeId());}};HeapSnapshotWorker.HeapSnapshot.AggregatedInfo;var HeapSnapshotMetainfo=class{constructor(){this.node_fields=[];this.node_types=[];this.edge_fields=[];this.edge_types=[];this.trace_function_info_fields=[];this.trace_node_fields=[];this.sample_fields=[];this.type_strings={};}};var HeapSnapshotHeader=class{constructor(){this.title='';this.meta=new HeapSnapshotMetainfo();this.node_count=0;this.edge_count=0;this.trace_function_count=0;}};HeapSnapshotWorker.HeapSnapshotItemProvider=class{constructor(iterator,indexProvider){this._iterator=iterator;this._indexProvider=indexProvider;this._isEmpty=!iterator.hasNext();this._iterationOrder=null;this._currentComparator=null;this._sortedPrefixLength=0;this._sortedSuffixLength=0;} -_createIterationOrder(){if(this._iterationOrder) -return;this._iterationOrder=[];for(var iterator=this._iterator;iterator.hasNext();iterator.next()) -this._iterationOrder.push(iterator.item().itemIndex());} -isEmpty(){return this._isEmpty;} -serializeItemsRange(begin,end){this._createIterationOrder();if(begin>end) -throw new Error('Start position > end position: '+begin+' > '+end);if(end>this._iterationOrder.length) -end=this._iterationOrder.length;if(this._sortedPrefixLength<end&&begin<this._iterationOrder.length-this._sortedSuffixLength){this.sort(this._currentComparator,this._sortedPrefixLength,this._iterationOrder.length-1-this._sortedSuffixLength,begin,end-1);if(begin<=this._sortedPrefixLength) -this._sortedPrefixLength=end;if(end>=this._iterationOrder.length-this._sortedSuffixLength) -this._sortedSuffixLength=this._iterationOrder.length-begin;} -var position=begin;var count=end-begin;var result=new Array(count);for(var i=0;i<count;++i){var itemIndex=this._iterationOrder[position++];var item=this._indexProvider.itemForIndex(itemIndex);result[i]=item.serialize();} -return new HeapSnapshotModel.ItemsRange(begin,end,this._iterationOrder.length,result);} -sortAndRewind(comparator){this._currentComparator=comparator;this._sortedPrefixLength=0;this._sortedSuffixLength=0;}};HeapSnapshotWorker.HeapSnapshotEdgesProvider=class extends HeapSnapshotWorker.HeapSnapshotItemProvider{constructor(snapshot,filter,edgesIter,indexProvider){var iter=filter?new HeapSnapshotWorker.HeapSnapshotFilteredIterator(edgesIter,(filter)):edgesIter;super(iter,indexProvider);this.snapshot=snapshot;} -sort(comparator,leftBound,rightBound,windowLeft,windowRight){var fieldName1=comparator.fieldName1;var fieldName2=comparator.fieldName2;var ascending1=comparator.ascending1;var ascending2=comparator.ascending2;var edgeA=this._iterator.item().clone();var edgeB=edgeA.clone();var nodeA=this.snapshot.createNode();var nodeB=this.snapshot.createNode();function compareEdgeFieldName(ascending,indexA,indexB){edgeA.edgeIndex=indexA;edgeB.edgeIndex=indexB;if(edgeB.name()==='__proto__') -return-1;if(edgeA.name()==='__proto__') -return 1;var result=edgeA.hasStringName()===edgeB.hasStringName()?(edgeA.name()<edgeB.name()?-1:(edgeA.name()>edgeB.name()?1:0)):(edgeA.hasStringName()?-1:1);return ascending?result:-result;} -function compareNodeField(fieldName,ascending,indexA,indexB){edgeA.edgeIndex=indexA;nodeA.nodeIndex=edgeA.nodeIndex();var valueA=nodeA[fieldName]();edgeB.edgeIndex=indexB;nodeB.nodeIndex=edgeB.nodeIndex();var valueB=nodeB[fieldName]();var result=valueA<valueB?-1:(valueA>valueB?1:0);return ascending?result:-result;} -function compareEdgeAndNode(indexA,indexB){var result=compareEdgeFieldName(ascending1,indexA,indexB);if(result===0) -result=compareNodeField(fieldName2,ascending2,indexA,indexB);if(result===0) -return indexA-indexB;return result;} -function compareNodeAndEdge(indexA,indexB){var result=compareNodeField(fieldName1,ascending1,indexA,indexB);if(result===0) -result=compareEdgeFieldName(ascending2,indexA,indexB);if(result===0) -return indexA-indexB;return result;} -function compareNodeAndNode(indexA,indexB){var result=compareNodeField(fieldName1,ascending1,indexA,indexB);if(result===0) -result=compareNodeField(fieldName2,ascending2,indexA,indexB);if(result===0) -return indexA-indexB;return result;} -if(fieldName1==='!edgeName') -this._iterationOrder.sortRange(compareEdgeAndNode,leftBound,rightBound,windowLeft,windowRight);else if(fieldName2==='!edgeName') -this._iterationOrder.sortRange(compareNodeAndEdge,leftBound,rightBound,windowLeft,windowRight);else -this._iterationOrder.sortRange(compareNodeAndNode,leftBound,rightBound,windowLeft,windowRight);}};HeapSnapshotWorker.HeapSnapshotNodesProvider=class extends HeapSnapshotWorker.HeapSnapshotItemProvider{constructor(snapshot,nodeIndexes){var indexProvider=new HeapSnapshotWorker.HeapSnapshotNodeIndexProvider(snapshot);var it=new HeapSnapshotWorker.HeapSnapshotIndexRangeIterator(indexProvider,nodeIndexes);super(it,indexProvider);this.snapshot=snapshot;} -nodePosition(snapshotObjectId){this._createIterationOrder();var node=this.snapshot.createNode();for(var i=0;i<this._iterationOrder.length;i++){node.nodeIndex=this._iterationOrder[i];if(node.id()===snapshotObjectId) -break;} -if(i===this._iterationOrder.length) -return-1;var targetNodeIndex=this._iterationOrder[i];var smallerCount=0;var compare=this._buildCompareFunction(this._currentComparator);for(var i=0;i<this._iterationOrder.length;i++){if(compare(this._iterationOrder[i],targetNodeIndex)<0) -++smallerCount;} -return smallerCount;} -_buildCompareFunction(comparator){var nodeA=this.snapshot.createNode();var nodeB=this.snapshot.createNode();var fieldAccessor1=nodeA[comparator.fieldName1];var fieldAccessor2=nodeA[comparator.fieldName2];var ascending1=comparator.ascending1?1:-1;var ascending2=comparator.ascending2?1:-1;function sortByNodeField(fieldAccessor,ascending){var valueA=fieldAccessor.call(nodeA);var valueB=fieldAccessor.call(nodeB);return valueA<valueB?-ascending:(valueA>valueB?ascending:0);} -function sortByComparator(indexA,indexB){nodeA.nodeIndex=indexA;nodeB.nodeIndex=indexB;var result=sortByNodeField(fieldAccessor1,ascending1);if(result===0) -result=sortByNodeField(fieldAccessor2,ascending2);return result||indexA-indexB;} -return sortByComparator;} -sort(comparator,leftBound,rightBound,windowLeft,windowRight){this._iterationOrder.sortRange(this._buildCompareFunction(comparator),leftBound,rightBound,windowLeft,windowRight);}};HeapSnapshotWorker.JSHeapSnapshot=class extends HeapSnapshotWorker.HeapSnapshot{constructor(profile,progress){super(profile,progress);this._nodeFlags={canBeQueried:1,detachedDOMTreeNode:2,pageObject:4};this._lazyStringCache={};this.initialize();} -createNode(nodeIndex){return new HeapSnapshotWorker.JSHeapSnapshotNode(this,nodeIndex===undefined?-1:nodeIndex);} -createEdge(edgeIndex){return new HeapSnapshotWorker.JSHeapSnapshotEdge(this,edgeIndex);} -createRetainingEdge(retainerIndex){return new HeapSnapshotWorker.JSHeapSnapshotRetainerEdge(this,retainerIndex);} -containmentEdgesFilter(){return edge=>!edge.isInvisible();} -retainingEdgesFilter(){var containmentEdgesFilter=this.containmentEdgesFilter();function filter(edge){return containmentEdgesFilter(edge)&&!edge.node().isRoot()&&!edge.isWeak();} -return filter;} -calculateFlags(){this._flags=new Uint32Array(this.nodeCount);this._markDetachedDOMTreeNodes();this._markQueriableHeapObjects();this._markPageOwnedNodes();} -calculateDistances(){function filter(node,edge){if(node.isHidden()) -return edge.name()!=='sloppy_function_map'||node.rawName()!=='system / NativeContext';if(node.isArray()){if(node.rawName()!=='(map descriptors)') -return true;var index=edge.name();return index<2||(index%3)!==1;} -return true;} -super.calculateDistances(filter);} -isUserRoot(node){return node.isUserRoot()||node.isDocumentDOMTreesRoot();} -forEachRoot(action,userRootsOnly){function getChildNodeByName(node,name){for(var iter=node.edges();iter.hasNext();iter.next()){var child=iter.edge.node();if(child.name()===name) -return child;} -return null;} -var visitedNodes={};function doAction(node){var ordinal=node.ordinal();if(!visitedNodes[ordinal]){action(node);visitedNodes[ordinal]=true;}} -var gcRoots=getChildNodeByName(this.rootNode(),'(GC roots)');if(!gcRoots) -return;if(userRootsOnly){for(var iter=this.rootNode().edges();iter.hasNext();iter.next()){var node=iter.edge.node();if(this.isUserRoot(node)) -doAction(node);}}else{for(var iter=gcRoots.edges();iter.hasNext();iter.next()){var subRoot=iter.edge.node();for(var iter2=subRoot.edges();iter2.hasNext();iter2.next()) -doAction(iter2.edge.node());doAction(subRoot);} -for(var iter=this.rootNode().edges();iter.hasNext();iter.next()) -doAction(iter.edge.node());}} -userObjectsMapAndFlag(){return{map:this._flags,flag:this._nodeFlags.pageObject};} -_flagsOfNode(node){return this._flags[node.nodeIndex/this._nodeFieldCount];} -_markDetachedDOMTreeNodes(){var flag=this._nodeFlags.detachedDOMTreeNode;var detachedDOMTreesRoot;for(var iter=this.rootNode().edges();iter.hasNext();iter.next()){var node=iter.edge.node();if(node.name()==='(Detached DOM trees)'){detachedDOMTreesRoot=node;break;}} -if(!detachedDOMTreesRoot) -return;var detachedDOMTreeRE=/^Detached DOM tree/;for(var iter=detachedDOMTreesRoot.edges();iter.hasNext();iter.next()){var node=iter.edge.node();if(detachedDOMTreeRE.test(node.className())){for(var edgesIter=node.edges();edgesIter.hasNext();edgesIter.next()) -this._flags[edgesIter.edge.node().nodeIndex/this._nodeFieldCount]|=flag;}}} -_markQueriableHeapObjects(){var flag=this._nodeFlags.canBeQueried;var hiddenEdgeType=this._edgeHiddenType;var internalEdgeType=this._edgeInternalType;var invisibleEdgeType=this._edgeInvisibleType;var weakEdgeType=this._edgeWeakType;var edgeToNodeOffset=this._edgeToNodeOffset;var edgeTypeOffset=this._edgeTypeOffset;var edgeFieldsCount=this._edgeFieldsCount;var containmentEdges=this.containmentEdges;var nodeFieldCount=this._nodeFieldCount;var firstEdgeIndexes=this._firstEdgeIndexes;var flags=this._flags;var list=[];for(var iter=this.rootNode().edges();iter.hasNext();iter.next()){if(iter.edge.node().isUserRoot()) -list.push(iter.edge.node().nodeIndex/nodeFieldCount);} -while(list.length){var nodeOrdinal=list.pop();if(flags[nodeOrdinal]&flag) -continue;flags[nodeOrdinal]|=flag;var beginEdgeIndex=firstEdgeIndexes[nodeOrdinal];var endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];for(var edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){var childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];var childNodeOrdinal=childNodeIndex/nodeFieldCount;if(flags[childNodeOrdinal]&flag) -continue;var type=containmentEdges[edgeIndex+edgeTypeOffset];if(type===hiddenEdgeType||type===invisibleEdgeType||type===internalEdgeType||type===weakEdgeType) -continue;list.push(childNodeOrdinal);}}} -_markPageOwnedNodes(){var edgeShortcutType=this._edgeShortcutType;var edgeElementType=this._edgeElementType;var edgeToNodeOffset=this._edgeToNodeOffset;var edgeTypeOffset=this._edgeTypeOffset;var edgeFieldsCount=this._edgeFieldsCount;var edgeWeakType=this._edgeWeakType;var firstEdgeIndexes=this._firstEdgeIndexes;var containmentEdges=this.containmentEdges;var nodeFieldCount=this._nodeFieldCount;var nodesCount=this.nodeCount;var flags=this._flags;var pageObjectFlag=this._nodeFlags.pageObject;var nodesToVisit=new Uint32Array(nodesCount);var nodesToVisitLength=0;var rootNodeOrdinal=this._rootNodeIndex/nodeFieldCount;var node=this.rootNode();for(var edgeIndex=firstEdgeIndexes[rootNodeOrdinal],endEdgeIndex=firstEdgeIndexes[rootNodeOrdinal+1];edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){var edgeType=containmentEdges[edgeIndex+edgeTypeOffset];var nodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];if(edgeType===edgeElementType){node.nodeIndex=nodeIndex;if(!node.isDocumentDOMTreesRoot()) -continue;}else if(edgeType!==edgeShortcutType){continue;} -var nodeOrdinal=nodeIndex/nodeFieldCount;nodesToVisit[nodesToVisitLength++]=nodeOrdinal;flags[nodeOrdinal]|=pageObjectFlag;} -while(nodesToVisitLength){var nodeOrdinal=nodesToVisit[--nodesToVisitLength];var beginEdgeIndex=firstEdgeIndexes[nodeOrdinal];var endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];for(var edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){var childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];var childNodeOrdinal=childNodeIndex/nodeFieldCount;if(flags[childNodeOrdinal]&pageObjectFlag) -continue;var type=containmentEdges[edgeIndex+edgeTypeOffset];if(type===edgeWeakType) -continue;nodesToVisit[nodesToVisitLength++]=childNodeOrdinal;flags[childNodeOrdinal]|=pageObjectFlag;}}} -calculateStatistics(){var nodeFieldCount=this._nodeFieldCount;var nodes=this.nodes;var nodesLength=nodes.length;var nodeTypeOffset=this._nodeTypeOffset;var nodeSizeOffset=this._nodeSelfSizeOffset;var nodeNativeType=this._nodeNativeType;var nodeCodeType=this._nodeCodeType;var nodeConsStringType=this._nodeConsStringType;var nodeSlicedStringType=this._nodeSlicedStringType;var distances=this._nodeDistances;var sizeNative=0;var sizeCode=0;var sizeStrings=0;var sizeJSArrays=0;var sizeSystem=0;var node=this.rootNode();for(var nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){var nodeSize=nodes[nodeIndex+nodeSizeOffset];var ordinal=nodeIndex/nodeFieldCount;if(distances[ordinal]>=HeapSnapshotModel.baseSystemDistance){sizeSystem+=nodeSize;continue;} -var nodeType=nodes[nodeIndex+nodeTypeOffset];node.nodeIndex=nodeIndex;if(nodeType===nodeNativeType) -sizeNative+=nodeSize;else if(nodeType===nodeCodeType) -sizeCode+=nodeSize;else if(nodeType===nodeConsStringType||nodeType===nodeSlicedStringType||node.type()==='string') -sizeStrings+=nodeSize;else if(node.name()==='Array') -sizeJSArrays+=this._calculateArraySize(node);} -this._statistics=new HeapSnapshotModel.Statistics();this._statistics.total=this.totalSize;this._statistics.v8heap=this.totalSize-sizeNative;this._statistics.native=sizeNative;this._statistics.code=sizeCode;this._statistics.jsArrays=sizeJSArrays;this._statistics.strings=sizeStrings;this._statistics.system=sizeSystem;} -_calculateArraySize(node){var size=node.selfSize();var beginEdgeIndex=node.edgeIndexesStart();var endEdgeIndex=node.edgeIndexesEnd();var containmentEdges=this.containmentEdges;var strings=this.strings;var edgeToNodeOffset=this._edgeToNodeOffset;var edgeTypeOffset=this._edgeTypeOffset;var edgeNameOffset=this._edgeNameOffset;var edgeFieldsCount=this._edgeFieldsCount;var edgeInternalType=this._edgeInternalType;for(var edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){var edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(edgeType!==edgeInternalType) -continue;var edgeName=strings[containmentEdges[edgeIndex+edgeNameOffset]];if(edgeName!=='elements') -continue;var elementsNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];node.nodeIndex=elementsNodeIndex;if(node.retainersCount()===1) -size+=node.selfSize();break;} -return size;} -getStatistics(){return this._statistics;}};HeapSnapshotWorker.JSHeapSnapshotNode=class extends HeapSnapshotWorker.HeapSnapshotNode{constructor(snapshot,nodeIndex){super(snapshot,nodeIndex);} -canBeQueried(){var flags=this._snapshot._flagsOfNode(this);return!!(flags&this._snapshot._nodeFlags.canBeQueried);} -rawName(){return super.name();} -name(){var snapshot=this._snapshot;if(this.rawType()===snapshot._nodeConsStringType){var string=snapshot._lazyStringCache[this.nodeIndex];if(typeof string==='undefined'){string=this._consStringName();snapshot._lazyStringCache[this.nodeIndex]=string;} -return string;} -return this.rawName();} -_consStringName(){var snapshot=this._snapshot;var consStringType=snapshot._nodeConsStringType;var edgeInternalType=snapshot._edgeInternalType;var edgeFieldsCount=snapshot._edgeFieldsCount;var edgeToNodeOffset=snapshot._edgeToNodeOffset;var edgeTypeOffset=snapshot._edgeTypeOffset;var edgeNameOffset=snapshot._edgeNameOffset;var strings=snapshot.strings;var edges=snapshot.containmentEdges;var firstEdgeIndexes=snapshot._firstEdgeIndexes;var nodeFieldCount=snapshot._nodeFieldCount;var nodeTypeOffset=snapshot._nodeTypeOffset;var nodeNameOffset=snapshot._nodeNameOffset;var nodes=snapshot.nodes;var nodesStack=[];nodesStack.push(this.nodeIndex);var name='';while(nodesStack.length&&name.length<1024){var nodeIndex=nodesStack.pop();if(nodes[nodeIndex+nodeTypeOffset]!==consStringType){name+=strings[nodes[nodeIndex+nodeNameOffset]];continue;} -var nodeOrdinal=nodeIndex/nodeFieldCount;var beginEdgeIndex=firstEdgeIndexes[nodeOrdinal];var endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];var firstNodeIndex=0;var secondNodeIndex=0;for(var edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex&&(!firstNodeIndex||!secondNodeIndex);edgeIndex+=edgeFieldsCount){var edgeType=edges[edgeIndex+edgeTypeOffset];if(edgeType===edgeInternalType){var edgeName=strings[edges[edgeIndex+edgeNameOffset]];if(edgeName==='first') -firstNodeIndex=edges[edgeIndex+edgeToNodeOffset];else if(edgeName==='second') -secondNodeIndex=edges[edgeIndex+edgeToNodeOffset];}} -nodesStack.push(secondNodeIndex);nodesStack.push(firstNodeIndex);} -return name;} -className(){var type=this.type();switch(type){case'hidden':return'(system)';case'object':case'native':return this.name();case'code':return'(compiled code)';default:return'('+type+')';}} -classIndex(){var snapshot=this._snapshot;var nodes=snapshot.nodes;var type=nodes[this.nodeIndex+snapshot._nodeTypeOffset];if(type===snapshot._nodeObjectType||type===snapshot._nodeNativeType) -return nodes[this.nodeIndex+snapshot._nodeNameOffset];return-1-type;} -id(){var snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeIdOffset];} -isHidden(){return this.rawType()===this._snapshot._nodeHiddenType;} -isArray(){return this.rawType()===this._snapshot._nodeArrayType;} -isSynthetic(){return this.rawType()===this._snapshot._nodeSyntheticType;} -isUserRoot(){return!this.isSynthetic();} -isDocumentDOMTreesRoot(){return this.isSynthetic()&&this.name()==='(Document DOM trees)';} -serialize(){var result=super.serialize();var flags=this._snapshot._flagsOfNode(this);if(flags&this._snapshot._nodeFlags.canBeQueried) -result.canBeQueried=true;if(flags&this._snapshot._nodeFlags.detachedDOMTreeNode) -result.detachedDOMTreeNode=true;return result;}};HeapSnapshotWorker.JSHeapSnapshotEdge=class extends HeapSnapshotWorker.HeapSnapshotEdge{constructor(snapshot,edgeIndex){super(snapshot,edgeIndex);} -clone(){var snapshot=(this._snapshot);return new HeapSnapshotWorker.JSHeapSnapshotEdge(snapshot,this.edgeIndex);} -hasStringName(){if(!this.isShortcut()) -return this._hasStringName();return isNaN(parseInt(this._name(),10));} -isElement(){return this.rawType()===this._snapshot._edgeElementType;} -isHidden(){return this.rawType()===this._snapshot._edgeHiddenType;} -isWeak(){return this.rawType()===this._snapshot._edgeWeakType;} -isInternal(){return this.rawType()===this._snapshot._edgeInternalType;} -isInvisible(){return this.rawType()===this._snapshot._edgeInvisibleType;} -isShortcut(){return this.rawType()===this._snapshot._edgeShortcutType;} -name(){var name=this._name();if(!this.isShortcut()) -return String(name);var numName=parseInt(name,10);return String(isNaN(numName)?name:numName);} -toString(){var name=this.name();switch(this.type()){case'context':return'->'+name;case'element':return'['+name+']';case'weak':return'[['+name+']]';case'property':return name.indexOf(' ')===-1?'.'+name:'["'+name+'"]';case'shortcut':if(typeof name==='string') -return name.indexOf(' ')===-1?'.'+name:'["'+name+'"]';else -return'['+name+']';case'internal':case'hidden':case'invisible':return'{'+name+'}';} -return'?'+name+'?';} -_hasStringName(){var type=this.rawType();var snapshot=this._snapshot;return type!==snapshot._edgeElementType&&type!==snapshot._edgeHiddenType;} -_name(){return this._hasStringName()?this._snapshot.strings[this._nameOrIndex()]:this._nameOrIndex();} -_nameOrIndex(){return this._edges[this.edgeIndex+this._snapshot._edgeNameOffset];} -rawType(){return this._edges[this.edgeIndex+this._snapshot._edgeTypeOffset];}};HeapSnapshotWorker.JSHeapSnapshotRetainerEdge=class extends HeapSnapshotWorker.HeapSnapshotRetainerEdge{constructor(snapshot,retainerIndex){super(snapshot,retainerIndex);} -clone(){var snapshot=(this._snapshot);return new HeapSnapshotWorker.JSHeapSnapshotRetainerEdge(snapshot,this.retainerIndex());} -isHidden(){return this._edge().isHidden();} -isInternal(){return this._edge().isInternal();} -isInvisible(){return this._edge().isInvisible();} -isShortcut(){return this._edge().isShortcut();} -isWeak(){return this._edge().isWeak();}};(function disableLoggingForTest(){if(self.Runtime&&Runtime.queryParam('test')) -console.warn=()=>undefined;})();;HeapSnapshotWorker.HeapSnapshotLoader=class{constructor(dispatcher){this._reset();this._progress=new HeapSnapshotWorker.HeapSnapshotProgress(dispatcher);} -dispose(){this._reset();} -_reset(){this._json='';this._state='find-snapshot-info';this._snapshot={};} -close(){if(this._json) -this._parseStringsArray();} -buildSnapshot(){this._progress.updateStatus('Processing snapshot\u2026');var result=new HeapSnapshotWorker.JSHeapSnapshot(this._snapshot,this._progress);this._reset();return result;} -_parseUintArray(){var index=0;var char0='0'.charCodeAt(0),char9='9'.charCodeAt(0),closingBracket=']'.charCodeAt(0);var length=this._json.length;while(true){while(index<length){var code=this._json.charCodeAt(index);if(char0<=code&&code<=char9){break;}else if(code===closingBracket){this._json=this._json.slice(index+1);return false;} -++index;} -if(index===length){this._json='';return true;} -var nextNumber=0;var startIndex=index;while(index<length){var code=this._json.charCodeAt(index);if(char0>code||code>char9) -break;nextNumber*=10;nextNumber+=(code-char0);++index;} -if(index===length){this._json=this._json.slice(startIndex);return true;} -this._array[this._arrayIndex++]=nextNumber;}} -_parseStringsArray(){this._progress.updateStatus('Parsing strings\u2026');var closingBracketIndex=this._json.lastIndexOf(']');if(closingBracketIndex===-1) -throw new Error('Incomplete JSON');this._json=this._json.slice(0,closingBracketIndex+1);this._snapshot.strings=JSON.parse(this._json);} -write(chunk){if(this._json!==null) -this._json+=chunk;while(true){switch(this._state){case'find-snapshot-info':{var snapshotToken='"snapshot"';var snapshotTokenIndex=this._json.indexOf(snapshotToken);if(snapshotTokenIndex===-1) -throw new Error('Snapshot token not found');var json=this._json.slice(snapshotTokenIndex+snapshotToken.length+1);this._state='parse-snapshot-info';this._progress.updateStatus('Loading snapshot info\u2026');this._json=null;this._jsonTokenizer=new TextUtils.TextUtils.BalancedJSONTokenizer(this._writeBalancedJSON.bind(this));chunk=json;} -case'parse-snapshot-info':{this._jsonTokenizer.write(chunk);if(this._jsonTokenizer) -return;break;} -case'find-nodes':{var nodesToken='"nodes"';var nodesTokenIndex=this._json.indexOf(nodesToken);if(nodesTokenIndex===-1) -return;var bracketIndex=this._json.indexOf('[',nodesTokenIndex);if(bracketIndex===-1) -return;this._json=this._json.slice(bracketIndex+1);var node_fields_count=this._snapshot.snapshot.meta.node_fields.length;var nodes_length=this._snapshot.snapshot.node_count*node_fields_count;this._array=new Uint32Array(nodes_length);this._arrayIndex=0;this._state='parse-nodes';break;} -case'parse-nodes':{var hasMoreData=this._parseUintArray();this._progress.updateProgress('Loading nodes\u2026 %d%%',this._arrayIndex,this._array.length);if(hasMoreData) -return;this._snapshot.nodes=this._array;this._state='find-edges';this._array=null;break;} -case'find-edges':{var edgesToken='"edges"';var edgesTokenIndex=this._json.indexOf(edgesToken);if(edgesTokenIndex===-1) -return;var bracketIndex=this._json.indexOf('[',edgesTokenIndex);if(bracketIndex===-1) -return;this._json=this._json.slice(bracketIndex+1);var edge_fields_count=this._snapshot.snapshot.meta.edge_fields.length;var edges_length=this._snapshot.snapshot.edge_count*edge_fields_count;this._array=new Uint32Array(edges_length);this._arrayIndex=0;this._state='parse-edges';break;} -case'parse-edges':{var hasMoreData=this._parseUintArray();this._progress.updateProgress('Loading edges\u2026 %d%%',this._arrayIndex,this._array.length);if(hasMoreData) -return;this._snapshot.edges=this._array;this._array=null;if(this._snapshot.snapshot.trace_function_count){this._state='find-trace-function-infos';this._progress.updateStatus('Loading allocation traces\u2026');}else if(this._snapshot.snapshot.meta.sample_fields){this._state='find-samples';this._progress.updateStatus('Loading samples\u2026');}else{this._state='find-strings';} -break;} -case'find-trace-function-infos':{var tracesToken='"trace_function_infos"';var tracesTokenIndex=this._json.indexOf(tracesToken);if(tracesTokenIndex===-1) -return;var bracketIndex=this._json.indexOf('[',tracesTokenIndex);if(bracketIndex===-1) -return;this._json=this._json.slice(bracketIndex+1);var trace_function_info_field_count=this._snapshot.snapshot.meta.trace_function_info_fields.length;var trace_function_info_length=this._snapshot.snapshot.trace_function_count*trace_function_info_field_count;this._array=new Uint32Array(trace_function_info_length);this._arrayIndex=0;this._state='parse-trace-function-infos';break;} -case'parse-trace-function-infos':{if(this._parseUintArray()) -return;this._snapshot.trace_function_infos=this._array;this._array=null;this._state='find-trace-tree';break;} -case'find-trace-tree':{var tracesToken='"trace_tree"';var tracesTokenIndex=this._json.indexOf(tracesToken);if(tracesTokenIndex===-1) -return;var bracketIndex=this._json.indexOf('[',tracesTokenIndex);if(bracketIndex===-1) -return;this._json=this._json.slice(bracketIndex);this._state='parse-trace-tree';break;} -case'parse-trace-tree':{var nextToken=this._snapshot.snapshot.meta.sample_fields?'"samples"':'"strings"';var nextTokenIndex=this._json.indexOf(nextToken);if(nextTokenIndex===-1) -return;var bracketIndex=this._json.lastIndexOf(']',nextTokenIndex);this._snapshot.trace_tree=JSON.parse(this._json.substring(0,bracketIndex+1));this._json=this._json.slice(bracketIndex+1);if(this._snapshot.snapshot.meta.sample_fields){this._state='find-samples';this._progress.updateStatus('Loading samples\u2026');}else{this._state='find-strings';this._progress.updateStatus('Loading strings\u2026');} -break;} -case'find-samples':{var samplesToken='"samples"';var samplesTokenIndex=this._json.indexOf(samplesToken);if(samplesTokenIndex===-1) -return;var bracketIndex=this._json.indexOf('[',samplesTokenIndex);if(bracketIndex===-1) -return;this._json=this._json.slice(bracketIndex+1);this._array=[];this._arrayIndex=0;this._state='parse-samples';break;} -case'parse-samples':{if(this._parseUintArray()) -return;this._snapshot.samples=this._array;this._array=null;this._state='find-strings';this._progress.updateStatus('Loading strings\u2026');break;} -case'find-strings':{var stringsToken='"strings"';var stringsTokenIndex=this._json.indexOf(stringsToken);if(stringsTokenIndex===-1) -return;var bracketIndex=this._json.indexOf('[',stringsTokenIndex);if(bracketIndex===-1) -return;this._json=this._json.slice(bracketIndex);this._state='accumulate-strings';break;} -case'accumulate-strings':return;}}} -_writeBalancedJSON(data){this._json=this._jsonTokenizer.remainder();this._jsonTokenizer=null;this._state='find-nodes';this._snapshot.snapshot=(JSON.parse(data));}};;HeapSnapshotWorker.HeapSnapshotWorkerDispatcher=class{constructor(globalObject,postMessage){this._objects=[];this._global=globalObject;this._postMessage=postMessage;} -_findFunction(name){var path=name.split('.');var result=this._global;for(var i=0;i<path.length;++i) -result=result[path[i]];return result;} -sendEvent(name,data){this._postMessage({eventName:name,data:data});} -dispatchMessage(event){var data=(event.data);var response={callId:data.callId};try{switch(data.disposition){case'create':var constructorFunction=this._findFunction(data.methodName);this._objects[data.objectId]=new constructorFunction(this);break;case'dispose':delete this._objects[data.objectId];break;case'getter':var object=this._objects[data.objectId];var result=object[data.methodName];response.result=result;break;case'factory':var object=this._objects[data.objectId];var result=object[data.methodName].apply(object,data.methodArguments);if(result) -this._objects[data.newObjectId]=result;response.result=!!result;break;case'method':var object=this._objects[data.objectId];response.result=object[data.methodName].apply(object,data.methodArguments);break;case'evaluateForTest':try{response.result=self.eval(data.source);}catch(e){response.result=e.toString();} -break;}}catch(e){response.error=e.toString();response.errorCallStack=e.stack;if(data.methodName) -response.errorMethodName=data.methodName;} -this._postMessage(response);}};;function postMessageWrapper(message){postMessage(message);} -var dispatcher=new HeapSnapshotWorker.HeapSnapshotWorkerDispatcher(this,postMessageWrapper);function installMessageEventListener(listener){self.addEventListener('message',listener,false);} -installMessageEventListener(dispatcher.dispatchMessage.bind(dispatcher));;applicationDescriptor={"has_html":false,"modules":[{"type":"autostart","name":"heap_snapshot_model"},{"type":"autostart","name":"platform"},{"type":"autostart","name":"heap_snapshot_worker"},{"type":"autostart","name":"text_utils"},{"type":"autostart","name":"common"}]};if(!self.Runtime) -self.importScripts('Runtime.js');Runtime.startWorker('heap_snapshot_worker'); \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/inline_editor/inline_editor_module.js b/src/cobalt/debug/content/devtools/inline_editor/inline_editor_module.js deleted file mode 100644 index 2e4a10c..0000000 --- a/src/cobalt/debug/content/devtools/inline_editor/inline_editor_module.js +++ /dev/null
@@ -1,165 +0,0 @@ -InlineEditor.BezierEditor=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('inline_editor/bezierEditor.css');this.contentElement.tabIndex=0;this.setDefaultFocusedElement(this.contentElement);this._previewElement=this.contentElement.createChild('div','bezier-preview-container');this._previewElement.createChild('div','bezier-preview-animation');this._previewElement.addEventListener('click',this._startPreviewAnimation.bind(this));this._previewOnion=this.contentElement.createChild('div','bezier-preview-onion');this._previewOnion.addEventListener('click',this._startPreviewAnimation.bind(this));this._outerContainer=this.contentElement.createChild('div','bezier-container');this._presetsContainer=this._outerContainer.createChild('div','bezier-presets');this._presetUI=new InlineEditor.BezierUI(40,40,0,2,false);this._presetCategories=[];for(var i=0;i<InlineEditor.BezierEditor.Presets.length;i++){this._presetCategories[i]=this._createCategory(InlineEditor.BezierEditor.Presets[i]);this._presetsContainer.appendChild(this._presetCategories[i].icon);} -this._curveUI=new InlineEditor.BezierUI(150,250,50,7,true);this._curve=this._outerContainer.createSVGChild('svg','bezier-curve');UI.installDragHandle(this._curve,this._dragStart.bind(this),this._dragMove.bind(this),this._dragEnd.bind(this),'default');this._header=this.contentElement.createChild('div','bezier-header');var minus=this._createPresetModifyIcon(this._header,'bezier-preset-minus','M 12 6 L 8 10 L 12 14');var plus=this._createPresetModifyIcon(this._header,'bezier-preset-plus','M 8 6 L 12 10 L 8 14');minus.addEventListener('click',this._presetModifyClicked.bind(this,false));plus.addEventListener('click',this._presetModifyClicked.bind(this,true));this._label=this._header.createChild('span','source-code bezier-display-value');} -setBezier(bezier){if(!bezier) -return;this._bezier=bezier;this._updateUI();} -bezier(){return this._bezier;} -wasShown(){this._unselectPresets();for(var category of this._presetCategories){for(var i=0;i<category.presets.length;i++){if(this._bezier.asCSSText()===category.presets[i].value){category.presetIndex=i;this._presetCategorySelected(category);}}} -this._updateUI();this._startPreviewAnimation();} -_onchange(){this._updateUI();this.dispatchEventToListeners(InlineEditor.BezierEditor.Events.BezierChanged,this._bezier.asCSSText());} -_updateUI(){var labelText=this._selectedCategory?this._selectedCategory.presets[this._selectedCategory.presetIndex].name:this._bezier.asCSSText().replace(/\s(-\d\.\d)/g,'$1');this._label.textContent=Common.UIString(labelText);this._curveUI.drawCurve(this._bezier,this._curve);this._previewOnion.removeChildren();} -_dragStart(event){this._mouseDownPosition=new UI.Geometry.Point(event.x,event.y);var ui=this._curveUI;this._controlPosition=new UI.Geometry.Point(Number.constrain((event.offsetX-ui.radius)/ui.curveWidth(),0,1),(ui.curveHeight()+ui.marginTop+ui.radius-event.offsetY)/ui.curveHeight());var firstControlPointIsCloser=this._controlPosition.distanceTo(this._bezier.controlPoints[0])<this._controlPosition.distanceTo(this._bezier.controlPoints[1]);this._selectedPoint=firstControlPointIsCloser?0:1;this._bezier.controlPoints[this._selectedPoint]=this._controlPosition;this._unselectPresets();this._onchange();event.consume(true);return true;} -_updateControlPosition(mouseX,mouseY){var deltaX=(mouseX-this._mouseDownPosition.x)/this._curveUI.curveWidth();var deltaY=(mouseY-this._mouseDownPosition.y)/this._curveUI.curveHeight();var newPosition=new UI.Geometry.Point(Number.constrain(this._controlPosition.x+deltaX,0,1),this._controlPosition.y-deltaY);this._bezier.controlPoints[this._selectedPoint]=newPosition;} -_dragMove(event){this._updateControlPosition(event.x,event.y);this._onchange();} -_dragEnd(event){this._updateControlPosition(event.x,event.y);this._onchange();this._startPreviewAnimation();} -_createCategory(presetGroup){var presetElement=createElementWithClass('div','bezier-preset-category');var iconElement=presetElement.createSVGChild('svg','bezier-preset monospace');var category={presets:presetGroup,presetIndex:0,icon:presetElement};this._presetUI.drawCurve(UI.Geometry.CubicBezier.parse(category.presets[0].value),iconElement);iconElement.addEventListener('click',this._presetCategorySelected.bind(this,category));return category;} -_createPresetModifyIcon(parentElement,className,drawPath){var icon=parentElement.createSVGChild('svg','bezier-preset-modify '+className);icon.setAttribute('width',20);icon.setAttribute('height',20);var path=icon.createSVGChild('path');path.setAttribute('d',drawPath);return icon;} -_unselectPresets(){for(var category of this._presetCategories) -category.icon.classList.remove('bezier-preset-selected');delete this._selectedCategory;this._header.classList.remove('bezier-header-active');} -_presetCategorySelected(category,event){if(this._selectedCategory===category) -return;this._unselectPresets();this._header.classList.add('bezier-header-active');this._selectedCategory=category;this._selectedCategory.icon.classList.add('bezier-preset-selected');this.setBezier(UI.Geometry.CubicBezier.parse(category.presets[category.presetIndex].value));this._onchange();this._startPreviewAnimation();if(event) -event.consume(true);} -_presetModifyClicked(intensify,event){if(!this._selectedCategory) -return;var length=this._selectedCategory.presets.length;this._selectedCategory.presetIndex=(this._selectedCategory.presetIndex+(intensify?1:-1)+length)%length;this.setBezier(UI.Geometry.CubicBezier.parse(this._selectedCategory.presets[this._selectedCategory.presetIndex].value));this._onchange();this._startPreviewAnimation();} -_startPreviewAnimation(){if(this._previewAnimation) -this._previewAnimation.cancel();const animationDuration=1600;const numberOnionSlices=20;var keyframes=[{offset:0,transform:'translateX(0px)',easing:this._bezier.asCSSText(),opacity:1},{offset:0.9,transform:'translateX(218px)',opacity:1},{offset:1,transform:'translateX(218px)',opacity:0}];this._previewAnimation=this._previewElement.animate(keyframes,animationDuration);this._previewOnion.removeChildren();for(var i=0;i<=numberOnionSlices;i++){var slice=this._previewOnion.createChild('div','bezier-preview-animation');var player=slice.animate([{transform:'translateX(0px)',easing:this._bezier.asCSSText()},{transform:'translateX(218px)'}],{duration:animationDuration,fill:'forwards'});player.pause();player.currentTime=animationDuration*i/numberOnionSlices;}}};InlineEditor.BezierEditor.Events={BezierChanged:Symbol('BezierChanged')};InlineEditor.BezierEditor.Presets=[[{name:'ease-in-out',value:'ease-in-out'},{name:'In Out · Sine',value:'cubic-bezier(0.45, 0.05, 0.55, 0.95)'},{name:'In Out · Quadratic',value:'cubic-bezier(0.46, 0.03, 0.52, 0.96)'},{name:'In Out · Cubic',value:'cubic-bezier(0.65, 0.05, 0.36, 1)'},{name:'Fast Out, Slow In',value:'cubic-bezier(0.4, 0, 0.2, 1)'},{name:'In Out · Back',value:'cubic-bezier(0.68, -0.55, 0.27, 1.55)'}],[{name:'Fast Out, Linear In',value:'cubic-bezier(0.4, 0, 1, 1)'},{name:'ease-in',value:'ease-in'},{name:'In · Sine',value:'cubic-bezier(0.47, 0, 0.75, 0.72)'},{name:'In · Quadratic',value:'cubic-bezier(0.55, 0.09, 0.68, 0.53)'},{name:'In · Cubic',value:'cubic-bezier(0.55, 0.06, 0.68, 0.19)'},{name:'In · Back',value:'cubic-bezier(0.6, -0.28, 0.74, 0.05)'}],[{name:'ease-out',value:'ease-out'},{name:'Out · Sine',value:'cubic-bezier(0.39, 0.58, 0.57, 1)'},{name:'Out · Quadratic',value:'cubic-bezier(0.25, 0.46, 0.45, 0.94)'},{name:'Out · Cubic',value:'cubic-bezier(0.22, 0.61, 0.36, 1)'},{name:'Linear Out, Slow In',value:'cubic-bezier(0, 0, 0.2, 1)'},{name:'Out · Back',value:'cubic-bezier(0.18, 0.89, 0.32, 1.28)'}]];InlineEditor.BezierEditor.PresetCategory;;InlineEditor.BezierUI=class{constructor(width,height,marginTop,controlPointRadius,linearLine){this.width=width;this.height=height;this.marginTop=marginTop;this.radius=controlPointRadius;this.linearLine=linearLine;} -static drawVelocityChart(bezier,path,width){var height=InlineEditor.BezierUI.Height;var pathBuilder=['M',0,height];var sampleSize=1/40;var prev=bezier.evaluateAt(0);for(var t=sampleSize;t<1+sampleSize;t+=sampleSize){var current=bezier.evaluateAt(t);var slope=(current.y-prev.y)/(current.x-prev.x);var weightedX=prev.x*(1-t)+current.x*t;slope=Math.tanh(slope/1.5);pathBuilder=pathBuilder.concat(['L',(weightedX*width).toFixed(2),(height-slope*height).toFixed(2)]);prev=current;} -pathBuilder=pathBuilder.concat(['L',width.toFixed(2),height,'Z']);path.setAttribute('d',pathBuilder.join(' '));} -curveWidth(){return this.width-this.radius*2;} -curveHeight(){return this.height-this.radius*2-this.marginTop*2;} -_drawLine(parentElement,className,x1,y1,x2,y2){var line=parentElement.createSVGChild('line',className);line.setAttribute('x1',x1+this.radius);line.setAttribute('y1',y1+this.radius+this.marginTop);line.setAttribute('x2',x2+this.radius);line.setAttribute('y2',y2+this.radius+this.marginTop);} -_drawControlPoints(parentElement,startX,startY,controlX,controlY){this._drawLine(parentElement,'bezier-control-line',startX,startY,controlX,controlY);var circle=parentElement.createSVGChild('circle','bezier-control-circle');circle.setAttribute('cx',controlX+this.radius);circle.setAttribute('cy',controlY+this.radius+this.marginTop);circle.setAttribute('r',this.radius);} -drawCurve(bezier,svg){if(!bezier) -return;var width=this.curveWidth();var height=this.curveHeight();svg.setAttribute('width',this.width);svg.setAttribute('height',this.height);svg.removeChildren();var group=svg.createSVGChild('g');if(this.linearLine) -this._drawLine(group,'linear-line',0,height,width,0);var curve=group.createSVGChild('path','bezier-path');var curvePoints=[new UI.Geometry.Point(bezier.controlPoints[0].x*width+this.radius,(1-bezier.controlPoints[0].y)*height+this.radius+this.marginTop),new UI.Geometry.Point(bezier.controlPoints[1].x*width+this.radius,(1-bezier.controlPoints[1].y)*height+this.radius+this.marginTop),new UI.Geometry.Point(width+this.radius,this.marginTop+this.radius)];curve.setAttribute('d','M'+this.radius+','+(height+this.radius+this.marginTop)+' C'+curvePoints.join(' '));this._drawControlPoints(group,0,height,bezier.controlPoints[0].x*width,(1-bezier.controlPoints[0].y)*height);this._drawControlPoints(group,width,0,bezier.controlPoints[1].x*width,(1-bezier.controlPoints[1].y)*height);}};InlineEditor.BezierUI.Height=26;;InlineEditor.ColorSwatch=class extends HTMLSpanElement{constructor(){super();} -static create(){if(!InlineEditor.ColorSwatch._constructor){InlineEditor.ColorSwatch._constructor=UI.registerCustomElement('span','color-swatch',InlineEditor.ColorSwatch.prototype);} -return(new InlineEditor.ColorSwatch._constructor());} -static _nextColorFormat(color,curFormat){var cf=Common.Color.Format;switch(curFormat){case cf.Original:return!color.hasAlpha()?cf.RGB:cf.RGBA;case cf.RGB:case cf.RGBA:return!color.hasAlpha()?cf.HSL:cf.HSLA;case cf.HSL:case cf.HSLA:if(color.nickname()) -return cf.Nickname;return color.detectHEXFormat();case cf.ShortHEX:return cf.HEX;case cf.ShortHEXA:return cf.HEXA;case cf.HEXA:case cf.HEX:return cf.Original;case cf.Nickname:return color.detectHEXFormat();default:return cf.RGBA;}} -color(){return this._color;} -setColor(color){this._color=color;this._format=this._color.format();var colorString=this._color.asString(this._format);this._colorValueElement.textContent=colorString;this._swatchInner.style.backgroundColor=colorString;} -hideText(hide){this._colorValueElement.hidden=hide;} -format(){return this._format;} -setFormat(format){this._format=format;this._colorValueElement.textContent=this._color.asString(this._format);} -toggleNextFormat(){do{this._format=InlineEditor.ColorSwatch._nextColorFormat(this._color,this._format);var currentValue=this._color.asString(this._format);}while(currentValue===this._colorValueElement.textContent);this._colorValueElement.textContent=currentValue;} -iconElement(){return this._iconElement;} -createdCallback(){var root=UI.createShadowRootWithCoreStyles(this,'inline_editor/colorSwatch.css');this._iconElement=root.createChild('span','color-swatch');this._iconElement.title=Common.UIString('Shift-click to change color format');this._swatchInner=this._iconElement.createChild('span','color-swatch-inner');this._swatchInner.addEventListener('dblclick',e=>e.consume(),false);this._swatchInner.addEventListener('mousedown',e=>e.consume(),false);this._swatchInner.addEventListener('click',this._handleClick.bind(this),true);root.createChild('content');this._colorValueElement=this.createChild('span');} -_handleClick(event){if(!event.shiftKey) -return;event.target.parentNode.parentNode.host.toggleNextFormat();event.consume(true);}};InlineEditor.BezierSwatch=class extends HTMLSpanElement{constructor(){super();} -static create(){if(!InlineEditor.BezierSwatch._constructor){InlineEditor.BezierSwatch._constructor=UI.registerCustomElement('span','bezier-swatch',InlineEditor.BezierSwatch.prototype);} -return(new InlineEditor.BezierSwatch._constructor());} -bezierText(){return this._textElement.textContent;} -setBezierText(text){this._textElement.textContent=text;} -hideText(hide){this._textElement.hidden=hide;} -iconElement(){return this._iconElement;} -createdCallback(){var root=UI.createShadowRootWithCoreStyles(this,'inline_editor/bezierSwatch.css');this._iconElement=UI.Icon.create('smallicon-bezier','bezier-swatch-icon');root.appendChild(this._iconElement);this._textElement=this.createChild('span');root.createChild('content');}};InlineEditor.CSSShadowSwatch=class extends HTMLSpanElement{constructor(){super();} -static create(){if(!InlineEditor.CSSShadowSwatch._constructor){InlineEditor.CSSShadowSwatch._constructor=UI.registerCustomElement('span','css-shadow-swatch',InlineEditor.CSSShadowSwatch.prototype);} -return(new InlineEditor.CSSShadowSwatch._constructor());} -model(){return this._model;} -setCSSShadow(model){this._model=model;this._contentElement.removeChildren();var results=TextUtils.TextUtils.splitStringByRegexes(model.asCSSText(),[/inset/g,Common.Color.Regex]);for(var i=0;i<results.length;i++){var result=results[i];if(result.regexIndex===1){if(!this._colorSwatch) -this._colorSwatch=InlineEditor.ColorSwatch.create();this._colorSwatch.setColor(model.color());this._contentElement.appendChild(this._colorSwatch);}else{this._contentElement.appendChild(createTextNode(result.value));}}} -hideText(hide){this._contentElement.hidden=hide;} -iconElement(){return this._iconElement;} -colorSwatch(){return this._colorSwatch;} -createdCallback(){var root=UI.createShadowRootWithCoreStyles(this,'inline_editor/cssShadowSwatch.css');this._iconElement=UI.Icon.create('smallicon-shadow','shadow-swatch-icon');root.appendChild(this._iconElement);root.createChild('content');this._contentElement=this.createChild('span');}};;InlineEditor.CSSShadowEditor=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('inline_editor/cssShadowEditor.css');this.contentElement.tabIndex=0;this.setDefaultFocusedElement(this.contentElement);this._typeField=this.contentElement.createChild('div','shadow-editor-field shadow-editor-flex-field');this._typeField.createChild('label','shadow-editor-label').textContent=Common.UIString('Type');this._outsetButton=this._typeField.createChild('button','shadow-editor-button-left');this._outsetButton.textContent=Common.UIString('Outset');this._outsetButton.addEventListener('click',this._onButtonClick.bind(this),false);this._insetButton=this._typeField.createChild('button','shadow-editor-button-right');this._insetButton.textContent=Common.UIString('Inset');this._insetButton.addEventListener('click',this._onButtonClick.bind(this),false);var xField=this.contentElement.createChild('div','shadow-editor-field');this._xInput=this._createTextInput(xField,Common.UIString('X offset'));var yField=this.contentElement.createChild('div','shadow-editor-field');this._yInput=this._createTextInput(yField,Common.UIString('Y offset'));this._xySlider=xField.createChild('canvas','shadow-editor-2D-slider');this._xySlider.width=InlineEditor.CSSShadowEditor.canvasSize;this._xySlider.height=InlineEditor.CSSShadowEditor.canvasSize;this._xySlider.tabIndex=-1;this._halfCanvasSize=InlineEditor.CSSShadowEditor.canvasSize/2;this._innerCanvasSize=this._halfCanvasSize-InlineEditor.CSSShadowEditor.sliderThumbRadius;UI.installDragHandle(this._xySlider,this._dragStart.bind(this),this._dragMove.bind(this),null,'default');this._xySlider.addEventListener('keydown',this._onCanvasArrowKey.bind(this),false);this._xySlider.addEventListener('blur',this._onCanvasBlur.bind(this),false);var blurField=this.contentElement.createChild('div','shadow-editor-field shadow-editor-flex-field shadow-editor-blur-field');this._blurInput=this._createTextInput(blurField,Common.UIString('Blur'));this._blurSlider=this._createSlider(blurField);this._spreadField=this.contentElement.createChild('div','shadow-editor-field shadow-editor-flex-field');this._spreadInput=this._createTextInput(this._spreadField,Common.UIString('Spread'));this._spreadSlider=this._createSlider(this._spreadField);} -_createTextInput(field,propertyName){var label=field.createChild('label','shadow-editor-label');label.textContent=propertyName;label.setAttribute('for',propertyName);var textInput=UI.createInput('shadow-editor-text-input','text');field.appendChild(textInput);textInput.id=propertyName;textInput.addEventListener('keydown',this._handleValueModification.bind(this),false);textInput.addEventListener('mousewheel',this._handleValueModification.bind(this),false);textInput.addEventListener('input',this._onTextInput.bind(this),false);textInput.addEventListener('blur',this._onTextBlur.bind(this),false);return textInput;} -_createSlider(field){var slider=UI.createSliderLabel(0,InlineEditor.CSSShadowEditor.maxRange,-1);slider.addEventListener('input',this._onSliderInput.bind(this),false);field.appendChild(slider);return slider;} -wasShown(){this._updateUI();} -setModel(model){this._model=model;this._typeField.hidden=!model.isBoxShadow();this._spreadField.hidden=!model.isBoxShadow();this._updateUI();} -_updateUI(){this._updateButtons();this._xInput.value=this._model.offsetX().asCSSText();this._yInput.value=this._model.offsetY().asCSSText();this._blurInput.value=this._model.blurRadius().asCSSText();this._spreadInput.value=this._model.spreadRadius().asCSSText();this._blurSlider.value=this._model.blurRadius().amount;this._spreadSlider.value=this._model.spreadRadius().amount;this._updateCanvas(false);} -_updateButtons(){this._insetButton.classList.toggle('enabled',this._model.inset());this._outsetButton.classList.toggle('enabled',!this._model.inset());} -_updateCanvas(drawFocus){var context=this._xySlider.getContext('2d');context.clearRect(0,0,this._xySlider.width,this._xySlider.height);context.save();context.setLineDash([1,1]);context.strokeStyle='rgba(210, 210, 210, 0.8)';context.beginPath();context.moveTo(this._halfCanvasSize,0);context.lineTo(this._halfCanvasSize,InlineEditor.CSSShadowEditor.canvasSize);context.moveTo(0,this._halfCanvasSize);context.lineTo(InlineEditor.CSSShadowEditor.canvasSize,this._halfCanvasSize);context.stroke();context.restore();var thumbPoint=this._sliderThumbPosition();context.save();context.translate(this._halfCanvasSize,this._halfCanvasSize);context.lineWidth=2;context.strokeStyle='rgba(130, 130, 130, 0.75)';context.beginPath();context.moveTo(0,0);context.lineTo(thumbPoint.x,thumbPoint.y);context.stroke();if(drawFocus){context.beginPath();context.fillStyle='rgba(66, 133, 244, 0.4)';context.arc(thumbPoint.x,thumbPoint.y,InlineEditor.CSSShadowEditor.sliderThumbRadius+2,0,2*Math.PI);context.fill();} -context.beginPath();context.fillStyle='#4285F4';context.arc(thumbPoint.x,thumbPoint.y,InlineEditor.CSSShadowEditor.sliderThumbRadius,0,2*Math.PI);context.fill();context.restore();} -_onButtonClick(event){var insetClicked=(event.currentTarget===this._insetButton);if(insetClicked&&this._model.inset()||!insetClicked&&!this._model.inset()) -return;this._model.setInset(insetClicked);this._updateButtons();this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);} -_handleValueModification(event){var modifiedValue=UI.createReplacementString(event.currentTarget.value,event,customNumberHandler);if(!modifiedValue) -return;var length=InlineEditor.CSSLength.parse(modifiedValue);if(!length) -return;if(event.currentTarget===this._blurInput&&length.amount<0) -length.amount=0;event.currentTarget.value=length.asCSSText();event.currentTarget.selectionStart=0;event.currentTarget.selectionEnd=event.currentTarget.value.length;this._onTextInput(event);event.consume(true);function customNumberHandler(prefix,number,suffix){if(!suffix.length) -suffix=InlineEditor.CSSShadowEditor.defaultUnit;return prefix+number+suffix;}} -_onTextInput(event){this._changedElement=event.currentTarget;this._changedElement.classList.remove('invalid');var length=InlineEditor.CSSLength.parse(event.currentTarget.value);if(!length||event.currentTarget===this._blurInput&&length.amount<0) -return;if(event.currentTarget===this._xInput){this._model.setOffsetX(length);this._updateCanvas(false);}else if(event.currentTarget===this._yInput){this._model.setOffsetY(length);this._updateCanvas(false);}else if(event.currentTarget===this._blurInput){this._model.setBlurRadius(length);this._blurSlider.value=length.amount;}else if(event.currentTarget===this._spreadInput){this._model.setSpreadRadius(length);this._spreadSlider.value=length.amount;} -this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);} -_onTextBlur(){if(!this._changedElement) -return;var length=!this._changedElement.value.trim()?InlineEditor.CSSLength.zero():InlineEditor.CSSLength.parse(this._changedElement.value);if(!length) -length=InlineEditor.CSSLength.parse(this._changedElement.value+InlineEditor.CSSShadowEditor.defaultUnit);if(!length){this._changedElement.classList.add('invalid');this._changedElement=null;return;} -if(this._changedElement===this._xInput){this._model.setOffsetX(length);this._xInput.value=length.asCSSText();this._updateCanvas(false);}else if(this._changedElement===this._yInput){this._model.setOffsetY(length);this._yInput.value=length.asCSSText();this._updateCanvas(false);}else if(this._changedElement===this._blurInput){if(length.amount<0) -length=InlineEditor.CSSLength.zero();this._model.setBlurRadius(length);this._blurInput.value=length.asCSSText();this._blurSlider.value=length.amount;}else if(this._changedElement===this._spreadInput){this._model.setSpreadRadius(length);this._spreadInput.value=length.asCSSText();this._spreadSlider.value=length.amount;} -this._changedElement=null;this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);} -_onSliderInput(event){if(event.currentTarget===this._blurSlider){this._model.setBlurRadius(new InlineEditor.CSSLength(this._blurSlider.value,this._model.blurRadius().unit||InlineEditor.CSSShadowEditor.defaultUnit));this._blurInput.value=this._model.blurRadius().asCSSText();this._blurInput.classList.remove('invalid');}else if(event.currentTarget===this._spreadSlider){this._model.setSpreadRadius(new InlineEditor.CSSLength(this._spreadSlider.value,this._model.spreadRadius().unit||InlineEditor.CSSShadowEditor.defaultUnit));this._spreadInput.value=this._model.spreadRadius().asCSSText();this._spreadInput.classList.remove('invalid');} -this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);} -_dragStart(event){this._xySlider.focus();this._updateCanvas(true);this._canvasOrigin=new UI.Geometry.Point(this._xySlider.totalOffsetLeft()+this._halfCanvasSize,this._xySlider.totalOffsetTop()+this._halfCanvasSize);var clickedPoint=new UI.Geometry.Point(event.x-this._canvasOrigin.x,event.y-this._canvasOrigin.y);var thumbPoint=this._sliderThumbPosition();if(clickedPoint.distanceTo(thumbPoint)>=InlineEditor.CSSShadowEditor.sliderThumbRadius) -this._dragMove(event);return true;} -_dragMove(event){var point=new UI.Geometry.Point(event.x-this._canvasOrigin.x,event.y-this._canvasOrigin.y);if(event.shiftKey) -point=this._snapToClosestDirection(point);var constrainedPoint=this._constrainPoint(point,this._innerCanvasSize);var newX=Math.round((constrainedPoint.x/this._innerCanvasSize)*InlineEditor.CSSShadowEditor.maxRange);var newY=Math.round((constrainedPoint.y/this._innerCanvasSize)*InlineEditor.CSSShadowEditor.maxRange);if(event.shiftKey){this._model.setOffsetX(new InlineEditor.CSSLength(newX,this._model.offsetX().unit||InlineEditor.CSSShadowEditor.defaultUnit));this._model.setOffsetY(new InlineEditor.CSSLength(newY,this._model.offsetY().unit||InlineEditor.CSSShadowEditor.defaultUnit));}else{if(!event.altKey){this._model.setOffsetX(new InlineEditor.CSSLength(newX,this._model.offsetX().unit||InlineEditor.CSSShadowEditor.defaultUnit));} -if(!UI.KeyboardShortcut.eventHasCtrlOrMeta(event)){this._model.setOffsetY(new InlineEditor.CSSLength(newY,this._model.offsetY().unit||InlineEditor.CSSShadowEditor.defaultUnit));}} -this._xInput.value=this._model.offsetX().asCSSText();this._yInput.value=this._model.offsetY().asCSSText();this._xInput.classList.remove('invalid');this._yInput.classList.remove('invalid');this._updateCanvas(true);this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);} -_onCanvasBlur(){this._updateCanvas(false);} -_onCanvasArrowKey(event){var shiftX=0;var shiftY=0;if(event.key==='ArrowRight') -shiftX=1;else if(event.key==='ArrowLeft') -shiftX=-1;else if(event.key==='ArrowUp') -shiftY=-1;else if(event.key==='ArrowDown') -shiftY=1;if(!shiftX&&!shiftY) -return;event.consume(true);if(shiftX){var offsetX=this._model.offsetX();var newAmount=Number.constrain(offsetX.amount+shiftX,-InlineEditor.CSSShadowEditor.maxRange,InlineEditor.CSSShadowEditor.maxRange);if(newAmount===offsetX.amount) -return;this._model.setOffsetX(new InlineEditor.CSSLength(newAmount,offsetX.unit||InlineEditor.CSSShadowEditor.defaultUnit));this._xInput.value=this._model.offsetX().asCSSText();this._xInput.classList.remove('invalid');} -if(shiftY){var offsetY=this._model.offsetY();var newAmount=Number.constrain(offsetY.amount+shiftY,-InlineEditor.CSSShadowEditor.maxRange,InlineEditor.CSSShadowEditor.maxRange);if(newAmount===offsetY.amount) -return;this._model.setOffsetY(new InlineEditor.CSSLength(newAmount,offsetY.unit||InlineEditor.CSSShadowEditor.defaultUnit));this._yInput.value=this._model.offsetY().asCSSText();this._yInput.classList.remove('invalid');} -this._updateCanvas(true);this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);} -_constrainPoint(point,max){if(Math.abs(point.x)<=max&&Math.abs(point.y)<=max) -return new UI.Geometry.Point(point.x,point.y);return point.scale(max/Math.max(Math.abs(point.x),Math.abs(point.y)));} -_snapToClosestDirection(point){var minDistance=Number.MAX_VALUE;var closestPoint=point;var directions=[new UI.Geometry.Point(0,-1),new UI.Geometry.Point(1,-1),new UI.Geometry.Point(1,0),new UI.Geometry.Point(1,1)];for(var direction of directions){var projection=point.projectOn(direction);var distance=point.distanceTo(projection);if(distance<minDistance){minDistance=distance;closestPoint=projection;}} -return closestPoint;} -_sliderThumbPosition(){var x=(this._model.offsetX().amount/InlineEditor.CSSShadowEditor.maxRange)*this._innerCanvasSize;var y=(this._model.offsetY().amount/InlineEditor.CSSShadowEditor.maxRange)*this._innerCanvasSize;return this._constrainPoint(new UI.Geometry.Point(x,y),this._innerCanvasSize);}};InlineEditor.CSSShadowEditor.Events={ShadowChanged:Symbol('ShadowChanged')};InlineEditor.CSSShadowEditor.maxRange=20;InlineEditor.CSSShadowEditor.defaultUnit='px';InlineEditor.CSSShadowEditor.sliderThumbRadius=6;InlineEditor.CSSShadowEditor.canvasSize=88;;InlineEditor.SwatchPopoverHelper=class extends Common.Object{constructor(){super();this._popover=new UI.GlassPane();this._popover.registerRequiredCSS('inline_editor/swatchPopover.css');this._popover.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);this._popover.setMarginBehavior(UI.GlassPane.MarginBehavior.Arrow);this._popover.element.addEventListener('mousedown',e=>e.consume(),false);this._hideProxy=this.hide.bind(this,true);this._boundOnKeyDown=this._onKeyDown.bind(this);this._boundFocusOut=this._onFocusOut.bind(this);this._isHidden=true;} -_onFocusOut(event){if(!event.relatedTarget||event.relatedTarget.isSelfOrDescendant(this._view.contentElement)) -return;this._hideProxy();} -isShowing(){return this._popover.isShowing();} -show(view,anchorElement,hiddenCallback){if(this._popover.isShowing()){if(this._anchorElement===anchorElement) -return;this.hide(true);} -delete this._isHidden;this._anchorElement=anchorElement;this._view=view;this._hiddenCallback=hiddenCallback;this.reposition();view.focus();var document=this._popover.element.ownerDocument;document.addEventListener('mousedown',this._hideProxy,false);document.defaultView.addEventListener('resize',this._hideProxy,false);this._view.contentElement.addEventListener('keydown',this._boundOnKeyDown,false);} -reposition(){this._view.contentElement.removeEventListener('focusout',this._boundFocusOut,false);this._view.show(this._popover.contentElement);this._popover.setContentAnchorBox(this._anchorElement.boxInWindow());this._popover.show(this._anchorElement.ownerDocument);this._view.contentElement.addEventListener('focusout',this._boundFocusOut,false);if(!this._focusRestorer) -this._focusRestorer=new UI.WidgetFocusRestorer(this._view);} -hide(commitEdit){if(this._isHidden) -return;var document=this._popover.element.ownerDocument;this._isHidden=true;this._popover.hide();document.removeEventListener('mousedown',this._hideProxy,false);document.defaultView.removeEventListener('resize',this._hideProxy,false);if(this._hiddenCallback) -this._hiddenCallback.call(null,!!commitEdit);this._focusRestorer.restore();delete this._anchorElement;if(this._view){this._view.detach();this._view.contentElement.removeEventListener('keydown',this._boundOnKeyDown,false);this._view.contentElement.removeEventListener('focusout',this._boundFocusOut,false);delete this._view;}} -_onKeyDown(event){if(event.key==='Enter'){this.hide(true);event.consume(true);return;} -if(event.key==='Escape'){this.hide(false);event.consume(true);}}};;InlineEditor.CSSShadowModel=class{constructor(isBoxShadow){this._isBoxShadow=isBoxShadow;this._inset=false;this._offsetX=InlineEditor.CSSLength.zero();this._offsetY=InlineEditor.CSSLength.zero();this._blurRadius=InlineEditor.CSSLength.zero();this._spreadRadius=InlineEditor.CSSLength.zero();this._color=(Common.Color.parse('black'));this._format=[InlineEditor.CSSShadowModel._Part.OffsetX,InlineEditor.CSSShadowModel._Part.OffsetY];} -static parseTextShadow(text){return InlineEditor.CSSShadowModel._parseShadow(text,false);} -static parseBoxShadow(text){return InlineEditor.CSSShadowModel._parseShadow(text,true);} -static _parseShadow(text,isBoxShadow){var shadowTexts=[];var splits=TextUtils.TextUtils.splitStringByRegexes(text,[Common.Color.Regex,/,/g]);var currentIndex=0;for(var i=0;i<splits.length;i++){if(splits[i].regexIndex===1){var comma=splits[i];shadowTexts.push(text.substring(currentIndex,comma.position));currentIndex=comma.position+1;}} -shadowTexts.push(text.substring(currentIndex,text.length));var shadows=[];for(var i=0;i<shadowTexts.length;i++){var shadow=new InlineEditor.CSSShadowModel(isBoxShadow);shadow._format=[];var nextPartAllowed=true;var regexes=[/inset/gi,Common.Color.Regex,InlineEditor.CSSLength.Regex];var results=TextUtils.TextUtils.splitStringByRegexes(shadowTexts[i],regexes);for(var j=0;j<results.length;j++){var result=results[j];if(result.regexIndex===-1){if(/\S/.test(result.value)) -return[];nextPartAllowed=true;}else{if(!nextPartAllowed) -return[];nextPartAllowed=false;if(result.regexIndex===0){shadow._inset=true;shadow._format.push(InlineEditor.CSSShadowModel._Part.Inset);}else if(result.regexIndex===1){var color=Common.Color.parse(result.value);if(!color) -return[];shadow._color=color;shadow._format.push(InlineEditor.CSSShadowModel._Part.Color);}else if(result.regexIndex===2){var length=InlineEditor.CSSLength.parse(result.value);if(!length) -return[];var previousPart=shadow._format.length>0?shadow._format[shadow._format.length-1]:'';if(previousPart===InlineEditor.CSSShadowModel._Part.OffsetX){shadow._offsetY=length;shadow._format.push(InlineEditor.CSSShadowModel._Part.OffsetY);}else if(previousPart===InlineEditor.CSSShadowModel._Part.OffsetY){shadow._blurRadius=length;shadow._format.push(InlineEditor.CSSShadowModel._Part.BlurRadius);}else if(previousPart===InlineEditor.CSSShadowModel._Part.BlurRadius){shadow._spreadRadius=length;shadow._format.push(InlineEditor.CSSShadowModel._Part.SpreadRadius);}else{shadow._offsetX=length;shadow._format.push(InlineEditor.CSSShadowModel._Part.OffsetX);}}}} -if(invalidCount(InlineEditor.CSSShadowModel._Part.OffsetX,1,1)||invalidCount(InlineEditor.CSSShadowModel._Part.OffsetY,1,1)||invalidCount(InlineEditor.CSSShadowModel._Part.Color,0,1)||invalidCount(InlineEditor.CSSShadowModel._Part.BlurRadius,0,1)||invalidCount(InlineEditor.CSSShadowModel._Part.Inset,0,isBoxShadow?1:0)||invalidCount(InlineEditor.CSSShadowModel._Part.SpreadRadius,0,isBoxShadow?1:0)) -return[];shadows.push(shadow);} -return shadows;function invalidCount(part,min,max){var count=0;for(var i=0;i<shadow._format.length;i++){if(shadow._format[i]===part) -count++;} -return count<min||count>max;}} -setInset(inset){this._inset=inset;if(this._format.indexOf(InlineEditor.CSSShadowModel._Part.Inset)===-1) -this._format.unshift(InlineEditor.CSSShadowModel._Part.Inset);} -setOffsetX(offsetX){this._offsetX=offsetX;} -setOffsetY(offsetY){this._offsetY=offsetY;} -setBlurRadius(blurRadius){this._blurRadius=blurRadius;if(this._format.indexOf(InlineEditor.CSSShadowModel._Part.BlurRadius)===-1){var yIndex=this._format.indexOf(InlineEditor.CSSShadowModel._Part.OffsetY);this._format.splice(yIndex+1,0,InlineEditor.CSSShadowModel._Part.BlurRadius);}} -setSpreadRadius(spreadRadius){this._spreadRadius=spreadRadius;if(this._format.indexOf(InlineEditor.CSSShadowModel._Part.SpreadRadius)===-1){this.setBlurRadius(this._blurRadius);var blurIndex=this._format.indexOf(InlineEditor.CSSShadowModel._Part.BlurRadius);this._format.splice(blurIndex+1,0,InlineEditor.CSSShadowModel._Part.SpreadRadius);}} -setColor(color){this._color=color;if(this._format.indexOf(InlineEditor.CSSShadowModel._Part.Color)===-1) -this._format.push(InlineEditor.CSSShadowModel._Part.Color);} -isBoxShadow(){return this._isBoxShadow;} -inset(){return this._inset;} -offsetX(){return this._offsetX;} -offsetY(){return this._offsetY;} -blurRadius(){return this._blurRadius;} -spreadRadius(){return this._spreadRadius;} -color(){return this._color;} -asCSSText(){var parts=[];for(var i=0;i<this._format.length;i++){var part=this._format[i];if(part===InlineEditor.CSSShadowModel._Part.Inset&&this._inset) -parts.push('inset');else if(part===InlineEditor.CSSShadowModel._Part.OffsetX) -parts.push(this._offsetX.asCSSText());else if(part===InlineEditor.CSSShadowModel._Part.OffsetY) -parts.push(this._offsetY.asCSSText());else if(part===InlineEditor.CSSShadowModel._Part.BlurRadius) -parts.push(this._blurRadius.asCSSText());else if(part===InlineEditor.CSSShadowModel._Part.SpreadRadius) -parts.push(this._spreadRadius.asCSSText());else if(part===InlineEditor.CSSShadowModel._Part.Color) -parts.push(this._color.asString(this._color.format()));} -return parts.join(' ');}};InlineEditor.CSSShadowModel._Part={Inset:'I',OffsetX:'X',OffsetY:'Y',BlurRadius:'B',SpreadRadius:'S',Color:'C'};InlineEditor.CSSLength=class{constructor(amount,unit){this.amount=amount;this.unit=unit;} -static parse(text){var lengthRegex=new RegExp('^(?:'+InlineEditor.CSSLength.Regex.source+')$','i');var match=text.match(lengthRegex);if(!match) -return null;if(match.length>2&&match[2]) -return new InlineEditor.CSSLength(parseFloat(match[1]),match[2]);return InlineEditor.CSSLength.zero();} -static zero(){return new InlineEditor.CSSLength(0,'');} -asCSSText(){return this.amount+this.unit;}};InlineEditor.CSSLength.Regex=(function(){var number='([+-]?(?:[0-9]*[.])?[0-9]+(?:[eE][+-]?[0-9]+)?)';var unit='(ch|cm|em|ex|in|mm|pc|pt|px|rem|vh|vmax|vmin|vw)';var zero='[+-]?(?:0*[.])?0+(?:[eE][+-]?[0-9]+)?';return new RegExp(number+unit+'|'+zero,'gi');})();;Runtime.cachedResources["inline_editor/bezierEditor.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n width: 270px;\n height: 350px;\n -webkit-user-select: none;\n padding: 16px;\n overflow: hidden;\n}\n\n.bezier-preset-selected > svg {\n background-color: rgb(56, 121, 217);\n}\n\n.bezier-preset-label {\n font-size: 10px;\n}\n\n.bezier-preset {\n width: 50px;\n height: 50px;\n padding: 5px;\n margin: auto;\n background-color: #f5f5f5;\n border-radius: 3px;\n}\n\n.bezier-preset line.bezier-control-line {\n stroke: #666;\n stroke-width: 1;\n stroke-linecap: round;\n fill: none;\n}\n\n.bezier-preset circle.bezier-control-circle {\n fill: #666;\n}\n\n.bezier-preset path.bezier-path {\n stroke: black;\n stroke-width: 2;\n stroke-linecap: round;\n fill: none;\n}\n\n.bezier-preset-selected path.bezier-path, .bezier-preset-selected line.bezier-control-line {\n stroke: white;\n}\n\n.bezier-preset-selected circle.bezier-control-circle {\n fill: white;\n}\n\n.bezier-curve line.linear-line {\n stroke: #eee;\n stroke-width: 2;\n stroke-linecap: round;\n fill: none;\n}\n\n.bezier-curve line.bezier-control-line {\n stroke: #9C27B0;\n stroke-width: 2;\n stroke-linecap: round;\n fill: none;\n opacity: 0.6;\n}\n\n.bezier-curve circle.bezier-control-circle {\n fill: #9C27B0;\n cursor: pointer;\n}\n\n.bezier-curve path.bezier-path {\n stroke: black;\n stroke-width: 3;\n stroke-linecap: round;\n fill: none;\n}\n\n.bezier-preview-container {\n position: relative;\n background-color: white;\n overflow: hidden;\n border-radius: 20px;\n width: 200%;\n height: 20px;\n z-index: 2;\n flex-shrink: 0;\n opacity: 0;\n}\n\n.bezier-preview-animation {\n background-color: #9C27B0;\n width: 20px;\n height: 20px;\n border-radius: 20px;\n position: absolute;\n}\n\n.bezier-preview-onion {\n margin-top: -20px;\n position: relative;\n z-index: 1;\n}\n\n.bezier-preview-onion > .bezier-preview-animation {\n opacity: 0.1;\n}\n\nsvg.bezier-preset-modify {\n background-color: #f5f5f5;\n border-radius: 35px;\n display: inline-block;\n visibility: hidden;\n transition: transform 100ms cubic-bezier(0.4, 0, 0.2, 1);\n cursor: pointer;\n position: absolute;\n}\n\nsvg.bezier-preset-modify:hover, .bezier-preset:hover {\n background-color: #999;\n}\n\n.bezier-preset-selected .bezier-preset:hover {\n background-color: rgb(56, 121, 217);\n}\n\n.bezier-preset-modify path {\n stroke-width: 2;\n stroke: black;\n fill: none;\n}\n\n.bezier-preset-selected .bezier-preset-modify {\n opacity: 1;\n}\n\n.bezier-preset-category {\n width: 50px;\n margin: 20px 0;\n cursor: pointer;\n transition: transform 100ms cubic-bezier(0.4, 0, 0.2, 1);\n}\n\nspan.bezier-display-value {\n width: 100%;\n -webkit-user-select: text;\n display: block;\n text-align: center;\n line-height: 20px;\n height: 20px;\n cursor: text;\n white-space: nowrap !important;\n}\n\n.bezier-container {\n display: flex;\n margin-top: 38px;\n}\n\nsvg.bezier-curve {\n margin-left: 32px;\n margin-top: -8px;\n}\n\nsvg.bezier-preset-modify.bezier-preset-plus {\n right: 0;\n}\n\n.bezier-header {\n margin-top: 16px;\n}\n\nsvg.bezier-preset-modify:active,\n.-theme-selection-color {\n transform: scale(1.1);\n background-color: rgb(56, 121, 217);\n}\n\n.bezier-preset-category:active {\n transform: scale(1.05);\n}\n\n.bezier-header-active > svg.bezier-preset-modify {\n visibility: visible;\n}\n\n.bezier-preset-modify:active path {\n stroke: white;\n}\n\n/*# sourceURL=inline_editor/bezierEditor.css */";Runtime.cachedResources["inline_editor/colorSwatch.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n white-space: nowrap;\n}\n\n.color-swatch {\n position: relative;\n margin-left: 1px;\n margin-right: 2px;\n width: 10px;\n height: 10px;\n top: 1px;\n display: inline-block;\n -webkit-user-select: none;\n background-image: url(Images/checker.png);\n line-height: 10px;\n}\n\n.color-swatch-inner {\n width: 100%;\n height: 100%;\n display: inline-block;\n border: 1px solid rgba(128, 128, 128, 0.6);\n cursor: default;\n}\n\n.color-swatch-inner:hover {\n border: 1px solid rgba(64, 64, 64, 0.8);\n}\n\n\n/*# sourceURL=inline_editor/colorSwatch.css */";Runtime.cachedResources["inline_editor/bezierSwatch.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n white-space: nowrap;\n}\n\n.bezier-swatch-icon {\n position: relative;\n margin-left: 1px;\n margin-right: 2px;\n top: 1px;\n -webkit-user-select: none;\n line-height: 10px;\n background-color: #9C27B0;\n cursor: default;\n}\n\n.bezier-swatch-icon:hover {\n background-color: #800080;\n}\n\n/*# sourceURL=inline_editor/bezierSwatch.css */";Runtime.cachedResources["inline_editor/cssShadowSwatch.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n white-space: nowrap;\n}\n\n.shadow-swatch-icon {\n position: relative;\n margin-left: 1px;\n margin-right: 2px;\n top: 1px;\n -webkit-user-select: none;\n line-height: 10px;\n background-color: #9C27B0;\n}\n\n.shadow-swatch-icon:hover {\n background-color: #800080;\n}\n\n/*# sourceURL=inline_editor/cssShadowSwatch.css */";Runtime.cachedResources["inline_editor/cssShadowEditor.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n -webkit-user-select: none;\n padding: 4px 12px 12px 12px;\n}\n\n.shadow-editor-field {\n height: 24px;\n margin-top: 8px;\n font-size: 12px;\n}\n\n.shadow-editor-flex-field {\n display: flex;\n align-items: center;\n flex-direction: row;\n}\n\n.shadow-editor-field.shadow-editor-blur-field {\n margin-top: 40px;\n}\n\n.shadow-editor-2D-slider {\n position: absolute;\n height: 88px;\n width: 88px;\n border: 1px solid rgba(0, 0, 0, 0.14);\n border-radius: 2px;\n}\n\n.shadow-editor-label {\n display: inline-block;\n width: 52px;\n height: 24px;\n line-height: 24px;\n margin-right: 8px;\n text-align: right;\n}\n\n.shadow-editor-button-left, .shadow-editor-button-right {\n width: 74px;\n height: 24px;\n padding: 3px 7px;\n line-height: 16px;\n border: 1px solid rgba(0, 0, 0, 0.14);\n background-color: #ffffff;\n text-align: center;\n font-weight: 500;\n}\n\n.shadow-editor-button-left {\n border-radius: 2px 0 0 2px;\n}\n\n.shadow-editor-button-right {\n border-radius: 0 2px 2px 0;\n border-left-width: 0;\n}\n\n.shadow-editor-button-left:hover, .shadow-editor-button-right:hover {\n box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);\n}\n\n.shadow-editor-button-left:focus, .shadow-editor-button-right:focus {\n background-color: #eeeeee;\n}\n\n.shadow-editor-button-left.enabled, .shadow-editor-button-right.enabled, -theme-preserve {\n background-color: #4285F4;\n color: #ffffff;\n}\n\n.shadow-editor-button-left.enabled:focus, .shadow-editor-button-right.enabled:focus, -theme-preserve {\n background-color: #3B78E7;\n}\n\n.shadow-editor-text-input {\n width: 52px;\n margin-right: 8px;\n text-align: right;\n}\n\n/*# sourceURL=inline_editor/cssShadowEditor.css */";Runtime.cachedResources["inline_editor/swatchPopover.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n display: flex;\n background: white;\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2), 0 2px 4px rgba(0, 0, 0, 0.2), 0 2px 6px rgba(0, 0, 0, 0.1);\n border-radius: 2px;\n overflow: auto;\n -webkit-user-select: text;\n line-height: 11px;\n}\n\n/*# sourceURL=inline_editor/swatchPopover.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/inspector.html b/src/cobalt/debug/content/devtools/inspector.html deleted file mode 100644 index 2997442..0000000 --- a/src/cobalt/debug/content/devtools/inspector.html +++ /dev/null
@@ -1,15 +0,0 @@ -<!-- - * Copyright 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. ---> -<!doctype html> -<html> -<head> - <meta http-equiv="content-type" content="text/html; charset=utf-8"> - <meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' https://chrome-devtools-frontend.appspot.com"> - <meta name="referrer" content="no-referrer"> - <script type="text/javascript" src="inspector.js"></script> -</head> -<body class="undocked" id="-blink-dev-tools"></body> -</html>
diff --git a/src/cobalt/debug/content/devtools/inspector.js b/src/cobalt/debug/content/devtools/inspector.js deleted file mode 100644 index 928abcb..0000000 --- a/src/cobalt/debug/content/devtools/inspector.js +++ /dev/null
@@ -1,8459 +0,0 @@ -var allDescriptors=[{"dependencies":["ui","platform","common","cm"],"extensions":[{"className":"TextEditor.CodeMirrorUtils.TokenizerFactory","type":"@TextUtils.TokenizerFactory"},{"className":"TextEditor.CodeMirrorTextEditorFactory","type":"@UI.TextEditorFactory"}],"name":"text_editor","scripts":["text_editor_module.js"],"skip_compilation":["acorn/acorn.js","../cm_web_modes/css.js","../cm_web_modes/javascript.js","../cm_web_modes/xml.js","../cm_web_modes/htmlmixed.js","../cm_web_modes/htmlembedded.js"]},{"dependencies":["common","protocol"],"name":"network_priorities","scripts":["network_priorities_module.js"]},{"skip_compilation":["../InspectorBackendCommands.js"],"name":"protocol"},{"dependencies":["ui","host"],"extensions":[{"title":"What's New","id":"release-note","className":"Help.ReleaseNoteView","location":"drawer-view","type":"view","order":1,"persistence":"closeable"}],"name":"help"},{"skip_compilation":["codemirror.js","multiplex.js","matchbrackets.js","closebrackets.js","markselection.js","comment.js","overlay.js","activeline.js"],"name":"cm","scripts":["cm_module.js"]},{"dependencies":[],"name":"heap_snapshot_model","scripts":["heap_snapshot_model_module.js"]},{"experiment":"accessibilityInspection","extensions":[{"title":"Accessibility","id":"accessibility.view","className":"Accessibility.AccessibilitySidebarView","location":"elements-sidebar","type":"view","order":10,"persistence":"permanent"}],"name":"accessibility","dependencies":["elements"],"scripts":["accessibility_module.js"],"skip_compilation":["ARIAConfig.js"]},{"dependencies":["text_editor"],"extensions":[{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-csrc","text/x-c","text/x-chdr","text/x-c++src","text/x-c++hdr","text/x-java","text/x-csharp","text/x-scala","x-shader/x-vertex","x-shader/x-fragment"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"clike.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-coffeescript"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"coffeescript.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["application/x-httpd-php","application/x-httpd-php-open","text/x-php"],"dependencies":["clike.js"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"php.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-python","text/x-cython"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"python.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-sh"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"shell.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-livescript"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"livescript.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-clojure"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"clojure.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/jsx"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"jsx.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-styl"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"stylus.js"}],"name":"cm_modes","scripts":["cm_modes_module.js"]},{"dependencies":["components","sdk","timeline_model","ui","perf_ui"],"name":"layer_viewer","scripts":["layer_viewer_module.js"]},{"dependencies":["components","source_frame","snippets","extensions","persistence","quick_open","inline_editor","color_picker","event_listeners","object_ui","formatter"],"extensions":[{"title":"Sources","id":"sources","className":"Sources.SourcesPanel","location":"panel","type":"view","order":30},{"className":"Sources.SourcesPanel","contextTypes":["Workspace.UISourceCode","Workspace.UILocation","SDK.RemoteObject","SDK.NetworkRequest","SourceFrame.UISourceCodeFrame"],"type":"@UI.ContextMenu.Provider"},{"category":"Debugger","iconClass":"largeicon-pause","toggledIconClass":"largeicon-resume","className":"Sources.SourcesPanel.RevealingActionDelegate","contextTypes":["Sources.SourcesPanel","UI.ShortcutRegistry.ForwardedShortcut"],"actionId":"debugger.toggle-pause","bindings":[{"platform":"windows,linux","shortcut":"F8 Ctrl+\\"},{"platform":"mac","shortcut":"F8 Meta+\\"}],"type":"@UI.ActionDelegate","options":[{"value":true,"title":"Pause script execution"},{"value":false,"title":"Resume script execution"}]},{"iconClass":"largeicon-step-over","title":"Step over next function call","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["Sources.SourcesPanel"],"actionId":"debugger.step-over","bindings":[{"platform":"windows,linux","shortcut":"F10 Ctrl+'"},{"platform":"mac","shortcut":"F10 Meta+'"}],"type":"@UI.ActionDelegate"},{"iconClass":"largeicon-step-in","title":"Step into next function call","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["Sources.SourcesPanel"],"actionId":"debugger.step-into","bindings":[{"platform":"windows,linux","shortcut":"F11 Ctrl+;"},{"platform":"mac","shortcut":"F11 Meta+;"}],"type":"@UI.ActionDelegate"},{"iconClass":"largeicon-step-out","title":"Step out of current function","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["Sources.SourcesPanel"],"actionId":"debugger.step-out","bindings":[{"platform":"windows,linux","shortcut":"Shift+F11 Shift+Ctrl+;"},{"platform":"mac","shortcut":"Shift+F11 Shift+Meta+;"}],"type":"@UI.ActionDelegate"},{"iconClass":"largeicon-play","title":"Run snippet","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["Sources.SourcesPanel"],"actionId":"debugger.run-snippet","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Enter"},{"platform":"mac","shortcut":"Meta+Enter"}],"type":"@UI.ActionDelegate"},{"category":"DevTools","title":"Search all files","className":"Sources.AdvancedSearchView.ActionDelegate","actionId":"sources.search.toggle","bindings":[{"platform":"mac","shortcut":"Meta+Alt+F"},{"platform":"windows,linux","shortcut":"Ctrl+Shift+F"}],"type":"@UI.ActionDelegate"},{"category":"Debugger","iconClass":"largeicon-deactivate-breakpoints","toggledIconClass":"largeicon-activate-breakpoints","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["Sources.SourcesPanel"],"actionId":"debugger.toggle-breakpoints-active","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+F8"},{"platform":"mac","shortcut":"Meta+F8"}],"type":"@UI.ActionDelegate","options":[{"value":true,"title":"Deactivate breakpoints"},{"value":false,"title":"Activate breakpoints"}]},{"title":"Add selected text to watches","className":"Sources.WatchExpressionsSidebarPane","contextTypes":["SourceFrame.UISourceCodeFrame"],"actionId":"sources.add-to-watch","bindings":[{"shortcut":"Ctrl+Shift+A"}],"type":"@UI.ActionDelegate"},{"className":"Sources.WatchExpressionsSidebarPane","contextTypes":["TextEditor.CodeMirrorTextEditor"],"type":"@UI.ContextMenu.Provider"},{"title":"Evaluate in console","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["SourceFrame.UISourceCodeFrame"],"actionId":"debugger.evaluate-selection","bindings":[{"shortcut":"Ctrl+Shift+E"}],"type":"@UI.ActionDelegate"},{"className":"Sources.OpenFileQuickOpen","prefix":"","type":"@QuickOpen.FilteredListWidget.Provider","title":"Open file"},{"className":"Sources.GoToLineQuickOpen","prefix":":","type":"@QuickOpen.FilteredListWidget.Provider","title":"Go to line"},{"className":"Sources.OutlineQuickOpen","prefix":"@","type":"@QuickOpen.FilteredListWidget.Provider","title":"Go to symbol"},{"type":"context-menu-item","location":"mainMenu/default","actionId":"sources.search.toggle"},{"type":"context-menu-item","location":"navigatorMenu/default","actionId":"quickOpen.show"},{"className":"Sources.SourcesPanel.UILocationRevealer","contextTypes":["Workspace.UILocation"],"type":"@Common.Revealer"},{"className":"Sources.SourcesPanel.DebuggerLocationRevealer","contextTypes":["SDK.DebuggerModel.Location"],"type":"@Common.Revealer"},{"className":"Sources.SourcesPanel.UISourceCodeRevealer","contextTypes":["Workspace.UISourceCode"],"type":"@Common.Revealer"},{"className":"Sources.SourcesPanel.DebuggerPausedDetailsRevealer","contextTypes":["SDK.DebuggerPausedDetails"],"type":"@Common.Revealer"},{"className":"Sources.InplaceFormatterEditorAction","type":"@Sources.SourcesView.EditorAction"},{"className":"Sources.ScriptFormatterEditorAction","type":"@Sources.SourcesView.EditorAction"},{"title":"Sources","id":"navigator-sources","className":"Sources.SourcesNavigatorView","experiment":"!persistence2","location":"navigator-view","type":"view","order":1,"persistence":"permanent"},{"title":"Network","id":"navigator-network","className":"Sources.NetworkNavigatorView","experiment":"persistence2","location":"navigator-view","type":"view","order":2,"persistence":"permanent"},{"title":"Filesystem","id":"navigator-files","className":"Sources.FilesNavigatorView","experiment":"persistence2","location":"navigator-view","type":"view","order":3,"persistence":"permanent"},{"title":"Overrides","id":"navigator-overrides","className":"Sources.OverridesNavigatorView","experiment":"networkPersistence","location":"navigator-view","type":"view","order":4,"persistence":"permanent"},{"title":"Content scripts","id":"navigator-contentScripts","className":"Sources.ContentScriptsNavigatorView","location":"navigator-view","type":"view","order":5,"persistence":"permanent"},{"title":"Snippets","id":"navigator-snippets","className":"Sources.SnippetsNavigatorView","location":"navigator-view","type":"view","order":6,"persistence":"permanent"},{"className":"Sources.SourcesNavigatorView","viewId":"navigator-sources","experiment":"!persistence2","type":"@Sources.NavigatorView"},{"className":"Sources.NetworkNavigatorView","viewId":"navigator-network","experiment":"persistence2","type":"@Sources.NavigatorView"},{"className":"Sources.FilesNavigatorView","viewId":"navigator-files","experiment":"persistence2","type":"@Sources.NavigatorView"},{"className":"Sources.OverridesNavigatorView","viewId":"navigator-overrides","experiment":"networkPersistence","type":"@Sources.NavigatorView"},{"className":"Sources.ContentScriptsNavigatorView","viewId":"navigator-contentScripts","type":"@Sources.NavigatorView"},{"className":"Sources.SnippetsNavigatorView","viewId":"navigator-snippets","type":"@Sources.NavigatorView"},{"className":"Sources.SourcesView.SwitchFileActionDelegate","contextTypes":["Sources.SourcesView"],"bindings":[{"shortcut":"Alt+O"}],"type":"@UI.ActionDelegate","actionId":"sources.switch-file"},{"defaultValue":"true","type":"setting","settingName":"navigatorGroupByFolder","settingType":"boolean"},{"category":"Sources","title":"Search in anonymous and content scripts","defaultValue":false,"settingName":"searchInAnonymousAndContentScripts","settingType":"boolean","type":"setting"},{"category":"Sources","title":"Automatically reveal files in navigator","defaultValue":false,"settingName":"autoRevealInNavigator","settingType":"boolean","type":"setting"},{"category":"Sources","title":"Enable JavaScript source maps","defaultValue":true,"settingName":"jsSourceMapsEnabled","settingType":"boolean","type":"setting"},{"category":"Sources","title":"Detect indentation","defaultValue":true,"settingName":"textEditorAutoDetectIndent","settingType":"boolean","type":"setting"},{"category":"Sources","title":"Autocompletion","defaultValue":true,"settingName":"textEditorAutocompletion","settingType":"boolean","type":"setting"},{"category":"Sources","title":"Bracket matching","defaultValue":true,"settingName":"textEditorBracketMatching","settingType":"boolean","type":"setting"},{"category":"Sources","title":"Show whitespace characters:","defaultValue":"original","settingName":"showWhitespacesInEditor","settingType":"enum","type":"setting","options":[{"text":"None","value":"none","title":"Do not show whitespace characters"},{"text":"All","value":"all","title":"Show all whitespace characters"},{"text":"Trailing","value":"trailing","title":"Show trailing whitespace characters"}]},{"category":"Sources","title":"Display variable values inline while debugging","defaultValue":true,"settingName":"inlineVariableValues","settingType":"boolean","type":"setting"},{"category":"Sources","title":"Enable CSS source maps","defaultValue":true,"settingName":"cssSourceMapsEnabled","settingType":"boolean","type":"setting"},{"title":"Search","id":"sources.search","className":"Sources.AdvancedSearchView","location":"drawer-view","type":"view","order":100,"persistence":"closeable"},{"title":"History","className":"Sources.RevisionHistoryView","location":"drawer-view","type":"view","id":"sources.history","persistence":"transient"},{"title":"Quick source","id":"sources.quick","className":"Sources.SourcesPanel.WrapperView","location":"drawer-view","type":"view","order":1000,"persistence":"closeable"},{"category":"Sources","className":"Sources.SourcesView.CloseAllActionDelegate","type":"@UI.ActionDelegate","actionId":"sources.close-all","title":"Close All"},{"category":"Sources","className":"Sources.SourcesNavigatorView.CreatingActionDelegate","type":"@UI.ActionDelegate","actionId":"sources.create-snippet","title":"Create new snippet"},{"category":"Sources","className":"Sources.SourcesNavigatorView.CreatingActionDelegate","type":"@UI.ActionDelegate","actionId":"sources.add-folder-to-workspace","title":"Add folder to workspace"},{"className":"Sources.SourcesPanel","type":"@UI.ViewLocationResolver","name":"navigator-view"},{"category":"Sources","className":"Sources.SourcesPanel","type":"@UI.ViewLocationResolver","name":"sources-sidebar"},{"title":"XHR/fetch Breakpoints","id":"sources.xhrBreakpoints","className":"Sources.XHRBreakpointsSidebarPane","location":"sources-sidebar","hasToolbar":true,"type":"view","order":5,"persistence":"permanent"},{"title":"Global Listeners","id":"sources.globalListeners","className":"Sources.ObjectEventListenersSidebarPane","location":"sources-sidebar","hasToolbar":true,"type":"view","order":8,"persistence":"permanent"},{"title":"Event Listener Breakpoints","id":"sources.eventListenerBreakpoints","className":"Sources.EventListenerBreakpointsSidebarPane","location":"sources-sidebar","type":"view","order":9,"persistence":"permanent"},{"className":"Sources.ThreadsSidebarPane","type":"view","id":"sources.threads","persistence":"permanent","title":"Threads"},{"className":"Sources.ScopeChainSidebarPane","type":"view","id":"sources.scopeChain","persistence":"permanent","title":"Scope"},{"title":"Watch","className":"Sources.WatchExpressionsSidebarPane","hasToolbar":true,"type":"view","id":"sources.watch","persistence":"permanent"},{"className":"Sources.JavaScriptBreakpointsSidebarPane","type":"view","id":"sources.jsBreakpoints","persistence":"permanent","title":"Breakpoints"},{"className":"Sources.JavaScriptBreakpointsSidebarPane","contextTypes":["SDK.DebuggerPausedDetails"],"type":"@UI.ContextFlavorListener"},{"className":"Sources.XHRBreakpointsSidebarPane","contextTypes":["SDK.DebuggerPausedDetails"],"type":"@UI.ContextFlavorListener"},{"className":"Sources.CallStackSidebarPane","contextTypes":["SDK.DebuggerPausedDetails"],"type":"@UI.ContextFlavorListener"},{"className":"Sources.ScopeChainSidebarPane","contextTypes":["SDK.DebuggerModel.CallFrame"],"type":"@UI.ContextFlavorListener"}],"name":"sources","scripts":["sources_module.js"]},{"dependencies":["ui","sdk","data_grid"],"name":"cookie_table","scripts":["cookie_table_module.js"]},{"dependencies":["emulation"],"extensions":[{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 4","screen":{"horizontal":{"width":480,"height":320},"device-pixel-ratio":2,"vertical":{"width":320,"height":480}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 5","screen":{"horizontal":{"width":568,"outline":{"insets":{"top":25,"right":115,"bottom":28,"left":115},"image":"@url(iPhone5-landscape.svg)"},"height":320},"device-pixel-ratio":2,"vertical":{"width":320,"outline":{"insets":{"top":105,"right":25,"bottom":111,"left":29},"image":"@url(iPhone5-portrait.svg)"},"height":568}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1","type":"phone"},"type":"emulated-device","order":40},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 6","screen":{"horizontal":{"width":667,"outline":{"insets":{"top":28,"right":106,"bottom":28,"left":106},"image":"@url(iPhone6-landscape.svg)"},"height":375},"device-pixel-ratio":2,"vertical":{"width":375,"outline":{"insets":{"top":105,"right":28,"bottom":105,"left":28},"image":"@url(iPhone6-portrait.svg)"},"height":667}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1","type":"phone"},"type":"emulated-device","order":50},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 6 Plus","screen":{"horizontal":{"width":736,"outline":{"insets":{"top":29,"right":109,"bottom":27,"left":109},"image":"@url(iPhone6Plus-landscape.svg)"},"height":414},"device-pixel-ratio":3,"vertical":{"width":414,"outline":{"insets":{"top":107,"right":30,"bottom":111,"left":26},"image":"@url(iPhone6Plus-portrait.svg)"},"height":736}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1","type":"phone"},"type":"emulated-device","order":60},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 7","screen":{"horizontal":{"width":667,"outline":{"insets":{"top":28,"right":106,"bottom":28,"left":106},"image":"@url(iPhone6-landscape.svg)"},"height":375},"device-pixel-ratio":2,"vertical":{"width":375,"outline":{"insets":{"top":105,"right":28,"bottom":105,"left":28},"image":"@url(iPhone6-portrait.svg)"},"height":667}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1","type":"phone"},"type":"emulated-device","order":61},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 7 Plus","screen":{"horizontal":{"width":736,"outline":{"insets":{"top":29,"right":109,"bottom":27,"left":109},"image":"@url(iPhone6Plus-landscape.svg)"},"height":414},"device-pixel-ratio":3,"vertical":{"width":414,"outline":{"insets":{"top":107,"right":30,"bottom":111,"left":26},"image":"@url(iPhone6Plus-portrait.svg)"},"height":736}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1","type":"phone"},"type":"emulated-device","order":62},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 8","screen":{"horizontal":{"width":667,"outline":{"insets":{"top":28,"right":106,"bottom":28,"left":106},"image":"@url(iPhone6-landscape.svg)"},"height":375},"device-pixel-ratio":2,"vertical":{"width":375,"outline":{"insets":{"top":105,"right":28,"bottom":105,"left":28},"image":"@url(iPhone6-portrait.svg)"},"height":667}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1","type":"phone"},"type":"emulated-device","order":63},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 8 Plus","screen":{"horizontal":{"width":736,"outline":{"insets":{"top":29,"right":109,"bottom":27,"left":109},"image":"@url(iPhone6Plus-landscape.svg)"},"height":414},"device-pixel-ratio":3,"vertical":{"width":414,"outline":{"insets":{"top":107,"right":30,"bottom":111,"left":26},"image":"@url(iPhone6Plus-portrait.svg)"},"height":736}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1","type":"phone"},"type":"emulated-device","order":64},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone X","screen":{"horizontal":{"width":812,"height":375},"device-pixel-ratio":3,"vertical":{"width":375,"height":812}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1","type":"phone"},"type":"emulated-device","order":65},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"BlackBerry Z30","screen":{"horizontal":{"width":640,"height":360},"device-pixel-ratio":2,"vertical":{"width":360,"height":640}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Nexus 4","screen":{"horizontal":{"width":640,"height":384},"device-pixel-ratio":2,"vertical":{"width":384,"height":640}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":25,"right":0,"bottom":48,"left":0},"image":"@url(google-nexus-5-vertical-default-1x.png) 1x, @url(google-nexus-5-vertical-default-2x.png) 2x","orientation":"vertical","title":"default"},{"insets":{"top":80,"right":0,"bottom":48,"left":0},"image":"@url(google-nexus-5-vertical-navigation-1x.png) 1x, @url(google-nexus-5-vertical-navigation-2x.png) 2x","orientation":"vertical","title":"navigation bar"},{"insets":{"top":80,"right":0,"bottom":312,"left":0},"image":"@url(google-nexus-5-vertical-keyboard-1x.png) 1x, @url(google-nexus-5-vertical-keyboard-2x.png) 2x","orientation":"vertical","title":"keyboard"},{"insets":{"top":25,"right":42,"bottom":0,"left":0},"image":"@url(google-nexus-5-horizontal-default-1x.png) 1x, @url(google-nexus-5-horizontal-default-2x.png) 2x","orientation":"horizontal","title":"default"},{"insets":{"top":80,"right":42,"bottom":0,"left":0},"image":"@url(google-nexus-5-horizontal-navigation-1x.png) 1x, @url(google-nexus-5-horizontal-navigation-2x.png) 2x","orientation":"horizontal","title":"navigation bar"},{"insets":{"top":80,"right":42,"bottom":202,"left":0},"image":"@url(google-nexus-5-horizontal-keyboard-1x.png) 1x, @url(google-nexus-5-horizontal-keyboard-2x.png) 2x","orientation":"horizontal","title":"keyboard"}],"title":"Nexus 5","screen":{"horizontal":{"width":640,"height":360},"device-pixel-ratio":3,"vertical":{"width":360,"height":640}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":true,"modes":[{"insets":{"top":24,"right":0,"bottom":48,"left":0},"image":"@url(google-nexus-5x-vertical-default-1x.png) 1x, @url(google-nexus-5x-vertical-default-2x.png) 2x","orientation":"vertical","title":"default"},{"insets":{"top":80,"right":0,"bottom":48,"left":0},"image":"@url(google-nexus-5x-vertical-navigation-1x.png) 1x, @url(google-nexus-5x-vertical-navigation-2x.png) 2x","orientation":"vertical","title":"navigation bar"},{"insets":{"top":80,"right":0,"bottom":342,"left":0},"image":"@url(google-nexus-5x-vertical-keyboard-1x.png) 1x, @url(google-nexus-5x-vertical-keyboard-2x.png) 2x","orientation":"vertical","title":"keyboard"},{"insets":{"top":24,"right":48,"bottom":0,"left":0},"image":"@url(google-nexus-5x-horizontal-default-1x.png) 1x, @url(google-nexus-5x-horizontal-default-2x.png) 2x","orientation":"horizontal","title":"default"},{"insets":{"top":80,"right":48,"bottom":0,"left":0},"image":"@url(google-nexus-5x-horizontal-navigation-1x.png) 1x, @url(google-nexus-5x-horizontal-navigation-2x.png) 2x","orientation":"horizontal","title":"navigation bar"},{"insets":{"top":80,"right":48,"bottom":222,"left":0},"image":"@url(google-nexus-5x-horizontal-keyboard-1x.png) 1x, @url(google-nexus-5x-horizontal-keyboard-2x.png) 2x","orientation":"horizontal","title":"keyboard"}],"title":"Nexus 5X","screen":{"horizontal":{"width":732,"outline":{"insets":{"top":21,"right":98,"bottom":19,"left":88},"image":"@url(Nexus5X-landscape.svg)"},"height":412},"device-pixel-ratio":2.625,"vertical":{"width":412,"outline":{"insets":{"top":88,"right":22,"bottom":98,"left":18},"image":"@url(Nexus5X-portrait.svg)"},"height":732}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36","type":"phone"},"type":"emulated-device","order":20},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Nexus 6","screen":{"horizontal":{"width":732,"height":412},"device-pixel-ratio":3.5,"vertical":{"width":412,"height":732}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Nexus 6P","screen":{"horizontal":{"width":732,"outline":{"insets":{"top":17,"right":88,"bottom":17,"left":94},"image":"@url(Nexus6P-landscape.svg)"},"height":412},"device-pixel-ratio":3.5,"vertical":{"width":412,"outline":{"insets":{"top":94,"right":16,"bottom":88,"left":16},"image":"@url(Nexus6P-portrait.svg)"},"height":732}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36","type":"phone"},"type":"emulated-device","order":30},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"LG Optimus L70","screen":{"horizontal":{"width":640,"height":384},"device-pixel-ratio":1.25,"vertical":{"width":384,"height":640}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/%s Mobile Safari/537.36","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Nokia N9","screen":{"horizontal":{"width":854,"height":480},"device-pixel-ratio":1,"vertical":{"width":480,"height":854}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Nokia Lumia 520","screen":{"horizontal":{"width":533,"height":320},"device-pixel-ratio":1.5,"vertical":{"width":320,"height":533}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Microsoft Lumia 550","screen":{"horizontal":{"width":640,"height":360},"device-pixel-ratio":2,"vertical":{"width":640,"height":360}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Microsoft Lumia 950","screen":{"horizontal":{"width":640,"height":360},"device-pixel-ratio":4,"vertical":{"width":360,"height":640}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Galaxy S III","screen":{"horizontal":{"width":640,"height":360},"device-pixel-ratio":2,"vertical":{"width":360,"height":640}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Galaxy S5","screen":{"horizontal":{"width":640,"height":360},"device-pixel-ratio":3,"vertical":{"width":360,"height":640}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36","type":"phone"},"type":"emulated-device","order":10},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Kindle Fire HDX","screen":{"horizontal":{"width":1280,"height":800},"device-pixel-ratio":2,"vertical":{"width":800,"height":1280}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true","type":"tablet"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPad Mini","screen":{"horizontal":{"width":1024,"height":768},"device-pixel-ratio":2,"vertical":{"width":768,"height":1024}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1","type":"tablet"},"type":"emulated-device"},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPad","screen":{"horizontal":{"width":1024,"outline":{"insets":{"top":56,"right":116,"bottom":52,"left":112},"image":"@url(iPad-landscape.svg)"},"height":768},"device-pixel-ratio":2,"vertical":{"width":768,"outline":{"insets":{"top":114,"right":55,"bottom":114,"left":52},"image":"@url(iPad-portrait.svg)"},"height":1024}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1","type":"tablet"},"type":"emulated-device","order":70},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPad Pro","screen":{"horizontal":{"width":1366,"height":1024},"device-pixel-ratio":2,"vertical":{"width":1024,"height":1366}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1","type":"tablet"},"type":"emulated-device","order":80},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Blackberry PlayBook","screen":{"horizontal":{"width":1024,"height":600},"device-pixel-ratio":1,"vertical":{"width":600,"height":1024}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+","type":"tablet"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Nexus 10","screen":{"horizontal":{"width":1280,"height":800},"device-pixel-ratio":2,"vertical":{"width":800,"height":1280}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; Android 4.3; Nexus 10 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36","type":"tablet"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Nexus 7","screen":{"horizontal":{"width":960,"height":600},"device-pixel-ratio":2,"vertical":{"width":600,"height":960}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36","type":"tablet"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Galaxy Note 3","screen":{"horizontal":{"width":640,"height":360},"device-pixel-ratio":3,"vertical":{"width":360,"height":640}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Galaxy Note II","screen":{"horizontal":{"width":640,"height":360},"device-pixel-ratio":2,"vertical":{"width":360,"height":640}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Laptop with touch","screen":{"horizontal":{"width":1280,"height":950},"device-pixel-ratio":1,"vertical":{"width":950,"height":1280}},"capabilities":["touch"],"user-agent":"","type":"notebook"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Laptop with HiDPI screen","screen":{"horizontal":{"width":1440,"height":900},"device-pixel-ratio":2,"vertical":{"width":900,"height":1440}},"capabilities":[],"user-agent":"","type":"notebook"},"type":"emulated-device"},{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"Laptop with MDPI screen","screen":{"horizontal":{"width":1280,"height":800},"device-pixel-ratio":1,"vertical":{"width":800,"height":1280}},"capabilities":[],"user-agent":"","type":"notebook"},"type":"emulated-device"}],"name":"emulated_devices","scripts":[]},{"dependencies":["common","product_registry"],"extensions":[{"className":"ProductRegistryImpl.Registry","type":"@ProductRegistry.Registry"}],"name":"product_registry_impl","scripts":["product_registry_impl_module.js"]},{"skip_compilation":["diff_match_patch.js"],"dependencies":["common"],"name":"diff","scripts":["diff_module.js"]},{"dependencies":["sdk","platform","services","workspace","console_model"],"name":"bindings"},{"dependencies":["components","extensions","network_log","object_ui","formatter"],"extensions":[{"title":"Legacy Audits","id":"audits","className":"Audits.AuditsPanel","location":"panel","type":"view","order":90,"persistence":"closeable"}],"name":"audits","scripts":["audits_module.js"]},{"dependencies":["bindings","quick_open"],"extensions":[{"className":"Snippets.SnippetsQuickOpen","prefix":"!","type":"@QuickOpen.FilteredListWidget.Provider","title":"Run snippet"}],"name":"snippets","scripts":["snippets_module.js"]},{"dependencies":["layer_viewer"],"extensions":[{"title":"Layers","id":"layers","className":"Layers.LayersPanel","location":"panel","type":"view","order":100,"persistence":"closeable"}],"name":"layers","scripts":["layers_module.js"]},{"dependencies":["common","network_log","sdk"],"name":"har_importer","scripts":["har_importer_module.js"]},{"dependencies":["components","data_grid","object_ui","console_model","product_registry","formatter"],"extensions":[{"title":"Console","id":"console","className":"Console.ConsolePanel","location":"panel","type":"view","order":20},{"title":"Console","id":"console-view","className":"Console.ConsolePanel.WrapperView","location":"drawer-view","type":"view","order":0,"persistence":"permanent"},{"className":"Console.ConsolePanel.ConsoleRevealer","contextTypes":["Common.Console"],"type":"@Common.Revealer"},{"className":"Console.ConsoleView.ActionDelegate","bindings":[{"shortcut":"Ctrl+`"}],"type":"@UI.ActionDelegate","actionId":"console.show"},{"category":"Console","iconClass":"largeicon-clear","title":"Clear console","className":"Console.ConsoleView.ActionDelegate","actionId":"console.clear","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+L"},{"platform":"mac","shortcut":"Ctrl+L Meta+K"}],"type":"@UI.ActionDelegate"},{"category":"Console","className":"Console.ConsoleView.ActionDelegate","type":"@UI.ActionDelegate","actionId":"console.clear.history","title":"Clear console history"},{"category":"Console","title":"Hide network messages","defaultValue":false,"settingName":"hideNetworkMessages","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Hide network messages"},{"value":false,"title":"Show network messages"}]},{"category":"Console","title":"Selected context only","storageType":"session","defaultValue":false,"settingName":"selectedContextFilterEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Only show messages from the current context (top, iframe, worker, extension)"},{"value":false,"title":"Show messages from all contexts"}]},{"category":"Console","title":"User messages only","storageType":"session","defaultValue":false,"settingName":"consoleAPIFilterEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Only show messages from console API methods"},{"value":false,"title":"Show messages from all sources"}]},{"category":"Console","title":"Log XMLHttpRequests","defaultValue":false,"settingName":"monitoringXHREnabled","settingType":"boolean","type":"setting"},{"category":"Console","title":"Show timestamps","defaultValue":false,"settingName":"consoleTimestampsEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show timestamps"},{"value":false,"title":"Hide timestamps"}]},{"category":"Console","title":"Autocomplete from history","defaultValue":true,"settingName":"consoleHistoryAutocomplete","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Autocomplete from history"},{"value":false,"title":"Do not autocomplete from history"}]},{"category":"Console","title":"Group similar","defaultValue":true,"settingName":"consoleGroupSimilar","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Group similar messages in console"},{"value":false,"title":"Do not group similar messages in console"}]}],"name":"console","scripts":["console_module.js"]},{"dependencies":["source_frame","components","perf_ui","cookie_table","data_grid","network_log","product_registry","mobile_throttling","har_importer","network_priorities","persistence"],"extensions":[{"title":"Network","id":"network","className":"Network.NetworkPanel","location":"panel","type":"view","order":40},{"className":"Network.NetworkPanel.ContextMenuProvider","contextTypes":["SDK.NetworkRequest","SDK.Resource","Workspace.UISourceCode"],"type":"@UI.ContextMenu.Provider"},{"className":"Network.NetworkPanel.RequestRevealer","contextTypes":["SDK.NetworkRequest"],"type":"@Common.Revealer"},{"category":"Network","title":"Color-code resource types","defaultValue":false,"tags":"color code, resource type","settingName":"networkColorCodeResourceTypes","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Color code by resource type"},{"value":false,"title":"Use default colors"}]},{"category":"Network","title":"Group network log by frame","defaultValue":false,"tags":"network, frame, group","settingName":"network.group-by-frame","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Group network log items by frame"},{"value":false,"title":"Don't group network log items by frame"}]},{"iconClass":"largeicon-start-recording","toggledIconClass":"largeicon-stop-recording","className":"Network.NetworkPanel.RecordActionDelegate","toggleWithRedColor":true,"actionId":"network.toggle-recording","contextTypes":["Network.NetworkPanel"],"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+E"},{"platform":"mac","shortcut":"Meta+E"}],"type":"@UI.ActionDelegate","options":[{"value":true,"title":"Record network log"},{"value":false,"title":"Stop recording network log"}]},{"title":"Request blocking","id":"network.blocked-urls","className":"Network.BlockedURLsPane","location":"drawer-view","type":"view","order":60,"persistence":"closeable"},{"title":"Network conditions","tags":"disk cache, network throttling, useragent, user agent","id":"network.config","className":"Network.NetworkConfigView","location":"drawer-view","type":"view","order":40,"persistence":"closeable"}],"name":"network","scripts":["network_module.js"]},{"dependencies":["workspace","diff"],"name":"workspace_diff","scripts":["workspace_diff_module.js"]},{"dependencies":["components","emulation"],"extensions":[{"className":"Screencast.ScreencastAppProvider","type":"@Common.AppProvider","order":1},{"className":"Screencast.ScreencastApp.ToolbarButtonProvider","type":"@UI.ToolbarItem.Provider","order":1,"location":"main-toolbar-left"},{"actionId":"components.request-app-banner","type":"context-menu-item","location":"mainMenu","condition":"remoteFrontend","order":10}],"name":"screencast","scripts":["screencast_module.js"]},{"dependencies":["ui","sdk","bindings","source_frame","text_editor"],"extensions":[{"className":"PerfUI.LineLevelProfile.LineDecorator","decoratorType":"performance","type":"@SourceFrame.UISourceCodeFrame.LineDecorator"},{"category":"Performance","title":"Flamechart mouse wheel action:","defaultValue":"zoom","settingName":"flamechartMouseWheelAction","settingType":"enum","type":"setting","options":[{"text":"Scroll","value":"scroll","title":"Scroll"},{"text":"Zoom","value":"zoom","title":"Zoom"}]}],"name":"perf_ui","scripts":["perf_ui_module.js"]},{"dependencies":["common","sdk","ui"],"extensions":[{"category":"Appearance","title":"Show third party URL badges","defaultValue":false,"settingName":"product_registry.badges-visible","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show third party badges"},{"value":false,"title":"Do not show third party badges"}]}],"name":"product_registry"},{"experiment":"terminalInDrawer","extensions":[{"title":"Terminal","id":"drawer.xterm","factoryName":"Terminal.TerminalWidget","location":"drawer-view","type":"view","order":10,"persistence":"closeable"}],"name":"terminal","dependencies":["components","ui","services"],"scripts":["terminal_module.js"],"skip_compilation":["xterm.js/build/xterm.js","xterm.js/addons/fit/fit.js"]},{"dependencies":[],"name":"platform"},{"dependencies":["elements"],"extensions":[{"title":"Animations","id":"animations","className":"Animation.AnimationTimeline","location":"drawer-view","type":"view","order":0,"persistence":"closeable"}],"name":"animation","scripts":["animation_module.js"]},{"dependencies":["text_editor","ui","platform","persistence","formatter","object_ui","workspace_diff"],"extensions":[{"category":"Sources","title":"Default indentation:","defaultValue":" ","settingName":"textEditorIndent","settingType":"enum","type":"setting","options":[{"text":"2 spaces","value":" ","title":"Set indentation to 2 spaces"},{"text":"4 spaces","value":" ","title":"Set indentation to 4 spaces"},{"text":"8 spaces","value":" ","title":"Set indentation to 8 spaces"},{"text":"Tab character","value":"\t","title":"Set indentation to tab character"}]}],"name":"source_frame","scripts":["source_frame_module.js"]},{"dependencies":["extensions","host","platform","sdk","persistence","help","console_model","network_log","console_counters"],"extensions":[{"className":"Main.SimpleAppProvider","type":"@Common.AppProvider","order":10},{"className":"Components.Linkifier.ContentProviderContextMenuProvider","contextTypes":["Workspace.UISourceCode","SDK.Resource","SDK.NetworkRequest"],"type":"@UI.ContextMenu.Provider"},{"className":"UI.ExternaLinkContextMenuProvider","contextTypes":["Node"],"type":"@UI.ContextMenu.Provider"},{"className":"Components.Linkifier.LinkContextMenuProvider","contextTypes":["Node"],"type":"@UI.ContextMenu.Provider"},{"category":"Navigation","iconClass":"largeicon-refresh","title":"Reload page","className":"Main.Main.ReloadActionDelegate","actionId":"main.reload","bindings":[{"platform":"windows,linux","shortcut":"F5 Ctrl+R"},{"platform":"mac","shortcut":"Meta+R"}],"type":"@UI.ActionDelegate"},{"category":"Navigation","title":"Hard reload page","className":"Main.Main.ReloadActionDelegate","actionId":"main.hard-reload","bindings":[{"platform":"windows,linux","shortcut":"Shift+F5 Ctrl+F5 Ctrl+Shift+F5 Shift+Ctrl+R"},{"platform":"mac","shortcut":"Shift+Meta+R"}],"type":"@UI.ActionDelegate"},{"category":"Drawer","title":"Toggle drawer","className":"UI.InspectorView.DrawerToggleActionDelegate","actionId":"main.toggle-drawer","bindings":[{"shortcut":"Esc"}],"type":"@UI.ActionDelegate","order":100},{"className":"Main.Main.ReloadActionDelegate","bindings":[{"shortcut":"Alt+R"}],"type":"@UI.ActionDelegate","actionId":"main.debug-reload"},{"category":"DevTools","title":"Restore last dock position","className":"Components.DockController.ToggleDockActionDelegate","actionId":"main.toggle-dock","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Shift+D"},{"platform":"mac","shortcut":"Meta+Shift+D"}],"type":"@UI.ActionDelegate"},{"className":"Main.Main.ZoomActionDelegate","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Plus Ctrl+Shift+Plus Ctrl+NumpadPlus Ctrl+Shift+NumpadPlus"},{"platform":"mac","shortcut":"Meta+Plus Meta+Shift+Plus Meta+NumpadPlus Meta+Shift+NumpadPlus"}],"type":"@UI.ActionDelegate","actionId":"main.zoom-in"},{"className":"Main.Main.ZoomActionDelegate","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Minus Ctrl+Shift+Minus Ctrl+NumpadMinus Ctrl+Shift+NumpadMinus"},{"platform":"mac","shortcut":"Meta+Minus Meta+Shift+Minus Meta+NumpadMinus Meta+Shift+NumpadMinus"}],"type":"@UI.ActionDelegate","actionId":"main.zoom-out"},{"className":"Main.Main.ZoomActionDelegate","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+0 Ctrl+Numpad0"},{"platform":"mac","shortcut":"Meta+0 Meta+Numpad0"}],"type":"@UI.ActionDelegate","actionId":"main.zoom-reset"},{"className":"Main.Main.SearchActionDelegate","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+F"},{"platform":"mac","shortcut":"Meta+F F3"}],"type":"@UI.ActionDelegate","actionId":"main.search-in-panel.find"},{"className":"Main.Main.SearchActionDelegate","bindings":[{"shortcut":"Esc"}],"type":"@UI.ActionDelegate","actionId":"main.search-in-panel.cancel","order":10},{"className":"Main.Main.SearchActionDelegate","bindings":[{"platform":"mac","shortcut":"Meta+G"}],"type":"@UI.ActionDelegate","actionId":"main.search-in-panel.find-next"},{"className":"Main.Main.SearchActionDelegate","bindings":[{"platform":"mac","shortcut":"Meta+Shift+G"}],"type":"@UI.ActionDelegate","actionId":"main.search-in-panel.find-previous"},{"separator":true,"type":"@UI.ToolbarItem.Provider","location":"main-toolbar-left","order":100},{"className":"Main.Main.NodeIndicator","type":"@UI.ToolbarItem.Provider","order":2,"condition":"!nodeFrontend","location":"main-toolbar-left"},{"separator":true,"type":"@UI.ToolbarItem.Provider","order":98,"location":"main-toolbar-right"},{"className":"Main.Main.MainMenuItem","type":"@UI.ToolbarItem.Provider","order":99,"location":"main-toolbar-right"},{"className":"Components.DockController.CloseButtonProvider","type":"@UI.ToolbarItem.Provider","order":100,"location":"main-toolbar-right"},{"category":"Network","title":"Disable cache (while DevTools is open)","defaultValue":false,"options":[{"value":true,"title":"Disable cache (while DevTools is open)"},{"value":false,"title":"Enable cache"}],"userActionCondition":"hasOtherClients","settingName":"cacheDisabled","settingType":"boolean","type":"setting","order":0},{"category":"Network","title":"Force ad blocking on this site","storageType":"session","defaultValue":false,"settingName":"network.adBlockingEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Block ads on this site"},{"value":false,"title":"Show ads on this site, if allowed"}]},{"category":"DevTools","title":"Auto-open DevTools for popups","defaultValue":false,"options":[{"value":true,"title":"Auto-open DevTools for popups"},{"value":false,"title":"Do not auto-open DevTools for popups"}],"settingName":"autoAttachToCreatedPages","settingType":"boolean","type":"setting","order":2},{"category":"Appearance","title":"Theme:","defaultValue":"default","tags":"dark, light","settingName":"uiTheme","settingType":"enum","type":"setting","options":[{"text":"Light","value":"default","title":"Switch to light theme"},{"text":"Dark","value":"dark","title":"Switch to dark theme"}]},{"category":"Appearance","title":"Panel layout:","defaultValue":"auto","settingName":"sidebarPosition","settingType":"enum","type":"setting","options":[{"text":"horizontal","value":"bottom","title":"Use horizontal panel layout"},{"text":"vertical","value":"right","title":"Use vertical panel layout"},{"text":"auto","value":"auto","title":"Use automatic panel layout"}]},{"category":"Appearance","title-mac":"Enable \u2318 + 1-9 shortcut to switch panels","title":"Enable Ctrl + 1-9 shortcut to switch panels","defaultValue":false,"settingName":"shortcutPanelSwitch","settingType":"boolean","type":"setting"},{"category":"Appearance","title":"Don't show Chrome Data Saver warning","defaultValue":false,"settingName":"disableDataSaverInfobar","settingType":"boolean","type":"setting"},{"category":"Appearance","title":"Disable paused state overlay","defaultValue":false,"settingName":"disablePausedStateOverlay","settingType":"boolean","type":"setting"},{"category":"Extensions","className":"Components.Linkifier.LinkHandlerSettingUI","type":"@UI.SettingUI"},{"category":"Elements","className":"Main.ShowMetricsRulersSettingUI","type":"@UI.SettingUI","order":3},{"title":"Rendering","condition":"!v8only","id":"rendering","className":"Main.RenderingOptionsView","location":"drawer-view","type":"view","order":50,"persistence":"closeable"},{"category":"DevTools","defaultValue":"right","settingName":"currentDockState","settingType":"enum","type":"setting","options":[{"text":"Right","value":"right","title":"Dock to right"},{"text":"Bottom","value":"bottom","title":"Dock to bottom"},{"text":"Undocked","value":"undocked","title":"Undock into separate window"}]},{"category":"Drawer","className":"UI.InspectorView","type":"@UI.ViewLocationResolver","name":"drawer-view"},{"category":"Panel","className":"UI.InspectorView","type":"@UI.ViewLocationResolver","name":"panel"},{"iconClass":"largeicon-trash-bin","className":"Main.GCActionDelegate","type":"@UI.ActionDelegate","actionId":"components.collect-garbage","title":"Collect garbage"},{"category":"Mobile","className":"Main.RequestAppBannerActionDelegate","type":"@UI.ActionDelegate","actionId":"components.request-app-banner","title":"Add to homescreen"}],"name":"main"},{"dependencies":["source_frame","cookie_table","inline_editor","data_grid","components","object_ui","perf_ui","mobile_throttling","network"],"extensions":[{"title":"Application","id":"resources","className":"Resources.ResourcesPanel","location":"panel","type":"view","order":70},{"className":"Resources.ResourcesPanel.ResourceRevealer","contextTypes":["SDK.Resource"],"type":"@Common.Revealer"}],"name":"resources","scripts":["resources_module.js"]},{"dependencies":["text_utils","platform"],"name":"common"},{"dependencies":["ui"],"name":"inline_editor","scripts":["inline_editor_module.js"]},{"dependencies":["common","ui","console_model"],"extensions":[{"className":"ConsoleCounters.WarningErrorCounter","type":"@UI.ToolbarItem.Provider","order":1,"location":"main-toolbar-right"}],"name":"console_counters"},{"dependencies":["sdk"],"extensions":[{"category":"Network","title":"Preserve log","storageType":"session","defaultValue":false,"tags":"preserve, clear, reset","settingName":"network_log.preserve-log","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Do not preserve log on page reload / navigation"},{"value":false,"title":"Preserve log on page reload / navigation"}]}],"name":"network_log"},{"dependencies":["components","extensions","inline_editor","color_picker","event_listeners"],"extensions":[{"title":"Elements","id":"elements","className":"Elements.ElementsPanel","location":"panel","type":"view","order":10},{"className":"Elements.ElementsPanel.ContextMenuProvider","contextTypes":["SDK.RemoteObject","SDK.DOMNode","SDK.DeferredDOMNode"],"type":"@UI.ContextMenu.Provider"},{"className":"Elements.ElementsTreeOutline.Renderer","contextTypes":["SDK.DOMNode","SDK.DeferredDOMNode"],"type":"@Common.Renderer"},{"className":"Elements.ElementsPanel.DOMNodeRevealer","contextTypes":["SDK.DOMNode","SDK.DeferredDOMNode","SDK.RemoteObject"],"type":"@Common.Revealer"},{"className":"Elements.ElementsPanel.CSSPropertyRevealer","contextTypes":["SDK.CSSProperty"],"type":"@Common.Revealer"},{"category":"Elements","title":"Color format:","defaultValue":"original","options":[{"text":"As authored","value":"original","title":"Set color format as authored"},{"raw":true,"text":"HEX: #dac0de","value":"hex","title":"Set color format to HEX"},{"raw":true,"text":"RGB: rgb(128, 255, 255)","value":"rgb","title":"Set color format to RGB"},{"raw":true,"text":"HSL: hsl(300, 80%, 90%)","value":"hsl","title":"Set color format to HSL"}],"settingName":"colorFormat","settingType":"enum","type":"setting","order":0},{"category":"Elements","title":"Show user agent shadow DOM","defaultValue":false,"settingName":"showUAShadowDOM","settingType":"boolean","type":"setting","order":1},{"category":"Elements","title":"Word wrap","defaultValue":true,"options":[{"value":true,"title":"Enable DOM word wrap"},{"value":false,"title":"Disable DOM word wrap"}],"settingName":"domWordWrap","settingType":"boolean","type":"setting","order":2},{"category":"Elements","title":"Show HTML comments","defaultValue":true,"options":[{"value":true,"title":"Show HTML comments"},{"value":false,"title":"Hide HTML comments"}],"settingName":"showHTMLComments","settingType":"boolean","type":"setting","order":3},{"category":"Elements","title":"Reveal DOM node on hover","defaultValue":true,"settingName":"highlightNodeOnHoverInOverlay","settingType":"boolean","type":"setting","order":4},{"defaultValue":true,"type":"setting","settingName":"showEventListenersForAncestors","settingType":"boolean"},{"className":"Elements.ElementStatePaneWidget.ButtonProvider","type":"@UI.ToolbarItem.Provider","order":1,"location":"styles-sidebarpane-toolbar"},{"className":"Elements.ClassesPaneWidget.ButtonProvider","type":"@UI.ToolbarItem.Provider","order":2,"location":"styles-sidebarpane-toolbar"},{"className":"Elements.StylesSidebarPane.ButtonProvider","type":"@UI.ToolbarItem.Provider","order":100,"location":"styles-sidebarpane-toolbar"},{"className":"Elements.ElementsActionDelegate","contextTypes":["Elements.ElementsPanel"],"bindings":[{"shortcut":"H"}],"type":"@UI.ActionDelegate","actionId":"elements.hide-element"},{"className":"Elements.ElementsActionDelegate","contextTypes":["Elements.ElementsPanel"],"bindings":[{"shortcut":"F2"}],"type":"@UI.ActionDelegate","actionId":"elements.edit-as-html"},{"className":"Elements.ElementsPanel.PseudoStateMarkerDecorator","marker":"pseudo-state-marker","type":"@Components.DOMPresentationUtils.MarkerDecorator"},{"marker":"hidden-marker","factoryName":"Components.DOMPresentationUtils.GenericDecorator","type":"@Components.DOMPresentationUtils.MarkerDecorator","color":"#555","title":"Element is hidden"},{"iconClass":"largeicon-node-search","title":"Select an element in the page to inspect it","className":"Elements.InspectElementModeController.ToggleSearchActionDelegate","actionId":"elements.toggle-element-search","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Shift+C"},{"platform":"mac","shortcut":"Meta+Shift+C"}],"type":"@UI.ActionDelegate"},{"order":0,"type":"@UI.ToolbarItem.Provider","actionId":"elements.toggle-element-search","location":"main-toolbar-left"},{"category":"Elements","className":"Elements.ElementsPanel","type":"@UI.ViewLocationResolver","name":"elements-sidebar"},{"title":"Event Listeners","id":"elements.eventListeners","className":"Elements.EventListenersWidget","location":"elements-sidebar","hasToolbar":true,"type":"view","order":5,"persistence":"permanent"},{"title":"Properties","id":"elements.domProperties","className":"Elements.PropertiesWidget","location":"elements-sidebar","type":"view","order":7,"persistence":"permanent"}],"name":"elements","scripts":["elements_module.js"]},{"dependencies":["common","host","platform"],"name":"workspace"},{"dependencies":["components","emulation","sdk","services","ui"],"extensions":[{"title":"Audits","id":"audits2","className":"Audits2.Audits2Panel","location":"panel","type":"view","order":90}],"name":"audits2","scripts":["audits2_module.js"]},{"dependencies":["components","layer_viewer","timeline_model","perf_ui","extensions","data_grid","product_registry","mobile_throttling","network_priorities"],"extensions":[{"title":"Performance","id":"timeline","className":"Timeline.TimelinePanel","location":"panel","type":"view","order":50},{"title":"Performance monitor","tags":"performance, system monitor, monitor, activity, metrics","id":"performance.monitor","className":"Timeline.PerformanceMonitor","experiment":"performanceMonitor","location":"drawer-view","type":"view","order":100,"persistence":"closeable"},{"category":"Performance","title":"Hide chrome frame in Layers view","defaultValue":false,"settingName":"frameViewerHideChromeWindow","settingType":"boolean","type":"setting"},{"className":"Timeline.LoadTimelineHandler","type":"@Common.QueryParamHandler","name":"loadTimelineFromURL"},{"order":10,"type":"context-menu-item","location":"timelineMenu/open","actionId":"timeline.load-from-file"},{"order":15,"type":"context-menu-item","location":"timelineMenu/open","actionId":"timeline.save-to-file"},{"iconClass":"largeicon-start-recording","toggledIconClass":"largeicon-stop-recording","className":"Timeline.TimelinePanel.ActionDelegate","toggleWithRedColor":true,"actionId":"timeline.toggle-recording","contextTypes":["Timeline.TimelinePanel"],"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+E"},{"platform":"mac","shortcut":"Meta+E"}],"type":"@UI.ActionDelegate","options":[{"value":true,"title":"Record"},{"value":false,"title":"Stop"}]},{"iconClass":"largeicon-refresh","category":"Performance","title":"Start profiling and reload page","className":"Timeline.TimelinePanel.ActionDelegate","contextTypes":["Timeline.TimelinePanel"],"actionId":"timeline.record-reload","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Shift+E"},{"platform":"mac","shortcut":"Meta+Shift+E"}],"type":"@UI.ActionDelegate"},{"category":"Timeline","title":"Save profile\u2026","className":"Timeline.TimelinePanel.ActionDelegate","contextTypes":["Timeline.TimelinePanel"],"actionId":"timeline.save-to-file","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+S"},{"platform":"mac","shortcut":"Meta+S"}],"type":"@UI.ActionDelegate"},{"category":"Timeline","title":"Load profile\u2026","className":"Timeline.TimelinePanel.ActionDelegate","contextTypes":["Timeline.TimelinePanel"],"actionId":"timeline.load-from-file","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+O"},{"platform":"mac","shortcut":"Meta+O"}],"type":"@UI.ActionDelegate"},{"className":"Timeline.TimelinePanel.ActionDelegate","contextTypes":["Timeline.TimelinePanel"],"bindings":[{"shortcut":"["}],"type":"@UI.ActionDelegate","actionId":"timeline.jump-to-previous-frame"},{"className":"Timeline.TimelinePanel.ActionDelegate","contextTypes":["Timeline.TimelinePanel"],"bindings":[{"shortcut":"]"}],"type":"@UI.ActionDelegate","actionId":"timeline.jump-to-next-frame"},{"category":"Performance","title":"Show recent timeline sessions","className":"Timeline.TimelinePanel.ActionDelegate","experiment":"timelineKeepHistory","contextTypes":["Timeline.TimelinePanel"],"actionId":"timeline.show-history","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+H"},{"platform":"mac","shortcut":"Meta+Y"}],"type":"@UI.ActionDelegate"}],"name":"timeline","scripts":["timeline_module.js"]},{"dependencies":["ui","diff"],"extensions":[{"className":"QuickOpen.CommandMenuProvider","prefix":">","type":"@QuickOpen.FilteredListWidget.Provider","title":"Run command"},{"className":"QuickOpen.HelpQuickOpen","prefix":"?","type":"@QuickOpen.FilteredListWidget.Provider"},{"className":"QuickOpen.CommandMenu.ShowActionDelegate","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Shift+P"},{"platform":"mac","shortcut":"Meta+Shift+P"}],"type":"@UI.ActionDelegate","actionId":"commandMenu.show"},{"title":"Open file","className":"QuickOpen.QuickOpen.ShowActionDelegate","actionId":"quickOpen.show","bindings":[{"platform":"mac","shortcut":"Meta+P Meta+O"},{"platform":"windows,linux","shortcut":"Ctrl+P Ctrl+O"}],"type":"@UI.ActionDelegate","order":100},{"type":"context-menu-item","location":"mainMenu/default","actionId":"quickOpen.show"}],"name":"quick_open","scripts":["quick_open_module.js"]},{"dependencies":["ui"],"name":"data_grid","scripts":["data_grid_module.js"]},{"dependencies":["bindings","components","platform","ui","mobile_throttling"],"extensions":[{"className":"Emulation.AdvancedAppProvider","type":"@Common.AppProvider","order":0,"condition":"can_dock"},{"category":"Mobile","iconClass":"largeicon-phone","title":"Toggle device toolbar","className":"Emulation.DeviceModeWrapper.ActionDelegate","actionId":"emulation.toggle-device-mode","bindings":[{"platform":"windows,linux","shortcut":"Shift+Ctrl+M"},{"platform":"mac","shortcut":"Shift+Meta+M"}],"type":"@UI.ActionDelegate","condition":"can_dock"},{"category":"Mobile","tags":"device","title":"Capture screenshot","className":"Emulation.DeviceModeWrapper.ActionDelegate","actionId":"emulation.capture-screenshot","type":"@UI.ActionDelegate"},{"actionId":"emulation.capture-screenshot","type":"context-menu-item","location":"deviceModeMenu/tools","order":12},{"order":1,"type":"@UI.ToolbarItem.Provider","actionId":"emulation.toggle-device-mode","condition":"can_dock","location":"main-toolbar-left"},{"category":"Mobile","tags":"device","title":"Capture full size screenshot","className":"Emulation.DeviceModeWrapper.ActionDelegate","actionId":"emulation.capture-full-height-screenshot","type":"@UI.ActionDelegate"},{"category":"Mobile","tags":"device","title":"Capture node screenshot","className":"Emulation.DeviceModeWrapper.ActionDelegate","actionId":"emulation.capture-node-screenshot","type":"@UI.ActionDelegate"},{"actionId":"emulation.capture-full-height-screenshot","type":"context-menu-item","location":"deviceModeMenu/tools","order":13},{"category":"Mobile","tags":"device","defaultValue":false,"settingName":"showMediaQueryInspector","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show media queries"},{"value":false,"title":"Hide media queries"}]},{"category":"Mobile","tags":"device","defaultValue":false,"settingName":"emulation.showRulers","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show rulers"},{"value":false,"title":"Hide rulers"}]},{"category":"Mobile","tags":"device","defaultValue":false,"settingName":"emulation.showDeviceOutline","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show device frame"},{"value":false,"title":"Hide device frame"}]},{"title":"Devices","settings":["standardEmulatedDeviceList","customEmulatedDeviceList"],"id":"devices","className":"Emulation.DevicesSettingsTab","location":"settings-view","type":"view","order":30},{"className":"Emulation.SensorsView.ShowActionDelegate","type":"@UI.ActionDelegate","actionId":"emulation.show-sensors","condition":"!v8only","title":"Sensors"},{"title":"Sensors","tags":"geolocation, accelerometer, device orientation","condition":"!v8only","order":100,"className":"Emulation.SensorsView","location":"drawer-view","type":"view","id":"sensors","persistence":"closeable"}],"name":"emulation"},{"dependencies":["sdk","ui","source_frame","sources","data_grid"],"extensions":[{"title":"Coverage","order":100,"className":"Coverage.CoverageView","location":"drawer-view","type":"view","id":"coverage","persistence":"closeable"},{"className":"Coverage.CoverageView.LineDecorator","decoratorType":"coverage","type":"@SourceFrame.UISourceCodeFrame.LineDecorator"},{"iconClass":"largeicon-start-recording","toggledIconClass":"largeicon-stop-recording","className":"Coverage.CoverageView.ActionDelegate","toggleWithRedColor":true,"actionId":"coverage.toggle-recording","category":"Performance","type":"@UI.ActionDelegate","options":[{"value":true,"title":"Instrument coverage"},{"value":false,"title":"Stop instrumenting coverage and show results"}]},{"iconClass":"largeicon-refresh","category":"Performance","title":"Start instrumenting coverage and reload page","className":"Coverage.CoverageView.ActionDelegate","actionId":"coverage.start-with-reload","type":"@UI.ActionDelegate"}],"name":"coverage","scripts":["coverage_module.js"]},{"dependencies":["common","host"],"name":"services"},{"dependencies":["platform","dom_extension","common","host"],"name":"ui"},{"dependencies":["ui","common","components","sdk","object_ui"],"name":"event_listeners","scripts":["event_listeners_module.js"]},{"dependencies":["platform"],"name":"dom_extension"},{"dependencies":["common","sdk","ui","protocol"],"extensions":[{"defaultValue":[],"type":"setting","settingName":"customNetworkConditions","settingType":"array"},{"category":"Network","tags":"device","title":"Go offline","className":"MobileThrottling.ThrottlingManager.ActionDelegate","actionId":"network-conditions.network-offline","type":"@UI.ActionDelegate"},{"category":"Network","tags":"device","title":"Go online","className":"MobileThrottling.ThrottlingManager.ActionDelegate","actionId":"network-conditions.network-online","type":"@UI.ActionDelegate"},{"title":"Throttling","settings":["customNetworkConditions"],"id":"throttling-conditions","className":"MobileThrottling.ThrottlingSettingsTab","location":"settings-view","type":"view","order":35}],"name":"mobile_throttling"},{"skip_compilation":["../SupportedCSSProperties.js"],"dependencies":["common","host","platform","protocol"],"extensions":[{"defaultValue":"","type":"setting","settingName":"skipStackFramesPattern","settingType":"regex"},{"defaultValue":false,"type":"setting","settingName":"skipContentScripts","settingType":"boolean"},{"category":"Console","title":"Preserve log upon navigation","defaultValue":false,"settingName":"preserveConsoleLog","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Preserve log upon navigation"},{"value":false,"title":"Do not preserve log upon navigation"}]},{"category":"Debugger","defaultValue":false,"settingName":"pauseOnExceptionEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Pause on exceptions"},{"value":false,"title":"Do not pause on exceptions"}]},{"defaultValue":false,"type":"setting","settingName":"pauseOnCaughtException","settingType":"boolean"},{"category":"Debugger","title":"Disable JavaScript","storageType":"session","defaultValue":false,"options":[{"value":true,"title":"Disable JavaScript"},{"value":false,"title":"Enable JavaScript"}],"settingName":"javaScriptDisabled","settingType":"boolean","type":"setting","order":1},{"category":"Debugger","title":"Disable async stack traces","defaultValue":false,"options":[{"value":true,"title":"Do not capture async stack traces"},{"value":false,"title":"Capture async stack traces"}],"settingName":"disableAsyncStackTraces","settingType":"boolean","type":"setting","order":2},{"defaultValue":false,"type":"setting","settingName":"showMetricsRulers","settingType":"boolean"},{"category":"Rendering","storageType":"session","defaultValue":false,"settingName":"showPaintRects","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show paint flashing rectangles"},{"value":false,"title":"Hide paint flashing rectangles"}]},{"category":"Rendering","storageType":"session","defaultValue":false,"settingName":"showDebugBorders","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show layer borders"},{"value":false,"title":"Hide layer borders"}]},{"category":"Rendering","storageType":"session","defaultValue":false,"settingName":"showFPSCounter","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show frames per second (FPS) meter"},{"value":false,"title":"Hide frames per second (FPS) meter"}]},{"category":"Rendering","storageType":"session","defaultValue":false,"settingName":"showScrollBottleneckRects","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show scroll performance bottlenecks"},{"value":false,"title":"Hide scroll performance bottlenecks"}]},{"category":"Rendering","tags":"query","storageType":"session","defaultValue":"","settingName":"emulatedCSSMedia","settingType":"enum","type":"setting","options":[{"text":"No emulation","value":"","title":"Do not emulate CSS media type"},{"text":"print","value":"print","title":"Emulate CSS print media type"},{"text":"screen","value":"screen","title":"Emulate CSS screen media type"}]},{"category":"Console","title":"Enable custom formatters","defaultValue":false,"settingName":"customFormatters","settingType":"boolean","type":"setting"},{"category":"Network","title":"Enable request blocking","storageType":"session","defaultValue":false,"settingName":"requestBlockingEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Enable request blocking"},{"value":false,"title":"Disable request blocking"}]}],"name":"sdk"},{"dependencies":["common"],"name":"formatter","scripts":["formatter_module.js"]},{"dependencies":["platform","common","diff","sdk","formatter"],"extensions":[{"className":"Sass.SASSSourceMapFactory","extensions":["scss"],"experiment":"liveSASS","type":"@SDK.SourceMapFactory"}],"name":"sass","scripts":["sass_module.js"]},{"dependencies":["components"],"extensions":[{"category":"Settings","title":"Settings","className":"Settings.SettingsScreen.ActionDelegate","actionId":"settings.show","bindings":[{"shortcut":"F1 Shift+?"}],"type":"@UI.ActionDelegate"},{"category":"Settings","className":"Settings.SettingsScreen.ActionDelegate","type":"@UI.ActionDelegate","actionId":"settings.documentation","title":"Documentation"},{"category":"Settings","className":"Settings.SettingsScreen.ActionDelegate","type":"@UI.ActionDelegate","actionId":"settings.shortcuts","title":"Shortcuts"},{"className":"Settings.SettingsScreen.Revealer","contextTypes":["Common.Setting"],"type":"@Common.Revealer"},{"type":"context-menu-item","location":"mainMenu/footer","actionId":"settings.shortcuts"},{"type":"context-menu-item","location":"mainMenu/footer","actionId":"settings.show"},{"title":"Preferences","id":"preferences","className":"Settings.GenericSettingsTab","location":"settings-view","type":"view","order":0},{"title":"Experiments","id":"experiments","className":"Settings.ExperimentsSettingsTab","experiment":"*","location":"settings-view","type":"view","order":2},{"title":"Blackboxing","id":"blackbox","className":"Settings.FrameworkBlackboxSettingsTab","location":"settings-view","type":"view","order":3},{"category":"Settings","className":"Settings.SettingsScreen","type":"@UI.ViewLocationResolver","name":"settings-view"}],"name":"settings","scripts":["settings_module.js"]},{"dependencies":["sdk","network_log"],"name":"console_model"},{"dependencies":["common","platform"],"name":"host"},{"dependencies":["platform","ui","host","components"],"extensions":[{"title":"Remote devices","tags":"usb, android, mobile","condition":"!v8only","id":"remote-devices","className":"Devices.DevicesView","location":"drawer-view","type":"view","order":50,"persistence":"closeable"},{"title":"Connection","tags":"node","id":"node-connection","className":"Devices.DevicesView.Panel","location":"panel","type":"view","order":0,"condition":"nodeFrontend"}],"name":"devices","scripts":["devices_module.js"]},{"dependencies":["components","perf_ui","data_grid","heap_snapshot_model","object_ui"],"extensions":[{"title":"Memory","id":"heap_profiler","className":"Profiler.HeapProfilerPanel","location":"panel","type":"view","order":60},{"title":"Profiler","id":"js_profiler","className":"Profiler.JSProfilerPanel","location":"panel","type":"view","order":65,"condition":"v8only"},{"title":"JavaScript Profiler","condition":"!v8only","id":"js_profiler","className":"Profiler.JSProfilerPanel","location":"panel","type":"view","order":65,"persistence":"closeable"},{"className":"Profiler.HeapProfilerPanel","contextTypes":["SDK.RemoteObject"],"type":"@UI.ContextMenu.Provider"},{"category":"Performance","title":"Record heap allocation stack traces","defaultValue":false,"settingName":"recordAllocationStacks","settingType":"boolean","type":"setting"},{"category":"Performance","title":"High resolution CPU profiling","defaultValue":true,"settingName":"highResolutionCpuProfiling","settingType":"boolean","type":"setting"},{"category":"Performance","title":"Show native functions in JS Profile","defaultValue":true,"settingName":"showNativeFunctionsInJSProfile","settingType":"boolean","type":"setting"},{"iconClass":"largeicon-start-recording","toggledIconClass":"largeicon-stop-recording","className":"Profiler.HeapProfilerPanel","toggleWithRedColor":true,"actionId":"profiler.heap-toggle-recording","contextTypes":["Profiler.HeapProfilerPanel"],"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+E"},{"platform":"mac","shortcut":"Meta+E"}],"type":"@UI.ActionDelegate"},{"iconClass":"largeicon-start-recording","toggledIconClass":"largeicon-stop-recording","className":"Profiler.JSProfilerPanel","toggleWithRedColor":true,"actionId":"profiler.js-toggle-recording","contextTypes":["Profiler.JSProfilerPanel"],"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+E"},{"platform":"mac","shortcut":"Meta+E"}],"type":"@UI.ActionDelegate"}],"name":"profiler","scripts":["profiler_module.js"]},{"dependencies":["ui","sdk"],"name":"color_picker","scripts":["color_picker_module.js"]},{"dependencies":["components","network_log","common"],"name":"extensions"},{"dependencies":["bindings","workspace","components","sdk"],"extensions":[{"title":"Workspace","id":"workspace","className":"Persistence.WorkspaceSettingsTab","location":"settings-view","type":"view","order":1},{"category":"Persistence","title":"Enable Network Overrides","storageType":"session","defaultValue":false,"tags":"interception, override, network, rewrite, request","settingName":"persistenceNetworkOverridesEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Enable override network requests"},{"value":false,"title":"Disable override network requests"}]},{"className":"Persistence.PersistenceActions.ContextMenuProvider","contextTypes":["Workspace.UISourceCode","SDK.Resource","SDK.NetworkRequest"],"type":"@UI.ContextMenu.Provider"}],"name":"persistence"},{"dependencies":["bindings","platform","ui","network_log"],"extensions":[{"marker":"breakpoint-marker","factoryName":"Components.DOMPresentationUtils.GenericDecorator","type":"@Components.DOMPresentationUtils.MarkerDecorator","color":"rgb(105, 140, 254)","title":"DOM Breakpoint"},{"className":"Components.DOMBreakpointsSidebarPane.ContextMenuProvider","contextTypes":["SDK.DOMNode"],"type":"@UI.ContextMenu.Provider"},{"className":"Components.DOMBreakpointsSidebarPane","contextTypes":["SDK.DebuggerPausedDetails"],"type":"@UI.ContextFlavorListener"},{"title":"DOM Breakpoints","id":"sources.domBreakpoints","factoryName":"Components.DOMBreakpointsSidebarPane","location":"sources-sidebar","type":"view","order":7,"persistence":"permanent"},{"title":"DOM Breakpoints","id":"elements.domBreakpoints","factoryName":"Components.DOMBreakpointsSidebarPane","location":"elements-sidebar","type":"view","order":6,"persistence":"permanent"}],"name":"components"},{"dependencies":["ui","sdk","components"],"extensions":[{"className":"ObjectUI.ObjectPropertiesSection.Renderer","contextTypes":["SDK.RemoteObject"],"type":"@Common.Renderer"}],"name":"object_ui","scripts":["object_ui_module.js"]},{"dependencies":["sdk"],"name":"timeline_model","scripts":["timeline_model_module.js"]},{"dependencies":["network","platform","ui","sdk"],"extensions":[{"title":"Security","id":"security","className":"Security.SecurityPanel","location":"panel","type":"view","order":80}],"name":"security","scripts":["security_module.js"]},{"dependencies":["workspace_diff","text_editor","workspace","diff","bindings","persistence","ui"],"extensions":[{"title":"Changes","className":"Changes.ChangesView","experiment":"changesDrawer","location":"drawer-view","type":"view","id":"changes.changes","persistence":"closeable"}],"name":"changes","scripts":["changes_module.js"]},{"dependencies":["platform"],"name":"text_utils"}];var applicationDescriptor;var _loadedScripts={};for(var k of[]){} -(function(){var baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();var Runtime=class{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(var i=0;i<descriptors.length;++i) -this._registerModule(descriptors[i]);} -static loadResourcePromise(url){return new Promise(load);function load(fulfill,reject){var xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE) -return;if([0,200,304].indexOf(xhr.status)===-1) -reject(new Error('While loading from url '+url+' server responded with a status of '+xhr.status));else -fulfill(e.target.response);} -xhr.send(null);}} -static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1) -return path;var normalizedSegments=[];var segments=path.split('/');for(var i=0;i<segments.length;i++){var segment=segments[i];if(segment==='.') -continue;else if(segment==='..') -normalizedSegments.pop();else if(segment) -normalizedSegments.push(segment);} -var normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/') -return normalizedPath;if(path[0]==='/'&&normalizedPath) -normalizedPath='/'+normalizedPath;if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..')) -normalizedPath=normalizedPath+'/';return normalizedPath;} -static _loadScriptsPromise(scriptNames,base){var promises=[];var urls=[];var sources=new Array(scriptNames.length);var scriptToEval=0;for(var i=0;i<scriptNames.length;++i){var scriptName=scriptNames[i];var sourceURL=(base||self._importScriptPathPrefix)+scriptName;var schemaIndex=sourceURL.indexOf('://')+3;var pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1) -pathIndex=sourceURL.length;sourceURL=sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));if(_loadedScripts[sourceURL]) -continue;urls.push(sourceURL);promises.push(Runtime.loadResourcePromise(sourceURL).then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));} -return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}} -function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;} -self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}} -static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;} -var sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}} -static startApplication(appName){console.timeStamp('Runtime.startApplication');var allDescriptorsByName={};for(var i=0;i<allDescriptors.length;++i){var d=allDescriptors[i];allDescriptorsByName[d['name']]=d;} -var applicationPromise;if(applicationDescriptor) -applicationPromise=Promise.resolve(applicationDescriptor);else -applicationPromise=Runtime.loadResourcePromise(appName+'.json').then(JSON.parse.bind(JSON));return applicationPromise.then(parseModuleDescriptors);function parseModuleDescriptors(appDescriptor){var configuration=appDescriptor.modules;var moduleJSONPromises=[];var coreModuleNames=[];for(var i=0;i<configuration.length;++i){var descriptor=configuration[i];var name=descriptor['name'];var moduleJSON=allDescriptorsByName[name];if(moduleJSON) -moduleJSONPromises.push(Promise.resolve(moduleJSON));else -moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));if(descriptor['type']==='autostart') -coreModuleNames.push(name);} -return Promise.all(moduleJSONPromises).then(instantiateRuntime);function instantiateRuntime(moduleDescriptors){for(var i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';} -self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames) -return(self.runtime._loadAutoStartModules(coreModuleNames));return Promise.resolve();}}} -static startWorker(appName){return Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}} -static queryParam(name){return Runtime._queryParamsObject[name]||null;} -static queryParamsString(){return location.search;} -static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}} -static _assert(value,message){if(value) -return;Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);} -static setPlatform(platform){Runtime._platform=platform;} -static _isDescriptorEnabled(descriptor){var activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*') -return Runtime.experiments.supportEnabled();if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1))) -return false;if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment)) -return false;var condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition)) -return false;if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1))) -return false;return true;} -static resolveSourceURL(path){var sourceURL=self.location.href;if(self.location.search) -sourceURL=sourceURL.replace(self.location.search,'');sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';} -useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend')) -Runtime._remoteBase+='debug/';} -_registerModule(descriptor){var module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;} -loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();} -_loadAutoStartModules(moduleNames){var promises=[];for(var i=0;i<moduleNames.length;++i) -promises.push(this.loadModulePromise(moduleNames[i]));return Promise.all(promises);} -_checkExtensionApplicability(extension,predicate){if(!predicate) -return false;var contextTypes=extension.descriptor().contextTypes;if(!contextTypes) -return true;for(var i=0;i<contextTypes.length;++i){var contextType=this._resolve(contextTypes[i]);var isMatching=!!contextType&&predicate(contextType);if(isMatching) -return true;} -return false;} -isExtensionApplicableToContext(extension,context){if(!context) -return true;return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}} -isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes) -return true;return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}} -extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type) -return false;if(!extension.enabled()) -return false;return!context||extension.isApplicable(context);} -function orderComparator(extension1,extension2){var order1=extension1.descriptor()['order']||0;var order2=extension2.descriptor()['order']||0;return order1-order2;} -function titleComparator(extension1,extension2){var title1=extension1.title()||'';var title2=extension2.title()||'';return title1.localeCompare(title2);}} -extension(type,context){return this.extensions(type,context)[0]||null;} -allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));} -_resolve(typeName){if(!this._cachedTypeClasses[typeName]){var path=typeName.split('.');var object=self;for(var i=0;object&&(i<path.length);++i) -object=object[path[i]];if(object) -this._cachedTypeClasses[typeName]=(object);} -return this._cachedTypeClasses[typeName]||null;} -sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction) -return constructorFunction[Runtime._instanceSymbol];var instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}};Runtime._queryParamsObject={__proto__:null};Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';Runtime.ModuleDescriptor=class{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.condition;this.remote;}};Runtime.ExtensionDescriptor=class{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}};Runtime.Module=class{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();var extensions=(descriptor.extensions);for(var i=0;extensions&&i<extensions.length;++i){var extension=new Runtime.Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);} -this._loadedForTest=false;} -name(){return this._name;} -enabled(){return Runtime._isDescriptorEnabled(this._descriptor);} -resource(name){var fullName=this._name+'/'+name;var content=Runtime.cachedResources[fullName];if(!content) -throw new Error(fullName+' not preloaded. Check module.json');return content;} -_loadPromise(){if(!this.enabled()) -return Promise.reject(new Error('Module '+this._name+' is not enabled'));if(this._pendingLoadPromise) -return this._pendingLoadPromise;var dependencies=this._descriptor.dependencies;var dependencyPromises=[];for(var i=0;dependencies&&i<dependencies.length;++i) -dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;} -_loadResources(){var resources=this._descriptor['resources'];if(!resources||!resources.length) -return Promise.resolve();var promises=[];for(var i=0;i<resources.length;++i){var url=this._modularizeURL(resources[i]);promises.push(Runtime._loadResourceIntoCache(url,true));} -return Promise.all(promises).then(undefined);} -_loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length) -return Promise.resolve();const specialCases={'sdk':'SDK','ui':'UI','object_ui':'ObjectUI','perf_ui':'PerfUI','har_importer':'HARImporter','sass_test_runner':'SASSTestRunner','sdk_test_runner':'SDKTestRunner'};var namespace=specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());} -_modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);} -_remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;} -substituteURL(value){var base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}};Runtime.Extension=class{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;} -descriptor(){return this._descriptor;} -module(){return this._module;} -enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());} -_typeClass(){if(!this._hasTypeClass) -return null;return this._module._manager._resolve(this._type.substring(1));} -isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);} -instance(){return this._module._loadPromise().then(this._createInstance.bind(this));} -_createInstance(){var className=this._className||this._factoryName;if(!className) -throw new Error('Could not instantiate extension with no class');var constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function)) -throw new Error('Could not instantiate: '+className);if(this._className) -return this._module._manager.sharedInstance(constructorFunction);return new constructorFunction(this);} -title(){return this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];} -hasContextType(contextType){var contextTypes=this.descriptor().contextTypes;if(!contextTypes) -return false;for(var i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i])) -return true;} -return false;}};Runtime.ExperimentsSupport=class{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};} -allConfigurableExperiments(){var result=[];for(var i=0;i<this._experiments.length;i++){var experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name]) -result.push(experiment);} -return result;} -supportEnabled(){return this._supportEnabled;} -_setExperimentsSetting(value){if(!self.localStorage) -return;self.localStorage['experiments']=JSON.stringify(value);} -register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));} -isEnabled(experimentName){this._checkExperiment(experimentName);if(this._enabledTransiently[experimentName]) -return true;if(!this.supportEnabled()) -return false;return!!Runtime._experimentsSetting()[experimentName];} -setEnabled(experimentName,enabled){this._checkExperiment(experimentName);var experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);} -setDefaultExperiments(experimentNames){for(var i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}} -enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;} -clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};} -cleanUpStaleExperiments(){var experimentsSetting=Runtime._experimentsSetting();var cleanedUpExperimentSetting={};for(var i=0;i<this._experiments.length;++i){var experimentName=this._experiments[i].name;if(experimentsSetting[experimentName]) -cleanedUpExperimentSetting[experimentName]=true;} -this._setExperimentsSetting(cleanedUpExperimentSetting);} -_checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}};Runtime.Experiment=class{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;} -isEnabled(){return this._experiments.isEnabled(this.name);} -setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}};{(function parseQueryParameters(){var queryParams=Runtime.queryParamsString();if(!queryParams) -return;var params=queryParams.substring(1).split('&');for(var i=0;i<params.length;++i){var pair=params[i].split('=');var name=pair.shift();Runtime._queryParamsObject[name]=pair.join('=');}})();} -Runtime.experiments=new Runtime.ExperimentsSupport();Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('chrome-devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){var versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch) -Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}})();function ServicePort(){} -ServicePort.prototype={setHandlers(messageHandler,closeHandler){},send(message){},close(){}};var runtime;self['Platform']=self['Platform']||{};var ArrayLike;function mod(m,n){return((m%n)+n)%n;} -String.prototype.findAll=function(string){var matches=[];var i=this.indexOf(string);while(i!==-1){matches.push(i);i=this.indexOf(string,i+string.length);} -return matches;};String.prototype.reverse=function(){return this.split('').reverse().join('');};String.prototype.replaceControlCharacters=function(){return this.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u0080-\u009f]/g,'�');};String.prototype.isWhitespace=function(){return/^\s*$/.test(this);};String.prototype.computeLineEndings=function(){var endings=this.findAll('\n');endings.push(this.length);return endings;};String.prototype.escapeCharacters=function(chars){var foundChar=false;for(var i=0;i<chars.length;++i){if(this.indexOf(chars.charAt(i))!==-1){foundChar=true;break;}} -if(!foundChar) -return String(this);var result='';for(var i=0;i<this.length;++i){if(chars.indexOf(this.charAt(i))!==-1) -result+='\\';result+=this.charAt(i);} -return result;};String.regexSpecialCharacters=function(){return'^[]{}()\\.^$*+?|-,';};String.prototype.escapeForRegExp=function(){return this.escapeCharacters(String.regexSpecialCharacters());};String.prototype.escapeHTML=function(){return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');};String.prototype.unescapeHTML=function(){return this.replace(/</g,'<').replace(/>/g,'>').replace(/:/g,':').replace(/"/g,'"').replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');};String.prototype.collapseWhitespace=function(){return this.replace(/[\s\xA0]+/g,' ');};String.prototype.trimMiddle=function(maxLength){if(this.length<=maxLength) -return String(this);var leftHalf=maxLength>>1;var rightHalf=maxLength-leftHalf-1;if(this.codePointAt(this.length-rightHalf-1)>=0x10000){--rightHalf;++leftHalf;} -if(leftHalf>0&&this.codePointAt(leftHalf-1)>=0x10000) ---leftHalf;return this.substr(0,leftHalf)+'\u2026'+this.substr(this.length-rightHalf,rightHalf);};String.prototype.trimEnd=function(maxLength){if(this.length<=maxLength) -return String(this);return this.substr(0,maxLength-1)+'\u2026';};String.prototype.trimURL=function(baseURLDomain){var result=this.replace(/^(https|http|file):\/\//i,'');if(baseURLDomain){if(result.toLowerCase().startsWith(baseURLDomain.toLowerCase())) -result=result.substr(baseURLDomain.length);} -return result;};String.prototype.toTitleCase=function(){return this.substring(0,1).toUpperCase()+this.substring(1);};String.prototype.compareTo=function(other){if(this>other) -return 1;if(this<other) -return-1;return 0;};String.prototype.removeURLFragment=function(){var fragmentIndex=this.indexOf('#');if(fragmentIndex===-1) -fragmentIndex=this.length;return this.substring(0,fragmentIndex);};String.hashCode=function(string){if(!string) -return 0;var p=((1<<30)*4-5);var z=0x5033d967;var z2=0x59d2f15d;var s=0;var zi=1;for(var i=0;i<string.length;i++){var xi=string.charCodeAt(i)*z2;s=(s+zi*xi)%p;zi=(zi*z)%p;} -s=(s+zi*(p-1))%p;return Math.abs(s|0);};String.isDigitAt=function(string,index){var c=string.charCodeAt(index);return(48<=c&&c<=57);};String.prototype.toBase64=function(){function encodeBits(b){return b<26?b+65:b<52?b+71:b<62?b-4:b===62?43:b===63?47:65;} -var encoder=new TextEncoder();var data=encoder.encode(this.toString());var n=data.length;var encoded='';if(n===0) -return encoded;var shift;var v=0;for(var i=0;i<n;i++){shift=i%3;v|=data[i]<<(16>>>shift&24);if(shift===2){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),encodeBits(v&63));v=0;}} -if(shift===0) -encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),61,61);else if(shift===1) -encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),61);return encoded;};String.naturalOrderComparator=function(a,b){var chunk=/^\d+|^\D+/;var chunka,chunkb,anum,bnum;while(1){if(a){if(!b) -return 1;}else{if(b) -return-1;else -return 0;} -chunka=a.match(chunk)[0];chunkb=b.match(chunk)[0];anum=!isNaN(chunka);bnum=!isNaN(chunkb);if(anum&&!bnum) -return-1;if(bnum&&!anum) -return 1;if(anum&&bnum){var diff=chunka-chunkb;if(diff) -return diff;if(chunka.length!==chunkb.length){if(!+chunka&&!+chunkb) -return chunka.length-chunkb.length;else -return chunkb.length-chunka.length;}}else if(chunka!==chunkb){return(chunka<chunkb)?-1:1;} -a=a.substring(chunka.length);b=b.substring(chunkb.length);}};String.caseInsensetiveComparator=function(a,b){a=a.toUpperCase();b=b.toUpperCase();if(a===b) -return 0;return a>b?1:-1;};Number.constrain=function(num,min,max){if(num<min) -num=min;else if(num>max) -num=max;return num;};Number.gcd=function(a,b){if(b===0) -return a;else -return Number.gcd(b,a%b);};Number.toFixedIfFloating=function(value){if(!value||isNaN(value)) -return value;var number=Number(value);return number%1?number.toFixed(3):String(number);};Date.prototype.isValid=function(){return!isNaN(this.getTime());};Date.prototype.toISO8601Compact=function(){function leadZero(x){return(x>9?'':'0')+x;} -return this.getFullYear()+leadZero(this.getMonth()+1)+leadZero(this.getDate())+'T'+ -leadZero(this.getHours())+leadZero(this.getMinutes())+leadZero(this.getSeconds());};Object.defineProperty(Array.prototype,'remove',{value:function(value,firstOnly){var index=this.indexOf(value);if(index===-1) -return false;if(firstOnly){this.splice(index,1);return true;} -for(var i=index+1,n=this.length;i<n;++i){if(this[i]!==value) -this[index++]=this[i];} -this.length=index;return true;}});Object.defineProperty(Array.prototype,'pushAll',{value:function(array){for(var i=0;i<array.length;++i) -this.push(array[i]);}});Object.defineProperty(Array.prototype,'rotate',{value:function(index){var result=[];for(var i=index;i<index+this.length;++i) -result.push(this[i%this.length]);return result;}});Object.defineProperty(Array.prototype,'sortNumbers',{value:function(){function numericComparator(a,b){return a-b;} -this.sort(numericComparator);}});Object.defineProperty(Uint32Array.prototype,'sort',{value:Array.prototype.sort});(function(){var partition={value:function(comparator,left,right,pivotIndex){function swap(array,i1,i2){var temp=array[i1];array[i1]=array[i2];array[i2]=temp;} -var pivotValue=this[pivotIndex];swap(this,right,pivotIndex);var storeIndex=left;for(var i=left;i<right;++i){if(comparator(this[i],pivotValue)<0){swap(this,storeIndex,i);++storeIndex;}} -swap(this,right,storeIndex);return storeIndex;}};Object.defineProperty(Array.prototype,'partition',partition);Object.defineProperty(Uint32Array.prototype,'partition',partition);var sortRange={value:function(comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight){function quickSortRange(array,comparator,left,right,sortWindowLeft,sortWindowRight){if(right<=left) -return;var pivotIndex=Math.floor(Math.random()*(right-left))+left;var pivotNewIndex=array.partition(comparator,left,right,pivotIndex);if(sortWindowLeft<pivotNewIndex) -quickSortRange(array,comparator,left,pivotNewIndex-1,sortWindowLeft,sortWindowRight);if(pivotNewIndex<sortWindowRight) -quickSortRange(array,comparator,pivotNewIndex+1,right,sortWindowLeft,sortWindowRight);} -if(leftBound===0&&rightBound===(this.length-1)&&sortWindowLeft===0&&sortWindowRight>=rightBound) -this.sort(comparator);else -quickSortRange(this,comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight);return this;}};Object.defineProperty(Array.prototype,'sortRange',sortRange);Object.defineProperty(Uint32Array.prototype,'sortRange',sortRange);})();Object.defineProperty(Array.prototype,'stableSort',{value:function(comparator){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);} -comparator=comparator||defaultComparator;var indices=new Array(this.length);for(var i=0;i<this.length;++i) -indices[i]=i;var self=this;function indexComparator(a,b){var result=comparator(self[a],self[b]);return result?result:a-b;} -indices.sort(indexComparator);for(var i=0;i<this.length;++i){if(indices[i]<0||i===indices[i]) -continue;var cyclical=i;var saved=this[i];while(true){var next=indices[cyclical];indices[cyclical]=-1;if(next===i){this[cyclical]=saved;break;}else{this[cyclical]=this[next];cyclical=next;}}} -return this;}});Object.defineProperty(Array.prototype,'qselect',{value:function(k,comparator){if(k<0||k>=this.length) -return;if(!comparator){comparator=function(a,b){return a-b;};} -var low=0;var high=this.length-1;for(;;){var pivotPosition=this.partition(comparator,low,high,Math.floor((high+low)/2));if(pivotPosition===k) -return this[k];else if(pivotPosition>k) -high=pivotPosition-1;else -low=pivotPosition+1;}}});Object.defineProperty(Array.prototype,'lowerBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);} -comparator=comparator||defaultComparator;var l=left||0;var r=right!==undefined?right:this.length;while(l<r){var m=(l+r)>>1;if(comparator(object,this[m])>0) -l=m+1;else -r=m;} -return r;}});Object.defineProperty(Array.prototype,'upperBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);} -comparator=comparator||defaultComparator;var l=left||0;var r=right!==undefined?right:this.length;while(l<r){var m=(l+r)>>1;if(comparator(object,this[m])>=0) -l=m+1;else -r=m;} -return r;}});Object.defineProperty(Uint32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Uint32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Int32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Int32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Float64Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Array.prototype,'binaryIndexOf',{value:function(value,comparator){var index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,'select',{value:function(field){var result=new Array(this.length);for(var i=0;i<this.length;++i) -result[i]=this[i][field];return result;}});Object.defineProperty(Array.prototype,'peekLast',{value:function(){return this[this.length-1];}});(function(){function mergeOrIntersect(array1,array2,comparator,mergeNotIntersect){var result=[];var i=0;var j=0;while(i<array1.length&&j<array2.length){var compareValue=comparator(array1[i],array2[j]);if(mergeNotIntersect||!compareValue) -result.push(compareValue<=0?array1[i]:array2[j]);if(compareValue<=0) -i++;if(compareValue>=0) -j++;} -if(mergeNotIntersect){while(i<array1.length) -result.push(array1[i++]);while(j<array2.length) -result.push(array2[j++]);} -return result;} -Object.defineProperty(Array.prototype,'intersectOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,false);}});Object.defineProperty(Array.prototype,'mergeOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,true);}});})();String.sprintf=function(format,var_arg){return String.vsprintf(format,Array.prototype.slice.call(arguments,1));};String.tokenizeFormatString=function(format,formatters){var tokens=[];var substitutionIndex=0;function addStringToken(str){if(tokens.length&&tokens[tokens.length-1].type==='string') -tokens[tokens.length-1].value+=str;else -tokens.push({type:'string',value:str});} -function addSpecifierToken(specifier,precision,substitutionIndex){tokens.push({type:'specifier',specifier:specifier,precision:precision,substitutionIndex:substitutionIndex});} -var index=0;for(var precentIndex=format.indexOf('%',index);precentIndex!==-1;precentIndex=format.indexOf('%',index)){if(format.length===index) -break;addStringToken(format.substring(index,precentIndex));index=precentIndex+1;if(format[index]==='%'){addStringToken('%');++index;continue;} -if(String.isDigitAt(format,index)){var number=parseInt(format.substring(index),10);while(String.isDigitAt(format,index)) -++index;if(number>0&&format[index]==='$'){substitutionIndex=(number-1);++index;}} -var precision=-1;if(format[index]==='.'){++index;precision=parseInt(format.substring(index),10);if(isNaN(precision)) -precision=0;while(String.isDigitAt(format,index)) -++index;} -if(!(format[index]in formatters)){addStringToken(format.substring(precentIndex,index+1));++index;continue;} -addSpecifierToken(format[index],precision,substitutionIndex);++substitutionIndex;++index;} -addStringToken(format.substring(index));return tokens;};String.standardFormatters={d:function(substitution){return!isNaN(substitution)?substitution:0;},f:function(substitution,token){if(substitution&&token.precision>-1) -substitution=substitution.toFixed(token.precision);return!isNaN(substitution)?substitution:(token.precision>-1?Number(0).toFixed(token.precision):0);},s:function(substitution){return substitution;}};String.vsprintf=function(format,substitutions){return String.format(format,substitutions,String.standardFormatters,'',function(a,b){return a+b;}).formattedResult;};String.format=function(format,substitutions,formatters,initialValue,append,tokenizedFormat){if(!format||!substitutions||!substitutions.length) -return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName(){return'String.format("'+format+'", "'+Array.prototype.join.call(substitutions,'", "')+'")';} -function warn(msg){console.warn(prettyFunctionName()+': '+msg);} -function error(msg){console.error(prettyFunctionName()+': '+msg);} -var result=initialValue;var tokens=tokenizedFormat||String.tokenizeFormatString(format,formatters);var usedSubstitutionIndexes={};for(var i=0;i<tokens.length;++i){var token=tokens[i];if(token.type==='string'){result=append(result,token.value);continue;} -if(token.type!=='specifier'){error('Unknown token type "'+token.type+'" found.');continue;} -if(token.substitutionIndex>=substitutions.length){error('not enough substitution arguments. Had '+substitutions.length+' but needed '+ -(token.substitutionIndex+1)+', so substitution was skipped.');result=append(result,'%'+(token.precision>-1?token.precision:'')+token.specifier);continue;} -usedSubstitutionIndexes[token.substitutionIndex]=true;if(!(token.specifier in formatters)){warn('unsupported format character \u201C'+token.specifier+'\u201D. Treating as a string.');result=append(result,substitutions[token.substitutionIndex]);continue;} -result=append(result,formatters[token.specifier](substitutions[token.substitutionIndex],token));} -var unusedSubstitutions=[];for(var i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes) -continue;unusedSubstitutions.push(substitutions[i]);} -return{formattedResult:result,unusedSubstitutions:unusedSubstitutions};};function createSearchRegex(query,caseSensitive,isRegex){var regexFlags=caseSensitive?'g':'gi';var regexObject;if(isRegex){try{regexObject=new RegExp(query,regexFlags);}catch(e){}} -if(!regexObject) -regexObject=createPlainTextSearchRegex(query,regexFlags);return regexObject;} -function createPlainTextSearchRegex(query,flags){var regexSpecialCharacters=String.regexSpecialCharacters();var regex='';for(var i=0;i<query.length;++i){var c=query.charAt(i);if(regexSpecialCharacters.indexOf(c)!==-1) -regex+='\\';regex+=c;} -return new RegExp(regex,flags||'');} -function countRegexMatches(regex,content){var text=content;var result=0;var match;while(text&&(match=regex.exec(text))){if(match[0].length>0) -++result;text=text.substring(match.index+1);} -return result;} -function spacesPadding(spacesCount){return'\u00a0'.repeat(spacesCount);} -function numberToStringWithSpacesPadding(value,symbolsCount){var numberString=value.toString();var paddingLength=Math.max(0,symbolsCount-numberString.length);return spacesPadding(paddingLength)+numberString;} -Set.prototype.valuesArray=function(){return Array.from(this.values());};Set.prototype.firstValue=function(){if(!this.size) -return null;return this.values().next().value;};Set.prototype.addAll=function(iterable){for(var e of iterable) -this.add(e);};Set.prototype.containsAll=function(iterable){for(var e of iterable){if(!this.has(e)) -return false;} -return true;};Map.prototype.remove=function(key){var value=this.get(key);this.delete(key);return value;};Map.prototype.valuesArray=function(){return Array.from(this.values());};Map.prototype.keysArray=function(){return Array.from(this.keys());};Map.prototype.inverse=function(){var result=new Multimap();for(var key of this.keys()){var value=this.get(key);result.set(value,key);} -return result;};var Multimap=function(){this._map=new Map();};Multimap.prototype={set:function(key,value){var set=this._map.get(key);if(!set){set=new Set();this._map.set(key,set);} -set.add(value);},get:function(key){var result=this._map.get(key);if(!result) -result=new Set();return result;},has:function(key){return this._map.has(key);},hasValue:function(key,value){var set=this._map.get(key);if(!set) -return false;return set.has(value);},get size(){return this._map.size;},delete:function(key,value){var values=this.get(key);if(!values) -return false;var result=values.delete(value);if(!values.size) -this._map.delete(key);return result;},deleteAll:function(key){this._map.delete(key);},keysArray:function(){return this._map.keysArray();},valuesArray:function(){var result=[];var keys=this.keysArray();for(var i=0;i<keys.length;++i) -result.pushAll(this.get(keys[i]).valuesArray());return result;},clear:function(){this._map.clear();}};function loadXHR(url){return new Promise(load);function load(successCallback,failureCallback){function onReadyStateChanged(){if(xhr.readyState!==XMLHttpRequest.DONE) -return;if(xhr.status!==200){xhr.onreadystatechange=null;failureCallback(new Error(xhr.status));return;} -xhr.onreadystatechange=null;successCallback(xhr.responseText);} -var xhr=new XMLHttpRequest();xhr.withCredentials=false;xhr.open('GET',url,true);xhr.onreadystatechange=onReadyStateChanged;xhr.send(null);}} -function suppressUnused(value){} -self.setImmediate=function(callback){const args=[...arguments].slice(1);Promise.resolve().then(()=>callback(...args));return 0;};Promise.prototype.spread=function(callback){return this.then(spreadPromise);function spreadPromise(arg){return callback.apply(null,arg);}};Promise.prototype.catchException=function(defaultValue){return this.catch(function(error){console.error(error);return defaultValue;});};Map.prototype.diff=function(other,isEqual){var leftKeys=this.keysArray();var rightKeys=other.keysArray();leftKeys.sort((a,b)=>a-b);rightKeys.sort((a,b)=>a-b);var removed=[];var added=[];var equal=[];var leftIndex=0;var rightIndex=0;while(leftIndex<leftKeys.length&&rightIndex<rightKeys.length){var leftKey=leftKeys[leftIndex];var rightKey=rightKeys[rightIndex];if(leftKey===rightKey&&isEqual(this.get(leftKey),other.get(rightKey))){equal.push(this.get(leftKey));++leftIndex;++rightIndex;continue;} -if(leftKey<=rightKey){removed.push(this.get(leftKey));++leftIndex;continue;} -added.push(other.get(rightKey));++rightIndex;} -while(leftIndex<leftKeys.length){var leftKey=leftKeys[leftIndex++];removed.push(this.get(leftKey));} -while(rightIndex<rightKeys.length){var rightKey=rightKeys[rightIndex++];added.push(other.get(rightKey));} -return{added:added,removed:removed,equal:equal};};function runOnWindowLoad(callback){function windowLoaded(){self.removeEventListener('DOMContentLoaded',windowLoaded,false);callback();} -if(document.readyState==='complete'||document.readyState==='interactive') -callback();else -self.addEventListener('DOMContentLoaded',windowLoaded,false);} -var _singletonSymbol=Symbol('singleton');function singleton(constructorFunction){if(_singletonSymbol in constructorFunction) -return constructorFunction[_singletonSymbol];var instance=new constructorFunction();constructorFunction[_singletonSymbol]=instance;return instance;};self['DomExtension']=self['DomExtension']||{};Node.prototype.rangeOfWord=function(offset,stopCharacters,stayWithinNode,direction){var startNode;var startOffset=0;var endNode;var endOffset=0;if(!stayWithinNode) -stayWithinNode=this;if(!direction||direction==='backward'||direction==='both'){var node=this;while(node){if(node===stayWithinNode){if(!startNode) -startNode=stayWithinNode;break;} -if(node.nodeType===Node.TEXT_NODE){var start=(node===this?(offset-1):(node.nodeValue.length-1));for(var i=start;i>=0;--i){if(stopCharacters.indexOf(node.nodeValue[i])!==-1){startNode=node;startOffset=i+1;break;}}} -if(startNode) -break;node=node.traversePreviousNode(stayWithinNode);} -if(!startNode){startNode=stayWithinNode;startOffset=0;}}else{startNode=this;startOffset=offset;} -if(!direction||direction==='forward'||direction==='both'){node=this;while(node){if(node===stayWithinNode){if(!endNode) -endNode=stayWithinNode;break;} -if(node.nodeType===Node.TEXT_NODE){var start=(node===this?offset:0);for(var i=start;i<node.nodeValue.length;++i){if(stopCharacters.indexOf(node.nodeValue[i])!==-1){endNode=node;endOffset=i;break;}}} -if(endNode) -break;node=node.traverseNextNode(stayWithinNode);} -if(!endNode){endNode=stayWithinNode;endOffset=stayWithinNode.nodeType===Node.TEXT_NODE?stayWithinNode.nodeValue.length:stayWithinNode.childNodes.length;}}else{endNode=this;endOffset=offset;} -var result=this.ownerDocument.createRange();result.setStart(startNode,startOffset);result.setEnd(endNode,endOffset);return result;};Node.prototype.traverseNextTextNode=function(stayWithin){var node=this.traverseNextNode(stayWithin);if(!node) -return null;var nonTextTags={'STYLE':1,'SCRIPT':1};while(node&&(node.nodeType!==Node.TEXT_NODE||nonTextTags[node.parentElement.nodeName])) -node=node.traverseNextNode(stayWithin);return node;};Element.prototype.positionAt=function(x,y,relativeTo){var shift={x:0,y:0};if(relativeTo) -shift=relativeTo.boxInWindow(this.ownerDocument.defaultView);if(typeof x==='number') -this.style.setProperty('left',(shift.x+x)+'px');else -this.style.removeProperty('left');if(typeof y==='number') -this.style.setProperty('top',(shift.y+y)+'px');else -this.style.removeProperty('top');if(typeof x==='number'||typeof y==='number') -this.style.setProperty('position','absolute');else -this.style.removeProperty('position');};Element.prototype.isScrolledToBottom=function(){return Math.abs(this.scrollTop+this.clientHeight-this.scrollHeight)<=2;};Node.prototype.enclosingNodeOrSelfWithNodeNameInArray=function(nameArray){for(var node=this;node&&node!==this.ownerDocument;node=node.parentNodeOrShadowHost()){for(var i=0;i<nameArray.length;++i){if(node.nodeName.toLowerCase()===nameArray[i].toLowerCase()) -return node;}} -return null;};Node.prototype.enclosingNodeOrSelfWithNodeName=function(nodeName){return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);};Node.prototype.enclosingNodeOrSelfWithClass=function(className,stayWithin){return this.enclosingNodeOrSelfWithClassList([className],stayWithin);};Node.prototype.enclosingNodeOrSelfWithClassList=function(classNames,stayWithin){for(var node=this;node&&node!==stayWithin&&node!==this.ownerDocument;node=node.parentNodeOrShadowHost()){if(node.nodeType===Node.ELEMENT_NODE){var containsAll=true;for(var i=0;i<classNames.length&&containsAll;++i){if(!node.classList.contains(classNames[i])) -containsAll=false;} -if(containsAll) -return(node);}} -return null;};Node.prototype.parentElementOrShadowHost=function(){var node=this.parentNode;if(!node) -return null;if(node.nodeType===Node.ELEMENT_NODE) -return(node);if(node.nodeType===Node.DOCUMENT_FRAGMENT_NODE) -return(node.host);return null;};Node.prototype.parentNodeOrShadowHost=function(){if(this.parentNode) -return this.parentNode;if(this.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&this.host) -return this.host;return null;};Node.prototype.getComponentSelection=function(){var parent=this.parentNode;while(parent&&parent.nodeType!==Node.DOCUMENT_FRAGMENT_NODE) -parent=parent.parentNode;return parent instanceof ShadowRoot?parent.getSelection():this.window().getSelection();};Node.prototype.hasSelection=function(){var contents=this.querySelectorAll('content');for(var content of contents){if(Array.prototype.some.call(content.getDistributedNodes(),node=>node.hasSelection())) -return true;} -var selection=this.getComponentSelection();if(selection.type!=='Range') -return false;return selection.containsNode(this,true)||selection.anchorNode.isSelfOrDescendant(this)||selection.focusNode.isSelfOrDescendant(this);};Node.prototype.window=function(){return this.ownerDocument.defaultView;};Element.prototype.removeChildren=function(){if(this.firstChild) -this.textContent='';};function createElement(tagName,customElementType){return document.createElement(tagName,customElementType||'');} -function createTextNode(data){return document.createTextNode(data);} -Document.prototype.createElementWithClass=function(elementName,className,customElementType){var element=this.createElement(elementName,customElementType||'');if(className) -element.className=className;return element;};function createElementWithClass(elementName,className,customElementType){return document.createElementWithClass(elementName,className,customElementType);} -Document.prototype.createSVGElement=function(childType,className){var element=this.createElementNS('http://www.w3.org/2000/svg',childType);if(className) -element.setAttribute('class',className);return element;};function createSVGElement(childType,className){return document.createSVGElement(childType,className);} -function createDocumentFragment(){return document.createDocumentFragment();} -Element.prototype.createChild=function(elementName,className,customElementType){var element=this.ownerDocument.createElementWithClass(elementName,className,customElementType);this.appendChild(element);return element;};DocumentFragment.prototype.createChild=Element.prototype.createChild;Element.prototype.createTextChild=function(text){var element=this.ownerDocument.createTextNode(text);this.appendChild(element);return element;};DocumentFragment.prototype.createTextChild=Element.prototype.createTextChild;Element.prototype.createTextChildren=function(var_args){for(var i=0,n=arguments.length;i<n;++i) -this.createTextChild(arguments[i]);};DocumentFragment.prototype.createTextChildren=Element.prototype.createTextChildren;Element.prototype.totalOffsetLeft=function(){return this.totalOffset().left;};Element.prototype.totalOffsetTop=function(){return this.totalOffset().top;};Element.prototype.totalOffset=function(){var rect=this.getBoundingClientRect();return{left:rect.left,top:rect.top};};Element.prototype.createSVGChild=function(childType,className){var child=this.ownerDocument.createSVGElement(childType,className);this.appendChild(child);return child;};var AnchorBox=class{constructor(x,y,width,height){this.x=x||0;this.y=y||0;this.width=width||0;this.height=height||0;} -contains(x,y){return x>=this.x&&x<=this.x+this.width&&y>=this.y&&y<=this.y+this.height;}};AnchorBox.prototype.relativeTo=function(box){return new AnchorBox(this.x-box.x,this.y-box.y,this.width,this.height);};AnchorBox.prototype.relativeToElement=function(element){return this.relativeTo(element.boxInWindow(element.ownerDocument.defaultView));};AnchorBox.prototype.equals=function(anchorBox){return!!anchorBox&&this.x===anchorBox.x&&this.y===anchorBox.y&&this.width===anchorBox.width&&this.height===anchorBox.height;};Element.prototype.boxInWindow=function(targetWindow){targetWindow=targetWindow||this.ownerDocument.defaultView;var anchorBox=new AnchorBox();var curElement=this;var curWindow=this.ownerDocument.defaultView;while(curWindow&&curElement){anchorBox.x+=curElement.totalOffsetLeft();anchorBox.y+=curElement.totalOffsetTop();if(curWindow===targetWindow) -break;curElement=curWindow.frameElement;curWindow=curWindow.parent;} -anchorBox.width=Math.min(this.offsetWidth,targetWindow.innerWidth-anchorBox.x);anchorBox.height=Math.min(this.offsetHeight,targetWindow.innerHeight-anchorBox.y);return anchorBox;};Event.prototype.consume=function(preventDefault){this.stopImmediatePropagation();if(preventDefault) -this.preventDefault();this.handled=true;};Text.prototype.select=function(start,end){start=start||0;end=end||this.textContent.length;if(start<0) -start=end+start;var selection=this.getComponentSelection();selection.removeAllRanges();var range=this.ownerDocument.createRange();range.setStart(this,start);range.setEnd(this,end);selection.addRange(range);return this;};Element.prototype.selectionLeftOffset=function(){var selection=this.getComponentSelection();if(!selection.containsNode(this,true)) -return null;var leftOffset=selection.anchorOffset;var node=selection.anchorNode;while(node!==this){while(node.previousSibling){node=node.previousSibling;leftOffset+=node.textContent.length;} -node=node.parentNodeOrShadowHost();} -return leftOffset;};Node.prototype.appendChildren=function(var_args){for(var i=0,n=arguments.length;i<n;++i) -this.appendChild(arguments[i]);};Node.prototype.deepTextContent=function(){return this.childTextNodes().map(function(node){return node.textContent;}).join('');};Node.prototype.childTextNodes=function(){var node=this.traverseNextTextNode(this);var result=[];var nonTextTags={'STYLE':1,'SCRIPT':1};while(node){if(!nonTextTags[node.parentElement.nodeName]) -result.push(node);node=node.traverseNextTextNode(this);} -return result;};Node.prototype.isAncestor=function(node){if(!node) -return false;var currentNode=node.parentNodeOrShadowHost();while(currentNode){if(this===currentNode) -return true;currentNode=currentNode.parentNodeOrShadowHost();} -return false;};Node.prototype.isDescendant=function(descendant){return!!descendant&&descendant.isAncestor(this);};Node.prototype.isSelfOrAncestor=function(node){return!!node&&(node===this||this.isAncestor(node));};Node.prototype.isSelfOrDescendant=function(node){return!!node&&(node===this||this.isDescendant(node));};Node.prototype.traverseNextNode=function(stayWithin){if(this.shadowRoot) -return this.shadowRoot;var distributedNodes=this.getDistributedNodes?this.getDistributedNodes():[];if(distributedNodes.length) -return distributedNodes[0];if(this.firstChild) -return this.firstChild;var node=this;while(node){if(stayWithin&&node===stayWithin) -return null;var sibling=nextSibling(node);if(sibling) -return sibling;node=insertionPoint(node)||node.parentNodeOrShadowHost();} -function nextSibling(node){var parent=insertionPoint(node);if(!parent) -return node.nextSibling;var distributedNodes=parent.getDistributedNodes?parent.getDistributedNodes():[];var position=Array.prototype.indexOf.call(distributedNodes,node);if(position+1<distributedNodes.length) -return distributedNodes[position+1];return null;} -function insertionPoint(node){var insertionPoints=node.getDestinationInsertionPoints?node.getDestinationInsertionPoints():[];return insertionPoints.length>0?insertionPoints[insertionPoints.length-1]:null;} -return null;};Node.prototype.traversePreviousNode=function(stayWithin){if(stayWithin&&this===stayWithin) -return null;var node=this.previousSibling;while(node&&node.lastChild) -node=node.lastChild;if(node) -return node;return this.parentNodeOrShadowHost();};Node.prototype.setTextContentTruncatedIfNeeded=function(text,placeholder){const maxTextContentLength=10000;if(typeof text==='string'&&text.length>maxTextContentLength){this.textContent=typeof placeholder==='string'?placeholder:text.trimMiddle(maxTextContentLength);return true;} -this.textContent=text;return false;};Event.prototype.deepElementFromPoint=function(){if(!this.which&&!this.pageX&&!this.pageY&&!this.clientX&&!this.clientY&&!this.movementX&&!this.movementY) -return null;var root=this.target&&this.target.getComponentRoot();return root?root.deepElementFromPoint(this.pageX,this.pageY):null;};Document.prototype.deepElementFromPoint=function(x,y){var container=this;var node=null;while(container){var innerNode=container.elementFromPoint(x,y);if(!innerNode) -break;node=innerNode;container=node.shadowRoot;} -return node;};DocumentFragment.prototype.deepElementFromPoint=Document.prototype.deepElementFromPoint;Document.prototype.deepActiveElement=function(){var activeElement=this.activeElement;while(activeElement&&activeElement.shadowRoot&&activeElement.shadowRoot.activeElement) -activeElement=activeElement.shadowRoot.activeElement;return activeElement;};DocumentFragment.prototype.deepActiveElement=Document.prototype.deepActiveElement;Element.prototype.hasFocus=function(){var root=this.getComponentRoot();return!!root&&this.isSelfOrAncestor(root.activeElement);};Node.prototype.getComponentRoot=function(){var node=this;while(node&&node.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&node.nodeType!==Node.DOCUMENT_NODE) -node=node.parentNode;return(node);};function isEnterKey(event){return event.keyCode!==229&&event.key==='Enter';} -function isEscKey(event){return event.keyCode===27;};self['TextUtils']=self['TextUtils']||{};TextUtils.Text=class{constructor(value){this._value=value;} -lineEndings(){if(!this._lineEndings) -this._lineEndings=this._value.computeLineEndings();return this._lineEndings;} -value(){return this._value;} -lineCount(){var lineEndings=this.lineEndings();return lineEndings.length;} -offsetFromPosition(lineNumber,columnNumber){return(lineNumber?this.lineEndings()[lineNumber-1]+1:0)+columnNumber;} -positionFromOffset(offset){var lineEndings=this.lineEndings();var lineNumber=lineEndings.lowerBound(offset);return{lineNumber:lineNumber,columnNumber:offset-(lineNumber&&(lineEndings[lineNumber-1]+1))};} -lineAt(lineNumber){var lineEndings=this.lineEndings();var lineStart=lineNumber>0?lineEndings[lineNumber-1]+1:0;var lineEnd=lineEndings[lineNumber];var lineContent=this._value.substring(lineStart,lineEnd);if(lineContent.length>0&&lineContent.charAt(lineContent.length-1)==='\r') -lineContent=lineContent.substring(0,lineContent.length-1);return lineContent;} -toSourceRange(range){var start=this.offsetFromPosition(range.startLine,range.startColumn);var end=this.offsetFromPosition(range.endLine,range.endColumn);return new TextUtils.SourceRange(start,end-start);} -toTextRange(sourceRange){var cursor=new TextUtils.TextCursor(this.lineEndings());var result=TextUtils.TextRange.createFromLocation(0,0);cursor.resetTo(sourceRange.offset);result.startLine=cursor.lineNumber();result.startColumn=cursor.columnNumber();cursor.advance(sourceRange.offset+sourceRange.length);result.endLine=cursor.lineNumber();result.endColumn=cursor.columnNumber();return result;} -replaceRange(range,replacement){var sourceRange=this.toSourceRange(range);return this._value.substring(0,sourceRange.offset)+replacement+ -this._value.substring(sourceRange.offset+sourceRange.length);} -extract(range){var sourceRange=this.toSourceRange(range);return this._value.substr(sourceRange.offset,sourceRange.length);}};TextUtils.Text.Position;TextUtils.TextCursor=class{constructor(lineEndings){this._lineEndings=lineEndings;this._offset=0;this._lineNumber=0;this._columnNumber=0;} -advance(offset){this._offset=offset;while(this._lineNumber<this._lineEndings.length&&this._lineEndings[this._lineNumber]<this._offset) -++this._lineNumber;this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;} -offset(){return this._offset;} -resetTo(offset){this._offset=offset;this._lineNumber=this._lineEndings.lowerBound(offset);this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;} -lineNumber(){return this._lineNumber;} -columnNumber(){return this._columnNumber;}};;TextUtils.TextUtils={isStopChar:function(char){return(char>' '&&char<'0')||(char>'9'&&char<'A')||(char>'Z'&&char<'_')||(char>'_'&&char<'a')||(char>'z'&&char<='~');},isWordChar:function(char){return!TextUtils.TextUtils.isStopChar(char)&&!TextUtils.TextUtils.isSpaceChar(char);},isSpaceChar:function(char){return TextUtils.TextUtils._SpaceCharRegex.test(char);},isWord:function(word){for(var i=0;i<word.length;++i){if(!TextUtils.TextUtils.isWordChar(word.charAt(i))) -return false;} -return true;},isOpeningBraceChar:function(char){return char==='('||char==='{';},isClosingBraceChar:function(char){return char===')'||char==='}';},isBraceChar:function(char){return TextUtils.TextUtils.isOpeningBraceChar(char)||TextUtils.TextUtils.isClosingBraceChar(char);},textToWords:function(text,isWordChar,wordCallback){var startWord=-1;for(var i=0;i<text.length;++i){if(!isWordChar(text.charAt(i))){if(startWord!==-1) -wordCallback(text.substring(startWord,i));startWord=-1;}else if(startWord===-1){startWord=i;}} -if(startWord!==-1) -wordCallback(text.substring(startWord));},lineIndent:function(line){var indentation=0;while(indentation<line.length&&TextUtils.TextUtils.isSpaceChar(line.charAt(indentation))) -++indentation;return line.substr(0,indentation);},isUpperCase:function(text){return text===text.toUpperCase();},isLowerCase:function(text){return text===text.toLowerCase();},splitStringByRegexes(text,regexes){var matches=[];var globalRegexes=[];for(var i=0;i<regexes.length;i++){var regex=regexes[i];if(!regex.global) -globalRegexes.push(new RegExp(regex.source,regex.flags?regex.flags+'g':'g'));else -globalRegexes.push(regex);} -doSplit(text,0,0);return matches;function doSplit(text,regexIndex,startIndex){if(regexIndex>=globalRegexes.length){matches.push({value:text,position:startIndex,regexIndex:-1,captureGroups:[]});return;} -var regex=globalRegexes[regexIndex];var currentIndex=0;var result;regex.lastIndex=0;while((result=regex.exec(text))!==null){var stringBeforeMatch=text.substring(currentIndex,result.index);if(stringBeforeMatch) -doSplit(stringBeforeMatch,regexIndex+1,startIndex+currentIndex);var match=result[0];matches.push({value:match,position:startIndex+result.index,regexIndex:regexIndex,captureGroups:result.slice(1)});currentIndex=result.index+match.length;} -var stringAfterMatches=text.substring(currentIndex);if(stringAfterMatches) -doSplit(stringAfterMatches,regexIndex+1,startIndex+currentIndex);}}};TextUtils.FilterParser=class{constructor(keys){this._keys=keys;} -static cloneFilter(filter){return{key:filter.key,text:filter.text,regex:filter.regex,negative:filter.negative};} -parse(query){var splitResult=TextUtils.TextUtils.splitStringByRegexes(query,[TextUtils.TextUtils._keyValueFilterRegex,TextUtils.TextUtils._regexFilterRegex,TextUtils.TextUtils._textFilterRegex]);var filters=[];for(var i=0;i<splitResult.length;i++){var regexIndex=splitResult[i].regexIndex;if(regexIndex===-1) -continue;var result=splitResult[i].captureGroups;if(regexIndex===0){if(this._keys.indexOf((result[1]))!==-1) -filters.push({key:result[1],text:result[2],negative:!!result[0]});else -filters.push({text:result[1]+':'+result[2],negative:!!result[0]});}else if(regexIndex===1){try{filters.push({regex:new RegExp(result[1],'i'),negative:!!result[0]});}catch(e){filters.push({text:'/'+result[1]+'/',negative:!!result[0]});}}else if(regexIndex===2){filters.push({text:result[1],negative:!!result[0]});}} -return filters;}};TextUtils.FilterParser.ParsedFilter;TextUtils.TextUtils._keyValueFilterRegex=/(?:^|\s)(\-)?([\w\-]+):([^\s]+)/;TextUtils.TextUtils._regexFilterRegex=/(?:^|\s)(\-)?\/([^\s]+)\//;TextUtils.TextUtils._textFilterRegex=/(?:^|\s)(\-)?([^\s]+)/;TextUtils.TextUtils._SpaceCharRegex=/\s/;TextUtils.TextUtils.Indent={TwoSpaces:' ',FourSpaces:' ',EightSpaces:' ',TabCharacter:'\t'};TextUtils.TextUtils.BalancedJSONTokenizer=class{constructor(callback,findMultiple){this._callback=callback;this._index=0;this._balance=0;this._buffer='';this._findMultiple=findMultiple||false;this._closingDoubleQuoteRegex=/[^\\](?:\\\\)*"/g;} -write(chunk){this._buffer+=chunk;var lastIndex=this._buffer.length;var buffer=this._buffer;for(var index=this._index;index<lastIndex;++index){var character=buffer[index];if(character==='"'){this._closingDoubleQuoteRegex.lastIndex=index;if(!this._closingDoubleQuoteRegex.test(buffer)) -break;index=this._closingDoubleQuoteRegex.lastIndex-1;}else if(character==='{'){++this._balance;}else if(character==='}'){--this._balance;if(this._balance<0){this._reportBalanced();return false;} -if(!this._balance){this._lastBalancedIndex=index+1;if(!this._findMultiple) -break;}}else if(character===']'&&!this._balance){this._reportBalanced();return false;}} -this._index=index;this._reportBalanced();return true;} -_reportBalanced(){if(!this._lastBalancedIndex) -return;this._callback(this._buffer.slice(0,this._lastBalancedIndex));this._buffer=this._buffer.slice(this._lastBalancedIndex);this._index-=this._lastBalancedIndex;this._lastBalancedIndex=0;} -remainder(){return this._buffer;}};TextUtils.TokenizerFactory=function(){};TextUtils.TokenizerFactory.prototype={createTokenizer(mimeType){}};TextUtils.isMinified=function(text){var kMaxNonMinifiedLength=500;var linesToCheck=10;var lastPosition=0;do{var eolIndex=text.indexOf('\n',lastPosition);if(eolIndex<0) -eolIndex=text.length;if(eolIndex-lastPosition>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#') -return true;lastPosition=eolIndex+1;}while(--linesToCheck>=0&&lastPosition<text.length);return false;};;TextUtils.TextRange=class{constructor(startLine,startColumn,endLine,endColumn){this.startLine=startLine;this.startColumn=startColumn;this.endLine=endLine;this.endColumn=endColumn;} -static createFromLocation(line,column){return new TextUtils.TextRange(line,column,line,column);} -static fromObject(serializedTextRange){return new TextUtils.TextRange(serializedTextRange.startLine,serializedTextRange.startColumn,serializedTextRange.endLine,serializedTextRange.endColumn);} -static comparator(range1,range2){return range1.compareTo(range2);} -static fromEdit(oldRange,newText){var endLine=oldRange.startLine;var endColumn=oldRange.startColumn+newText.length;var lineEndings=newText.computeLineEndings();if(lineEndings.length>1){endLine=oldRange.startLine+lineEndings.length-1;var len=lineEndings.length;endColumn=lineEndings[len-1]-lineEndings[len-2]-1;} -return new TextUtils.TextRange(oldRange.startLine,oldRange.startColumn,endLine,endColumn);} -isEmpty(){return this.startLine===this.endLine&&this.startColumn===this.endColumn;} -immediatelyPrecedes(range){if(!range) -return false;return this.endLine===range.startLine&&this.endColumn===range.startColumn;} -immediatelyFollows(range){if(!range) -return false;return range.immediatelyPrecedes(this);} -follows(range){return(range.endLine===this.startLine&&range.endColumn<=this.startColumn)||range.endLine<this.startLine;} -get linesCount(){return this.endLine-this.startLine;} -collapseToEnd(){return new TextUtils.TextRange(this.endLine,this.endColumn,this.endLine,this.endColumn);} -collapseToStart(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.startLine,this.startColumn);} -normalize(){if(this.startLine>this.endLine||(this.startLine===this.endLine&&this.startColumn>this.endColumn)) -return new TextUtils.TextRange(this.endLine,this.endColumn,this.startLine,this.startColumn);else -return this.clone();} -clone(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.endLine,this.endColumn);} -serializeToObject(){var serializedTextRange={};serializedTextRange.startLine=this.startLine;serializedTextRange.startColumn=this.startColumn;serializedTextRange.endLine=this.endLine;serializedTextRange.endColumn=this.endColumn;return serializedTextRange;} -compareTo(other){if(this.startLine>other.startLine) -return 1;if(this.startLine<other.startLine) -return-1;if(this.startColumn>other.startColumn) -return 1;if(this.startColumn<other.startColumn) -return-1;return 0;} -compareToPosition(lineNumber,columnNumber){if(lineNumber<this.startLine||(lineNumber===this.startLine&&columnNumber<this.startColumn)) -return-1;if(lineNumber>this.endLine||(lineNumber===this.endLine&&columnNumber>this.endColumn)) -return 1;return 0;} -equal(other){return this.startLine===other.startLine&&this.endLine===other.endLine&&this.startColumn===other.startColumn&&this.endColumn===other.endColumn;} -relativeTo(line,column){var relative=this.clone();if(this.startLine===line) -relative.startColumn-=column;if(this.endLine===line) -relative.endColumn-=column;relative.startLine-=line;relative.endLine-=line;return relative;} -rebaseAfterTextEdit(originalRange,editedRange){console.assert(originalRange.startLine===editedRange.startLine);console.assert(originalRange.startColumn===editedRange.startColumn);var rebase=this.clone();if(!this.follows(originalRange)) -return rebase;var lineDelta=editedRange.endLine-originalRange.endLine;var columnDelta=editedRange.endColumn-originalRange.endColumn;rebase.startLine+=lineDelta;rebase.endLine+=lineDelta;if(rebase.startLine===editedRange.endLine) -rebase.startColumn+=columnDelta;if(rebase.endLine===editedRange.endLine) -rebase.endColumn+=columnDelta;return rebase;} -toString(){return JSON.stringify(this);} -containsLocation(lineNumber,columnNumber){if(this.startLine===this.endLine) -return this.startLine===lineNumber&&this.startColumn<=columnNumber&&columnNumber<=this.endColumn;if(this.startLine===lineNumber) -return this.startColumn<=columnNumber;if(this.endLine===lineNumber) -return columnNumber<=this.endColumn;return this.startLine<lineNumber&&lineNumber<this.endLine;}};TextUtils.SourceRange=class{constructor(offset,length){this.offset=offset;this.length=length;}};TextUtils.SourceEdit=class{constructor(sourceURL,oldRange,newText){this.sourceURL=sourceURL;this.oldRange=oldRange;this.newText=newText;} -static comparator(edit1,edit2){return TextUtils.TextRange.comparator(edit1.oldRange,edit2.oldRange);} -newRange(){return TextUtils.TextRange.fromEdit(this.oldRange,this.newText);}};;self['Common']=self['Common']||{};Common.Worker=class{constructor(appName){var url=appName+'.js';url+=Runtime.queryParamsString();this._workerPromise=new Promise(fulfill=>{this._worker=new Worker(url);this._worker.onmessage=onMessage.bind(this);function onMessage(event){console.assert(event.data==='workerReady');this._worker.onmessage=null;fulfill(this._worker);this._worker=null;}});} -postMessage(message){this._workerPromise.then(worker=>{if(!this._disposed) -worker.postMessage(message);});} -dispose(){this._disposed=true;this._workerPromise.then(worker=>worker.terminate());} -terminate(){this.dispose();} -set onmessage(listener){this._workerPromise.then(worker=>worker.onmessage=listener);} -set onerror(listener){this._workerPromise.then(worker=>worker.onerror=listener);}};;Common.TextDictionary=class{constructor(){this._words=new Map();this._index=new Common.Trie();} -addWord(word){var count=this._words.get(word)||0;++count;this._words.set(word,count);this._index.add(word);} -removeWord(word){var count=this._words.get(word)||0;if(!count) -return;if(count===1){this._words.delete(word);this._index.remove(word);return;} ---count;this._words.set(word,count);} -wordsWithPrefix(prefix){return this._index.words(prefix);} -hasWord(word){return this._words.has(word);} -wordCount(word){return this._words.get(word)||0;} -reset(){this._words.clear();this._index.clear();}};;Common.Object=class{constructor(){this._listeners;} -addEventListener(eventType,listener,thisObject){if(!listener) -console.assert(false);if(!this._listeners) -this._listeners=new Map();if(!this._listeners.has(eventType)) -this._listeners.set(eventType,[]);this._listeners.get(eventType).push({thisObject:thisObject,listener:listener});return{eventTarget:this,eventType:eventType,thisObject:thisObject,listener:listener};} -once(eventType){return new Promise(resolve=>{var descriptor=this.addEventListener(eventType,event=>{this.removeEventListener(eventType,descriptor.listener);resolve(event.data);});});} -removeEventListener(eventType,listener,thisObject){console.assert(listener);if(!this._listeners||!this._listeners.has(eventType)) -return;var listeners=this._listeners.get(eventType);for(var i=0;i<listeners.length;++i){if(listeners[i].listener===listener&&listeners[i].thisObject===thisObject) -listeners.splice(i--,1);} -if(!listeners.length) -this._listeners.delete(eventType);} -hasEventListeners(eventType){return!!(this._listeners&&this._listeners.has(eventType));} -dispatchEventToListeners(eventType,eventData){if(!this._listeners||!this._listeners.has(eventType)) -return;var event=({data:eventData});var listeners=this._listeners.get(eventType).slice(0);for(var i=0;i<listeners.length;++i) -listeners[i].listener.call(listeners[i].thisObject,event);}};Common.Event;Common.Object._listenerCallbackTuple;Common.EventTarget=function(){};Common.EventTarget.EventDescriptor;Common.EventTarget.removeEventListeners=function(eventList){for(var i=0;i<eventList.length;++i){var eventInfo=eventList[i];eventInfo.eventTarget.removeEventListener(eventInfo.eventType,eventInfo.listener,eventInfo.thisObject);} -eventList.splice(0,eventList.length);};Common.EventTarget.prototype={addEventListener(eventType,listener,thisObject){},once(eventType){},removeEventListener(eventType,listener,thisObject){},hasEventListeners(eventType){},dispatchEventToListeners(eventType,eventData){},};;Common.Color=class{constructor(rgba,format,originalText){this._rgba=rgba;this._originalText=originalText||null;this._originalTextIsValid=!!this._originalText;this._format=format;if(typeof this._rgba[3]==='undefined') -this._rgba[3]=1;for(var i=0;i<4;++i){if(this._rgba[i]<0){this._rgba[i]=0;this._originalTextIsValid=false;} -if(this._rgba[i]>1){this._rgba[i]=1;this._originalTextIsValid=false;}}} -static parse(text){var value=text.toLowerCase().replace(/\s+/g,'');var simple=/^(?:#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgb\(((?:-?\d+%?,){2}-?\d+%?)\)|(\w+)|hsl\((-?\d+\.?\d*(?:,-?\d+\.?\d*%){2})\))$/i;var match=value.match(simple);if(match){if(match[1]){var hex=match[1].toLowerCase();var format;if(hex.length===3){format=Common.Color.Format.ShortHEX;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2);}else if(hex.length===4){format=Common.Color.Format.ShortHEXA;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2)+ -hex.charAt(3)+hex.charAt(3);}else if(hex.length===6){format=Common.Color.Format.HEX;}else{format=Common.Color.Format.HEXA;} -var r=parseInt(hex.substring(0,2),16);var g=parseInt(hex.substring(2,4),16);var b=parseInt(hex.substring(4,6),16);var a=1;if(hex.length===8) -a=parseInt(hex.substring(6,8),16)/255;return new Common.Color([r/255,g/255,b/255,a],format,text);} -if(match[2]){var rgbString=match[2].split(/\s*,\s*/);var rgba=[Common.Color._parseRgbNumeric(rgbString[0]),Common.Color._parseRgbNumeric(rgbString[1]),Common.Color._parseRgbNumeric(rgbString[2]),1];return new Common.Color(rgba,Common.Color.Format.RGB,text);} -if(match[3]){var nickname=match[3].toLowerCase();if(nickname in Common.Color.Nicknames){var rgba=Common.Color.Nicknames[nickname];var color=Common.Color.fromRGBA(rgba);color._format=Common.Color.Format.Nickname;color._originalText=text;return color;} -return null;} -if(match[4]){var hslString=match[4].replace(/%/g,'').split(/\s*,\s*/);var hsla=[Common.Color._parseHueNumeric(hslString[0]),Common.Color._parseSatLightNumeric(hslString[1]),Common.Color._parseSatLightNumeric(hslString[2]),1];var rgba=[];Common.Color.hsl2rgb(hsla,rgba);return new Common.Color(rgba,Common.Color.Format.HSL,text);} -return null;} -var advanced=/^(?:rgba\(((?:-?\d+%?,){3}-?(?:\d+|\d*\.\d+))\)|hsla\((-?(?:\d+|\d*\.\d+)(?:,-?(?:\d+|\d*\.\d+)*%){2},-?(?:\d+|\d*\.\d+))\))$/;match=value.match(advanced);if(match){if(match[1]){var rgbaString=match[1].split(/\s*,\s*/);var rgba=[Common.Color._parseRgbNumeric(rgbaString[0]),Common.Color._parseRgbNumeric(rgbaString[1]),Common.Color._parseRgbNumeric(rgbaString[2]),Common.Color._parseAlphaNumeric(rgbaString[3])];return new Common.Color(rgba,Common.Color.Format.RGBA,text);} -if(match[2]){var hslaString=match[2].replace(/%/g,'').split(/\s*,\s*/);var hsla=[Common.Color._parseHueNumeric(hslaString[0]),Common.Color._parseSatLightNumeric(hslaString[1]),Common.Color._parseSatLightNumeric(hslaString[2]),Common.Color._parseAlphaNumeric(hslaString[3])];var rgba=[];Common.Color.hsl2rgb(hsla,rgba);return new Common.Color(rgba,Common.Color.Format.HSLA,text);}} -return null;} -static fromRGBA(rgba){return new Common.Color([rgba[0]/255,rgba[1]/255,rgba[2]/255,rgba[3]],Common.Color.Format.RGBA);} -static fromHSVA(hsva){var rgba=[];Common.Color.hsva2rgba(hsva,rgba);return new Common.Color(rgba,Common.Color.Format.HSLA);} -static _parseRgbNumeric(value){var parsed=parseInt(value,10);if(value.indexOf('%')!==-1) -parsed/=100;else -parsed/=255;return parsed;} -static _parseHueNumeric(value){return isNaN(value)?0:(parseFloat(value)/360)%1;} -static _parseSatLightNumeric(value){return Math.min(1,parseFloat(value)/100);} -static _parseAlphaNumeric(value){return isNaN(value)?0:parseFloat(value);} -static _hsva2hsla(hsva,out_hsla){var h=hsva[0];var s=hsva[1];var v=hsva[2];var t=(2-s)*v;if(v===0||s===0) -s=0;else -s*=v/(t<1?t:2-t);out_hsla[0]=h;out_hsla[1]=s;out_hsla[2]=t/2;out_hsla[3]=hsva[3];} -static hsl2rgb(hsl,out_rgb){var h=hsl[0];var s=hsl[1];var l=hsl[2];function hue2rgb(p,q,h){if(h<0) -h+=1;else if(h>1) -h-=1;if((h*6)<1) -return p+(q-p)*h*6;else if((h*2)<1) -return q;else if((h*3)<2) -return p+(q-p)*((2/3)-h)*6;else -return p;} -if(s<0) -s=0;if(l<=0.5) -var q=l*(1+s);else -var q=l+s-(l*s);var p=2*l-q;var tr=h+(1/3);var tg=h;var tb=h-(1/3);out_rgb[0]=hue2rgb(p,q,tr);out_rgb[1]=hue2rgb(p,q,tg);out_rgb[2]=hue2rgb(p,q,tb);out_rgb[3]=hsl[3];} -static hsva2rgba(hsva,out_rgba){Common.Color._hsva2hsla(hsva,Common.Color.hsva2rgba._tmpHSLA);Common.Color.hsl2rgb(Common.Color.hsva2rgba._tmpHSLA,out_rgba);for(var i=0;i<Common.Color.hsva2rgba._tmpHSLA.length;i++) -Common.Color.hsva2rgba._tmpHSLA[i]=0;} -static luminance(rgba){var rSRGB=rgba[0];var gSRGB=rgba[1];var bSRGB=rgba[2];var r=rSRGB<=0.03928?rSRGB/12.92:Math.pow(((rSRGB+0.055)/1.055),2.4);var g=gSRGB<=0.03928?gSRGB/12.92:Math.pow(((gSRGB+0.055)/1.055),2.4);var b=bSRGB<=0.03928?bSRGB/12.92:Math.pow(((bSRGB+0.055)/1.055),2.4);return 0.2126*r+0.7152*g+0.0722*b;} -static blendColors(fgRGBA,bgRGBA,out_blended){var alpha=fgRGBA[3];out_blended[0]=((1-alpha)*bgRGBA[0])+(alpha*fgRGBA[0]);out_blended[1]=((1-alpha)*bgRGBA[1])+(alpha*fgRGBA[1]);out_blended[2]=((1-alpha)*bgRGBA[2])+(alpha*fgRGBA[2]);out_blended[3]=alpha+(bgRGBA[3]*(1-alpha));} -static calculateContrastRatio(fgRGBA,bgRGBA){Common.Color.blendColors(fgRGBA,bgRGBA,Common.Color.calculateContrastRatio._blendedFg);var fgLuminance=Common.Color.luminance(Common.Color.calculateContrastRatio._blendedFg);var bgLuminance=Common.Color.luminance(bgRGBA);var contrastRatio=(Math.max(fgLuminance,bgLuminance)+0.05)/(Math.min(fgLuminance,bgLuminance)+0.05);for(var i=0;i<Common.Color.calculateContrastRatio._blendedFg.length;i++) -Common.Color.calculateContrastRatio._blendedFg[i]=0;return contrastRatio;} -static desiredLuminance(luminance,contrast,lighter){function computeLuminance(){if(lighter) -return(luminance+0.05)*contrast-0.05;else -return(luminance+0.05)/contrast-0.05;} -var desiredLuminance=computeLuminance();if(desiredLuminance<0||desiredLuminance>1){lighter=!lighter;desiredLuminance=computeLuminance();} -return desiredLuminance;} -static detectColorFormat(color){const cf=Common.Color.Format;var format;var formatSetting=Common.moduleSetting('colorFormat').get();if(formatSetting===cf.Original) -format=cf.Original;else if(formatSetting===cf.RGB) -format=(color.hasAlpha()?cf.RGBA:cf.RGB);else if(formatSetting===cf.HSL) -format=(color.hasAlpha()?cf.HSLA:cf.HSL);else if(formatSetting===cf.HEX) -format=color.detectHEXFormat();else -format=cf.RGBA;return format;} -format(){return this._format;} -hsla(){if(this._hsla) -return this._hsla;var r=this._rgba[0];var g=this._rgba[1];var b=this._rgba[2];var max=Math.max(r,g,b);var min=Math.min(r,g,b);var diff=max-min;var add=max+min;if(min===max) -var h=0;else if(r===max) -var h=((1/6*(g-b)/diff)+1)%1;else if(g===max) -var h=(1/6*(b-r)/diff)+1/3;else -var h=(1/6*(r-g)/diff)+2/3;var l=0.5*add;if(l===0) -var s=0;else if(l===1) -var s=0;else if(l<=0.5) -var s=diff/add;else -var s=diff/(2-add);this._hsla=[h,s,l,this._rgba[3]];return this._hsla;} -canonicalHSLA(){var hsla=this.hsla();return[Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]];} -hsva(){var hsla=this.hsla();var h=hsla[0];var s=hsla[1];var l=hsla[2];s*=l<0.5?l:1-l;return[h,s!==0?2*s/(l+s):0,(l+s),hsla[3]];} -hasAlpha(){return this._rgba[3]!==1;} -detectHEXFormat(){var canBeShort=true;for(var i=0;i<4;++i){var c=Math.round(this._rgba[i]*255);if(c%17){canBeShort=false;break;}} -var hasAlpha=this.hasAlpha();var cf=Common.Color.Format;if(canBeShort) -return hasAlpha?cf.ShortHEXA:cf.ShortHEX;return hasAlpha?cf.HEXA:cf.HEX;} -asString(format){if(format===this._format&&this._originalTextIsValid) -return this._originalText;if(!format) -format=this._format;function toRgbValue(value){return Math.round(value*255);} -function toHexValue(value){var hex=Math.round(value*255).toString(16);return hex.length===1?'0'+hex:hex;} -function toShortHexValue(value){return(Math.round(value*255)/17).toString(16);} -switch(format){case Common.Color.Format.Original:return this._originalText;case Common.Color.Format.RGB:if(this.hasAlpha()) -return null;return String.sprintf('rgb(%d, %d, %d)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]));case Common.Color.Format.RGBA:return String.sprintf('rgba(%d, %d, %d, %f)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]),this._rgba[3]);case Common.Color.Format.HSL:if(this.hasAlpha()) -return null;var hsl=this.hsla();return String.sprintf('hsl(%d, %d%, %d%)',Math.round(hsl[0]*360),Math.round(hsl[1]*100),Math.round(hsl[2]*100));case Common.Color.Format.HSLA:var hsla=this.hsla();return String.sprintf('hsla(%d, %d%, %d%, %f)',Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]);case Common.Color.Format.HEXA:return String.sprintf('#%s%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2]),toHexValue(this._rgba[3])).toLowerCase();case Common.Color.Format.HEX:if(this.hasAlpha()) -return null;return String.sprintf('#%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2])).toLowerCase();case Common.Color.Format.ShortHEXA:var hexFormat=this.detectHEXFormat();if(hexFormat!==Common.Color.Format.ShortHEXA&&hexFormat!==Common.Color.Format.ShortHEX) -return null;return String.sprintf('#%s%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2]),toShortHexValue(this._rgba[3])).toLowerCase();case Common.Color.Format.ShortHEX:if(this.hasAlpha()) -return null;if(this.detectHEXFormat()!==Common.Color.Format.ShortHEX) -return null;return String.sprintf('#%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2])).toLowerCase();case Common.Color.Format.Nickname:return this.nickname();} -return this._originalText;} -rgba(){return this._rgba.slice();} -canonicalRGBA(){var rgba=new Array(4);for(var i=0;i<3;++i) -rgba[i]=Math.round(this._rgba[i]*255);rgba[3]=this._rgba[3];return rgba;} -nickname(){if(!Common.Color._rgbaToNickname){Common.Color._rgbaToNickname={};for(var nickname in Common.Color.Nicknames){var rgba=Common.Color.Nicknames[nickname];if(rgba.length!==4) -rgba=rgba.concat(1);Common.Color._rgbaToNickname[rgba]=nickname;}} -return Common.Color._rgbaToNickname[this.canonicalRGBA()]||null;} -toProtocolRGBA(){var rgba=this.canonicalRGBA();var result={r:rgba[0],g:rgba[1],b:rgba[2]};if(rgba[3]!==1) -result.a=rgba[3];return result;} -invert(){var rgba=[];rgba[0]=1-this._rgba[0];rgba[1]=1-this._rgba[1];rgba[2]=1-this._rgba[2];rgba[3]=this._rgba[3];return new Common.Color(rgba,Common.Color.Format.RGBA);} -setAlpha(alpha){var rgba=this._rgba.slice();rgba[3]=alpha;return new Common.Color(rgba,Common.Color.Format.RGBA);} -blendWith(fgColor){var rgba=[];Common.Color.blendColors(fgColor._rgba,this._rgba,rgba);return new Common.Color(rgba,Common.Color.Format.RGBA);}};Common.Color.Regex=/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b[a-zA-Z]+\b(?!-))/g;Common.Color.Format={Original:'original',Nickname:'nickname',HEX:'hex',ShortHEX:'shorthex',HEXA:'hexa',ShortHEXA:'shorthexa',RGB:'rgb',RGBA:'rgba',HSL:'hsl',HSLA:'hsla'};Common.Color.hsva2rgba._tmpHSLA=[0,0,0,0];Common.Color.calculateContrastRatio._blendedFg=[0,0,0,0];Common.Color.Nicknames={'aliceblue':[240,248,255],'antiquewhite':[250,235,215],'aqua':[0,255,255],'aquamarine':[127,255,212],'azure':[240,255,255],'beige':[245,245,220],'bisque':[255,228,196],'black':[0,0,0],'blanchedalmond':[255,235,205],'blue':[0,0,255],'blueviolet':[138,43,226],'brown':[165,42,42],'burlywood':[222,184,135],'cadetblue':[95,158,160],'chartreuse':[127,255,0],'chocolate':[210,105,30],'coral':[255,127,80],'cornflowerblue':[100,149,237],'cornsilk':[255,248,220],'crimson':[237,20,61],'cyan':[0,255,255],'darkblue':[0,0,139],'darkcyan':[0,139,139],'darkgoldenrod':[184,134,11],'darkgray':[169,169,169],'darkgrey':[169,169,169],'darkgreen':[0,100,0],'darkkhaki':[189,183,107],'darkmagenta':[139,0,139],'darkolivegreen':[85,107,47],'darkorange':[255,140,0],'darkorchid':[153,50,204],'darkred':[139,0,0],'darksalmon':[233,150,122],'darkseagreen':[143,188,143],'darkslateblue':[72,61,139],'darkslategray':[47,79,79],'darkslategrey':[47,79,79],'darkturquoise':[0,206,209],'darkviolet':[148,0,211],'deeppink':[255,20,147],'deepskyblue':[0,191,255],'dimgray':[105,105,105],'dimgrey':[105,105,105],'dodgerblue':[30,144,255],'firebrick':[178,34,34],'floralwhite':[255,250,240],'forestgreen':[34,139,34],'fuchsia':[255,0,255],'gainsboro':[220,220,220],'ghostwhite':[248,248,255],'gold':[255,215,0],'goldenrod':[218,165,32],'gray':[128,128,128],'grey':[128,128,128],'green':[0,128,0],'greenyellow':[173,255,47],'honeydew':[240,255,240],'hotpink':[255,105,180],'indianred':[205,92,92],'indigo':[75,0,130],'ivory':[255,255,240],'khaki':[240,230,140],'lavender':[230,230,250],'lavenderblush':[255,240,245],'lawngreen':[124,252,0],'lemonchiffon':[255,250,205],'lightblue':[173,216,230],'lightcoral':[240,128,128],'lightcyan':[224,255,255],'lightgoldenrodyellow':[250,250,210],'lightgreen':[144,238,144],'lightgray':[211,211,211],'lightgrey':[211,211,211],'lightpink':[255,182,193],'lightsalmon':[255,160,122],'lightseagreen':[32,178,170],'lightskyblue':[135,206,250],'lightslategray':[119,136,153],'lightslategrey':[119,136,153],'lightsteelblue':[176,196,222],'lightyellow':[255,255,224],'lime':[0,255,0],'limegreen':[50,205,50],'linen':[250,240,230],'magenta':[255,0,255],'maroon':[128,0,0],'mediumaquamarine':[102,205,170],'mediumblue':[0,0,205],'mediumorchid':[186,85,211],'mediumpurple':[147,112,219],'mediumseagreen':[60,179,113],'mediumslateblue':[123,104,238],'mediumspringgreen':[0,250,154],'mediumturquoise':[72,209,204],'mediumvioletred':[199,21,133],'midnightblue':[25,25,112],'mintcream':[245,255,250],'mistyrose':[255,228,225],'moccasin':[255,228,181],'navajowhite':[255,222,173],'navy':[0,0,128],'oldlace':[253,245,230],'olive':[128,128,0],'olivedrab':[107,142,35],'orange':[255,165,0],'orangered':[255,69,0],'orchid':[218,112,214],'palegoldenrod':[238,232,170],'palegreen':[152,251,152],'paleturquoise':[175,238,238],'palevioletred':[219,112,147],'papayawhip':[255,239,213],'peachpuff':[255,218,185],'peru':[205,133,63],'pink':[255,192,203],'plum':[221,160,221],'powderblue':[176,224,230],'purple':[128,0,128],'rebeccapurple':[102,51,153],'red':[255,0,0],'rosybrown':[188,143,143],'royalblue':[65,105,225],'saddlebrown':[139,69,19],'salmon':[250,128,114],'sandybrown':[244,164,96],'seagreen':[46,139,87],'seashell':[255,245,238],'sienna':[160,82,45],'silver':[192,192,192],'skyblue':[135,206,235],'slateblue':[106,90,205],'slategray':[112,128,144],'slategrey':[112,128,144],'snow':[255,250,250],'springgreen':[0,255,127],'steelblue':[70,130,180],'tan':[210,180,140],'teal':[0,128,128],'thistle':[216,191,216],'tomato':[255,99,71],'turquoise':[64,224,208],'violet':[238,130,238],'wheat':[245,222,179],'white':[255,255,255],'whitesmoke':[245,245,245],'yellow':[255,255,0],'yellowgreen':[154,205,50],'transparent':[0,0,0,0],};Common.Color.PageHighlight={Content:Common.Color.fromRGBA([111,168,220,.66]),ContentLight:Common.Color.fromRGBA([111,168,220,.5]),ContentOutline:Common.Color.fromRGBA([9,83,148]),Padding:Common.Color.fromRGBA([147,196,125,.55]),PaddingLight:Common.Color.fromRGBA([147,196,125,.4]),Border:Common.Color.fromRGBA([255,229,153,.66]),BorderLight:Common.Color.fromRGBA([255,229,153,.5]),Margin:Common.Color.fromRGBA([246,178,107,.66]),MarginLight:Common.Color.fromRGBA([246,178,107,.5]),EventTarget:Common.Color.fromRGBA([255,196,196,.66]),Shape:Common.Color.fromRGBA([96,82,177,0.8]),ShapeMargin:Common.Color.fromRGBA([96,82,127,.6]),CssGrid:Common.Color.fromRGBA([0x4b,0,0x82,1])};Common.Color.Generator=class{constructor(hueSpace,satSpace,lightnessSpace,alphaSpace){this._hueSpace=hueSpace||{min:0,max:360};this._satSpace=satSpace||67;this._lightnessSpace=lightnessSpace||80;this._alphaSpace=alphaSpace||1;this._colors=new Map();} -setColorForID(id,color){this._colors.set(id,color);} -colorForID(id){var color=this._colors.get(id);if(!color){color=this._generateColorForID(id);this._colors.set(id,color);} -return color;} -_generateColorForID(id){var hash=String.hashCode(id);var h=this._indexToValueInSpace(hash,this._hueSpace);var s=this._indexToValueInSpace(hash>>8,this._satSpace);var l=this._indexToValueInSpace(hash>>16,this._lightnessSpace);var a=this._indexToValueInSpace(hash>>24,this._alphaSpace);return`hsla(${h}, ${s}%, ${l}%, ${a})`;} -_indexToValueInSpace(index,space){if(typeof space==='number') -return space;var count=space.count||space.max-space.min;index%=count;return space.min+Math.floor(index/(count-1)*(space.max-space.min));}};;Common.Console=class extends Common.Object{constructor(){super();this._messages=[];} -addMessage(text,level,show){var message=new Common.Console.Message(text,level||Common.Console.MessageLevel.Info,Date.now(),show||false);this._messages.push(message);this.dispatchEventToListeners(Common.Console.Events.MessageAdded,message);} -log(text){this.addMessage(text,Common.Console.MessageLevel.Info);} -warn(text){this.addMessage(text,Common.Console.MessageLevel.Warning);} -error(text){this.addMessage(text,Common.Console.MessageLevel.Error,true);} -messages(){return this._messages;} -show(){this.showPromise();} -showPromise(){return Common.Revealer.revealPromise(this);}};Common.Console.Events={MessageAdded:Symbol('messageAdded')};Common.Console.MessageLevel={Info:'info',Warning:'warning',Error:'error'};Common.Console.Message=class{constructor(text,level,timestamp,show){this.text=text;this.level=level;this.timestamp=(typeof timestamp==='number')?timestamp:Date.now();this.show=show;}};Common.console=new Common.Console();;Common.ContentProvider=function(){};Common.ContentProvider.prototype={contentURL(){},contentType(){},contentEncoded(){},requestContent(){},searchInContent(query,caseSensitive,isRegex){}};Common.ContentProvider.SearchMatch=class{constructor(lineNumber,lineContent){this.lineNumber=lineNumber;this.lineContent=lineContent;}};Common.ContentProvider.performSearchInContent=function(content,query,caseSensitive,isRegex){var regex=createSearchRegex(query,caseSensitive,isRegex);var text=new TextUtils.Text(content);var result=[];for(var i=0;i<text.lineCount();++i){var lineContent=text.lineAt(i);regex.lastIndex=0;if(regex.exec(lineContent)) -result.push(new Common.ContentProvider.SearchMatch(i,lineContent));} -return result;};Common.ContentProvider.contentAsDataURL=function(content,mimeType,contentEncoded,charset){const maxDataUrlSize=1024*1024;if(content===null||content.length>maxDataUrlSize) -return null;return'data:'+mimeType+(charset?';charset='+charset:'')+(contentEncoded?';base64':'')+','+ -content;};;Common.ParsedURL=class{constructor(url){this.isValid=false;this.url=url;this.scheme='';this.user='';this.host='';this.port='';this.path='';this.queryParams='';this.fragment='';this.folderPathComponents='';this.lastPathComponent='';var match=url.match(Common.ParsedURL._urlRegex());if(match){this.isValid=true;this.scheme=match[2].toLowerCase();this.user=match[3];this.host=match[4];this.port=match[5];this.path=match[6]||'/';this.queryParams=match[7]||'';this.fragment=match[8];}else{if(this.url.startsWith('data:')){this.scheme='data';return;} -if(this.url==='about:blank'){this.scheme='about';return;} -this.path=this.url;} -var lastSlashIndex=this.path.lastIndexOf('/');if(lastSlashIndex!==-1){this.folderPathComponents=this.path.substring(0,lastSlashIndex);this.lastPathComponent=this.path.substring(lastSlashIndex+1);}else{this.lastPathComponent=this.path;}} -static platformPathToURL(fileSystemPath){fileSystemPath=fileSystemPath.replace(/\\/g,'/');if(!fileSystemPath.startsWith('file://')){if(fileSystemPath.startsWith('/')) -fileSystemPath='file://'+fileSystemPath;else -fileSystemPath='file:///'+fileSystemPath;} -return fileSystemPath;} -static _urlRegex(){if(Common.ParsedURL._urlRegexInstance) -return Common.ParsedURL._urlRegexInstance;var schemeRegex=/([A-Za-z][A-Za-z0-9+.-]*):\/\//;var userRegex=/(?:([A-Za-z0-9\-._~%!$&'()*+,;=:]*)@)?/;var hostRegex=/([^\s\/:]*)/;var portRegex=/(?::([\d]+))?/;var pathRegex=/(\/[^#?]*)?/;var queryRegex=/(?:\?([^#]*))?/;var fragmentRegex=/(?:#(.*))?/;Common.ParsedURL._urlRegexInstance=new RegExp('^('+schemeRegex.source+userRegex.source+hostRegex.source+portRegex.source+')'+pathRegex.source+ -queryRegex.source+fragmentRegex.source+'$');return Common.ParsedURL._urlRegexInstance;} -static extractPath(url){var parsedURL=url.asParsedURL();return parsedURL?parsedURL.path:'';} -static extractOrigin(url){var parsedURL=url.asParsedURL();return parsedURL?parsedURL.securityOrigin():'';} -static extractExtension(url){var lastIndexOfDot=url.lastIndexOf('.');var extension=lastIndexOfDot!==-1?url.substr(lastIndexOfDot+1):'';var indexOfQuestionMark=extension.indexOf('?');if(indexOfQuestionMark!==-1) -extension=extension.substr(0,indexOfQuestionMark);return extension;} -static extractName(url){var index=url.lastIndexOf('/');return index!==-1?url.substr(index+1):url;} -static completeURL(baseURL,href){var trimmedHref=href.trim();if(trimmedHref.startsWith('data:')||trimmedHref.startsWith('blob:')||trimmedHref.startsWith('javascript:')) -return href;var parsedHref=trimmedHref.asParsedURL();if(parsedHref&&parsedHref.scheme) -return trimmedHref;var parsedURL=baseURL.asParsedURL();if(!parsedURL) -return null;if(parsedURL.isDataURL()) -return href;if(href.length>1&&href.charAt(0)==='/'&&href.charAt(1)==='/'){return parsedURL.scheme+':'+href;} -var securityOrigin=parsedURL.securityOrigin();var pathText=parsedURL.path;var queryText=parsedURL.queryParams?'?'+parsedURL.queryParams:'';if(!href.length) -return securityOrigin+pathText+queryText;if(href.charAt(0)==='#') -return securityOrigin+pathText+queryText+href;if(href.charAt(0)==='?') -return securityOrigin+pathText+href;var hrefPath=href.match(/^[^#?]*/)[0];var hrefSuffix=href.substring(hrefPath.length);if(hrefPath.charAt(0)!=='/') -hrefPath=parsedURL.folderPathComponents+'/'+hrefPath;return securityOrigin+Runtime.normalizePath(hrefPath)+hrefSuffix;} -static splitLineAndColumn(string){var beforePathMatch=string.match(Common.ParsedURL._urlRegex());var beforePath='';var pathAndAfter=string;if(beforePathMatch){beforePath=beforePathMatch[1];pathAndAfter=string.substring(beforePathMatch[1].length);} -var lineColumnRegEx=/(?::(\d+))?(?::(\d+))?$/;var lineColumnMatch=lineColumnRegEx.exec(pathAndAfter);var lineNumber;var columnNumber;console.assert(lineColumnMatch);if(typeof(lineColumnMatch[1])==='string'){lineNumber=parseInt(lineColumnMatch[1],10);lineNumber=isNaN(lineNumber)?undefined:lineNumber-1;} -if(typeof(lineColumnMatch[2])==='string'){columnNumber=parseInt(lineColumnMatch[2],10);columnNumber=isNaN(columnNumber)?undefined:columnNumber-1;} -return{url:beforePath+pathAndAfter.substring(0,pathAndAfter.length-lineColumnMatch[0].length),lineNumber:lineNumber,columnNumber:columnNumber};} -static isRelativeURL(url){return!(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(url));} -get displayName(){if(this._displayName) -return this._displayName;if(this.isDataURL()) -return this.dataURLDisplayName();if(this.isAboutBlank()) -return this.url;this._displayName=this.lastPathComponent;if(!this._displayName) -this._displayName=(this.host||'')+'/';if(this._displayName==='/') -this._displayName=this.url;return this._displayName;} -dataURLDisplayName(){if(this._dataURLDisplayName) -return this._dataURLDisplayName;if(!this.isDataURL()) -return'';this._dataURLDisplayName=this.url.trimEnd(20);return this._dataURLDisplayName;} -isAboutBlank(){return this.url==='about:blank';} -isDataURL(){return this.scheme==='data';} -lastPathComponentWithFragment(){return this.lastPathComponent+(this.fragment?'#'+this.fragment:'');} -domain(){if(this.isDataURL()) -return'data:';return this.host+(this.port?':'+this.port:'');} -securityOrigin(){if(this.isDataURL()) -return'data:';return this.scheme+'://'+this.domain();} -urlWithoutScheme(){if(this.scheme&&this.url.startsWith(this.scheme+'://')) -return this.url.substring(this.scheme.length+3);return this.url;}};String.prototype.asParsedURL=function(){var parsedURL=new Common.ParsedURL(this.toString());if(parsedURL.isValid) -return parsedURL;return null;};;Common.Progress=function(){};Common.Progress.prototype={setTotalWork(totalWork){},setTitle(title){},setWorked(worked,title){},worked(worked){},done(){},isCanceled(){return false;},};Common.CompositeProgress=class{constructor(parent){this._parent=parent;this._children=[];this._childrenDone=0;this._parent.setTotalWork(1);this._parent.setWorked(0);} -_childDone(){if(++this._childrenDone!==this._children.length) -return;this._parent.done();} -createSubProgress(weight){var child=new Common.SubProgress(this,weight);this._children.push(child);return child;} -_update(){var totalWeights=0;var done=0;for(var i=0;i<this._children.length;++i){var child=this._children[i];if(child._totalWork) -done+=child._weight*child._worked/child._totalWork;totalWeights+=child._weight;} -this._parent.setWorked(done/totalWeights);}};Common.SubProgress=class{constructor(composite,weight){this._composite=composite;this._weight=weight||1;this._worked=0;} -isCanceled(){return this._composite._parent.isCanceled();} -setTitle(title){this._composite._parent.setTitle(title);} -done(){this.setWorked(this._totalWork);this._composite._childDone();} -setTotalWork(totalWork){this._totalWork=totalWork;this._composite._update();} -setWorked(worked,title){this._worked=worked;if(typeof title!=='undefined') -this.setTitle(title);this._composite._update();} -worked(worked){this.setWorked(this._worked+(worked||1));}};Common.ProgressProxy=class{constructor(delegate,doneCallback){this._delegate=delegate;this._doneCallback=doneCallback;} -isCanceled(){return this._delegate?this._delegate.isCanceled():false;} -setTitle(title){if(this._delegate) -this._delegate.setTitle(title);} -done(){if(this._delegate) -this._delegate.done();if(this._doneCallback) -this._doneCallback();} -setTotalWork(totalWork){if(this._delegate) -this._delegate.setTotalWork(totalWork);} -setWorked(worked,title){if(this._delegate) -this._delegate.setWorked(worked,title);} -worked(worked){if(this._delegate) -this._delegate.worked(worked);}};;Common.ResourceType=class{constructor(name,title,category,isTextType){this._name=name;this._title=title;this._category=category;this._isTextType=isTextType;} -static fromMimeType(mimeType){if(mimeType.startsWith('text/html')) -return Common.resourceTypes.Document;if(mimeType.startsWith('text/css')) -return Common.resourceTypes.Stylesheet;if(mimeType.startsWith('image/')) -return Common.resourceTypes.Image;if(mimeType.startsWith('text/')) -return Common.resourceTypes.Script;if(mimeType.includes('font')) -return Common.resourceTypes.Font;if(mimeType.includes('script')) -return Common.resourceTypes.Script;if(mimeType.includes('octet')) -return Common.resourceTypes.Other;if(mimeType.includes('application')) -return Common.resourceTypes.Script;return Common.resourceTypes.Other;} -static fromURL(url){return Common.ResourceType._resourceTypeByExtension.get(Common.ParsedURL.extractExtension(url))||null;} -static mimeFromURL(url){var name=Common.ParsedURL.extractName(url);if(Common.ResourceType._mimeTypeByName.has(name)) -return Common.ResourceType._mimeTypeByName.get(name);var ext=Common.ParsedURL.extractExtension(url).toLowerCase();return Common.ResourceType._mimeTypeByExtension.get(ext);} -name(){return this._name;} -title(){return this._title;} -category(){return this._category;} -isTextType(){return this._isTextType;} -isScript(){return this._name==='script'||this._name==='sm-script'||this._name==='snippet';} -hasScripts(){return this.isScript()||this.isDocument();} -isStyleSheet(){return this._name==='stylesheet'||this._name==='sm-stylesheet';} -isDocument(){return this._name==='document';} -isDocumentOrScriptOrStyleSheet(){return this.isDocument()||this.isScript()||this.isStyleSheet();} -isFromSourceMap(){return this._name.startsWith('sm-');} -toString(){return this._name;} -canonicalMimeType(){if(this.isDocument()) -return'text/html';if(this.isScript()) -return'text/javascript';if(this.isStyleSheet()) -return'text/css';return'';}};Common.ResourceCategory=class{constructor(title,shortTitle){this.title=title;this.shortTitle=shortTitle;}};Common.resourceCategories={XHR:new Common.ResourceCategory('XHR and Fetch','XHR'),Script:new Common.ResourceCategory('Scripts','JS'),Stylesheet:new Common.ResourceCategory('Stylesheets','CSS'),Image:new Common.ResourceCategory('Images','Img'),Media:new Common.ResourceCategory('Media','Media'),Font:new Common.ResourceCategory('Fonts','Font'),Document:new Common.ResourceCategory('Documents','Doc'),WebSocket:new Common.ResourceCategory('WebSockets','WS'),Manifest:new Common.ResourceCategory('Manifest','Manifest'),Other:new Common.ResourceCategory('Other','Other')};Common.resourceTypes={XHR:new Common.ResourceType('xhr','XHR',Common.resourceCategories.XHR,true),Fetch:new Common.ResourceType('fetch','Fetch',Common.resourceCategories.XHR,true),EventSource:new Common.ResourceType('eventsource','EventSource',Common.resourceCategories.XHR,true),Script:new Common.ResourceType('script','Script',Common.resourceCategories.Script,true),Snippet:new Common.ResourceType('snippet','Snippet',Common.resourceCategories.Script,true),Stylesheet:new Common.ResourceType('stylesheet','Stylesheet',Common.resourceCategories.Stylesheet,true),Image:new Common.ResourceType('image','Image',Common.resourceCategories.Image,false),Media:new Common.ResourceType('media','Media',Common.resourceCategories.Media,false),Font:new Common.ResourceType('font','Font',Common.resourceCategories.Font,false),Document:new Common.ResourceType('document','Document',Common.resourceCategories.Document,true),TextTrack:new Common.ResourceType('texttrack','TextTrack',Common.resourceCategories.Other,true),WebSocket:new Common.ResourceType('websocket','WebSocket',Common.resourceCategories.WebSocket,false),Other:new Common.ResourceType('other','Other',Common.resourceCategories.Other,false),SourceMapScript:new Common.ResourceType('sm-script','Script',Common.resourceCategories.Script,false),SourceMapStyleSheet:new Common.ResourceType('sm-stylesheet','Stylesheet',Common.resourceCategories.Stylesheet,false),Manifest:new Common.ResourceType('manifest','Manifest',Common.resourceCategories.Manifest,true),};Common.ResourceType._mimeTypeByName=new Map([['Cakefile','text/x-coffeescript']]);Common.ResourceType._resourceTypeByExtension=new Map([['js',Common.resourceTypes.Script],['css',Common.resourceTypes.Stylesheet],['xsl',Common.resourceTypes.Stylesheet],['jpeg',Common.resourceTypes.Image],['jpg',Common.resourceTypes.Image],['svg',Common.resourceTypes.Image],['gif',Common.resourceTypes.Image],['png',Common.resourceTypes.Image],['ico',Common.resourceTypes.Image],['tiff',Common.resourceTypes.Image],['tif',Common.resourceTypes.Image],['bmp',Common.resourceTypes.Image],['webp',Common.resourceTypes.Media],['ttf',Common.resourceTypes.Font],['otf',Common.resourceTypes.Font],['ttc',Common.resourceTypes.Font],['woff',Common.resourceTypes.Font]]);Common.ResourceType._mimeTypeByExtension=new Map([['js','text/javascript'],['css','text/css'],['html','text/html'],['htm','text/html'],['xml','application/xml'],['xsl','application/xml'],['asp','application/x-aspx'],['aspx','application/x-aspx'],['jsp','application/x-jsp'],['c','text/x-c++src'],['cc','text/x-c++src'],['cpp','text/x-c++src'],['h','text/x-c++src'],['m','text/x-c++src'],['mm','text/x-c++src'],['coffee','text/x-coffeescript'],['dart','text/javascript'],['ts','text/typescript'],['tsx','text/typescript'],['json','application/json'],['gyp','application/json'],['gypi','application/json'],['cs','text/x-csharp'],['java','text/x-java'],['less','text/x-less'],['php','text/x-php'],['phtml','application/x-httpd-php'],['py','text/x-python'],['sh','text/x-sh'],['scss','text/x-scss'],['vtt','text/vtt'],['ls','text/x-livescript'],['cljs','text/x-clojure'],['cljc','text/x-clojure'],['cljx','text/x-clojure'],['styl','text/x-styl'],['jsx','text/jsx'],['jpeg','image/jpeg'],['jpg','image/jpeg'],['svg','image/svg+xml'],['gif','image/gif'],['webp','image/webp'],['png','image/png'],['ico','image/ico'],['tiff','image/tiff'],['tif','image/tif'],['bmp','image/bmp'],['ttf','font/opentype'],['otf','font/opentype'],['ttc','font/opentype'],['woff','application/font-woff']]);;Common.Settings=class{constructor(globalStorage,localStorage){this._globalStorage=globalStorage;this._localStorage=localStorage;this._sessionStorage=new Common.SettingsStorage({});this._eventSupport=new Common.Object();this._registry=new Map();this._moduleSettings=new Map();self.runtime.extensions('setting').forEach(this._registerModuleSetting.bind(this));} -_registerModuleSetting(extension){var descriptor=extension.descriptor();var settingName=descriptor['settingName'];var isRegex=descriptor['settingType']==='regex';var defaultValue=descriptor['defaultValue'];var storageType;switch(descriptor['storageType']){case('local'):storageType=Common.SettingStorageType.Local;break;case('session'):storageType=Common.SettingStorageType.Session;break;case('global'):storageType=Common.SettingStorageType.Global;break;default:storageType=Common.SettingStorageType.Global;} -var setting=isRegex?this.createRegExpSetting(settingName,defaultValue,undefined,storageType):this.createSetting(settingName,defaultValue,storageType);if(descriptor['title']) -setting.setTitle(descriptor['title']);if(descriptor['userActionCondition']) -setting.setRequiresUserAction(!!Runtime.queryParam(descriptor['userActionCondition']));setting._extension=extension;this._moduleSettings.set(settingName,setting);} -moduleSetting(settingName){var setting=this._moduleSettings.get(settingName);if(!setting) -throw new Error('No setting registered: '+settingName);return setting;} -settingForTest(settingName){var setting=this._registry.get(settingName);if(!setting) -throw new Error('No setting registered: '+settingName);return setting;} -createSetting(key,defaultValue,storageType){var storage=this._storageFromType(storageType);if(!this._registry.get(key)) -this._registry.set(key,new Common.Setting(this,key,defaultValue,this._eventSupport,storage));return(this._registry.get(key));} -createLocalSetting(key,defaultValue){return this.createSetting(key,defaultValue,Common.SettingStorageType.Local);} -createRegExpSetting(key,defaultValue,regexFlags,storageType){if(!this._registry.get(key)){this._registry.set(key,new Common.RegExpSetting(this,key,defaultValue,this._eventSupport,this._storageFromType(storageType),regexFlags));} -return(this._registry.get(key));} -clearAll(){this._globalStorage.removeAll();this._localStorage.removeAll();var versionSetting=Common.settings.createSetting(Common.VersionController._currentVersionName,0);versionSetting.set(Common.VersionController.currentVersion);} -_storageFromType(storageType){switch(storageType){case(Common.SettingStorageType.Local):return this._localStorage;case(Common.SettingStorageType.Session):return this._sessionStorage;case(Common.SettingStorageType.Global):return this._globalStorage;} -return this._globalStorage;}};Common.SettingsStorage=class{constructor(object,setCallback,removeCallback,removeAllCallback,storagePrefix){this._object=object;this._setCallback=setCallback||function(){};this._removeCallback=removeCallback||function(){};this._removeAllCallback=removeAllCallback||function(){};this._storagePrefix=storagePrefix||'';} -set(name,value){name=this._storagePrefix+name;this._object[name]=value;this._setCallback(name,value);} -has(name){name=this._storagePrefix+name;return name in this._object;} -get(name){name=this._storagePrefix+name;return this._object[name];} -remove(name){name=this._storagePrefix+name;delete this._object[name];this._removeCallback(name);} -removeAll(){this._object={};this._removeAllCallback();} -_dumpSizes(){Common.console.log('Ten largest settings: ');var sizes={__proto__:null};for(var key in this._object) -sizes[key]=this._object[key].length;var keys=Object.keys(sizes);function comparator(key1,key2){return sizes[key2]-sizes[key1];} -keys.sort(comparator);for(var i=0;i<10&&i<keys.length;++i) -Common.console.log('Setting: \''+keys[i]+'\', size: '+sizes[keys[i]]);}};Common.Setting=class{constructor(settings,name,defaultValue,eventSupport,storage){this._settings=settings;this._name=name;this._defaultValue=defaultValue;this._eventSupport=eventSupport;this._storage=storage;this._title='';this._extension=null;} -addChangeListener(listener,thisObject){this._eventSupport.addEventListener(this._name,listener,thisObject);} -removeChangeListener(listener,thisObject){this._eventSupport.removeEventListener(this._name,listener,thisObject);} -get name(){return this._name;} -title(){return this._title;} -setTitle(title){this._title=title;} -setRequiresUserAction(requiresUserAction){this._requiresUserAction=requiresUserAction;} -get(){if(this._requiresUserAction&&!this._hadUserAction) -return this._defaultValue;if(typeof this._value!=='undefined') -return this._value;this._value=this._defaultValue;if(this._storage.has(this._name)){try{this._value=JSON.parse(this._storage.get(this._name));}catch(e){this._storage.remove(this._name);}} -return this._value;} -set(value){this._hadUserAction=true;this._value=value;try{var settingString=JSON.stringify(value);try{this._storage.set(this._name,settingString);}catch(e){this._printSettingsSavingError(e.message,this._name,settingString);}}catch(e){Common.console.error('Cannot stringify setting with name: '+this._name+', error: '+e.message);} -this._eventSupport.dispatchEventToListeners(this._name,value);} -remove(){this._settings._registry.delete(this._name);this._settings._moduleSettings.delete(this._name);this._storage.remove(this._name);} -extension(){return this._extension;} -_printSettingsSavingError(message,name,value){var errorMessage='Error saving setting with name: '+this._name+', value length: '+value.length+'. Error: '+message;console.error(errorMessage);Common.console.error(errorMessage);this._storage._dumpSizes();}};Common.RegExpSetting=class extends Common.Setting{constructor(settings,name,defaultValue,eventSupport,storage,regexFlags){super(settings,name,defaultValue?[{pattern:defaultValue}]:[],eventSupport,storage);this._regexFlags=regexFlags;} -get(){var result=[];var items=this.getAsArray();for(var i=0;i<items.length;++i){var item=items[i];if(item.pattern&&!item.disabled) -result.push(item.pattern);} -return result.join('|');} -getAsArray(){return super.get();} -set(value){this.setAsArray([{pattern:value}]);} -setAsArray(value){delete this._regex;super.set(value);} -asRegExp(){if(typeof this._regex!=='undefined') -return this._regex;this._regex=null;try{var pattern=this.get();if(pattern) -this._regex=new RegExp(pattern,this._regexFlags||'');}catch(e){} -return this._regex;}};Common.VersionController=class{updateVersion(){var localStorageVersion=window.localStorage?window.localStorage[Common.VersionController._currentVersionName]:0;var versionSetting=Common.settings.createSetting(Common.VersionController._currentVersionName,0);var currentVersion=Common.VersionController.currentVersion;var oldVersion=versionSetting.get()||parseInt(localStorageVersion||'0',10);if(oldVersion===0){versionSetting.set(currentVersion);return;} -var methodsToRun=this._methodsToRunToUpdateVersion(oldVersion,currentVersion);for(var i=0;i<methodsToRun.length;++i) -this[methodsToRun[i]].call(this);versionSetting.set(currentVersion);} -_methodsToRunToUpdateVersion(oldVersion,currentVersion){var result=[];for(var i=oldVersion;i<currentVersion;++i) -result.push('_updateVersionFrom'+i+'To'+(i+1));return result;} -_updateVersionFrom0To1(){this._clearBreakpointsWhenTooMany(Common.settings.createLocalSetting('breakpoints',[]),500000);} -_updateVersionFrom1To2(){Common.settings.createSetting('previouslyViewedFiles',[]).set([]);} -_updateVersionFrom2To3(){Common.settings.createSetting('fileSystemMapping',{}).set({});Common.settings.createSetting('fileMappingEntries',[]).remove();} -_updateVersionFrom3To4(){var advancedMode=Common.settings.createSetting('showHeaSnapshotObjectsHiddenProperties',false);Common.moduleSetting('showAdvancedHeapSnapshotProperties').set(advancedMode.get());advancedMode.remove();} -_updateVersionFrom4To5(){var settingNames={'FileSystemViewSidebarWidth':'fileSystemViewSplitViewState','elementsSidebarWidth':'elementsPanelSplitViewState','StylesPaneSplitRatio':'stylesPaneSplitViewState','heapSnapshotRetainersViewSize':'heapSnapshotSplitViewState','InspectorView.splitView':'InspectorView.splitViewState','InspectorView.screencastSplitView':'InspectorView.screencastSplitViewState','Inspector.drawerSplitView':'Inspector.drawerSplitViewState','layerDetailsSplitView':'layerDetailsSplitViewState','networkSidebarWidth':'networkPanelSplitViewState','sourcesSidebarWidth':'sourcesPanelSplitViewState','scriptsPanelNavigatorSidebarWidth':'sourcesPanelNavigatorSplitViewState','sourcesPanelSplitSidebarRatio':'sourcesPanelDebuggerSidebarSplitViewState','timeline-details':'timelinePanelDetailsSplitViewState','timeline-split':'timelinePanelRecorsSplitViewState','timeline-view':'timelinePanelTimelineStackSplitViewState','auditsSidebarWidth':'auditsPanelSplitViewState','layersSidebarWidth':'layersPanelSplitViewState','profilesSidebarWidth':'profilesPanelSplitViewState','resourcesSidebarWidth':'resourcesPanelSplitViewState'};var empty={};for(var oldName in settingNames){var newName=settingNames[oldName];var oldNameH=oldName+'H';var newValue=null;var oldSetting=Common.settings.createSetting(oldName,empty);if(oldSetting.get()!==empty){newValue=newValue||{};newValue.vertical={};newValue.vertical.size=oldSetting.get();oldSetting.remove();} -var oldSettingH=Common.settings.createSetting(oldNameH,empty);if(oldSettingH.get()!==empty){newValue=newValue||{};newValue.horizontal={};newValue.horizontal.size=oldSettingH.get();oldSettingH.remove();} -if(newValue) -Common.settings.createSetting(newName,{}).set(newValue);}} -_updateVersionFrom5To6(){var settingNames={'debuggerSidebarHidden':'sourcesPanelSplitViewState','navigatorHidden':'sourcesPanelNavigatorSplitViewState','WebInspector.Drawer.showOnLoad':'Inspector.drawerSplitViewState'};for(var oldName in settingNames){var oldSetting=Common.settings.createSetting(oldName,null);if(oldSetting.get()===null){oldSetting.remove();continue;} -var newName=settingNames[oldName];var invert=oldName==='WebInspector.Drawer.showOnLoad';var hidden=oldSetting.get()!==invert;oldSetting.remove();var showMode=hidden?'OnlyMain':'Both';var newSetting=Common.settings.createSetting(newName,{});var newValue=newSetting.get()||{};newValue.vertical=newValue.vertical||{};newValue.vertical.showMode=showMode;newValue.horizontal=newValue.horizontal||{};newValue.horizontal.showMode=showMode;newSetting.set(newValue);}} -_updateVersionFrom6To7(){var settingNames={'sourcesPanelNavigatorSplitViewState':'sourcesPanelNavigatorSplitViewState','elementsPanelSplitViewState':'elementsPanelSplitViewState','stylesPaneSplitViewState':'stylesPaneSplitViewState','sourcesPanelDebuggerSidebarSplitViewState':'sourcesPanelDebuggerSidebarSplitViewState'};var empty={};for(var name in settingNames){var setting=Common.settings.createSetting(name,empty);var value=setting.get();if(value===empty) -continue;if(value.vertical&&value.vertical.size&&value.vertical.size<1) -value.vertical.size=0;if(value.horizontal&&value.horizontal.size&&value.horizontal.size<1) -value.horizontal.size=0;setting.set(value);}} -_updateVersionFrom7To8(){} -_updateVersionFrom8To9(){var settingNames=['skipStackFramesPattern','workspaceFolderExcludePattern'];for(var i=0;i<settingNames.length;++i){var setting=Common.settings.createSetting(settingNames[i],'');var value=setting.get();if(!value) -return;if(typeof value==='string') -value=[value];for(var j=0;j<value.length;++j){if(typeof value[j]==='string') -value[j]={pattern:value[j]};} -setting.set(value);}} -_updateVersionFrom9To10(){if(!window.localStorage) -return;for(var key in window.localStorage){if(key.startsWith('revision-history')) -window.localStorage.removeItem(key);}} -_updateVersionFrom10To11(){var oldSettingName='customDevicePresets';var newSettingName='customEmulatedDeviceList';var oldSetting=Common.settings.createSetting(oldSettingName,undefined);var list=oldSetting.get();if(!Array.isArray(list)) -return;var newList=[];for(var i=0;i<list.length;++i){var value=list[i];var device={};device['title']=value['title'];device['type']='unknown';device['user-agent']=value['userAgent'];device['capabilities']=[];if(value['touch']) -device['capabilities'].push('touch');if(value['mobile']) -device['capabilities'].push('mobile');device['screen']={};device['screen']['vertical']={width:value['width'],height:value['height']};device['screen']['horizontal']={width:value['height'],height:value['width']};device['screen']['device-pixel-ratio']=value['deviceScaleFactor'];device['modes']=[];device['show-by-default']=true;device['show']='Default';newList.push(device);} -if(newList.length) -Common.settings.createSetting(newSettingName,[]).set(newList);oldSetting.remove();} -_updateVersionFrom11To12(){this._migrateSettingsFromLocalStorage();} -_updateVersionFrom12To13(){this._migrateSettingsFromLocalStorage();Common.settings.createSetting('timelineOverviewMode','').remove();} -_updateVersionFrom13To14(){var defaultValue={'throughput':-1,'latency':0};Common.settings.createSetting('networkConditions',defaultValue).set(defaultValue);} -_updateVersionFrom14To15(){var setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});var oldValue=setting.get();var newValue={};for(var fileSystemPath in oldValue){newValue[fileSystemPath]=[];for(var entry of oldValue[fileSystemPath]) -newValue[fileSystemPath].push(entry.path);} -setting.set(newValue);} -_updateVersionFrom15To16(){var setting=Common.settings.createSetting('InspectorView.panelOrder',{});var tabOrders=setting.get();for(var key of Object.keys(tabOrders)) -tabOrders[key]=(tabOrders[key]+1)*10;setting.set(tabOrders);} -_updateVersionFrom16To17(){var setting=Common.settings.createSetting('networkConditionsCustomProfiles',[]);var oldValue=setting.get();var newValue=[];if(Array.isArray(oldValue)){for(var preset of oldValue){if(typeof preset.title==='string'&&typeof preset.value==='object'&&typeof preset.value.throughput==='number'&&typeof preset.value.latency==='number'){newValue.push({title:preset.title,value:{download:preset.value.throughput,upload:preset.value.throughput,latency:preset.value.latency}});}}} -setting.set(newValue);} -_updateVersionFrom17To18(){var setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});var oldValue=setting.get();var newValue={};for(var oldKey in oldValue){var newKey=oldKey.replace(/\\/g,'/');if(!newKey.startsWith('file://')){if(newKey.startsWith('/')) -newKey='file://'+newKey;else -newKey='file:///'+newKey;} -newValue[newKey]=oldValue[oldKey];} -setting.set(newValue);} -_updateVersionFrom18To19(){var defaultColumns={status:true,type:true,initiator:true,size:true,time:true};var visibleColumnSettings=Common.settings.createSetting('networkLogColumnsVisibility',defaultColumns);var visibleColumns=visibleColumnSettings.get();visibleColumns.name=true;visibleColumns.timeline=true;var configs={};for(var columnId in visibleColumns){if(!visibleColumns.hasOwnProperty(columnId)) -continue;configs[columnId.toLowerCase()]={visible:visibleColumns[columnId]};} -var newSetting=Common.settings.createSetting('networkLogColumns',{});newSetting.set(configs);visibleColumnSettings.remove();} -_updateVersionFrom19To20(){var oldSetting=Common.settings.createSetting('InspectorView.panelOrder',{});var newSetting=Common.settings.createSetting('panel-tabOrder',{});newSetting.set(oldSetting.get());oldSetting.remove();} -_updateVersionFrom20To21(){var networkColumns=Common.settings.createSetting('networkLogColumns',{});var columns=(networkColumns.get());delete columns['timeline'];delete columns['waterfall'];networkColumns.set(columns);} -_updateVersionFrom21To22(){var breakpointsSetting=Common.settings.createLocalSetting('breakpoints',[]);var breakpoints=breakpointsSetting.get();for(var breakpoint of breakpoints){breakpoint['url']=breakpoint['sourceFileId'];delete breakpoint['sourceFileId'];} -breakpointsSetting.set(breakpoints);} -_updateVersionFrom22To23(){} -_updateVersionFrom23To24(){var oldSetting=Common.settings.createSetting('searchInContentScripts',false);var newSetting=Common.settings.createSetting('searchInAnonymousAndContentScripts',false);newSetting.set(oldSetting.get());oldSetting.remove();} -_updateVersionFrom24To25(){var defaultColumns={status:true,type:true,initiator:true,size:true,time:true};var networkLogColumnsSetting=Common.settings.createSetting('networkLogColumns',defaultColumns);var columns=networkLogColumnsSetting.get();delete columns.product;networkLogColumnsSetting.set(columns);} -_migrateSettingsFromLocalStorage(){var localSettings=new Set(['advancedSearchConfig','breakpoints','consoleHistory','domBreakpoints','eventListenerBreakpoints','fileSystemMapping','lastSelectedSourcesSidebarPaneTab','previouslyViewedFiles','savedURLs','watchExpressions','workspaceExcludedFolders','xhrBreakpoints']);if(!window.localStorage) -return;for(var key in window.localStorage){if(localSettings.has(key)) -continue;var value=window.localStorage[key];window.localStorage.removeItem(key);Common.settings._globalStorage[key]=value;}} -_clearBreakpointsWhenTooMany(breakpointsSetting,maxBreakpointsCount){if(breakpointsSetting.get().length>maxBreakpointsCount) -breakpointsSetting.set([]);}};Common.VersionController._currentVersionName='inspectorVersion';Common.VersionController.currentVersion=25;Common.settings;Common.SettingStorageType={Global:Symbol('Global'),Local:Symbol('Local'),Session:Symbol('Session')};Common.moduleSetting=function(settingName){return Common.settings.moduleSetting(settingName);};Common.settingForTest=function(settingName){return Common.settings.settingForTest(settingName);};;Common.StaticContentProvider=class{constructor(contentURL,contentType,lazyContent){this._contentURL=contentURL;this._contentType=contentType;this._lazyContent=lazyContent;} -static fromString(contentURL,contentType,content){var lazyContent=()=>Promise.resolve(content);return new Common.StaticContentProvider(contentURL,contentType,lazyContent);} -contentURL(){return this._contentURL;} -contentType(){return this._contentType;} -contentEncoded(){return Promise.resolve(false);} -requestContent(){return this._lazyContent();} -async searchInContent(query,caseSensitive,isRegex){var content=await this._lazyContent();return content?Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex):[];}};;Common.OutputStream=function(){};Common.OutputStream.prototype={write(data){},close(){}};Common.StringOutputStream=class{constructor(){this._data='';} -async write(chunk){this._data+=chunk;} -close(){} -data(){return this._data;}};;Common.Segment=class{constructor(begin,end,data){if(begin>end) -console.assert(false,'Invalid segment');this.begin=begin;this.end=end;this.data=data;} -intersects(that){return this.begin<that.end&&that.begin<this.end;}};Common.SegmentedRange=class{constructor(mergeCallback){this._segments=[];this._mergeCallback=mergeCallback;} -append(newSegment){var startIndex=this._segments.lowerBound(newSegment,(a,b)=>a.begin-b.begin);var endIndex=startIndex;var merged=null;if(startIndex>0){var precedingSegment=this._segments[startIndex-1];merged=this._tryMerge(precedingSegment,newSegment);if(merged){--startIndex;newSegment=merged;}else if(this._segments[startIndex-1].end>=newSegment.begin){if(newSegment.end<precedingSegment.end){this._segments.splice(startIndex,0,new Common.Segment(newSegment.end,precedingSegment.end,precedingSegment.data));} -precedingSegment.end=newSegment.begin;}} -while(endIndex<this._segments.length&&this._segments[endIndex].end<=newSegment.end) -++endIndex;if(endIndex<this._segments.length){merged=this._tryMerge(newSegment,this._segments[endIndex]);if(merged){endIndex++;newSegment=merged;}else if(newSegment.intersects(this._segments[endIndex])){this._segments[endIndex].begin=newSegment.end;}} -this._segments.splice(startIndex,endIndex-startIndex,newSegment);} -appendRange(that){that.segments().forEach(segment=>this.append(segment));} -segments(){return this._segments;} -_tryMerge(first,second){var merged=this._mergeCallback&&this._mergeCallback(first,second);if(!merged) -return null;merged.begin=first.begin;merged.end=Math.max(first.end,second.end);return merged;}};;Common.Throttler=class{constructor(timeout){this._timeout=timeout;this._isRunningProcess=false;this._asSoonAsPossible=false;this._process=null;this._lastCompleteTime=0;} -_processCompleted(){this._lastCompleteTime=window.performance.now();this._isRunningProcess=false;if(this._process) -this._innerSchedule(false);this._processCompletedForTests();} -_processCompletedForTests(){} -_onTimeout(){delete this._processTimeout;this._asSoonAsPossible=false;this._isRunningProcess=true;Promise.resolve().then(this._process).catch(console.error.bind(console)).then(this._processCompleted.bind(this));this._process=null;} -schedule(process,asSoonAsPossible){this._process=process;var hasScheduledTasks=!!this._processTimeout||this._isRunningProcess;var okToFire=window.performance.now()-this._lastCompleteTime>this._timeout;asSoonAsPossible=!!asSoonAsPossible||(!hasScheduledTasks&&okToFire);var forceTimerUpdate=asSoonAsPossible&&!this._asSoonAsPossible;this._asSoonAsPossible=this._asSoonAsPossible||asSoonAsPossible;this._innerSchedule(forceTimerUpdate);} -_innerSchedule(forceTimerUpdate){if(this._isRunningProcess) -return;if(this._processTimeout&&!forceTimerUpdate) -return;if(this._processTimeout) -this._clearTimeout(this._processTimeout);var timeout=this._asSoonAsPossible?0:this._timeout;this._processTimeout=this._setTimeout(this._onTimeout.bind(this),timeout);} -_clearTimeout(timeoutId){clearTimeout(timeoutId);} -_setTimeout(operation,timeout){return setTimeout(operation,timeout);}};Common.Throttler.FinishCallback;;Common.Trie=class{constructor(){this.clear();} -add(word){var node=this._root;++this._wordsInSubtree[this._root];for(var i=0;i<word.length;++i){var edge=word[i];var next=this._edges[node][edge];if(!next){if(this._freeNodes.length){next=this._freeNodes.pop();}else{next=this._size++;this._isWord.push(false);this._wordsInSubtree.push(0);this._edges.push({__proto__:null});} -this._edges[node][edge]=next;} -++this._wordsInSubtree[next];node=next;} -this._isWord[node]=true;} -remove(word){if(!this.has(word)) -return false;var node=this._root;--this._wordsInSubtree[this._root];for(var i=0;i<word.length;++i){var edge=word[i];var next=this._edges[node][edge];if(!--this._wordsInSubtree[next]){delete this._edges[node][edge];this._freeNodes.push(next);} -node=next;} -this._isWord[node]=false;return true;} -has(word){var node=this._root;for(var i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node) -return false;} -return this._isWord[node];} -words(prefix){prefix=prefix||'';var node=this._root;for(var i=0;i<prefix.length;++i){node=this._edges[node][prefix[i]];if(!node) -return[];} -var results=[];this._dfs(node,prefix,results);return results;} -_dfs(node,prefix,results){if(this._isWord[node]) -results.push(prefix);var edges=this._edges[node];for(var edge in edges) -this._dfs(edges[edge],prefix+edge,results);} -longestPrefix(word,fullWordOnly){var node=this._root;var wordIndex=0;for(var i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node) -break;if(!fullWordOnly||this._isWord[node]) -wordIndex=i+1;} -return word.substring(0,wordIndex);} -clear(){this._size=1;this._root=0;this._edges=[{__proto__:null}];this._isWord=[false];this._wordsInSubtree=[0];this._freeNodes=[];}};;self['Common']=self['Common']||{};Common.UIString=function(string,vararg){return String.vsprintf(Common.localize(string),Array.prototype.slice.call(arguments,1));};Common.localize=function(string){return string;};Common.UIStringFormat=class{constructor(format){this._localizedFormat=Common.localize(format);this._tokenizedFormat=String.tokenizeFormatString(this._localizedFormat,String.standardFormatters);} -static _append(a,b){return a+b;} -format(vararg){return String.format(this._localizedFormat,arguments,String.standardFormatters,'',Common.UIStringFormat._append,this._tokenizedFormat).formattedResult;}};;Common.Renderer=function(){};Common.Renderer.prototype={render(object,options){}};Common.Renderer.renderPromise=function(object,options){if(!object) -return Promise.reject(new Error('Can\'t render '+object));return self.runtime.extension(Common.Renderer,object).instance().then(render);function render(renderer){return renderer.render(object,options||{});}};Common.Renderer.Options;Common.Revealer=function(){};Common.Revealer.reveal=function(revealable,omitFocus){Common.Revealer.revealPromise(revealable,omitFocus);};Common.Revealer.revealPromise=function(revealable,omitFocus){if(!revealable) -return Promise.reject(new Error('Can\'t reveal '+revealable));return self.runtime.allInstances(Common.Revealer,revealable).then(reveal);function reveal(revealers){var promises=[];for(var i=0;i<revealers.length;++i) -promises.push(revealers[i].reveal((revealable),omitFocus));return Promise.race(promises);}};Common.Revealer.prototype={reveal(object,omitFocus){}};Common.App=function(){};Common.App.prototype={presentUI(document){}};Common.AppProvider=function(){};Common.AppProvider.prototype={createApp(){}};Common.QueryParamHandler=function(){};Common.QueryParamHandler.prototype={handleQueryParam(value){}};;Common.CharacterIdMap=class{constructor(){this._elementToCharacter=new Map();this._characterToElement=new Map();this._charCode=33;} -toChar(object){var character=this._elementToCharacter.get(object);if(!character){if(this._charCode>=0xFFFF) -throw new Error('CharacterIdMap ran out of capacity!');character=String.fromCharCode(this._charCode++);this._elementToCharacter.set(object,character);this._characterToElement.set(character,object);} -return character;} -fromChar(character){var object=this._characterToElement.get(character);if(object===undefined) -return null;return object;}};;self['Host']=self['Host']||{};function InspectorFrontendHostAPI(){} -window.InspectorFrontendHostAPI=InspectorFrontendHostAPI;InspectorFrontendHostAPI.ContextMenuDescriptor;InspectorFrontendHostAPI.LoadNetworkResourceResult;InspectorFrontendHostAPI.Events={AddExtensions:Symbol('addExtensions'),AppendedToURL:Symbol('appendedToURL'),CanceledSaveURL:Symbol('canceledSaveURL'),ContextMenuCleared:Symbol('contextMenuCleared'),ContextMenuItemSelected:Symbol('contextMenuItemSelected'),DeviceCountUpdated:Symbol('deviceCountUpdated'),DevicesDiscoveryConfigChanged:Symbol('devicesDiscoveryConfigChanged'),DevicesPortForwardingStatusChanged:Symbol('devicesPortForwardingStatusChanged'),DevicesUpdated:Symbol('devicesUpdated'),DispatchMessage:Symbol('dispatchMessage'),DispatchMessageChunk:Symbol('dispatchMessageChunk'),EnterInspectElementMode:Symbol('enterInspectElementMode'),EvaluateForTestInFrontend:Symbol('evaluateForTestInFrontend'),EyeDropperPickedColor:Symbol('eyeDropperPickedColor'),FileSystemsLoaded:Symbol('fileSystemsLoaded'),FileSystemRemoved:Symbol('fileSystemRemoved'),FileSystemAdded:Symbol('fileSystemAdded'),FileSystemFilesChangedAddedRemoved:Symbol('FileSystemFilesChangedAddedRemoved'),IndexingTotalWorkCalculated:Symbol('indexingTotalWorkCalculated'),IndexingWorked:Symbol('indexingWorked'),IndexingDone:Symbol('indexingDone'),KeyEventUnhandled:Symbol('keyEventUnhandled'),ReloadInspectedPage:Symbol('reloadInspectedPage'),RevealSourceLine:Symbol('revealSourceLine'),SavedURL:Symbol('savedURL'),SearchCompleted:Symbol('searchCompleted'),SetInspectedTabId:Symbol('setInspectedTabId'),SetUseSoftMenu:Symbol('setUseSoftMenu'),ShowPanel:Symbol('showPanel')};InspectorFrontendHostAPI.EventDescriptors=[[InspectorFrontendHostAPI.Events.AddExtensions,'addExtensions',['extensions']],[InspectorFrontendHostAPI.Events.AppendedToURL,'appendedToURL',['url']],[InspectorFrontendHostAPI.Events.CanceledSaveURL,'canceledSaveURL',['url']],[InspectorFrontendHostAPI.Events.ContextMenuCleared,'contextMenuCleared',[]],[InspectorFrontendHostAPI.Events.ContextMenuItemSelected,'contextMenuItemSelected',['id']],[InspectorFrontendHostAPI.Events.DeviceCountUpdated,'deviceCountUpdated',['count']],[InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged,'devicesDiscoveryConfigChanged',['config']],[InspectorFrontendHostAPI.Events.DevicesPortForwardingStatusChanged,'devicesPortForwardingStatusChanged',['status']],[InspectorFrontendHostAPI.Events.DevicesUpdated,'devicesUpdated',['devices']],[InspectorFrontendHostAPI.Events.DispatchMessage,'dispatchMessage',['messageObject']],[InspectorFrontendHostAPI.Events.DispatchMessageChunk,'dispatchMessageChunk',['messageChunk','messageSize']],[InspectorFrontendHostAPI.Events.EnterInspectElementMode,'enterInspectElementMode',[]],[InspectorFrontendHostAPI.Events.EvaluateForTestInFrontend,'evaluateForTestInFrontend',['callId','script']],[InspectorFrontendHostAPI.Events.EyeDropperPickedColor,'eyeDropperPickedColor',['color']],[InspectorFrontendHostAPI.Events.FileSystemsLoaded,'fileSystemsLoaded',['fileSystems']],[InspectorFrontendHostAPI.Events.FileSystemRemoved,'fileSystemRemoved',['fileSystemPath']],[InspectorFrontendHostAPI.Events.FileSystemAdded,'fileSystemAdded',['errorMessage','fileSystem']],[InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,'fileSystemFilesChangedAddedRemoved',['changed','added','removed']],[InspectorFrontendHostAPI.Events.IndexingTotalWorkCalculated,'indexingTotalWorkCalculated',['requestId','fileSystemPath','totalWork']],[InspectorFrontendHostAPI.Events.IndexingWorked,'indexingWorked',['requestId','fileSystemPath','worked']],[InspectorFrontendHostAPI.Events.IndexingDone,'indexingDone',['requestId','fileSystemPath']],[InspectorFrontendHostAPI.Events.KeyEventUnhandled,'keyEventUnhandled',['event']],[InspectorFrontendHostAPI.Events.ReloadInspectedPage,'reloadInspectedPage',['hard']],[InspectorFrontendHostAPI.Events.RevealSourceLine,'revealSourceLine',['url','lineNumber','columnNumber']],[InspectorFrontendHostAPI.Events.SavedURL,'savedURL',['url','fileSystemPath']],[InspectorFrontendHostAPI.Events.SearchCompleted,'searchCompleted',['requestId','fileSystemPath','files']],[InspectorFrontendHostAPI.Events.SetInspectedTabId,'setInspectedTabId',['tabId']],[InspectorFrontendHostAPI.Events.SetUseSoftMenu,'setUseSoftMenu',['useSoftMenu']],[InspectorFrontendHostAPI.Events.ShowPanel,'showPanel',['panelName']]];InspectorFrontendHostAPI.prototype={addFileSystem(type){},append(url,content){},loadCompleted(){},indexPath(requestId,fileSystemPath){},getSelectionBackgroundColor(){},getSelectionForegroundColor(){},setInspectedPageBounds(bounds){},showCertificateViewer(certChain){},setWhitelistedShortcuts(shortcuts){},setEyeDropperActive(active){},inspectElementCompleted(){},openInNewTab(url){},removeFileSystem(fileSystemPath){},requestFileSystems(){},save(url,content,forceSaveAs){},searchInPath(requestId,fileSystemPath,query){},stopIndexing(requestId){},bringToFront(){},closeWindow(){},copyText(text){},inspectedURLChanged(url){},isolatedFileSystem(fileSystemId,registeredName){},loadNetworkResource(url,headers,streamId,callback){},getPreferences(callback){},setPreference(name,value){},removePreference(name){},clearPreferences(){},upgradeDraggedFileSystemPermissions(fileSystem){},platform(){},recordEnumeratedHistogram(actionName,actionCode,bucketSize){},sendMessageToBackend(message){},setDevicesDiscoveryConfig(config){},setDevicesUpdatesEnabled(enabled){},performActionOnRemotePage(pageId,action){},openRemotePage(browserId,url){},openNodeFrontend(){},setInjectedScriptForOrigin(origin,script){},setIsDocked(isDocked,callback){},zoomFactor(){},zoomIn(){},zoomOut(){},resetZoom(){},showContextMenuAtPoint(x,y,items,document){},reattach(callback){},isUnderTest(){},readyForTest(){},isHostedMode(){}};;Host.InspectorFrontendHostStub=class{constructor(){function stopEventPropagation(event){var zoomModifier=Host.isMac()?event.metaKey:event.ctrlKey;if(zoomModifier&&(event.keyCode===187||event.keyCode===189)) -event.stopPropagation();} -document.addEventListener('keydown',stopEventPropagation,true);} -getSelectionBackgroundColor(){return'#6e86ff';} -getSelectionForegroundColor(){return'#ffffff';} -platform(){var match=navigator.userAgent.match(/Windows NT/);if(match) -return'windows';match=navigator.userAgent.match(/Mac OS X/);if(match) -return'mac';return'linux';} -loadCompleted(){} -bringToFront(){this._windowVisible=true;} -closeWindow(){this._windowVisible=false;} -setIsDocked(isDocked,callback){setTimeout(callback,0);} -setInspectedPageBounds(bounds){} -inspectElementCompleted(){} -setInjectedScriptForOrigin(origin,script){} -inspectedURLChanged(url){document.title=Common.UIString('Developer Tools - %s',url);} -copyText(text){Common.console.error('Clipboard is not enabled in hosted mode. Please inspect using chrome://inspect');} -openInNewTab(url){window.open(url,'_blank');} -save(url,content,forceSaveAs){Common.console.error('Saving files is not enabled in hosted mode. Please inspect using chrome://inspect');this.events.dispatchEventToListeners(InspectorFrontendHostAPI.Events.CanceledSaveURL,url);} -append(url,content){Common.console.error('Saving files is not enabled in hosted mode. Please inspect using chrome://inspect');} -sendMessageToBackend(message){} -recordEnumeratedHistogram(actionName,actionCode,bucketSize){} -requestFileSystems(){this.events.dispatchEventToListeners(InspectorFrontendHostAPI.Events.FileSystemsLoaded,[]);} -addFileSystem(type){} -removeFileSystem(fileSystemPath){} -isolatedFileSystem(fileSystemId,registeredName){return null;} -loadNetworkResource(url,headers,streamId,callback){Runtime.loadResourcePromise(url).then(function(text){Host.ResourceLoader.streamWrite(streamId,text);callback({statusCode:200});}).catch(function(){callback({statusCode:404});});} -getPreferences(callback){var prefs={};for(var name in window.localStorage) -prefs[name]=window.localStorage[name];callback(prefs);} -setPreference(name,value){window.localStorage[name]=value;} -removePreference(name){delete window.localStorage[name];} -clearPreferences(){window.localStorage.clear();} -upgradeDraggedFileSystemPermissions(fileSystem){} -indexPath(requestId,fileSystemPath){} -stopIndexing(requestId){} -searchInPath(requestId,fileSystemPath,query){} -zoomFactor(){return 1;} -zoomIn(){} -zoomOut(){} -resetZoom(){} -setWhitelistedShortcuts(shortcuts){} -setEyeDropperActive(active){} -showCertificateViewer(certChain){} -isUnderTest(){return false;} -reattach(callback){} -readyForTest(){} -setDevicesDiscoveryConfig(config){} -setDevicesUpdatesEnabled(enabled){} -performActionOnRemotePage(pageId,action){} -openRemotePage(browserId,url){} -openNodeFrontend(){} -showContextMenuAtPoint(x,y,items,document){throw'Soft context menu should be used';} -isHostedMode(){return true;}};Host.InspectorFrontendAPIImpl=class{constructor(){this._debugFrontend=!!Runtime.queryParam('debugFrontend')||(window['InspectorTest']&&window['InspectorTest']['debugTest']);var descriptors=InspectorFrontendHostAPI.EventDescriptors;for(var i=0;i<descriptors.length;++i) -this[descriptors[i][1]]=this._dispatch.bind(this,descriptors[i][0],descriptors[i][2],descriptors[i][3]);} -_dispatch(name,signature,runOnceLoaded){var params=Array.prototype.slice.call(arguments,3);if(this._debugFrontend) -setImmediate(innerDispatch);else -innerDispatch();function innerDispatch(){if(signature.length<2){try{InspectorFrontendHost.events.dispatchEventToListeners(name,params[0]);}catch(e){console.error(e+' '+e.stack);} -return;} -var data={};for(var i=0;i<signature.length;++i) -data[signature[i]]=params[i];try{InspectorFrontendHost.events.dispatchEventToListeners(name,data);}catch(e){console.error(e+' '+e.stack);}}} -streamWrite(id,chunk){Host.ResourceLoader.streamWrite(id,chunk);}};var InspectorFrontendHost=window.InspectorFrontendHost||null;window.InspectorFrontendHost=InspectorFrontendHost;(function(){function initializeInspectorFrontendHost(){if(!InspectorFrontendHost){window.InspectorFrontendHost=InspectorFrontendHost=new Host.InspectorFrontendHostStub();}else{var proto=Host.InspectorFrontendHostStub.prototype;for(var name in proto){var value=proto[name];if(typeof value!=='function'||InspectorFrontendHost[name]) -continue;InspectorFrontendHost[name]=stub.bind(null,name);}} -function stub(name){console.error('Incompatible embedder: method InspectorFrontendHost.'+name+' is missing. Using stub instead.');var args=Array.prototype.slice.call(arguments,1);return proto[name].apply(InspectorFrontendHost,args);} -InspectorFrontendHost.events=new Common.Object();} -initializeInspectorFrontendHost();window.InspectorFrontendAPI=new Host.InspectorFrontendAPIImpl();})();InspectorFrontendHost.events;Host.isUnderTest=function(prefs){if(InspectorFrontendHost.isUnderTest()) -return true;if(prefs) -return prefs['isUnderTest']==='true';return Common.settings.createSetting('isUnderTest',false).get();};;Host.platform=function(){if(!Host._platform) -Host._platform=InspectorFrontendHost.platform();return Host._platform;};Host.isMac=function(){if(typeof Host._isMac==='undefined') -Host._isMac=Host.platform()==='mac';return Host._isMac;};Host.isWin=function(){if(typeof Host._isWin==='undefined') -Host._isWin=Host.platform()==='windows';return Host._isWin;};Host.isCustomDevtoolsFrontend=function(){if(typeof Host._isCustomDevtoolsFronend==='undefined') -Host._isCustomDevtoolsFronend=window.location.toString().startsWith('chrome-devtools://devtools/custom/');return Host._isCustomDevtoolsFronend;};Host.fontFamily=function(){if(Host._fontFamily) -return Host._fontFamily;switch(Host.platform()){case'linux':Host._fontFamily='Roboto, Ubuntu, Arial, sans-serif';break;case'mac':Host._fontFamily='\'Lucida Grande\', sans-serif';break;case'windows':Host._fontFamily='\'Segoe UI\', Tahoma, sans-serif';break;} -return Host._fontFamily;};;Host.ResourceLoader={};Host.ResourceLoader._lastStreamId=0;Host.ResourceLoader._boundStreams={};Host.ResourceLoader._bindOutputStream=function(stream){Host.ResourceLoader._boundStreams[++Host.ResourceLoader._lastStreamId]=stream;return Host.ResourceLoader._lastStreamId;};Host.ResourceLoader._discardOutputStream=function(id){Host.ResourceLoader._boundStreams[id].close();delete Host.ResourceLoader._boundStreams[id];};Host.ResourceLoader.streamWrite=function(id,chunk){Host.ResourceLoader._boundStreams[id].write(chunk);};Host.ResourceLoader.load=function(url,headers,callback){var stream=new Common.StringOutputStream();Host.ResourceLoader.loadAsStream(url,headers,stream,mycallback);function mycallback(statusCode,headers){callback(statusCode,headers,stream.data());}};Host.ResourceLoader.loadAsStream=function(url,headers,stream,callback){var streamId=Host.ResourceLoader._bindOutputStream(stream);var parsedURL=new Common.ParsedURL(url);if(parsedURL.isDataURL()){loadXHR(url).then(dataURLDecodeSuccessful).catch(dataURLDecodeFailed);return;} -var rawHeaders=[];if(headers){for(var key in headers) -rawHeaders.push(key+': '+headers[key]);} -InspectorFrontendHost.loadNetworkResource(url,rawHeaders.join('\r\n'),streamId,finishedCallback);function finishedCallback(response){if(callback) -callback(response.statusCode,response.headers||{});Host.ResourceLoader._discardOutputStream(streamId);} -function dataURLDecodeSuccessful(text){Host.ResourceLoader.streamWrite(streamId,text);finishedCallback(({statusCode:200}));} -function dataURLDecodeFailed(){finishedCallback(({statusCode:404}));}};;Host.UserMetrics=class{panelShown(panelName){var code=Host.UserMetrics._PanelCodes[panelName]||0;var size=Object.keys(Host.UserMetrics._PanelCodes).length+1;InspectorFrontendHost.recordEnumeratedHistogram('DevTools.PanelShown',code,size);} -drawerShown(drawerId){this.panelShown('drawer-'+drawerId);} -actionTaken(action){var size=Object.keys(Host.UserMetrics.Action).length+1;InspectorFrontendHost.recordEnumeratedHistogram('DevTools.ActionTaken',action,size);}};Host.UserMetrics.Action={WindowDocked:1,WindowUndocked:2,ScriptsBreakpointSet:3,TimelineStarted:4,ProfilesCPUProfileTaken:5,ProfilesHeapProfileTaken:6,AuditsStarted:7,ConsoleEvaluated:8,FileSavedInWorkspace:9,DeviceModeEnabled:10,AnimationsPlaybackRateChanged:11,RevisionApplied:12,FileSystemDirectoryContentReceived:13,StyleRuleEdited:14,CommandEvaluatedInConsolePanel:15,DOMPropertiesExpanded:16,ResizedViewInResponsiveMode:17,TimelinePageReloadStarted:18,ConnectToNodeJSFromFrontend:19,ConnectToNodeJSDirectly:20,CpuThrottlingEnabled:21,CpuProfileNodeFocused:22,CpuProfileNodeExcluded:23,SelectFileFromFilePicker:24,SelectCommandFromCommandMenu:25,ChangeInspectedNodeInElementsPanel:26,StyleRuleCopied:27,CoverageStarted:28,Audits2Started:29,Audits2Finished:30};Host.UserMetrics._PanelCodes={elements:1,resources:2,network:3,sources:4,timeline:5,heap_profiler:6,audits:7,console:8,layers:9,'drawer-console':10,'drawer-animations':11,'drawer-network.config':12,'drawer-rendering':13,'drawer-sensors':14,'drawer-sources.search':15,security:16,js_profiler:17,audits2:18,};Host.userMetrics=new Host.UserMetrics();;self['UI']=self['UI']||{};UI.Widget=class extends Common.Object{constructor(isWebComponent){super();this.contentElement=createElementWithClass('div','widget');if(isWebComponent){this.element=createElementWithClass('div','vbox flex-auto');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element);this._shadowRoot.appendChild(this.contentElement);}else{this.element=this.contentElement;} -this._isWebComponent=isWebComponent;this.element.__widget=this;this._visible=false;this._isRoot=false;this._isShowing=false;this._children=[];this._hideOnDetach=false;this._notificationDepth=0;this._invalidationsSuspended=0;this._defaultFocusedChild=null;} -static _incrementWidgetCounter(parentElement,childElement){var count=(childElement.__widgetCounter||0)+(childElement.__widget?1:0);if(!count) -return;while(parentElement){parentElement.__widgetCounter=(parentElement.__widgetCounter||0)+count;parentElement=parentElement.parentElementOrShadowHost();}} -static _decrementWidgetCounter(parentElement,childElement){var count=(childElement.__widgetCounter||0)+(childElement.__widget?1:0);if(!count) -return;while(parentElement){parentElement.__widgetCounter-=count;parentElement=parentElement.parentElementOrShadowHost();}} -static __assert(condition,message){if(!condition) -throw new Error(message);} -static focusWidgetForNode(node){while(node){if(node.__widget) -break;node=node.parentNodeOrShadowHost();} -if(!node) -return;var widget=node.__widget;while(widget._parentWidget){widget._parentWidget._defaultFocusedChild=widget;widget=widget._parentWidget;}} -markAsRoot(){UI.Widget.__assert(!this.element.parentElement,'Attempt to mark as root attached node');this._isRoot=true;} -parentWidget(){return this._parentWidget;} -children(){return this._children;} -childWasDetached(widget){} -isShowing(){return this._isShowing;} -shouldHideOnDetach(){if(!this.element.parentElement) -return false;if(this._hideOnDetach) -return true;for(var child of this._children){if(child.shouldHideOnDetach()) -return true;} -return false;} -setHideOnDetach(){this._hideOnDetach=true;} -_inNotification(){return!!this._notificationDepth||(this._parentWidget&&this._parentWidget._inNotification());} -_parentIsShowing(){if(this._isRoot) -return true;return!!this._parentWidget&&this._parentWidget.isShowing();} -_callOnVisibleChildren(method){var copy=this._children.slice();for(var i=0;i<copy.length;++i){if(copy[i]._parentWidget===this&©[i]._visible) -method.call(copy[i]);}} -_processWillShow(){this._callOnVisibleChildren(this._processWillShow);this._isShowing=true;} -_processWasShown(){if(this._inNotification()) -return;this.restoreScrollPositions();this._notify(this.wasShown);this._callOnVisibleChildren(this._processWasShown);} -_processWillHide(){if(this._inNotification()) -return;this.storeScrollPositions();this._callOnVisibleChildren(this._processWillHide);this._notify(this.willHide);this._isShowing=false;} -_processWasHidden(){this._callOnVisibleChildren(this._processWasHidden);} -_processOnResize(){if(this._inNotification()) -return;if(!this.isShowing()) -return;this._notify(this.onResize);this._callOnVisibleChildren(this._processOnResize);} -_notify(notification){++this._notificationDepth;try{notification.call(this);}finally{--this._notificationDepth;}} -wasShown(){} -willHide(){} -onResize(){} -onLayout(){} -ownerViewDisposed(){} -show(parentElement,insertBefore){UI.Widget.__assert(parentElement,'Attempt to attach widget with no parent element');if(!this._isRoot){var currentParent=parentElement;while(currentParent&&!currentParent.__widget) -currentParent=currentParent.parentElementOrShadowHost();UI.Widget.__assert(currentParent,'Attempt to attach widget to orphan node');this._attach(currentParent.__widget);} -this._showWidget(parentElement,insertBefore);} -_attach(parentWidget){if(parentWidget===this._parentWidget) -return;if(this._parentWidget) -this.detach();this._parentWidget=parentWidget;this._parentWidget._children.push(this);this._isRoot=false;} -showWidget(){if(this._visible) -return;UI.Widget.__assert(this.element.parentElement,'Attempt to show widget that is not hidden using hideWidget().');this._showWidget((this.element.parentElement),this.element.nextSibling);} -_showWidget(parentElement,insertBefore){var currentParent=parentElement;while(currentParent&&!currentParent.__widget) -currentParent=currentParent.parentElementOrShadowHost();if(this._isRoot){UI.Widget.__assert(!currentParent,'Attempt to show root widget under another widget');}else{UI.Widget.__assert(currentParent&¤tParent.__widget===this._parentWidget,'Attempt to show under node belonging to alien widget');} -var wasVisible=this._visible;if(wasVisible&&this.element.parentElement===parentElement) -return;this._visible=true;if(!wasVisible&&this._parentIsShowing()) -this._processWillShow();this.element.classList.remove('hidden');if(this.element.parentElement!==parentElement){UI.Widget._incrementWidgetCounter(parentElement,this.element);if(insertBefore) -UI.Widget._originalInsertBefore.call(parentElement,this.element,insertBefore);else -UI.Widget._originalAppendChild.call(parentElement,this.element);} -if(!wasVisible&&this._parentIsShowing()) -this._processWasShown();if(this._parentWidget&&this._hasNonZeroConstraints()) -this._parentWidget.invalidateConstraints();else -this._processOnResize();} -hideWidget(){if(!this._visible) -return;this._hideWidget(false);} -_hideWidget(removeFromDOM){this._visible=false;var parentElement=this.element.parentElement;if(this._parentIsShowing()) -this._processWillHide();if(removeFromDOM){UI.Widget._decrementWidgetCounter(parentElement,this.element);UI.Widget._originalRemoveChild.call(parentElement,this.element);}else{this.element.classList.add('hidden');} -if(this._parentIsShowing()) -this._processWasHidden();if(this._parentWidget&&this._hasNonZeroConstraints()) -this._parentWidget.invalidateConstraints();} -detach(overrideHideOnDetach){if(!this._parentWidget&&!this._isRoot) -return;var removeFromDOM=overrideHideOnDetach||!this.shouldHideOnDetach();if(this._visible){this._hideWidget(removeFromDOM);}else if(removeFromDOM&&this.element.parentElement){var parentElement=this.element.parentElement;UI.Widget._decrementWidgetCounter(parentElement,this.element);UI.Widget._originalRemoveChild.call(parentElement,this.element);} -if(this._parentWidget){var childIndex=this._parentWidget._children.indexOf(this);UI.Widget.__assert(childIndex>=0,'Attempt to remove non-child widget');this._parentWidget._children.splice(childIndex,1);if(this._parentWidget._defaultFocusedChild===this) -this._parentWidget._defaultFocusedChild=null;this._parentWidget.childWasDetached(this);this._parentWidget=null;}else{UI.Widget.__assert(this._isRoot,'Removing non-root widget from DOM');}} -detachChildWidgets(){var children=this._children.slice();for(var i=0;i<children.length;++i) -children[i].detach();} -elementsToRestoreScrollPositionsFor(){return[this.element];} -storeScrollPositions(){var elements=this.elementsToRestoreScrollPositionsFor();for(var i=0;i<elements.length;++i){var container=elements[i];container._scrollTop=container.scrollTop;container._scrollLeft=container.scrollLeft;}} -restoreScrollPositions(){var elements=this.elementsToRestoreScrollPositionsFor();for(var i=0;i<elements.length;++i){var container=elements[i];if(container._scrollTop) -container.scrollTop=container._scrollTop;if(container._scrollLeft) -container.scrollLeft=container._scrollLeft;}} -doResize(){if(!this.isShowing()) -return;if(!this._inNotification()) -this._callOnVisibleChildren(this._processOnResize);} -doLayout(){if(!this.isShowing()) -return;this._notify(this.onLayout);this.doResize();} -registerRequiredCSS(cssFile){UI.appendStyle(this._isWebComponent?this._shadowRoot:this.element,cssFile);} -printWidgetHierarchy(){var lines=[];this._collectWidgetHierarchy('',lines);console.log(lines.join('\n'));} -_collectWidgetHierarchy(prefix,lines){lines.push(prefix+'['+this.element.className+']'+(this._children.length?' {':''));for(var i=0;i<this._children.length;++i) -this._children[i]._collectWidgetHierarchy(prefix+' ',lines);if(this._children.length) -lines.push(prefix+'}');} -setDefaultFocusedElement(element){this._defaultFocusedElement=element;} -setDefaultFocusedChild(child){UI.Widget.__assert(child._parentWidget===this,'Attempt to set non-child widget as default focused.');this._defaultFocusedChild=child;} -focus(){if(!this.isShowing()) -return;var element=this._defaultFocusedElement;if(element){if(!element.hasFocus()) -element.focus();return;} -if(this._defaultFocusedChild&&this._defaultFocusedChild._visible){this._defaultFocusedChild.focus();}else{for(var child of this._children){if(child._visible){child.focus();break;}}}} -hasFocus(){return this.element.hasFocus();} -calculateConstraints(){return new UI.Constraints();} -constraints(){if(typeof this._constraints!=='undefined') -return this._constraints;if(typeof this._cachedConstraints==='undefined') -this._cachedConstraints=this.calculateConstraints();return this._cachedConstraints;} -setMinimumAndPreferredSizes(width,height,preferredWidth,preferredHeight){this._constraints=new UI.Constraints(new UI.Size(width,height),new UI.Size(preferredWidth,preferredHeight));this.invalidateConstraints();} -setMinimumSize(width,height){this._constraints=new UI.Constraints(new UI.Size(width,height));this.invalidateConstraints();} -_hasNonZeroConstraints(){var constraints=this.constraints();return!!(constraints.minimum.width||constraints.minimum.height||constraints.preferred.width||constraints.preferred.height);} -suspendInvalidations(){++this._invalidationsSuspended;} -resumeInvalidations(){--this._invalidationsSuspended;if(!this._invalidationsSuspended&&this._invalidationsRequested) -this.invalidateConstraints();} -invalidateConstraints(){if(this._invalidationsSuspended){this._invalidationsRequested=true;return;} -this._invalidationsRequested=false;var cached=this._cachedConstraints;delete this._cachedConstraints;var actual=this.constraints();if(!actual.isEqual(cached)&&this._parentWidget) -this._parentWidget.invalidateConstraints();else -this.doLayout();}};UI.Widget._originalAppendChild=Element.prototype.appendChild;UI.Widget._originalInsertBefore=Element.prototype.insertBefore;UI.Widget._originalRemoveChild=Element.prototype.removeChild;UI.Widget._originalRemoveChildren=Element.prototype.removeChildren;UI.VBox=class extends UI.Widget{constructor(isWebComponent){super(isWebComponent);this.contentElement.classList.add('vbox');} -calculateConstraints(){var constraints=new UI.Constraints();function updateForChild(){var child=this.constraints();constraints=constraints.widthToMax(child);constraints=constraints.addHeight(child);} -this._callOnVisibleChildren(updateForChild);return constraints;}};UI.HBox=class extends UI.Widget{constructor(isWebComponent){super(isWebComponent);this.contentElement.classList.add('hbox');} -calculateConstraints(){var constraints=new UI.Constraints();function updateForChild(){var child=this.constraints();constraints=constraints.addWidth(child);constraints=constraints.heightToMax(child);} -this._callOnVisibleChildren(updateForChild);return constraints;}};UI.VBoxWithResizeCallback=class extends UI.VBox{constructor(resizeCallback){super();this._resizeCallback=resizeCallback;} -onResize(){this._resizeCallback();}};UI.WidgetFocusRestorer=class{constructor(widget){this._widget=widget;this._previous=widget.element.ownerDocument.deepActiveElement();widget.focus();} -restore(){if(!this._widget) -return;if(this._widget.hasFocus()&&this._previous) -this._previous.focus();this._previous=null;this._widget=null;}};Element.prototype.appendChild=function(child){UI.Widget.__assert(!child.__widget||child.parentElement===this,'Attempt to add widget via regular DOM operation.');return UI.Widget._originalAppendChild.call(this,child);};Element.prototype.insertBefore=function(child,anchor){UI.Widget.__assert(!child.__widget||child.parentElement===this,'Attempt to add widget via regular DOM operation.');return UI.Widget._originalInsertBefore.call(this,child,anchor);};Element.prototype.removeChild=function(child){UI.Widget.__assert(!child.__widgetCounter&&!child.__widget,'Attempt to remove element containing widget via regular DOM operation');return UI.Widget._originalRemoveChild.call(this,child);};Element.prototype.removeChildren=function(){UI.Widget.__assert(!this.__widgetCounter,'Attempt to remove element containing widget via regular DOM operation');UI.Widget._originalRemoveChildren.call(this);};;UI.View=function(){};UI.View.prototype={viewId(){},title(){},isCloseable(){},isTransient(){},toolbarItems(){},widget(){},disposeView(){}};UI.View._symbol=Symbol('view');UI.View._widgetSymbol=Symbol('widget');UI.SimpleView=class extends UI.VBox{constructor(title,isWebComponent){super(isWebComponent);this._title=title;this._toolbarItems=[];this[UI.View._symbol]=this;} -viewId(){return this._title;} -title(){return this._title;} -isCloseable(){return false;} -isTransient(){return false;} -toolbarItems(){return Promise.resolve(this.syncToolbarItems());} -syncToolbarItems(){return this._toolbarItems;} -widget(){return(Promise.resolve(this));} -addToolbarItem(item){this._toolbarItems.push(item);} -revealView(){return UI.viewManager.revealView(this);} -disposeView(){}};UI.ProvidedView=class{constructor(extension){this._extension=extension;} -viewId(){return this._extension.descriptor()['id'];} -title(){return this._extension.title();} -isCloseable(){return this._extension.descriptor()['persistence']==='closeable';} -isTransient(){return this._extension.descriptor()['persistence']==='transient';} -toolbarItems(){const actionIds=this._extension.descriptor()['actionIds'];if(actionIds){const result=actionIds.split(',').map(id=>UI.Toolbar.createActionButtonForId(id.trim()));return Promise.resolve(result);} -if(this._extension.descriptor()['hasToolbar']) -return this.widget().then(widget=>(widget).toolbarItems());return Promise.resolve([]);} -async widget(){this._widgetRequested=true;var widget=await this._extension.instance();if(!(widget instanceof UI.Widget)) -throw new Error('view className should point to a UI.Widget');widget[UI.View._symbol]=this;return(widget);} -async disposeView(){if(!this._widgetRequested) -return;var widget=await this.widget();widget.ownerViewDisposed();}};UI.ViewLocation=function(){};UI.ViewLocation.prototype={appendApplicableItems(locationName){},appendView(view,insertBefore){},showView(view,insertBefore,userGesture){},removeView(view){},widget(){}};UI.TabbedViewLocation=function(){};UI.TabbedViewLocation.prototype={tabbedPane(){},enableMoreTabsButton(){}};UI.ViewLocationResolver=function(){};UI.ViewLocationResolver.prototype={resolveLocation(location){}};UI.ViewManager=class{constructor(){this._views=new Map();this._locationNameByViewId=new Map();for(var extension of self.runtime.extensions('view')){var descriptor=extension.descriptor();this._views.set(descriptor['id'],new UI.ProvidedView(extension));this._locationNameByViewId.set(descriptor['id'],descriptor['location']);}} -static _populateToolbar(element,toolbarItems){if(!toolbarItems.length) -return;var toolbar=new UI.Toolbar('');element.insertBefore(toolbar.element,element.firstChild);for(var item of toolbarItems) -toolbar.appendToolbarItem(item);} -revealView(view){var location=(view[UI.ViewManager._Location.symbol]);if(!location) -return Promise.resolve();location._reveal();return location.showView(view);} -view(viewId){return this._views.get(viewId);} -materializedWidget(viewId){var view=this.view(viewId);return view?view[UI.View._widgetSymbol]:null;} -showView(viewId,userGesture,omitFocus){var view=this._views.get(viewId);if(!view){console.error('Could not find view for id: \''+viewId+'\' '+new Error().stack);return Promise.resolve();} -var locationName=this._locationNameByViewId.get(viewId);if(locationName==='drawer-view') -Host.userMetrics.drawerShown(viewId);var location=view[UI.ViewManager._Location.symbol];if(location){location._reveal();return location.showView(view,undefined,userGesture,omitFocus);} -return this._resolveLocation(locationName).then(location=>{if(!location) -throw new Error('Could not resolve location for view: '+viewId);location._reveal();return location.showView(view,undefined,userGesture,omitFocus);});} -_resolveLocation(location){if(!location) -return(Promise.resolve(null));var resolverExtensions=self.runtime.extensions(UI.ViewLocationResolver).filter(extension=>extension.descriptor()['name']===location);if(!resolverExtensions.length) -throw new Error('Unresolved location: '+location);var resolverExtension=resolverExtensions[0];return resolverExtension.instance().then(resolver=>(resolver.resolveLocation(location)));} -createTabbedLocation(revealCallback,location,restoreSelection,allowReorder,defaultTab){return new UI.ViewManager._TabbedLocation(this,revealCallback,location,restoreSelection,allowReorder,defaultTab);} -createStackLocation(revealCallback,location){return new UI.ViewManager._StackLocation(this,revealCallback,location);} -_viewsForLocation(location){var result=[];for(var id of this._views.keys()){if(this._locationNameByViewId.get(id)===location) -result.push(this._views.get(id));} -return result;}};UI.ViewManager._ContainerWidget=class extends UI.VBox{constructor(view){super();this.element.classList.add('flex-auto','view-container','overflow-auto');this._view=view;this.element.tabIndex=-1;this.setDefaultFocusedElement(this.element);} -_materialize(){if(this._materializePromise) -return this._materializePromise;var promises=[];promises.push(this._view.toolbarItems().then(UI.ViewManager._populateToolbar.bind(UI.ViewManager,this.element)));promises.push(this._view.widget().then(widget=>{var shouldFocus=this.element.hasFocus();this.setDefaultFocusedElement(null);this._view[UI.View._widgetSymbol]=widget;widget.show(this.element);if(shouldFocus) -widget.focus();}));this._materializePromise=Promise.all(promises);return this._materializePromise;} -wasShown(){this._materialize();}};UI.ViewManager._ExpandableContainerWidget=class extends UI.VBox{constructor(view){super(true);this.element.classList.add('flex-none');this.registerRequiredCSS('ui/viewContainers.css');this._titleElement=createElementWithClass('div','expandable-view-title');this._titleExpandIcon=UI.Icon.create('smallicon-triangle-right','title-expand-icon');this._titleElement.appendChild(this._titleExpandIcon);this._titleElement.createTextChild(view.title());this._titleElement.tabIndex=0;this._titleElement.addEventListener('click',this._toggleExpanded.bind(this),false);this._titleElement.addEventListener('keydown',this._onTitleKeyDown.bind(this),false);this.contentElement.insertBefore(this._titleElement,this.contentElement.firstChild);this.contentElement.createChild('content');this._view=view;view[UI.ViewManager._ExpandableContainerWidget._symbol]=this;} -_materialize(){if(this._materializePromise) -return this._materializePromise;var promises=[];promises.push(this._view.toolbarItems().then(UI.ViewManager._populateToolbar.bind(UI.ViewManager,this._titleElement)));promises.push(this._view.widget().then(widget=>{this._widget=widget;this._view[UI.View._widgetSymbol]=widget;widget.show(this.element);}));this._materializePromise=Promise.all(promises);return this._materializePromise;} -_expand(){if(this._titleElement.classList.contains('expanded')) -return this._materialize();this._titleElement.classList.add('expanded');this._titleExpandIcon.setIconType('smallicon-triangle-down');return this._materialize().then(()=>this._widget.show(this.element));} -_collapse(){if(!this._titleElement.classList.contains('expanded')) -return;this._titleElement.classList.remove('expanded');this._titleExpandIcon.setIconType('smallicon-triangle-right');this._materialize().then(()=>this._widget.detach());} -_toggleExpanded(){if(this._titleElement.classList.contains('expanded')) -this._collapse();else -this._expand();} -_onTitleKeyDown(event){if(isEnterKey(event)||event.keyCode===UI.KeyboardShortcut.Keys.Space.code) -this._toggleExpanded();}};UI.ViewManager._ExpandableContainerWidget._symbol=Symbol('container');UI.ViewManager._Location=class{constructor(manager,widget,revealCallback){this._manager=manager;this._revealCallback=revealCallback;this._widget=widget;} -widget(){return this._widget;} -_reveal(){if(this._revealCallback) -this._revealCallback();}};UI.ViewManager._Location.symbol=Symbol('location');UI.ViewManager._TabbedLocation=class extends UI.ViewManager._Location{constructor(manager,revealCallback,location,restoreSelection,allowReorder,defaultTab){var tabbedPane=new UI.TabbedPane();if(allowReorder) -tabbedPane.setAllowTabReorder(true);super(manager,tabbedPane,revealCallback);this._tabbedPane=tabbedPane;this._allowReorder=allowReorder;this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabClosed,this._tabClosed,this);this._closeableTabSetting=Common.settings.createSetting(location+'-closeableTabs',{});this._tabOrderSetting=Common.settings.createSetting(location+'-tabOrder',{});this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabOrderChanged,this._persistTabOrder,this);if(restoreSelection) -this._lastSelectedTabSetting=Common.settings.createSetting(location+'-selectedTab','');this._defaultTab=defaultTab;this._views=new Map();if(location) -this.appendApplicableItems(location);} -widget(){return this._tabbedPane;} -tabbedPane(){return this._tabbedPane;} -enableMoreTabsButton(){this._tabbedPane.leftToolbar().appendToolbarItem(new UI.ToolbarMenuButton(this._appendTabsToMenu.bind(this)));this._tabbedPane.disableOverflowMenu();} -appendApplicableItems(locationName){var views=this._manager._viewsForLocation(locationName);if(this._allowReorder){var i=0;var persistedOrders=this._tabOrderSetting.get();var orders=new Map();for(var view of views) -orders.set(view.viewId(),persistedOrders[view.viewId()]||(++i)*UI.ViewManager._TabbedLocation.orderStep);views.sort((a,b)=>orders.get(a.viewId())-orders.get(b.viewId()));} -for(var view of views){var id=view.viewId();this._views.set(id,view);view[UI.ViewManager._Location.symbol]=this;if(view.isTransient()) -continue;if(!view.isCloseable()) -this._appendTab(view);else if(this._closeableTabSetting.get()[id]) -this._appendTab(view);} -if(this._defaultTab&&this._tabbedPane.hasTab(this._defaultTab)) -this._tabbedPane.selectTab(this._defaultTab);else if(this._lastSelectedTabSetting&&this._tabbedPane.hasTab(this._lastSelectedTabSetting.get())) -this._tabbedPane.selectTab(this._lastSelectedTabSetting.get());} -_appendTabsToMenu(contextMenu){var views=Array.from(this._views.values());views.sort((viewa,viewb)=>viewa.title().localeCompare(viewb.title()));for(var view of views){var title=Common.UIString(view.title());contextMenu.defaultSection().appendItem(title,this.showView.bind(this,view,undefined,true));}} -_appendTab(view,index){this._tabbedPane.appendTab(view.viewId(),view.title(),new UI.ViewManager._ContainerWidget(view),undefined,false,view.isCloseable()||view.isTransient(),index);} -appendView(view,insertBefore){if(this._tabbedPane.hasTab(view.viewId())) -return;view[UI.ViewManager._Location.symbol]=this;this._manager._views.set(view.viewId(),view);this._views.set(view.viewId(),view);var index=undefined;var tabIds=this._tabbedPane.tabIds();if(this._allowReorder){var orderSetting=this._tabOrderSetting.get();var order=orderSetting[view.viewId()];for(var i=0;order&&i<tabIds.length;++i){if(orderSetting[tabIds[i]]&&orderSetting[tabIds[i]]>order){index=i;break;}}}else if(insertBefore){for(var i=0;i<tabIds.length;++i){if(tabIds[i]===insertBefore.viewId()){index=i;break;}}} -this._appendTab(view,index);if(view.isCloseable()){var tabs=this._closeableTabSetting.get();var tabId=view.viewId();if(!tabs[tabId]){tabs[tabId]=true;this._closeableTabSetting.set(tabs);}} -this._persistTabOrder();} -showView(view,insertBefore,userGesture,omitFocus){this.appendView(view,insertBefore);this._tabbedPane.selectTab(view.viewId(),userGesture);if(!omitFocus) -this._tabbedPane.focus();var widget=(this._tabbedPane.tabView(view.viewId()));return widget._materialize();} -removeView(view){if(!this._tabbedPane.hasTab(view.viewId())) -return;delete view[UI.ViewManager._Location.symbol];this._manager._views.delete(view.viewId());this._views.delete(view.viewId());this._tabbedPane.closeTab(view.viewId());} -_tabSelected(event){var tabId=(event.data.tabId);if(this._lastSelectedTabSetting&&event.data['isUserGesture']) -this._lastSelectedTabSetting.set(tabId);} -_tabClosed(event){var id=(event.data['tabId']);var tabs=this._closeableTabSetting.get();if(tabs[id]){delete tabs[id];this._closeableTabSetting.set(tabs);} -this._views.get(id).disposeView();} -_persistTabOrder(){var tabIds=this._tabbedPane.tabIds();var tabOrders={};for(var i=0;i<tabIds.length;i++) -tabOrders[tabIds[i]]=(i+1)*UI.ViewManager._TabbedLocation.orderStep;this._tabOrderSetting.set(tabOrders);}};UI.ViewManager._TabbedLocation.orderStep=10;UI.ViewManager._StackLocation=class extends UI.ViewManager._Location{constructor(manager,revealCallback,location){var vbox=new UI.VBox();super(manager,vbox,revealCallback);this._vbox=vbox;this._expandableContainers=new Map();if(location) -this.appendApplicableItems(location);} -appendView(view,insertBefore){var container=this._expandableContainers.get(view.viewId());if(!container){view[UI.ViewManager._Location.symbol]=this;this._manager._views.set(view.viewId(),view);container=new UI.ViewManager._ExpandableContainerWidget(view);var beforeElement=null;if(insertBefore){var beforeContainer=insertBefore[UI.ViewManager._ExpandableContainerWidget._symbol];beforeElement=beforeContainer?beforeContainer.element:null;} -container.show(this._vbox.contentElement,beforeElement);this._expandableContainers.set(view.viewId(),container);}} -showView(view,insertBefore){this.appendView(view,insertBefore);var container=this._expandableContainers.get(view.viewId());return container._expand();} -removeView(view){var container=this._expandableContainers.get(view.viewId());if(!container) -return;container.detach();this._expandableContainers.delete(view.viewId());delete view[UI.ViewManager._Location.symbol];this._manager._views.delete(view.viewId());} -appendApplicableItems(locationName){for(var view of this._manager._viewsForLocation(locationName)) -this.appendView(view);}};UI.viewManager;;UI.TreeOutline=class extends Common.Object{constructor(){super();this._createRootElement();this.selectedTreeElement=null;this.expandTreeElementsWhenArrowing=false;this._comparator=null;this.contentElement=this._rootElement._childrenListNode;this.contentElement.addEventListener('keydown',this._treeKeyDown.bind(this),true);this._focusable=true;this.setFocusable(this._focusable);if(this._focusable) -this.contentElement.setAttribute('tabIndex',-1);this.element=this.contentElement;UI.ARIAUtils.markAsTree(this.element);this._paddingSize=0;} -_createRootElement(){this._rootElement=new UI.TreeElement();this._rootElement.treeOutline=this;this._rootElement.root=true;this._rootElement.selectable=false;this._rootElement.expanded=true;this._rootElement._childrenListNode.classList.remove('children');} -rootElement(){return this._rootElement;} -firstChild(){return this._rootElement.firstChild();} -appendChild(child){this._rootElement.appendChild(child);} -insertChild(child,index){this._rootElement.insertChild(child,index);} -removeChild(child){this._rootElement.removeChild(child);} -removeChildren(){this._rootElement.removeChildren();} -treeElementFromPoint(x,y){var node=this.contentElement.ownerDocument.deepElementFromPoint(x,y);if(!node) -return null;var listNode=node.enclosingNodeOrSelfWithNodeNameInArray(['ol','li']);if(listNode) -return listNode.parentTreeElement||listNode.treeElement;return null;} -treeElementFromEvent(event){return event?this.treeElementFromPoint(event.pageX,event.pageY):null;} -setComparator(comparator){this._comparator=comparator;} -setFocusable(focusable){if(focusable){this._focusable=true;this.contentElement.setAttribute('tabIndex',-1);if(this.selectedTreeElement) -this.selectedTreeElement._setFocusable(true);}else{this._focusable=false;this.contentElement.removeAttribute('tabIndex');if(this.selectedTreeElement) -this.selectedTreeElement._setFocusable(false);}} -focus(){if(this.selectedTreeElement) -this.selectedTreeElement.listItemElement.focus();else -this.contentElement.focus();} -_bindTreeElement(element){if(element.treeOutline) -console.error('Binding element for the second time: '+new Error().stack);element.treeOutline=this;element.onbind();} -_unbindTreeElement(element){if(!element.treeOutline) -console.error('Unbinding element that was not bound: '+new Error().stack);element.deselect();element.onunbind();element.treeOutline=null;} -selectPrevious(){var nextSelectedElement=this.selectedTreeElement.traversePreviousTreeElement(true);while(nextSelectedElement&&!nextSelectedElement.selectable) -nextSelectedElement=nextSelectedElement.traversePreviousTreeElement(!this.expandTreeElementsWhenArrowing);if(!nextSelectedElement) -return false;nextSelectedElement.select(false,true);return true;} -selectNext(){var nextSelectedElement=this.selectedTreeElement.traverseNextTreeElement(true);while(nextSelectedElement&&!nextSelectedElement.selectable) -nextSelectedElement=nextSelectedElement.traverseNextTreeElement(!this.expandTreeElementsWhenArrowing);if(!nextSelectedElement) -return false;nextSelectedElement.select(false,true);return true;} -setPaddingSize(paddingSize){this._paddingSize=paddingSize;} -_treeKeyDown(event){if(!this.selectedTreeElement||event.target!==this.selectedTreeElement.listItemElement||event.shiftKey||event.metaKey||event.ctrlKey) -return;var handled=false;if(event.key==='ArrowUp'&&!event.altKey){handled=this.selectPrevious();}else if(event.key==='ArrowDown'&&!event.altKey){handled=this.selectNext();}else if(event.key==='ArrowLeft'){handled=this.selectedTreeElement.collapseOrAscend(event.altKey);}else if(event.key==='ArrowRight'){if(!this.selectedTreeElement.revealed()){this.selectedTreeElement.reveal();handled=true;}else{handled=this.selectedTreeElement.descendOrExpand(event.altKey);}}else if(event.keyCode===8||event.keyCode===46){handled=this.selectedTreeElement.ondelete();}else if(isEnterKey(event)){handled=this.selectedTreeElement.onenter();}else if(event.keyCode===UI.KeyboardShortcut.Keys.Space.code){handled=this.selectedTreeElement.onspace();} -if(handled) -event.consume(true);} -_deferredScrollIntoView(treeElement,center){if(!this._treeElementToScrollIntoView) -this.element.window().requestAnimationFrame(deferredScrollIntoView.bind(this));this._treeElementToScrollIntoView=treeElement;this._centerUponScrollIntoView=center;function deferredScrollIntoView(){this._treeElementToScrollIntoView.listItemElement.scrollIntoViewIfNeeded(this._centerUponScrollIntoView);delete this._treeElementToScrollIntoView;delete this._centerUponScrollIntoView;}}};UI.TreeOutline.Events={ElementAttached:Symbol('ElementAttached'),ElementExpanded:Symbol('ElementExpanded'),ElementCollapsed:Symbol('ElementCollapsed'),ElementSelected:Symbol('ElementSelected')};UI.TreeOutlineInShadow=class extends UI.TreeOutline{constructor(){super();this.contentElement.classList.add('tree-outline');this.element=createElement('div');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/treeoutline.css');this._disclosureElement=this._shadowRoot.createChild('div','tree-outline-disclosure');this._disclosureElement.appendChild(this.contentElement);this._renderSelection=true;} -registerRequiredCSS(cssFile){UI.appendStyle(this._shadowRoot,cssFile);} -hideOverflow(){this._disclosureElement.classList.add('tree-outline-disclosure-hide-overflow');} -makeDense(){this.contentElement.classList.add('tree-outline-dense');}};UI.TreeElement=class{constructor(title,expandable){this.treeOutline=null;this.parent=null;this.previousSibling=null;this.nextSibling=null;this._boundOnFocus=this._onFocus.bind(this);this._boundOnBlur=this._onBlur.bind(this);this._listItemNode=createElement('li');this._titleElement=this._listItemNode.createChild('span','tree-element-title');this._listItemNode.treeElement=this;if(title) -this.title=title;this._listItemNode.addEventListener('mousedown',this._handleMouseDown.bind(this),false);this._listItemNode.addEventListener('click',this._treeElementToggled.bind(this),false);this._listItemNode.addEventListener('dblclick',this._handleDoubleClick.bind(this),false);UI.ARIAUtils.markAsTreeitem(this._listItemNode);this._childrenListNode=createElement('ol');this._childrenListNode.parentTreeElement=this;this._childrenListNode.classList.add('children');UI.ARIAUtils.markAsGroup(this._childrenListNode);this._hidden=false;this._selectable=true;this.expanded=false;this.selected=false;this.setExpandable(expandable||false);this._collapsible=true;} -hasAncestor(ancestor){if(!ancestor) -return false;var currentNode=this.parent;while(currentNode){if(ancestor===currentNode) -return true;currentNode=currentNode.parent;} -return false;} -hasAncestorOrSelf(ancestor){return this===ancestor||this.hasAncestor(ancestor);} -children(){return this._children||[];} -childCount(){return this._children?this._children.length:0;} -firstChild(){return this._children?this._children[0]:null;} -lastChild(){return this._children?this._children[this._children.length-1]:null;} -childAt(index){return this._children?this._children[index]:null;} -indexOfChild(child){return this._children?this._children.indexOf(child):-1;} -appendChild(child){if(!this._children) -this._children=[];var insertionIndex;if(this.treeOutline&&this.treeOutline._comparator) -insertionIndex=this._children.lowerBound(child,this.treeOutline._comparator);else -insertionIndex=this._children.length;this.insertChild(child,insertionIndex);} -insertChild(child,index){if(!this._children) -this._children=[];if(!child) -throw'child can\'t be undefined or null';console.assert(!child.parent,'Attempting to insert a child that is already in the tree, reparenting is not supported.');var previousChild=(index>0?this._children[index-1]:null);if(previousChild){previousChild.nextSibling=child;child.previousSibling=previousChild;}else{child.previousSibling=null;} -var nextChild=this._children[index];if(nextChild){nextChild.previousSibling=child;child.nextSibling=nextChild;}else{child.nextSibling=null;} -this._children.splice(index,0,child);this.setExpandable(true);child.parent=this;if(this.treeOutline) -this.treeOutline._bindTreeElement(child);for(var current=child.firstChild();this.treeOutline&¤t;current=current.traverseNextTreeElement(false,child,true)) -this.treeOutline._bindTreeElement(current);child.onattach();child._ensureSelection();if(this.treeOutline) -this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementAttached,child);var nextSibling=child.nextSibling?child.nextSibling._listItemNode:null;this._childrenListNode.insertBefore(child._listItemNode,nextSibling);this._childrenListNode.insertBefore(child._childrenListNode,nextSibling);if(child.selected) -child.select();if(child.expanded) -child.expand();} -removeChildAtIndex(childIndex){if(childIndex<0||childIndex>=this._children.length) -throw'childIndex out of range';var child=this._children[childIndex];this._children.splice(childIndex,1);var parent=child.parent;if(this.treeOutline&&this.treeOutline.selectedTreeElement&&this.treeOutline.selectedTreeElement.hasAncestorOrSelf(child)){if(child.nextSibling) -child.nextSibling.select(true);else if(child.previousSibling) -child.previousSibling.select(true);else if(parent) -parent.select(true);} -if(child.previousSibling) -child.previousSibling.nextSibling=child.nextSibling;if(child.nextSibling) -child.nextSibling.previousSibling=child.previousSibling;child.parent=null;if(this.treeOutline) -this.treeOutline._unbindTreeElement(child);for(var current=child.firstChild();this.treeOutline&¤t;current=current.traverseNextTreeElement(false,child,true)) -this.treeOutline._unbindTreeElement(current);child._detach();} -removeChild(child){if(!child) -throw'child can\'t be undefined or null';if(child.parent!==this) -return;var childIndex=this._children.indexOf(child);if(childIndex===-1) -throw'child not found in this node\'s children';this.removeChildAtIndex(childIndex);} -removeChildren(){if(!this.root&&this.treeOutline&&this.treeOutline.selectedTreeElement&&this.treeOutline.selectedTreeElement.hasAncestorOrSelf(this)) -this.select(true);for(var i=0;this._children&&i<this._children.length;++i){var child=this._children[i];child.previousSibling=null;child.nextSibling=null;child.parent=null;if(this.treeOutline) -this.treeOutline._unbindTreeElement(child);for(var current=child.firstChild();this.treeOutline&¤t;current=current.traverseNextTreeElement(false,child,true)) -this.treeOutline._unbindTreeElement(current);child._detach();} -this._children=[];} -get selectable(){if(this._hidden) -return false;return this._selectable;} -set selectable(x){this._selectable=x;} -get listItemElement(){return this._listItemNode;} -titleElement(){return this._titleElement;} -get childrenListElement(){return this._childrenListNode;} -get title(){return this._title;} -set title(x){if(this._title===x) -return;this._title=x;if(typeof x==='string'){this._titleElement.textContent=x;this.tooltip=x;}else{this._titleElement=x;this.tooltip='';} -this._listItemNode.removeChildren();if(this._leadingIconsElement) -this._listItemNode.appendChild(this._leadingIconsElement);this._listItemNode.appendChild(this._titleElement);if(this._trailingIconsElement) -this._listItemNode.appendChild(this._trailingIconsElement);this._ensureSelection();} -titleAsText(){if(!this._title) -return'';if(typeof this._title==='string') -return this._title;return this._title.textContent;} -startEditingTitle(editingConfig){UI.InplaceEditor.startEditing(this._titleElement,editingConfig);this.treeOutline._shadowRoot.getSelection().selectAllChildren(this._titleElement);} -setLeadingIcons(icons){if(!this._leadingIconsElement&&!icons.length) -return;if(!this._leadingIconsElement){this._leadingIconsElement=createElementWithClass('div','leading-icons');this._leadingIconsElement.classList.add('icons-container');this._listItemNode.insertBefore(this._leadingIconsElement,this._titleElement);this._ensureSelection();} -this._leadingIconsElement.removeChildren();for(var icon of icons) -this._leadingIconsElement.appendChild(icon);} -setTrailingIcons(icons){if(!this._trailingIconsElement&&!icons.length) -return;if(!this._trailingIconsElement){this._trailingIconsElement=createElementWithClass('div','trailing-icons');this._trailingIconsElement.classList.add('icons-container');this._listItemNode.appendChild(this._trailingIconsElement);this._ensureSelection();} -this._trailingIconsElement.removeChildren();for(var icon of icons) -this._trailingIconsElement.appendChild(icon);} -get tooltip(){return this._tooltip||'';} -set tooltip(x){if(this._tooltip===x) -return;this._tooltip=x;this._listItemNode.title=x;} -isExpandable(){return this._expandable;} -setExpandable(expandable){if(this._expandable===expandable) -return;this._expandable=expandable;this._listItemNode.classList.toggle('parent',expandable);if(!expandable){this.collapse();UI.ARIAUtils.unsetExpanded(this._listItemNode);}else{UI.ARIAUtils.setExpanded(this._listItemNode,false);}} -setCollapsible(collapsible){if(this._collapsible===collapsible) -return;this._collapsible=collapsible;this._listItemNode.classList.toggle('always-parent',!collapsible);if(!collapsible) -this.expand();} -get hidden(){return this._hidden;} -set hidden(x){if(this._hidden===x) -return;this._hidden=x;this._listItemNode.classList.toggle('hidden',x);this._childrenListNode.classList.toggle('hidden',x);} -invalidateChildren(){if(this._children){this.removeChildren();this._children=null;}} -computeLeftMargin(){var treeElement=this.parent;var depth=0;while(treeElement!==null){depth++;treeElement=treeElement.parent;} -return-(this.treeOutline._paddingSize*(depth-1)+4);} -_ensureSelection(){if(!this.treeOutline||!this.treeOutline._renderSelection) -return;if(!this._selectionElement) -this._selectionElement=createElementWithClass('div','selection fill');if(this.treeOutline._paddingSize) -this._selectionElement.style.setProperty('margin-left',this.computeLeftMargin()+'px');this._listItemNode.insertBefore(this._selectionElement,this.listItemElement.firstChild);} -_treeElementToggled(event){var element=event.currentTarget;if(element.treeElement!==this||element.hasSelection()) -return;var toggleOnClick=this.toggleOnClick&&!this.selectable;var isInTriangle=this.isEventWithinDisclosureTriangle(event);if(!toggleOnClick&&!isInTriangle) -return;if(this.expanded){if(event.altKey) -this.collapseRecursively();else -this.collapse();}else{if(event.altKey) -this.expandRecursively();else -this.expand();} -event.consume();} -_handleMouseDown(event){var element=event.currentTarget;if(!element) -return;if(!this.selectable) -return;if(element.treeElement!==this) -return;if(this.isEventWithinDisclosureTriangle(event)) -return;this.selectOnMouseDown(event);} -_handleDoubleClick(event){var element=event.currentTarget;if(!element||element.treeElement!==this) -return;var handled=this.ondblclick(event);if(handled) -return;if(this._expandable&&!this.expanded) -this.expand();} -_detach(){this._listItemNode.remove();this._childrenListNode.remove();} -collapse(){if(!this.expanded||!this._collapsible) -return;this._listItemNode.classList.remove('expanded');this._childrenListNode.classList.remove('expanded');UI.ARIAUtils.setExpanded(this._listItemNode,false);this.expanded=false;this.oncollapse();if(this.treeOutline) -this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementCollapsed,this);} -collapseRecursively(){var item=this;while(item){if(item.expanded) -item.collapse();item=item.traverseNextTreeElement(false,this,true);}} -expand(){if(!this._expandable||(this.expanded&&this._children)) -return;this.expanded=true;this._populateIfNeeded();this._listItemNode.classList.add('expanded');this._childrenListNode.classList.add('expanded');UI.ARIAUtils.setExpanded(this._listItemNode,true);if(this.treeOutline){this.onexpand();this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementExpanded,this);}} -expandRecursively(maxDepth){var item=this;var info={};var depth=0;if(isNaN(maxDepth)) -maxDepth=3;while(item){if(depth<maxDepth) -item.expand();item=item.traverseNextTreeElement(false,this,(depth>=maxDepth),info);depth+=info.depthChange;}} -collapseOrAscend(altKey){if(this.expanded){if(altKey) -this.collapseRecursively();else -this.collapse();return true;} -if(!this.parent||this.parent.root) -return false;if(!this.parent.selectable){this.parent.collapse();return true;} -var nextSelectedElement=this.parent;while(nextSelectedElement&&!nextSelectedElement.selectable) -nextSelectedElement=nextSelectedElement.parent;if(!nextSelectedElement) -return false;nextSelectedElement.select(false,true);return true;} -descendOrExpand(altKey){if(!this._expandable) -return false;if(!this.expanded){if(altKey) -this.expandRecursively();else -this.expand();return true;} -var nextSelectedElement=this.firstChild();while(nextSelectedElement&&!nextSelectedElement.selectable) -nextSelectedElement=nextSelectedElement.nextSibling;if(!nextSelectedElement) -return false;nextSelectedElement.select(false,true);return true;} -reveal(center){var currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded) -currentAncestor.expand();currentAncestor=currentAncestor.parent;} -this.treeOutline._deferredScrollIntoView(this,!!center);} -revealed(){var currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded) -return false;currentAncestor=currentAncestor.parent;} -return true;} -selectOnMouseDown(event){if(this.select(false,true)) -event.consume(true);} -select(omitFocus,selectedByUser){if(!this.treeOutline||!this.selectable||this.selected) -return false;var lastSelected=this.treeOutline.selectedTreeElement;this.treeOutline.selectedTreeElement=null;if(this.treeOutline._rootElement===this){if(lastSelected) -lastSelected.deselect();return false;} -this.selected=true;this.treeOutline.selectedTreeElement=this;if(this.treeOutline._focusable) -this._setFocusable(true);if(!omitFocus||this.treeOutline.contentElement.hasFocus()) -this.listItemElement.focus();this._listItemNode.classList.add('selected');this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementSelected,this);if(lastSelected) -lastSelected.deselect();return this.onselect(selectedByUser);} -_setFocusable(focusable){if(focusable){this._listItemNode.setAttribute('tabIndex',0);this._listItemNode.addEventListener('focus',this._boundOnFocus,false);this._listItemNode.addEventListener('blur',this._boundOnBlur,false);}else{this._listItemNode.removeAttribute('tabIndex');this._listItemNode.removeEventListener('focus',this._boundOnFocus,false);this._listItemNode.removeEventListener('blur',this._boundOnBlur,false);}} -_onFocus(){this._listItemNode.classList.add('force-white-icons');} -_onBlur(){this._listItemNode.classList.remove('force-white-icons');} -revealAndSelect(omitFocus){this.reveal(true);this.select(omitFocus);} -deselect(){var hadFocus=this._listItemNode.hasFocus();this.selected=false;this._listItemNode.classList.remove('selected');this._setFocusable(false);if(this.treeOutline&&this.treeOutline.selectedTreeElement===this){this.treeOutline.selectedTreeElement=null;if(hadFocus) -this.treeOutline.focus();}} -_populateIfNeeded(){if(this.treeOutline&&this._expandable&&!this._children){this._children=[];this.onpopulate();}} -onpopulate(){} -onenter(){return false;} -ondelete(){return false;} -onspace(){return false;} -onbind(){} -onunbind(){} -onattach(){} -onexpand(){} -oncollapse(){} -ondblclick(e){return false;} -onselect(selectedByUser){return false;} -traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate,info){if(!dontPopulate) -this._populateIfNeeded();if(info) -info.depthChange=0;var element=skipUnrevealed?(this.revealed()?this.firstChild():null):this.firstChild();if(element&&(!skipUnrevealed||(skipUnrevealed&&this.expanded))){if(info) -info.depthChange=1;return element;} -if(this===stayWithin) -return null;element=skipUnrevealed?(this.revealed()?this.nextSibling:null):this.nextSibling;if(element) -return element;element=this;while(element&&!element.root&&!(skipUnrevealed?(element.revealed()?element.nextSibling:null):element.nextSibling)&&element.parent!==stayWithin){if(info) -info.depthChange-=1;element=element.parent;} -if(!element||element.root) -return null;return(skipUnrevealed?(element.revealed()?element.nextSibling:null):element.nextSibling);} -traversePreviousTreeElement(skipUnrevealed,dontPopulate){var element=skipUnrevealed?(this.revealed()?this.previousSibling:null):this.previousSibling;if(!dontPopulate&&element) -element._populateIfNeeded();while(element&&(skipUnrevealed?(element.revealed()&&element.expanded?element.lastChild():null):element.lastChild())){if(!dontPopulate) -element._populateIfNeeded();element=(skipUnrevealed?(element.revealed()&&element.expanded?element.lastChild():null):element.lastChild());} -if(element) -return element;if(!this.parent||this.parent.root) -return null;return this.parent;} -isEventWithinDisclosureTriangle(event){var paddingLeftValue=window.getComputedStyle(this._listItemNode).paddingLeft;console.assert(paddingLeftValue.endsWith('px'));var computedLeftPadding=parseFloat(paddingLeftValue);var left=this._listItemNode.totalOffsetLeft()+computedLeftPadding;return event.pageX>=left&&event.pageX<=left+UI.TreeElement._ArrowToggleWidth&&this._expandable;}};UI.TreeElement._ArrowToggleWidth=10;(function(){var img=new Image();if(window.devicePixelRatio>1) -img.src='Images/treeoutlineTriangles_2x.png';else -img.src='Images/treeoutlineTriangles.png';UI.TreeElement._imagePreload=img;})();;UI.InspectorView=class extends UI.VBox{constructor(){super();UI.GlassPane.setContainer(this.element);this.setMinimumSize(240,72);this._drawerSplitWidget=new UI.SplitWidget(false,true,'Inspector.drawerSplitViewState',200,200);this._drawerSplitWidget.hideSidebar();this._drawerSplitWidget.hideDefaultResizer();this._drawerSplitWidget.enableShowModeSaving();this._drawerSplitWidget.show(this.element);this._drawerTabbedLocation=UI.viewManager.createTabbedLocation(this._showDrawer.bind(this,false),'drawer-view',true,true);this._drawerTabbedLocation.enableMoreTabsButton();this._drawerTabbedPane=this._drawerTabbedLocation.tabbedPane();this._drawerTabbedPane.setMinimumSize(0,27);var closeDrawerButton=new UI.ToolbarButton(Common.UIString('Close drawer'),'largeicon-delete');closeDrawerButton.addEventListener(UI.ToolbarButton.Events.Click,this._closeDrawer,this);this._drawerTabbedPane.rightToolbar().appendToolbarItem(closeDrawerButton);this._drawerSplitWidget.installResizer(this._drawerTabbedPane.headerElement());this._drawerSplitWidget.setSidebarWidget(this._drawerTabbedPane);this._tabbedLocation=UI.viewManager.createTabbedLocation(InspectorFrontendHost.bringToFront.bind(InspectorFrontendHost),'panel',true,true,Runtime.queryParam('panel'));this._tabbedPane=this._tabbedLocation.tabbedPane();this._tabbedPane.registerRequiredCSS('ui/inspectorViewTabbedPane.css');this._tabbedPane.setTabSlider(true);this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);this._tabbedPane.setAccessibleName(Common.UIString('Panels'));if(Host.isUnderTest()) -this._tabbedPane.setAutoSelectFirstItemOnShow(false);this._drawerSplitWidget.setMainWidget(this._tabbedPane);this._keyDownBound=this._keyDown.bind(this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ShowPanel,showPanel.bind(this));function showPanel(event){var panelName=(event.data);this.showPanel(panelName);}} -static instance(){return(self.runtime.sharedInstance(UI.InspectorView));} -wasShown(){this.element.ownerDocument.addEventListener('keydown',this._keyDownBound,false);} -willHide(){this.element.ownerDocument.removeEventListener('keydown',this._keyDownBound,false);} -resolveLocation(locationName){if(locationName==='drawer-view') -return this._drawerTabbedLocation;if(locationName==='panel') -return this._tabbedLocation;return null;} -createToolbars(){this._tabbedPane.leftToolbar().appendLocationItems('main-toolbar-left');this._tabbedPane.rightToolbar().appendLocationItems('main-toolbar-right');} -addPanel(view){this._tabbedLocation.appendView(view);} -hasPanel(panelName){return this._tabbedPane.hasTab(panelName);} -panel(panelName){return(UI.viewManager.view(panelName).widget());} -onSuspendStateChanged(allTargetsSuspended){this._currentPanelLocked=allTargetsSuspended;this._tabbedPane.setCurrentTabLocked(this._currentPanelLocked);this._tabbedPane.leftToolbar().setEnabled(!this._currentPanelLocked);this._tabbedPane.rightToolbar().setEnabled(!this._currentPanelLocked);} -canSelectPanel(panelName){return!this._currentPanelLocked||this._tabbedPane.selectedTabId===panelName;} -showPanel(panelName){return UI.viewManager.showView(panelName);} -setPanelIcon(panelName,icon){this._tabbedPane.setTabIcon(panelName,icon);} -currentPanelDeprecated(){return(UI.viewManager.materializedWidget(this._tabbedPane.selectedTabId||''));} -_showDrawer(focus){if(this._drawerTabbedPane.isShowing()) -return;this._drawerSplitWidget.showBoth();if(focus) -this._focusRestorer=new UI.WidgetFocusRestorer(this._drawerTabbedPane);else -this._focusRestorer=null;} -drawerVisible(){return this._drawerTabbedPane.isShowing();} -_closeDrawer(){if(!this._drawerTabbedPane.isShowing()) -return;if(this._focusRestorer) -this._focusRestorer.restore();this._drawerSplitWidget.hideSidebar(true);} -setDrawerMinimized(minimized){this._drawerSplitWidget.setSidebarMinimized(minimized);this._drawerSplitWidget.setResizable(!minimized);} -isDrawerMinimized(){return this._drawerSplitWidget.isSidebarMinimized();} -closeDrawerTab(id,userGesture){this._drawerTabbedPane.closeTab(id,userGesture);} -_keyDown(event){var keyboardEvent=(event);if(!UI.KeyboardShortcut.eventHasCtrlOrMeta(keyboardEvent)||event.altKey||event.shiftKey) -return;var panelShortcutEnabled=Common.moduleSetting('shortcutPanelSwitch').get();if(panelShortcutEnabled){var panelIndex=-1;if(event.keyCode>0x30&&event.keyCode<0x3A) -panelIndex=event.keyCode-0x31;else if(event.keyCode>0x60&&event.keyCode<0x6A&&keyboardEvent.location===KeyboardEvent.DOM_KEY_LOCATION_NUMPAD) -panelIndex=event.keyCode-0x61;if(panelIndex!==-1){var panelName=this._tabbedPane.allTabs()[panelIndex];if(panelName){if(!UI.Dialog.hasInstance()&&!this._currentPanelLocked) -this.showPanel(panelName);event.consume(true);}}} -if(event.key==='['){this._tabbedPane.selectPrevTab();event.consume(true);} -if(event.key===']'){this._tabbedPane.selectNextTab();event.consume(true);}} -onResize(){UI.GlassPane.containerMoved(this.element);} -topResizerElement(){return this._tabbedPane.headerElement();} -toolbarItemResized(){this._tabbedPane.headerResized();} -_tabSelected(event){var tabId=(event.data['tabId']);Host.userMetrics.panelShown(tabId);} -setOwnerSplit(splitWidget){this._ownerSplitWidget=splitWidget;} -minimize(){if(this._ownerSplitWidget) -this._ownerSplitWidget.setSidebarMinimized(true);} -restore(){if(this._ownerSplitWidget) -this._ownerSplitWidget.setSidebarMinimized(false);}};UI.inspectorView;UI.InspectorView.DrawerToggleActionDelegate=class{handleAction(context,actionId){if(UI.inspectorView.drawerVisible()) -UI.inspectorView._closeDrawer();else -UI.inspectorView._showDrawer(true);return true;}};;UI.ActionRegistry=class{constructor(){this._actionsById=new Map();this._registerActions();} -_registerActions(){self.runtime.extensions(UI.ActionDelegate).forEach(registerExtension,this);function registerExtension(extension){var actionId=extension.descriptor()['actionId'];console.assert(actionId);console.assert(!this._actionsById.get(actionId));this._actionsById.set(actionId,new UI.Action(extension));}} -availableActions(){return this.applicableActions(this._actionsById.keysArray(),UI.context);} -applicableActions(actionIds,context){var extensions=[];actionIds.forEach(function(actionId){var action=this._actionsById.get(actionId);if(action) -extensions.push(action._extension);},this);return context.applicableExtensions(extensions).valuesArray().map(extensionToAction.bind(this));function extensionToAction(extension){return(this.action(extension.descriptor()['actionId']));}} -action(actionId){return this._actionsById.get(actionId)||null;}};UI.Action=class extends Common.Object{constructor(extension){super();this._extension=extension;this._enabled=true;this._toggled=false;} -id(){return this._extension.descriptor()['actionId'];} -execute(){return this._extension.instance().then(handleAction.bind(this));function handleAction(actionDelegate){var actionId=this._extension.descriptor()['actionId'];var delegate=(actionDelegate);return delegate.handleAction(UI.context,actionId);}} -icon(){return this._extension.descriptor()['iconClass']||'';} -toggledIcon(){return this._extension.descriptor()['toggledIconClass']||'';} -toggleWithRedColor(){return!!this._extension.descriptor()['toggleWithRedColor'];} -setEnabled(enabled){if(this._enabled===enabled) -return;this._enabled=enabled;this.dispatchEventToListeners(UI.Action.Events.Enabled,enabled);} -enabled(){return this._enabled;} -category(){return this._extension.descriptor()['category']||'';} -tags(){return this._extension.descriptor()['tags']||'';} -title(){var title=this._extension.title();var options=this._extension.descriptor()['options'];if(options){for(var pair of options){if(pair['value']!==this._toggled) -title=pair['title'];}} -return title;} -toggled(){return this._toggled;} -setToggled(toggled){if(this._toggled===toggled) -return;this._toggled=toggled;this.dispatchEventToListeners(UI.Action.Events.Toggled,toggled);}};UI.Action.Events={Enabled:Symbol('Enabled'),Toggled:Symbol('Toggled')};UI.ActionDelegate=function(){};UI.ActionDelegate.prototype={handleAction(context,actionId){}};UI.actionRegistry;;UI.ShortcutRegistry=class{constructor(actionRegistry,document){this._actionRegistry=actionRegistry;this._defaultKeyToActions=new Multimap();this._defaultActionToShortcut=new Multimap();this._registerBindings(document);} -_applicableActions(key){return this._actionRegistry.applicableActions(this._defaultActionsForKey(key).valuesArray(),UI.context);} -_defaultActionsForKey(key){return this._defaultKeyToActions.get(String(key));} -shortcutDescriptorsForAction(actionId){return this._defaultActionToShortcut.get(actionId).valuesArray();} -keysForActions(actionIds){var result=[];for(var i=0;i<actionIds.length;++i){var descriptors=this.shortcutDescriptorsForAction(actionIds[i]);for(var j=0;j<descriptors.length;++j) -result.push(descriptors[j].key);} -return result;} -shortcutTitleForAction(actionId){var descriptors=this.shortcutDescriptorsForAction(actionId);if(descriptors.length) -return descriptors[0].name;} -handleShortcut(event){this.handleKey(UI.KeyboardShortcut.makeKeyFromEvent(event),event.key,event);} -handleKey(key,domKey,event){var keyModifiers=key>>8;var actions=this._applicableActions(key);if(!actions.length) -return;if(UI.Dialog.hasInstance()){if(event&&!isPossiblyInputKey()) -event.consume(true);return;} -if(!isPossiblyInputKey()){if(event) -event.consume(true);processNextAction.call(this,false);}else{this._pendingActionTimer=setTimeout(processNextAction.bind(this,false),0);} -function processNextAction(handled){delete this._pendingActionTimer;var action=actions.shift();if(!action||handled) -return;action.execute().then(processNextAction.bind(this));} -function isPossiblyInputKey(){if(!event||!UI.isEditing()||/^F\d+|Control|Shift|Alt|Meta|Escape|Win|U\+001B$/.test(domKey)) -return false;if(!keyModifiers) -return true;var modifiers=UI.KeyboardShortcut.Modifiers;if((keyModifiers&(modifiers.Ctrl|modifiers.Alt))===(modifiers.Ctrl|modifiers.Alt)) -return Host.isWin();return!hasModifier(modifiers.Ctrl)&&!hasModifier(modifiers.Alt)&&!hasModifier(modifiers.Meta);} -function hasModifier(mod){return!!(keyModifiers&mod);}} -registerShortcut(actionId,shortcut){var descriptor=UI.KeyboardShortcut.makeDescriptorFromBindingShortcut(shortcut);if(!descriptor) -return;this._defaultActionToShortcut.set(actionId,descriptor);this._defaultKeyToActions.set(String(descriptor.key),actionId);} -dismissPendingShortcutAction(){if(this._pendingActionTimer){clearTimeout(this._pendingActionTimer);delete this._pendingActionTimer;}} -_registerBindings(document){document.addEventListener('input',this.dismissPendingShortcutAction.bind(this),true);var extensions=self.runtime.extensions(UI.ActionDelegate);extensions.forEach(registerExtension,this);function registerExtension(extension){var descriptor=extension.descriptor();var bindings=descriptor['bindings'];for(var i=0;bindings&&i<bindings.length;++i){if(!platformMatches(bindings[i].platform)) -continue;var shortcuts=bindings[i]['shortcut'].split(/\s+/);shortcuts.forEach(this.registerShortcut.bind(this,descriptor['actionId']));}} -function platformMatches(platformsString){if(!platformsString) -return true;var platforms=platformsString.split(',');var isMatch=false;var currentPlatform=Host.platform();for(var i=0;!isMatch&&i<platforms.length;++i) -isMatch=platforms[i]===currentPlatform;return isMatch;}}};UI.ShortcutRegistry.ForwardedShortcut=class{};UI.ShortcutRegistry.ForwardedShortcut.instance=new UI.ShortcutRegistry.ForwardedShortcut();UI.shortcutRegistry;;UI.Context=class{constructor(){this._flavors=new Map();this._eventDispatchers=new Map();} -setFlavor(flavorType,flavorValue){var value=this._flavors.get(flavorType)||null;if(value===flavorValue) -return;if(flavorValue) -this._flavors.set(flavorType,flavorValue);else -this._flavors.remove(flavorType);this._dispatchFlavorChange(flavorType,flavorValue);} -_dispatchFlavorChange(flavorType,flavorValue){for(var extension of self.runtime.extensions(UI.ContextFlavorListener)){if(extension.hasContextType(flavorType)){extension.instance().then(instance=>(instance).flavorChanged(flavorValue));}} -var dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher) -return;dispatcher.dispatchEventToListeners(UI.Context.Events.FlavorChanged,flavorValue);} -addFlavorChangeListener(flavorType,listener,thisObject){var dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher){dispatcher=new Common.Object();this._eventDispatchers.set(flavorType,dispatcher);} -dispatcher.addEventListener(UI.Context.Events.FlavorChanged,listener,thisObject);} -removeFlavorChangeListener(flavorType,listener,thisObject){var dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher) -return;dispatcher.removeEventListener(UI.Context.Events.FlavorChanged,listener,thisObject);if(!dispatcher.hasEventListeners(UI.Context.Events.FlavorChanged)) -this._eventDispatchers.remove(flavorType);} -flavor(flavorType){return this._flavors.get(flavorType)||null;} -flavors(){return new Set(this._flavors.keys());} -applicableExtensions(extensions){var targetExtensionSet=new Set();var availableFlavors=this.flavors();extensions.forEach(function(extension){if(self.runtime.isExtensionApplicableToContextTypes(extension,availableFlavors)) -targetExtensionSet.add(extension);});return targetExtensionSet;}};UI.Context.Events={FlavorChanged:Symbol('FlavorChanged')};UI.ContextFlavorListener=function(){};UI.ContextFlavorListener.prototype={flavorChanged(object){}};UI.context=new UI.Context();;UI.ContextMenuItem=class{constructor(contextMenu,type,label,disabled,checked){this._type=type;this._label=label;this._disabled=disabled;this._checked=checked;this._contextMenu=contextMenu;if(type==='item'||type==='checkbox') -this._id=contextMenu?contextMenu._nextId():0;} -id(){return this._id;} -type(){return this._type;} -isEnabled(){return!this._disabled;} -setEnabled(enabled){this._disabled=!enabled;} -_buildDescriptor(){switch(this._type){case'item':var result={type:'item',id:this._id,label:this._label,enabled:!this._disabled};if(this._customElement) -result.element=this._customElement;if(this._shortcut) -result.shortcut=this._shortcut;return result;case'separator':return{type:'separator'};case'checkbox':return{type:'checkbox',id:this._id,label:this._label,checked:!!this._checked,enabled:!this._disabled};} -throw new Error('Invalid item type:'+this._type);} -setShortcut(shortcut){this._shortcut=shortcut;}};UI.ContextMenuSection=class{constructor(contextMenu){this._contextMenu=contextMenu;this._items=[];} -appendItem(label,handler,disabled){var item=new UI.ContextMenuItem(this._contextMenu,'item',label,disabled);this._items.push(item);this._contextMenu._setHandler(item.id(),handler);return item;} -appendCustomItem(element){var item=new UI.ContextMenuItem(this._contextMenu,'item','<custom>');item._customElement=element;this._items.push(item);return item;} -appendAction(actionId,label){var action=UI.actionRegistry.action(actionId);if(!label) -label=action.title();var result=this.appendItem(label,action.execute.bind(action));var shortcut=UI.shortcutRegistry.shortcutTitleForAction(actionId);if(shortcut) -result.setShortcut(shortcut);return result;} -appendSubMenuItem(label,disabled){var item=new UI.ContextSubMenu(this._contextMenu,label,disabled);item._init();this._items.push(item);return item;} -appendCheckboxItem(label,handler,checked,disabled){var item=new UI.ContextMenuItem(this._contextMenu,'checkbox',label,disabled,checked);this._items.push(item);this._contextMenu._setHandler(item.id(),handler);return item;}};UI.ContextSubMenu=class extends UI.ContextMenuItem{constructor(contextMenu,label,disabled){super(contextMenu,'subMenu',label,disabled);this._sections=new Map();this._sectionList=[];} -_init(){UI.ContextMenu._groupWeights.forEach(name=>this.section(name));} -section(name){var section=name?this._sections.get(name):null;if(!section){section=new UI.ContextMenuSection(this._contextMenu);if(name){this._sections.set(name,section);this._sectionList.push(section);}else{this._sectionList.splice(UI.ContextMenu._groupWeights.indexOf('default'),0,section);}} -return section;} -headerSection(){return this.section('header');} -newSection(){return this.section('new');} -revealSection(){return this.section('reveal');} -clipboardSection(){return this.section('clipboard');} -editSection(){return this.section('edit');} -debugSection(){return this.section('debug');} -viewSection(){return this.section('view');} -defaultSection(){return this.section('default');} -saveSection(){return this.section('save');} -footerSection(){return this.section('footer');} -_buildDescriptor(){var result={type:'subMenu',label:this._label,enabled:!this._disabled,subItems:[]};var nonEmptySections=this._sectionList.filter(section=>!!section._items.length);for(var section of nonEmptySections){for(var item of section._items) -result.subItems.push(item._buildDescriptor());if(section!==nonEmptySections.peekLast()) -result.subItems.push({type:'separator'});} -return result;}};UI.ContextMenuItem._uniqueSectionName=0;UI.ContextMenu=class extends UI.ContextSubMenu{constructor(event,useSoftMenu,x,y){super(null);this._contextMenu=this;super._init();this._defaultSection=this.defaultSection();this._pendingPromises=[];this._pendingTargets=[];this._event=event;this._useSoftMenu=!!useSoftMenu;this._x=x===undefined?event.x:x;this._y=y===undefined?event.y:y;this._handlers={};this._id=0;var target=event.deepElementFromPoint();if(target) -this.appendApplicableItems((target));} -static initialize(){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SetUseSoftMenu,setUseSoftMenu);function setUseSoftMenu(event){UI.ContextMenu._useSoftMenu=(event.data);}} -static installHandler(doc){doc.body.addEventListener('contextmenu',handler,false);function handler(event){var contextMenu=new UI.ContextMenu(event);contextMenu.show();}} -_nextId(){return this._id++;} -show(){Promise.all(this._pendingPromises).then(populate.bind(this)).then(this._innerShow.bind(this));UI.ContextMenu._pendingMenu=this;function populate(appendCallResults){if(UI.ContextMenu._pendingMenu!==this) -return;delete UI.ContextMenu._pendingMenu;for(var i=0;i<appendCallResults.length;++i){var providers=appendCallResults[i];var target=this._pendingTargets[i];for(var j=0;j<providers.length;++j){var provider=(providers[j]);provider.appendApplicableItems(this._event,this,target);}} -this._pendingPromises=[];this._pendingTargets=[];} -this._event.consume(true);} -discard(){if(this._softMenu) -this._softMenu.discard();} -_innerShow(){var menuObject=this._buildMenuDescriptors();if(this._useSoftMenu||UI.ContextMenu._useSoftMenu||InspectorFrontendHost.isHostedMode()){this._softMenu=new UI.SoftContextMenu(menuObject,this._itemSelected.bind(this));this._softMenu.show(this._event.target.ownerDocument,new AnchorBox(this._x,this._y,0,0));}else{InspectorFrontendHost.showContextMenuAtPoint(this._x,this._y,menuObject,this._event.target.ownerDocument);function listenToEvents(){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ContextMenuCleared,this._menuCleared,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ContextMenuItemSelected,this._onItemSelected,this);} -setImmediate(listenToEvents.bind(this));}} -_setHandler(id,handler){if(handler) -this._handlers[id]=handler;} -_buildMenuDescriptors(){return(super._buildDescriptor().subItems);} -_onItemSelected(event){this._itemSelected((event.data));} -_itemSelected(id){if(this._handlers[id]) -this._handlers[id].call(this);this._menuCleared();} -_menuCleared(){InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.ContextMenuCleared,this._menuCleared,this);InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.ContextMenuItemSelected,this._onItemSelected,this);} -appendApplicableItems(target){this._pendingPromises.push(self.runtime.allInstances(UI.ContextMenu.Provider,target));this._pendingTargets.push(target);} -appendItemsAtLocation(location){for(var extension of self.runtime.extensions('context-menu-item')){var itemLocation=extension.descriptor()['location']||'';if(!itemLocation.startsWith(location+'/')) -continue;var section=itemLocation.substr(location.length+1);if(!section||section.includes('/')) -continue;this.section(section).appendAction(extension.descriptor()['actionId']);}}};UI.ContextMenu._groupWeights=['header','new','reveal','edit','clipboard','debug','view','default','save','footer'];UI.ContextMenu.Provider=function(){};UI.ContextMenu.Provider.prototype={appendApplicableItems(event,contextMenu,target){}};;UI.GlassPane=class{constructor(){this._widget=new UI.Widget(true);this._widget.markAsRoot();this.element=this._widget.element;this.contentElement=this._widget.contentElement;this._arrowElement=UI.Icon.create('','arrow hidden');this.element.shadowRoot.appendChild(this._arrowElement);this.registerRequiredCSS('ui/glassPane.css');this.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.PierceGlassPane);this._onMouseDownBound=this._onMouseDown.bind(this);this._onClickOutsideCallback=null;this._maxSize=null;this._positionX=null;this._positionY=null;this._anchorBox=null;this._anchorBehavior=UI.GlassPane.AnchorBehavior.PreferTop;this._sizeBehavior=UI.GlassPane.SizeBehavior.SetExactSize;this._marginBehavior=UI.GlassPane.MarginBehavior.DefaultMargin;} -isShowing(){return this._widget.isShowing();} -registerRequiredCSS(cssFile){this._widget.registerRequiredCSS(cssFile);} -setDimmed(dimmed){this.element.classList.toggle('dimmed-pane',dimmed);} -setPointerEventsBehavior(pointerEventsBehavior){this.element.classList.toggle('no-pointer-events',pointerEventsBehavior!==UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this.contentElement.classList.toggle('no-pointer-events',pointerEventsBehavior===UI.GlassPane.PointerEventsBehavior.PierceContents);} -setOutsideClickCallback(callback){this._onClickOutsideCallback=callback;} -setMaxContentSize(size){this._maxSize=size;this._positionContent();} -setSizeBehavior(sizeBehavior){this._sizeBehavior=sizeBehavior;this._positionContent();} -setContentPosition(x,y){this._positionX=x;this._positionY=y;this._positionContent();} -setContentAnchorBox(anchorBox){this._anchorBox=anchorBox;this._positionContent();} -setAnchorBehavior(behavior){this._anchorBehavior=behavior;} -setMarginBehavior(behavior){this._marginBehavior=behavior;this._arrowElement.classList.toggle('hidden',behavior!==UI.GlassPane.MarginBehavior.Arrow);} -show(document){if(this.isShowing()) -return;this.element.style.zIndex=3000+1000*UI.GlassPane._panes.size;document.body.addEventListener('mousedown',this._onMouseDownBound,true);this._widget.show(document.body);UI.GlassPane._panes.add(this);this._positionContent();} -hide(){if(!this.isShowing()) -return;UI.GlassPane._panes.delete(this);this.element.ownerDocument.body.removeEventListener('mousedown',this._onMouseDownBound,true);this._widget.detach();} -_onMouseDown(event){if(!this._onClickOutsideCallback) -return;var node=event.deepElementFromPoint();if(!node||this.contentElement.isSelfOrAncestor(node)) -return;this._onClickOutsideCallback.call(null,event);} -_positionContent(){if(!this.isShowing()) -return;var showArrow=this._marginBehavior===UI.GlassPane.MarginBehavior.Arrow;var gutterSize=showArrow?8:(this._marginBehavior===UI.GlassPane.MarginBehavior.NoMargin?0:3);var scrollbarSize=15;var arrowSize=10;var container=UI.GlassPane._containers.get((this.element.ownerDocument));if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){this.contentElement.positionAt(0,0);this.contentElement.style.width='';this.contentElement.style.maxWidth='';this.contentElement.style.height='';this.contentElement.style.maxHeight='';} -var containerWidth=container.offsetWidth;var containerHeight=container.offsetHeight;var width=containerWidth-gutterSize*2;var height=containerHeight-gutterSize*2;var positionX=gutterSize;var positionY=gutterSize;if(this._maxSize){width=Math.min(width,this._maxSize.width);height=Math.min(height,this._maxSize.height);} -if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){var measuredWidth=this.contentElement.offsetWidth;var measuredHeight=this.contentElement.offsetHeight;var widthOverflow=height<measuredHeight?scrollbarSize:0;var heightOverflow=width<measuredWidth?scrollbarSize:0;width=Math.min(width,measuredWidth+widthOverflow);height=Math.min(height,measuredHeight+heightOverflow);} -if(this._anchorBox){var anchorBox=this._anchorBox.relativeToElement(container);var behavior=this._anchorBehavior;this._arrowElement.classList.remove('arrow-none','arrow-top','arrow-bottom','arrow-left','arrow-right');if(behavior===UI.GlassPane.AnchorBehavior.PreferTop||behavior===UI.GlassPane.AnchorBehavior.PreferBottom){var top=anchorBox.y-2*gutterSize;var bottom=containerHeight-anchorBox.y-anchorBox.height-2*gutterSize;if(behavior===UI.GlassPane.AnchorBehavior.PreferTop&&top<height&&bottom>top) -behavior=UI.GlassPane.AnchorBehavior.PreferBottom;if(behavior===UI.GlassPane.AnchorBehavior.PreferBottom&&bottom<height&&top>bottom) -behavior=UI.GlassPane.AnchorBehavior.PreferTop;var arrowY;var enoughHeight=true;if(behavior===UI.GlassPane.AnchorBehavior.PreferTop){positionY=Math.max(gutterSize,anchorBox.y-height-gutterSize);var spaceTop=anchorBox.y-positionY-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(height>spaceTop){this._arrowElement.classList.add('arrow-none');enoughHeight=false;}}else{height=Math.min(height,spaceTop);} -this._arrowElement.setIconType('mediumicon-arrow-bottom');this._arrowElement.classList.add('arrow-bottom');arrowY=anchorBox.y-gutterSize;}else{positionY=anchorBox.y+anchorBox.height+gutterSize;var spaceBottom=containerHeight-positionY-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(height>spaceBottom){this._arrowElement.classList.add('arrow-none');positionY=containerHeight-gutterSize-height;enoughHeight=false;}}else{height=Math.min(height,spaceBottom);} -this._arrowElement.setIconType('mediumicon-arrow-top');this._arrowElement.classList.add('arrow-top');arrowY=anchorBox.y+anchorBox.height+gutterSize;} -positionX=Math.max(gutterSize,Math.min(anchorBox.x,containerWidth-width-gutterSize));if(!enoughHeight) -positionX=Math.min(positionX+arrowSize,containerWidth-width-gutterSize);else if(showArrow&&positionX-arrowSize>=gutterSize) -positionX-=arrowSize;width=Math.min(width,containerWidth-positionX-gutterSize);if(2*arrowSize>=width){this._arrowElement.classList.add('arrow-none');}else{var arrowX=anchorBox.x+Math.min(50,Math.floor(anchorBox.width/2));arrowX=Number.constrain(arrowX,positionX+arrowSize,positionX+width-arrowSize);this._arrowElement.positionAt(arrowX,arrowY,container);}}else{var left=anchorBox.x-2*gutterSize;var right=containerWidth-anchorBox.x-anchorBox.width-2*gutterSize;if(behavior===UI.GlassPane.AnchorBehavior.PreferLeft&&left<width&&right>left) -behavior=UI.GlassPane.AnchorBehavior.PreferRight;if(behavior===UI.GlassPane.AnchorBehavior.PreferRight&&right<width&&left>right) -behavior=UI.GlassPane.AnchorBehavior.PreferLeft;var arrowX;var enoughWidth=true;if(behavior===UI.GlassPane.AnchorBehavior.PreferLeft){positionX=Math.max(gutterSize,anchorBox.x-width-gutterSize);var spaceLeft=anchorBox.x-positionX-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(width>spaceLeft){this._arrowElement.classList.add('arrow-none');enoughWidth=false;}}else{width=Math.min(width,spaceLeft);} -this._arrowElement.setIconType('mediumicon-arrow-right');this._arrowElement.classList.add('arrow-right');arrowX=anchorBox.x-gutterSize;}else{positionX=anchorBox.x+anchorBox.width+gutterSize;var spaceRight=containerWidth-positionX-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(width>spaceRight){this._arrowElement.classList.add('arrow-none');positionX=containerWidth-gutterSize-width;enoughWidth=false;}}else{width=Math.min(width,spaceRight);} -this._arrowElement.setIconType('mediumicon-arrow-left');this._arrowElement.classList.add('arrow-left');arrowX=anchorBox.x+anchorBox.width+gutterSize;} -positionY=Math.max(gutterSize,Math.min(anchorBox.y,containerHeight-height-gutterSize));if(!enoughWidth) -positionY=Math.min(positionY+arrowSize,containerHeight-height-gutterSize);else if(showArrow&&positionY-arrowSize>=gutterSize) -positionY-=arrowSize;height=Math.min(height,containerHeight-positionY-gutterSize);if(2*arrowSize>=height){this._arrowElement.classList.add('arrow-none');}else{var arrowY=anchorBox.y+Math.min(50,Math.floor(anchorBox.height/2));arrowY=Number.constrain(arrowY,positionY+arrowSize,positionY+height-arrowSize);this._arrowElement.positionAt(arrowX,arrowY,container);}}}else{positionX=this._positionX!==null?this._positionX:(containerWidth-width)/2;positionY=this._positionY!==null?this._positionY:(containerHeight-height)/2;width=Math.min(width,containerWidth-positionX-gutterSize);height=Math.min(height,containerHeight-positionY-gutterSize);this._arrowElement.classList.add('arrow-none');} -this.contentElement.style.width=width+'px';if(this._sizeBehavior===UI.GlassPane.SizeBehavior.SetExactWidthMaxHeight) -this.contentElement.style.maxHeight=height+'px';else -this.contentElement.style.height=height+'px';this.contentElement.positionAt(positionX,positionY,container);this._widget.doResize();} -widget(){return this._widget;} -static setContainer(element){UI.GlassPane._containers.set((element.ownerDocument),element);UI.GlassPane.containerMoved(element);} -static container(document){return UI.GlassPane._containers.get(document);} -static containerMoved(element){for(var pane of UI.GlassPane._panes){if(pane.isShowing()&&pane.element.ownerDocument===element.ownerDocument) -pane._positionContent();}}};UI.GlassPane.PointerEventsBehavior={BlockedByGlassPane:Symbol('BlockedByGlassPane'),PierceGlassPane:Symbol('PierceGlassPane'),PierceContents:Symbol('PierceContents')};UI.GlassPane.AnchorBehavior={PreferTop:Symbol('PreferTop'),PreferBottom:Symbol('PreferBottom'),PreferLeft:Symbol('PreferLeft'),PreferRight:Symbol('PreferRight'),};UI.GlassPane.SizeBehavior={SetExactSize:Symbol('SetExactSize'),SetExactWidthMaxHeight:Symbol('SetExactWidthMaxHeight'),MeasureContent:Symbol('MeasureContent')};UI.GlassPane.MarginBehavior={Arrow:Symbol('Arrow'),DefaultMargin:Symbol('DefaultMargin'),NoMargin:Symbol('NoMargin')};UI.GlassPane._containers=new Map();UI.GlassPane._panes=new Set();;UI.Dialog=class extends UI.GlassPane{constructor(){super();this.registerRequiredCSS('ui/dialog.css');this.contentElement.tabIndex=0;this.contentElement.addEventListener('focus',()=>this.widget().focus(),false);this.contentElement.addEventListener('keydown',this._onKeyDown.bind(this),false);this.widget().setDefaultFocusedElement(this.contentElement);this.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this.setOutsideClickCallback(event=>{this.hide();event.consume(true);});this._tabIndexMap=new Map();this._focusRestorer=null;this._closeOnEscape=true;} -static hasInstance(){return!!UI.Dialog._instance;} -show(where){var document=(where instanceof Document?where:(where||UI.inspectorView.element).ownerDocument);if(UI.Dialog._instance) -UI.Dialog._instance.hide();UI.Dialog._instance=this;this._disableTabIndexOnElements(document);super.show(document);this._focusRestorer=new UI.WidgetFocusRestorer(this.widget());} -hide(){this._focusRestorer.restore();super.hide();this._restoreTabIndexOnElements();delete UI.Dialog._instance;} -setCloseOnEscape(close){this._closeOnEscape=close;} -addCloseButton(){var closeButton=this.contentElement.createChild('div','dialog-close-button','dt-close-button');closeButton.gray=true;closeButton.addEventListener('click',()=>this.hide(),false);} -_disableTabIndexOnElements(document){this._tabIndexMap.clear();for(var node=document;node;node=node.traverseNextNode(document)){if(node instanceof HTMLElement){var element=(node);var tabIndex=element.tabIndex;if(tabIndex>=0){this._tabIndexMap.set(element,tabIndex);element.tabIndex=-1;}}}} -_restoreTabIndexOnElements(){for(var element of this._tabIndexMap.keys()) -element.tabIndex=(this._tabIndexMap.get(element));this._tabIndexMap.clear();} -_onKeyDown(event){if(this._closeOnEscape&&event.keyCode===UI.KeyboardShortcut.Keys.Esc.code){event.consume(true);this.hide();}}};;UI.SyntaxHighlighter=class{constructor(mimeType,stripExtraWhitespace){this._mimeType=mimeType;this._stripExtraWhitespace=stripExtraWhitespace;} -createSpan(content,className){var span=createElement('span');span.className='cm-'+className;if(this._stripExtraWhitespace&&className!=='whitespace') -content=content.replace(/^[\n\r]*/,'').replace(/\s*$/,'');span.createTextChild(content);return span;} -syntaxHighlightNode(node){var lines=node.textContent.split('\n');var plainTextStart;var line;return self.runtime.extension(TextUtils.TokenizerFactory).instance().then(processTokens.bind(this));function processTokens(tokenizerFactory){node.removeChildren();var tokenize=tokenizerFactory.createTokenizer(this._mimeType);for(var i=0;i<lines.length;++i){line=lines[i];plainTextStart=0;tokenize(line,processToken.bind(this));if(plainTextStart<line.length){var plainText=line.substring(plainTextStart,line.length);node.createTextChild(plainText);} -if(i<lines.length-1) -node.createTextChild('\n');}} -function processToken(token,tokenType,column,newColumn){if(!tokenType) -return;if(column>plainTextStart){var plainText=line.substring(plainTextStart,column);node.createTextChild(plainText);} -node.appendChild(this.createSpan(token,tokenType));plainTextStart=newColumn;}}};;UI.DropTarget=class{constructor(element,transferTypes,messageText,handleDrop){element.addEventListener('dragenter',this._onDragEnter.bind(this),true);element.addEventListener('dragover',this._onDragOver.bind(this),true);this._element=element;this._transferTypes=transferTypes;this._messageText=messageText;this._handleDrop=handleDrop;this._enabled=true;} -setEnabled(enabled){this._enabled=enabled;} -_onDragEnter(event){if(this._enabled&&this._hasMatchingType(event)) -event.consume(true);} -_hasMatchingType(event){for(var transferType of this._transferTypes){var found=Array.from(event.dataTransfer.items).find(item=>{return transferType.kind===item.kind&&!!transferType.type.exec(item.type);});if(found) -return true;} -return false;} -_onDragOver(event){if(!this._enabled||!this._hasMatchingType(event)) -return;event.dataTransfer.dropEffect='copy';event.consume(true);if(this._dragMaskElement) -return;this._dragMaskElement=this._element.createChild('div','');var shadowRoot=UI.createShadowRootWithCoreStyles(this._dragMaskElement,'ui/dropTarget.css');shadowRoot.createChild('div','drop-target-message').textContent=this._messageText;this._dragMaskElement.addEventListener('drop',this._onDrop.bind(this),true);this._dragMaskElement.addEventListener('dragleave',this._onDragLeave.bind(this),true);} -_onDrop(event){event.consume(true);this._removeMask();if(this._enabled) -this._handleDrop(event.dataTransfer);} -_onDragLeave(event){event.consume(true);this._removeMask();} -_removeMask(){this._dragMaskElement.remove();delete this._dragMaskElement;}};UI.DropTarget.Type={URI:{kind:'string',type:/text\/uri-list/},Folder:{kind:'file',type:/$^/},File:{kind:'file',type:/.*/},WebFile:{kind:'file',type:/[\w]+/},ImageFile:{kind:'file',type:/image\/.*/},};;UI.EmptyWidget=class extends UI.VBox{constructor(text){super();this.registerRequiredCSS('ui/emptyWidget.css');this.element.classList.add('empty-view-scroller');this._contentElement=this.element.createChild('div','empty-view');this._textElement=this._contentElement.createChild('h2');this._textElement.textContent=text;} -appendParagraph(){return this._contentElement.createChild('p');} -set text(text){this._textElement.textContent=text;}};;UI.FilterBar=class extends UI.HBox{constructor(name,visibleByDefault){super();this.registerRequiredCSS('ui/filter.css');this._enabled=true;this.element.classList.add('filter-bar');this._stateSetting=Common.settings.createSetting('filterBar-'+name+'-toggled',!!visibleByDefault);this._filterButton=new UI.ToolbarSettingToggle(this._stateSetting,'largeicon-filter',Common.UIString('Filter'));this._filters=[];this._updateFilterBar();this._stateSetting.addChangeListener(this._updateFilterBar.bind(this));} -filterButton(){return this._filterButton;} -addFilter(filter){this._filters.push(filter);this.element.appendChild(filter.element());filter.addEventListener(UI.FilterUI.Events.FilterChanged,this._filterChanged,this);this._updateFilterButton();} -setEnabled(enabled){this._enabled=enabled;this._filterButton.setEnabled(enabled);this._updateFilterBar();} -forceShowFilterBar(){this._alwaysShowFilters=true;this._updateFilterBar();} -showOnce(){this._stateSetting.set(true);} -_filterChanged(event){this._updateFilterButton();} -wasShown(){super.wasShown();this._updateFilterBar();} -_updateFilterBar(){if(!this.parentWidget()||this._showingWidget) -return;var visible=this._alwaysShowFilters||(this._stateSetting.get()&&this._enabled);if(visible){this._showingWidget=true;this.showWidget();this._showingWidget=false;}else{this.hideWidget();}} -focus(){for(var i=0;i<this._filters.length;++i){if(this._filters[i]instanceof UI.TextFilterUI){var textFilterUI=(this._filters[i]);textFilterUI.focus();break;}}} -_updateFilterButton(){var isActive=false;for(var filter of this._filters) -isActive=isActive||filter.isActive();this._filterButton.setDefaultWithRedColor(isActive);this._filterButton.setToggleWithRedColor(isActive);} -clear(){this.element.removeChildren();this._filters=[];this._updateFilterButton();}};UI.FilterUI=function(){};UI.FilterUI.Events={FilterChanged:Symbol('FilterChanged')};UI.FilterUI.prototype={isActive(){},element(){}};UI.TextFilterUI=class extends Common.Object{constructor(){super();this._filterElement=createElement('div');this._filterElement.className='filter-text-filter';this._filterInputElement=this._filterElement.createChild('span','filter-input-field');this._prompt=new UI.TextPrompt();this._prompt.initialize(this._completions.bind(this),' ');this._proxyElement=this._prompt.attach(this._filterInputElement);this._proxyElement.title=Common.UIString('e.g. /small[\\d]+/ url:a.com/b');this._prompt.setPlaceholder(Common.UIString('Filter'));this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged,this._valueChanged.bind(this));this._suggestionProvider=null;} -_completions(expression,prefix,force){if(this._suggestionProvider) -return this._suggestionProvider(expression,prefix,force);return Promise.resolve([]);} -isActive(){return!!this._prompt.text();} -element(){return this._filterElement;} -value(){return this._prompt.textWithCurrentSuggestion();} -setValue(value){this._prompt.setText(value);this._valueChanged();} -focus(){this._filterInputElement.focus();} -setSuggestionProvider(suggestionProvider){this._prompt.clearAutocomplete();this._suggestionProvider=suggestionProvider;} -_valueChanged(){this.dispatchEventToListeners(UI.FilterUI.Events.FilterChanged,null);}};UI.NamedBitSetFilterUI=class extends Common.Object{constructor(items,setting){super();this._filtersElement=createElementWithClass('div','filter-bitset-filter');this._filtersElement.title=Common.UIString('%sClick to select multiple types',UI.KeyboardShortcut.shortcutToString('',UI.KeyboardShortcut.Modifiers.CtrlOrMeta));this._allowedTypes={};this._typeFilterElements={};this._addBit(UI.NamedBitSetFilterUI.ALL_TYPES,Common.UIString('All'));this._filtersElement.createChild('div','filter-bitset-filter-divider');for(var i=0;i<items.length;++i) -this._addBit(items[i].name,items[i].label,items[i].title);if(setting){this._setting=setting;setting.addChangeListener(this._settingChanged.bind(this));this._settingChanged();}else{this._toggleTypeFilter(UI.NamedBitSetFilterUI.ALL_TYPES,false);}} -reset(){this._toggleTypeFilter(UI.NamedBitSetFilterUI.ALL_TYPES,false);} -isActive(){return!this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES];} -element(){return this._filtersElement;} -accept(typeName){return!!this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]||!!this._allowedTypes[typeName];} -_settingChanged(){var allowedTypes=this._setting.get();this._allowedTypes={};for(var typeName in this._typeFilterElements){if(allowedTypes[typeName]) -this._allowedTypes[typeName]=true;} -this._update();} -_update(){if((Object.keys(this._allowedTypes).length===0)||this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]){this._allowedTypes={};this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]=true;} -for(var typeName in this._typeFilterElements) -this._typeFilterElements[typeName].classList.toggle('selected',this._allowedTypes[typeName]);this.dispatchEventToListeners(UI.FilterUI.Events.FilterChanged,null);} -_addBit(name,label,title){var typeFilterElement=this._filtersElement.createChild('li',name);typeFilterElement.typeName=name;typeFilterElement.createTextChild(label);if(title) -typeFilterElement.title=title;typeFilterElement.addEventListener('click',this._onTypeFilterClicked.bind(this),false);this._typeFilterElements[name]=typeFilterElement;} -_onTypeFilterClicked(e){var toggle;if(Host.isMac()) -toggle=e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.shiftKey;else -toggle=e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey;this._toggleTypeFilter(e.target.typeName,toggle);} -_toggleTypeFilter(typeName,allowMultiSelect){if(allowMultiSelect&&typeName!==UI.NamedBitSetFilterUI.ALL_TYPES) -this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]=false;else -this._allowedTypes={};this._allowedTypes[typeName]=!this._allowedTypes[typeName];if(this._setting) -this._setting.set(this._allowedTypes);else -this._update();}};UI.NamedBitSetFilterUI.Item;UI.NamedBitSetFilterUI.ALL_TYPES='all';UI.CheckboxFilterUI=class extends Common.Object{constructor(className,title,activeWhenChecked,setting){super();this._filterElement=createElementWithClass('div','filter-checkbox-filter');this._activeWhenChecked=!!activeWhenChecked;this._label=UI.CheckboxLabel.create(title);this._filterElement.appendChild(this._label);this._checkboxElement=this._label.checkboxElement;if(setting) -UI.SettingsUI.bindCheckbox(this._checkboxElement,setting);else -this._checkboxElement.checked=true;this._checkboxElement.addEventListener('change',this._fireUpdated.bind(this),false);} -isActive(){return this._activeWhenChecked===this._checkboxElement.checked;} -checked(){return this._checkboxElement.checked;} -setChecked(checked){this._checkboxElement.checked=checked;} -element(){return this._filterElement;} -labelElement(){return this._label;} -_fireUpdated(){this.dispatchEventToListeners(UI.FilterUI.Events.FilterChanged,null);} -setColor(backgroundColor,borderColor){this._label.backgroundColor=backgroundColor;this._label.borderColor=borderColor;}};;UI.FilterSuggestionBuilder=class{constructor(keys,valueSorter){this._keys=keys;this._valueSorter=valueSorter||((key,result)=>result.sort());this._valuesMap=new Map();} -completions(expression,prefix,force){if(!prefix&&!force) -return Promise.resolve([]);var negative=prefix.startsWith('-');if(negative) -prefix=prefix.substring(1);var modifier=negative?'-':'';var valueDelimiterIndex=prefix.indexOf(':');var suggestions=[];if(valueDelimiterIndex===-1){var matcher=new RegExp('^'+prefix.escapeForRegExp(),'i');for(var key of this._keys){if(matcher.test(key)) -suggestions.push({text:modifier+key+':'});}}else{var key=prefix.substring(0,valueDelimiterIndex).toLowerCase();var value=prefix.substring(valueDelimiterIndex+1);var matcher=new RegExp('^'+value.escapeForRegExp(),'i');var values=Array.from(this._valuesMap.get(key)||new Set());this._valueSorter(key,values);for(var item of values){if(matcher.test(item)&&(item!==value)) -suggestions.push({text:modifier+key+':'+item});}} -return Promise.resolve(suggestions);} -addItem(key,value){if(!value) -return;if(!this._valuesMap.get(key)) -this._valuesMap.set(key,(new Set()));this._valuesMap.get(key).add(value);} -clear(){this._valuesMap.clear();}};;UI.ForwardedInputEventHandler=class{constructor(){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.KeyEventUnhandled,this._onKeyEventUnhandled,this);} -_onKeyEventUnhandled(event){var data=event.data;var type=(data.type);var key=(data.key);var keyCode=(data.keyCode);var modifiers=(data.modifiers);if(type!=='keydown') -return;UI.context.setFlavor(UI.ShortcutRegistry.ForwardedShortcut,UI.ShortcutRegistry.ForwardedShortcut.instance);UI.shortcutRegistry.handleKey(UI.KeyboardShortcut.makeKey(keyCode,modifiers),key);UI.context.setFlavor(UI.ShortcutRegistry.ForwardedShortcut,null);}};UI.forwardedEventHandler=new UI.ForwardedInputEventHandler();;UI.HistoryInput=class extends HTMLInputElement{constructor(){super();} -static create(){if(!UI.HistoryInput._constructor) -UI.HistoryInput._constructor=UI.registerCustomElement('input','history-input',UI.HistoryInput.prototype);return(new UI.HistoryInput._constructor());} -createdCallback(){this._history=[''];this._historyPosition=0;this.addEventListener('keydown',this._onKeyDown.bind(this),false);this.addEventListener('input',this._onInput.bind(this),false);} -_onInput(event){if(this._history.length===this._historyPosition+1) -this._history[this._history.length-1]=this.value;} -_onKeyDown(event){if(event.keyCode===UI.KeyboardShortcut.Keys.Up.code){this._historyPosition=Math.max(this._historyPosition-1,0);this.value=this._history[this._historyPosition];this.dispatchEvent(new Event('input',{'bubbles':true,'cancelable':true}));event.consume(true);}else if(event.keyCode===UI.KeyboardShortcut.Keys.Down.code){this._historyPosition=Math.min(this._historyPosition+1,this._history.length-1);this.value=this._history[this._historyPosition];this.dispatchEvent(new Event('input',{'bubbles':true,'cancelable':true}));event.consume(true);}else if(event.keyCode===UI.KeyboardShortcut.Keys.Enter.code){this._saveToHistory();}} -_saveToHistory(){if(this._history.length>1&&this._history[this._history.length-2]===this.value) -return;this._history[this._history.length-1]=this.value;this._historyPosition=this._history.length-1;this._history.push('');}};;UI.Icon=class extends HTMLSpanElement{constructor(){super();throw new Error('icon must be created via factory method.');} -static create(iconType,className){if(!UI.Icon._constructor) -UI.Icon._constructor=UI.registerCustomElement('span','ui-icon',UI.Icon.prototype);var icon=(new UI.Icon._constructor());if(className) -icon.className=className;if(iconType) -icon.setIconType(iconType);return icon;} -createdCallback(){this._descriptor=null;this._spriteSheet=null;this._iconType='';} -setIconType(iconType){if(this._descriptor){this.style.removeProperty('--spritesheet-position');this.style.removeProperty('width');this.style.removeProperty('height');this._toggleClasses(false);this._iconType='';this._descriptor=null;this._spriteSheet=null;} -var descriptor=UI.Icon.Descriptors[iconType]||null;if(descriptor){this._iconType=iconType;this._descriptor=descriptor;this._spriteSheet=UI.Icon.SpriteSheets[this._descriptor.spritesheet];console.assert(this._spriteSheet,`ERROR: icon ${this._iconType} has unknown spritesheet: ${this._descriptor.spritesheet}`);this.style.setProperty('--spritesheet-position',this._propertyValue());this.style.setProperty('width',this._spriteSheet.cellWidth+'px');this.style.setProperty('height',this._spriteSheet.cellHeight+'px');this._toggleClasses(true);}else if(iconType){throw new Error(`ERROR: failed to find icon descriptor for type: ${iconType}`);}} -_toggleClasses(value){this.classList.toggle('spritesheet-'+this._descriptor.spritesheet,value);this.classList.toggle(this._iconType,value);this.classList.toggle('icon-mask',value&&!!this._descriptor.isMask);this.classList.toggle('icon-invert',value&&!!this._descriptor.invert);} -_propertyValue(){if(!this._descriptor.coordinates){if(!this._descriptor.position||!UI.Icon._positionRegex.test(this._descriptor.position)) -throw new Error(`ERROR: icon '${this._iconType}' has malformed position: '${this._descriptor.position}'`);var column=this._descriptor.position[0].toLowerCase().charCodeAt(0)-97;var row=parseInt(this._descriptor.position.substring(1),10)-1;this._descriptor.coordinates={x:-(this._spriteSheet.cellWidth+this._spriteSheet.padding)*column,y:(this._spriteSheet.cellHeight+this._spriteSheet.padding)*(row+1)-this._spriteSheet.padding};} -return`${this._descriptor.coordinates.x}px ${this._descriptor.coordinates.y}px`;}};UI.Icon._positionRegex=/^[a-z][1-9][0-9]*$/;UI.Icon.Descriptor;UI.Icon.SpriteSheet;UI.Icon.SpriteSheets={'smallicons':{cellWidth:10,cellHeight:10,padding:10},'mediumicons':{cellWidth:16,cellHeight:16,padding:0},'largeicons':{cellWidth:28,cellHeight:24,padding:0},'arrowicons':{cellWidth:19,cellHeight:19,padding:0}};UI.Icon.Descriptors={'smallicon-bezier':{position:'a5',spritesheet:'smallicons',isMask:true},'smallicon-checkmark':{position:'b5',spritesheet:'smallicons'},'smallicon-checkmark-square':{position:'b6',spritesheet:'smallicons',isMask:true},'smallicon-checkmark-behind':{position:'d6',spritesheet:'smallicons',isMask:true},'smallicon-command-result':{position:'a4',spritesheet:'smallicons'},'smallicon-contrast-ratio':{position:'a6',spritesheet:'smallicons',isMask:true},'smallicon-cross':{position:'b4',spritesheet:'smallicons'},'smallicon-device':{position:'c5',spritesheet:'smallicons'},'smallicon-error':{position:'c4',spritesheet:'smallicons'},'smallicon-green-arrow':{position:'a3',spritesheet:'smallicons'},'smallicon-green-ball':{position:'b3',spritesheet:'smallicons'},'smallicon-info':{position:'c3',spritesheet:'smallicons'},'smallicon-inline-breakpoint-conditional':{position:'d5',spritesheet:'smallicons'},'smallicon-inline-breakpoint':{position:'d4',spritesheet:'smallicons'},'smallicon-no':{position:'c6',spritesheet:'smallicons',isMask:true},'smallicon-orange-ball':{position:'d3',spritesheet:'smallicons'},'smallicon-red-ball':{position:'a2',spritesheet:'smallicons'},'smallicon-shadow':{position:'b2',spritesheet:'smallicons',isMask:true},'smallicon-step-in':{position:'c2',spritesheet:'smallicons'},'smallicon-step-out':{position:'d2',spritesheet:'smallicons'},'smallicon-text-prompt':{position:'e5',spritesheet:'smallicons'},'smallicon-thick-left-arrow':{position:'e4',spritesheet:'smallicons'},'smallicon-thick-right-arrow':{position:'e3',spritesheet:'smallicons'},'smallicon-triangle-down':{position:'e2',spritesheet:'smallicons',isMask:true},'smallicon-triangle-right':{position:'a1',spritesheet:'smallicons',isMask:true},'smallicon-triangle-up':{position:'b1',spritesheet:'smallicons',isMask:true},'smallicon-user-command':{position:'c1',spritesheet:'smallicons'},'smallicon-warning':{position:'d1',spritesheet:'smallicons'},'smallicon-network-product':{position:'e1',spritesheet:'smallicons'},'smallicon-clear-warning':{position:'f1',spritesheet:'smallicons',isMask:true},'smallicon-clear-info':{position:'f2',spritesheet:'smallicons'},'smallicon-clear-error':{position:'f3',spritesheet:'smallicons'},'smallicon-account-circle':{position:'f4',spritesheet:'smallicons'},'mediumicon-clear-storage':{position:'a4',spritesheet:'mediumicons',isMask:true},'mediumicon-cookie':{position:'b4',spritesheet:'mediumicons',isMask:true},'mediumicon-database':{position:'c4',spritesheet:'mediumicons',isMask:true},'mediumicon-info':{position:'c1',spritesheet:'mediumicons',isMask:true},'mediumicon-manifest':{position:'d4',spritesheet:'mediumicons',isMask:true},'mediumicon-service-worker':{position:'a3',spritesheet:'mediumicons',isMask:true},'mediumicon-table':{position:'b3',spritesheet:'mediumicons',isMask:true},'mediumicon-arrow-in-circle':{position:'c3',spritesheet:'mediumicons',isMask:true},'mediumicon-file-sync':{position:'d3',spritesheet:'mediumicons',invert:true},'mediumicon-file':{position:'a2',spritesheet:'mediumicons',invert:true},'mediumicon-gray-cross-active':{position:'b2',spritesheet:'mediumicons'},'mediumicon-gray-cross-hover':{position:'c2',spritesheet:'mediumicons'},'mediumicon-red-cross-active':{position:'d2',spritesheet:'mediumicons'},'mediumicon-red-cross-hover':{position:'a1',spritesheet:'mediumicons'},'mediumicon-search':{position:'b1',spritesheet:'mediumicons'},'mediumicon-account-circle':{position:'e4',spritesheet:'mediumicons'},'mediumicon-warning-triangle':{position:'e1',spritesheet:'mediumicons'},'mediumicon-error-circle':{position:'e3',spritesheet:'mediumicons'},'mediumicon-info-circle':{position:'e2',spritesheet:'mediumicons'},'mediumicon-bug':{position:'d1',spritesheet:'mediumicons'},'mediumicon-list':{position:'e5',spritesheet:'mediumicons'},'badge-navigator-file-sync':{position:'a9',spritesheet:'largeicons'},'largeicon-activate-breakpoints':{position:'b9',spritesheet:'largeicons',isMask:true},'largeicon-add':{position:'a8',spritesheet:'largeicons',isMask:true},'largeicon-background-color':{position:'b8',spritesheet:'largeicons',isMask:true},'largeicon-box-shadow':{position:'a7',spritesheet:'largeicons',isMask:true},'largeicon-camera':{position:'b7',spritesheet:'largeicons',isMask:true},'largeicon-center':{position:'c9',spritesheet:'largeicons',isMask:true},'largeicon-checkmark':{position:'c8',spritesheet:'largeicons',isMask:true},'largeicon-chevron':{position:'c7',spritesheet:'largeicons',isMask:true},'largeicon-clear':{position:'a6',spritesheet:'largeicons',isMask:true},'largeicon-copy':{position:'b6',spritesheet:'largeicons',isMask:true},'largeicon-deactivate-breakpoints':{position:'c6',spritesheet:'largeicons',isMask:true},'largeicon-delete':{position:'d9',spritesheet:'largeicons',isMask:true},'largeicon-dock-to-bottom':{position:'d8',spritesheet:'largeicons',isMask:true},'largeicon-dock-to-left':{position:'d7',spritesheet:'largeicons',isMask:true},'largeicon-dock-to-right':{position:'d6',spritesheet:'largeicons',isMask:true},'largeicon-download':{position:'h6',spritesheet:'largeicons',isMask:true},'largeicon-edit':{position:'a5',spritesheet:'largeicons',isMask:true},'largeicon-eyedropper':{position:'b5',spritesheet:'largeicons',isMask:true},'largeicon-filter':{position:'c5',spritesheet:'largeicons',isMask:true},'largeicon-foreground-color':{position:'d5',spritesheet:'largeicons',isMask:true},'largeicon-hide-bottom-sidebar':{position:'e9',spritesheet:'largeicons',isMask:true},'largeicon-hide-left-sidebar':{position:'e8',spritesheet:'largeicons',isMask:true},'largeicon-hide-right-sidebar':{position:'e7',spritesheet:'largeicons',isMask:true},'largeicon-hide-top-sidebar':{position:'e6',spritesheet:'largeicons',isMask:true},'largeicon-large-list':{position:'e5',spritesheet:'largeicons',isMask:true},'largeicon-layout-editor':{position:'a4',spritesheet:'largeicons',isMask:true},'largeicon-load':{position:'h5',spritesheet:'largeicons',isMask:true},'largeicon-longclick-triangle':{position:'b4',spritesheet:'largeicons',isMask:true},'largeicon-menu':{position:'c4',spritesheet:'largeicons',isMask:true},'largeicon-navigator-domain':{position:'d4',spritesheet:'largeicons',isMask:true},'largeicon-navigator-file':{position:'e4',spritesheet:'largeicons',isMask:true},'largeicon-navigator-file-sync':{position:'f9',spritesheet:'largeicons',isMask:true},'largeicon-navigator-folder':{position:'f8',spritesheet:'largeicons',isMask:true},'largeicon-navigator-frame':{position:'f7',spritesheet:'largeicons',isMask:true},'largeicon-navigator-snippet':{position:'f6',spritesheet:'largeicons',isMask:true},'largeicon-navigator-worker':{position:'f5',spritesheet:'largeicons',isMask:true},'largeicon-node-search':{position:'f4',spritesheet:'largeicons',isMask:true},'largeicon-pan':{position:'a3',spritesheet:'largeicons',isMask:true},'largeicon-pause-animation':{position:'b3',spritesheet:'largeicons',isMask:true},'largeicon-pause':{position:'c3',spritesheet:'largeicons',isMask:true},'largeicon-pause-on-exceptions':{position:'d3',spritesheet:'largeicons',isMask:true},'largeicon-phone':{position:'e3',spritesheet:'largeicons',isMask:true},'largeicon-play-animation':{position:'f3',spritesheet:'largeicons',isMask:true},'largeicon-play-back':{position:'a2',spritesheet:'largeicons',isMask:true},'largeicon-play':{position:'b2',spritesheet:'largeicons',isMask:true},'largeicon-pretty-print':{position:'c2',spritesheet:'largeicons',isMask:true},'largeicon-refresh':{position:'d2',spritesheet:'largeicons',isMask:true},'largeicon-replay-animation':{position:'e2',spritesheet:'largeicons',isMask:true},'largeicon-resume':{position:'f2',spritesheet:'largeicons',isMask:true},'largeicon-rotate':{position:'g9',spritesheet:'largeicons',isMask:true},'largeicon-rotate-screen':{position:'g8',spritesheet:'largeicons',isMask:true},'largeicon-settings-gear':{position:'g7',spritesheet:'largeicons',isMask:true},'largeicon-show-bottom-sidebar':{position:'g6',spritesheet:'largeicons',isMask:true},'largeicon-show-left-sidebar':{position:'g5',spritesheet:'largeicons',isMask:true},'largeicon-show-right-sidebar':{position:'g4',spritesheet:'largeicons',isMask:true},'largeicon-show-top-sidebar':{position:'g3',spritesheet:'largeicons',isMask:true},'largeicon-start-recording':{position:'g2',spritesheet:'largeicons',isMask:true},'largeicon-step-in':{position:'a1',spritesheet:'largeicons',isMask:true},'largeicon-step-out':{position:'b1',spritesheet:'largeicons',isMask:true},'largeicon-step-over':{position:'c1',spritesheet:'largeicons',isMask:true},'largeicon-stop-recording':{position:'d1',spritesheet:'largeicons',isMask:true},'largeicon-text-shadow':{position:'e1',spritesheet:'largeicons',isMask:true},'largeicon-trash-bin':{position:'f1',spritesheet:'largeicons',isMask:true},'largeicon-undo':{position:'h7',spritesheet:'largeicons',isMask:true},'largeicon-undock':{position:'g1',spritesheet:'largeicons',isMask:true},'largeicon-visibility':{position:'h9',spritesheet:'largeicons',isMask:true},'largeicon-waterfall':{position:'h8',spritesheet:'largeicons',isMask:true},'mediumicon-arrow-top':{position:'a4',spritesheet:'arrowicons'},'mediumicon-arrow-bottom':{position:'a3',spritesheet:'arrowicons'},'mediumicon-arrow-left':{position:'a2',spritesheet:'arrowicons'},'mediumicon-arrow-right':{position:'a1',spritesheet:'arrowicons'}};;UI.Infobar=class{constructor(type,text,disableSetting){this.element=createElementWithClass('div','flex-none');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/infobar.css');this._contentElement=this._shadowRoot.createChild('div','infobar infobar-'+type);this._mainRow=this._contentElement.createChild('div','infobar-main-row');this._mainRow.createChild('div',type+'-icon icon');this._mainRowText=this._mainRow.createChild('div','infobar-main-title');this._mainRowText.textContent=text;this._detailsRows=this._contentElement.createChild('div','infobar-details-rows hidden');this._toggleElement=this._mainRow.createChild('div','infobar-toggle hidden');this._toggleElement.addEventListener('click',this._onToggleDetails.bind(this),false);this._toggleElement.textContent=Common.UIString('more');this._disableSetting=disableSetting||null;if(disableSetting){var disableButton=this._mainRow.createChild('div','infobar-toggle');disableButton.textContent=Common.UIString('never show');disableButton.addEventListener('click',this._onDisable.bind(this),false);} -this._closeButton=this._contentElement.createChild('div','close-button','dt-close-button');this._closeButton.addEventListener('click',this.dispose.bind(this),false);this._closeCallback=null;} -static create(type,text,disableSetting){if(disableSetting&&disableSetting.get()) -return null;return new UI.Infobar(type,text,disableSetting);} -dispose(){this.element.remove();this._onResize();if(this._closeCallback) -this._closeCallback.call(null);} -setText(text){this._mainRowText.textContent=text;this._onResize();} -setCloseCallback(callback){this._closeCallback=callback;} -setParentView(parentView){this._parentView=parentView;} -_onResize(){if(this._parentView) -this._parentView.doResize();} -_onDisable(){this._disableSetting.set(true);this.dispose();} -_onToggleDetails(){this._detailsRows.classList.remove('hidden');this._toggleElement.remove();this._onResize();} -createDetailsRowMessage(message){this._toggleElement.classList.remove('hidden');var infobarDetailsRow=this._detailsRows.createChild('div','infobar-details-row');var detailsRowMessage=infobarDetailsRow.createChild('span','infobar-row-message');detailsRowMessage.textContent=message||'';return detailsRowMessage;}};UI.Infobar.Type={Warning:'warning',Info:'info'};;UI.InplaceEditor=class{static startEditing(element,config){if(!UI.InplaceEditor._defaultInstance) -UI.InplaceEditor._defaultInstance=new UI.InplaceEditor();return UI.InplaceEditor._defaultInstance.startEditing(element,config);} -editorContent(editingContext){var element=editingContext.element;if(element.tagName==='INPUT'&&element.type==='text') -return element.value;return element.textContent;} -setUpEditor(editingContext){var element=editingContext.element;element.classList.add('editing');element.setAttribute('contenteditable','plaintext-only');var oldTabIndex=element.getAttribute('tabIndex');if(typeof oldTabIndex!=='number'||oldTabIndex<0) -element.tabIndex=0;this._focusRestorer=new UI.ElementFocusRestorer(element);editingContext.oldTabIndex=oldTabIndex;} -closeEditor(editingContext){var element=editingContext.element;element.classList.remove('editing');element.removeAttribute('contenteditable');if(typeof editingContext.oldTabIndex!=='number') -element.removeAttribute('tabIndex');else -element.tabIndex=editingContext.oldTabIndex;element.scrollTop=0;element.scrollLeft=0;} -cancelEditing(editingContext){var element=editingContext.element;if(element.tagName==='INPUT'&&element.type==='text') -element.value=editingContext.oldText;else -element.textContent=editingContext.oldText;} -augmentEditingHandle(editingContext,handle){} -startEditing(element,config){if(!UI.markBeingEdited(element,true)) -return null;config=config||new UI.InplaceEditor.Config(function(){},function(){});var editingContext={element:element,config:config};var committedCallback=config.commitHandler;var cancelledCallback=config.cancelHandler;var pasteCallback=config.pasteHandler;var context=config.context;var moveDirection='';var self=this;this.setUpEditor(editingContext);editingContext.oldText=this.editorContent(editingContext);function blurEventListener(e){if(config.blurHandler&&!config.blurHandler(element,e)) -return;editingCommitted.call(element);} -function cleanUpAfterEditing(){UI.markBeingEdited(element,false);element.removeEventListener('blur',blurEventListener,false);element.removeEventListener('keydown',keyDownEventListener,true);if(pasteCallback) -element.removeEventListener('paste',pasteEventListener,true);if(self._focusRestorer) -self._focusRestorer.restore();self.closeEditor(editingContext);} -function editingCancelled(){self.cancelEditing(editingContext);cleanUpAfterEditing();cancelledCallback(this,context);} -function editingCommitted(){cleanUpAfterEditing();committedCallback(this,self.editorContent(editingContext),editingContext.oldText,context,moveDirection);} -function defaultFinishHandler(event){if(isEnterKey(event)) -return'commit';else if(event.keyCode===UI.KeyboardShortcut.Keys.Esc.code||event.key==='Escape') -return'cancel';else if(event.key==='Tab') -return'move-'+(event.shiftKey?'backward':'forward');return'';} -function handleEditingResult(result,event){if(result==='commit'){editingCommitted.call(element);event.consume(true);}else if(result==='cancel'){editingCancelled.call(element);event.consume(true);}else if(result&&result.startsWith('move-')){moveDirection=result.substring(5);if(event.key==='Tab') -event.consume(true);blurEventListener();}} -function pasteEventListener(event){var result=pasteCallback(event);handleEditingResult(result,event);} -function keyDownEventListener(event){var result=defaultFinishHandler(event);if(!result&&config.postKeydownFinishHandler) -result=config.postKeydownFinishHandler(event);handleEditingResult(result,event);} -element.addEventListener('blur',blurEventListener,false);element.addEventListener('keydown',keyDownEventListener,true);if(pasteCallback) -element.addEventListener('paste',pasteEventListener,true);var handle={cancel:editingCancelled.bind(element),commit:editingCommitted.bind(element)};this.augmentEditingHandle(editingContext,handle);return handle;}};UI.InplaceEditor.Controller;UI.InplaceEditor.Config=class{constructor(commitHandler,cancelHandler,context,blurHandler){this.commitHandler=commitHandler;this.cancelHandler=cancelHandler;this.context=context;this.blurHandler=blurHandler;this.pasteHandler;this.postKeydownFinishHandler;} -setPasteHandler(pasteHandler){this.pasteHandler=pasteHandler;} -setPostKeydownFinishHandler(postKeydownFinishHandler){this.postKeydownFinishHandler=postKeydownFinishHandler;}};;UI.TextEditorFactory=function(){};UI.TextEditorFactory.prototype={createEditor(options){}};UI.TextEditor=function(){};UI.TextEditor.prototype={widget(){},fullRange(){},selection(){},setSelection(selection){},text(textRange){},setText(text){},line(lineNumber){},newlineAndIndent(){},addKeyDownHandler(handler){},configureAutocomplete(config){},clearAutocomplete(){},tokenAtTextPosition(lineNumber,columnNumber){}};UI.TextEditor.Events={TextChanged:Symbol('TextChanged')};UI.TextEditor.Options;UI.AutocompleteConfig;;UI.KeyboardShortcut=class{static makeKey(keyCode,modifiers){if(typeof keyCode==='string') -keyCode=keyCode.charCodeAt(0)-(/^[a-z]/.test(keyCode)?32:0);modifiers=modifiers||UI.KeyboardShortcut.Modifiers.None;return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode,modifiers);} -static makeKeyFromEvent(keyboardEvent){var modifiers=UI.KeyboardShortcut.Modifiers.None;if(keyboardEvent.shiftKey) -modifiers|=UI.KeyboardShortcut.Modifiers.Shift;if(keyboardEvent.ctrlKey) -modifiers|=UI.KeyboardShortcut.Modifiers.Ctrl;if(keyboardEvent.altKey) -modifiers|=UI.KeyboardShortcut.Modifiers.Alt;if(keyboardEvent.metaKey) -modifiers|=UI.KeyboardShortcut.Modifiers.Meta;var keyCode=keyboardEvent.keyCode||keyboardEvent['__keyCode'];return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode,modifiers);} -static makeKeyFromEventIgnoringModifiers(keyboardEvent){var keyCode=keyboardEvent.keyCode||keyboardEvent['__keyCode'];return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode,UI.KeyboardShortcut.Modifiers.None);} -static eventHasCtrlOrMeta(event){return Host.isMac()?event.metaKey&&!event.ctrlKey:event.ctrlKey&&!event.metaKey;} -static hasNoModifiers(event){return!event.ctrlKey&&!event.shiftKey&&!event.altKey&&!event.metaKey;} -static makeDescriptor(key,modifiers){return{key:UI.KeyboardShortcut.makeKey(typeof key==='string'?key:key.code,modifiers),name:UI.KeyboardShortcut.shortcutToString(key,modifiers)};} -static makeDescriptorFromBindingShortcut(shortcut){var parts=shortcut.split(/\+(?!$)/);var modifiers=0;var keyString;for(var i=0;i<parts.length;++i){if(typeof UI.KeyboardShortcut.Modifiers[parts[i]]!=='undefined'){modifiers|=UI.KeyboardShortcut.Modifiers[parts[i]];continue;} -console.assert(i===parts.length-1,'Only one key other than modifier is allowed in shortcut <'+shortcut+'>');keyString=parts[i];break;} -console.assert(keyString,'Modifiers-only shortcuts are not allowed (encountered <'+shortcut+'>)');if(!keyString) -return null;var key=UI.KeyboardShortcut.Keys[keyString]||UI.KeyboardShortcut.KeyBindings[keyString];if(key&&key.shiftKey) -modifiers|=UI.KeyboardShortcut.Modifiers.Shift;return UI.KeyboardShortcut.makeDescriptor(key?key:keyString,modifiers);} -static shortcutToString(key,modifiers){return UI.KeyboardShortcut._modifiersToString(modifiers)+UI.KeyboardShortcut._keyName(key);} -static _keyName(key){if(typeof key==='string') -return key.toUpperCase();if(typeof key.name==='string') -return key.name;return key.name[Host.platform()]||key.name.other||'';} -static _makeKeyFromCodeAndModifiers(keyCode,modifiers){return(keyCode&255)|(modifiers<<8);} -static keyCodeAndModifiersFromKey(key){return{keyCode:key&255,modifiers:key>>8};} -static _modifiersToString(modifiers){var isMac=Host.isMac();var m=UI.KeyboardShortcut.Modifiers;var modifierNames=new Map([[m.Ctrl,isMac?'Ctrl\u2004':'Ctrl\u200A+\u200A'],[m.Alt,isMac?'\u2325\u2004':'Alt\u200A+\u200A'],[m.Shift,isMac?'\u21e7\u2004':'Shift\u200A+\u200A'],[m.Meta,isMac?'\u2318\u2004':'Win\u200A+\u200A']]);return[m.Meta,m.Ctrl,m.Alt,m.Shift].map(mapModifiers).join('');function mapModifiers(m){return modifiers&m?(modifierNames.get(m)):'';}}};UI.KeyboardShortcut.Modifiers={None:0,Shift:1,Ctrl:2,Alt:4,Meta:8,get CtrlOrMeta(){return Host.isMac()?this.Meta:this.Ctrl;},get ShiftOrOption(){return Host.isMac()?this.Alt:this.Shift;}};UI.KeyboardShortcut.Key;UI.KeyboardShortcut.Keys={Backspace:{code:8,name:'\u21a4'},Tab:{code:9,name:{mac:'\u21e5',other:'Tab'}},Enter:{code:13,name:{mac:'\u21a9',other:'Enter'}},Shift:{code:16,name:{mac:'\u21e7',other:'Shift'}},Ctrl:{code:17,name:'Ctrl'},Esc:{code:27,name:'Esc'},Space:{code:32,name:'Space'},PageUp:{code:33,name:{mac:'\u21de',other:'PageUp'}},PageDown:{code:34,name:{mac:'\u21df',other:'PageDown'}},End:{code:35,name:{mac:'\u2197',other:'End'}},Home:{code:36,name:{mac:'\u2196',other:'Home'}},Left:{code:37,name:'\u2190'},Up:{code:38,name:'\u2191'},Right:{code:39,name:'\u2192'},Down:{code:40,name:'\u2193'},Delete:{code:46,name:'Del'},Zero:{code:48,name:'0'},H:{code:72,name:'H'},N:{code:78,name:'N'},P:{code:80,name:'P'},Meta:{code:91,name:'Meta'},F1:{code:112,name:'F1'},F2:{code:113,name:'F2'},F3:{code:114,name:'F3'},F4:{code:115,name:'F4'},F5:{code:116,name:'F5'},F6:{code:117,name:'F6'},F7:{code:118,name:'F7'},F8:{code:119,name:'F8'},F9:{code:120,name:'F9'},F10:{code:121,name:'F10'},F11:{code:122,name:'F11'},F12:{code:123,name:'F12'},Semicolon:{code:186,name:';'},NumpadPlus:{code:107,name:'Numpad +'},NumpadMinus:{code:109,name:'Numpad -'},Numpad0:{code:96,name:'Numpad 0'},Plus:{code:187,name:'+'},Comma:{code:188,name:','},Minus:{code:189,name:'-'},Period:{code:190,name:'.'},Slash:{code:191,name:'/'},QuestionMark:{code:191,name:'?'},Apostrophe:{code:192,name:'`'},Tilde:{code:192,name:'Tilde'},LeftSquareBracket:{code:219,name:'['},RightSquareBracket:{code:221,name:']'},Backslash:{code:220,name:'\\'},SingleQuote:{code:222,name:'\''},get CtrlOrMeta(){return Host.isMac()?this.Meta:this.Ctrl;},};UI.KeyboardShortcut.KeyBindings={};(function(){for(var key in UI.KeyboardShortcut.Keys){var descriptor=UI.KeyboardShortcut.Keys[key];if(typeof descriptor==='object'&&descriptor['code']){var name=typeof descriptor['name']==='string'?descriptor['name']:key;UI.KeyboardShortcut.KeyBindings[name]=descriptor;}}})();UI.KeyboardShortcut.Descriptor;;UI.ListDelegate=function(){};UI.ListDelegate.prototype={createElementForItem(item){},heightForItem(item){},isItemSelectable(item){},selectedItemChanged(from,to,fromElement,toElement){},};UI.ListMode={NonViewport:Symbol('UI.ListMode.NonViewport'),EqualHeightItems:Symbol('UI.ListMode.EqualHeightItems'),VariousHeightItems:Symbol('UI.ListMode.VariousHeightItems')};UI.ListControl=class{constructor(model,delegate,mode){this.element=createElement('div');this.element.style.overflowY='auto';this._topElement=this.element.createChild('div');this._bottomElement=this.element.createChild('div');this._firstIndex=0;this._lastIndex=0;this._renderedHeight=0;this._topHeight=0;this._bottomHeight=0;this._model=model;this._model.addEventListener(UI.ListModel.Events.ItemsReplaced,this._replacedItemsInRange,this);this._itemToElement=new Map();this._selectedIndex=-1;this._selectedItem=null;this.element.tabIndex=-1;this.element.addEventListener('click',this._onClick.bind(this),false);this.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this._delegate=delegate;this._mode=mode||UI.ListMode.EqualHeightItems;this._fixedHeight=0;this._variableOffsets=new Int32Array(0);this._clearContents();if(this._mode!==UI.ListMode.NonViewport){this.element.addEventListener('scroll',()=>{this._updateViewport(this.element.scrollTop,this.element.offsetHeight);},false);}} -setModel(model){this._itemToElement.clear();var length=this._model.length;this._model.removeEventListener(UI.ListModel.Events.ItemsReplaced,this._replacedItemsInRange,this);this._model=model;this._model.addEventListener(UI.ListModel.Events.ItemsReplaced,this._replacedItemsInRange,this);this.invalidateRange(0,length);} -_replacedItemsInRange(event){var data=(event.data);var from=data.index;var to=from+data.removed.length;var oldSelectedItem=this._selectedItem;var oldSelectedElement=oldSelectedItem?(this._itemToElement.get(oldSelectedItem)||null):null;for(var i=0;i<data.removed.length;i++) -this._itemToElement.delete(data.removed[i]);this._invalidate(from,to,data.inserted);if(this._selectedIndex>=to){this._selectedIndex+=data.inserted-(to-from);this._selectedItem=this._model.at(this._selectedIndex);}else if(this._selectedIndex>=from){var index=this._findFirstSelectable(from+data.inserted,+1,false);if(index===-1) -index=this._findFirstSelectable(from-1,-1,false);this._select(index,oldSelectedItem,oldSelectedElement);}} -refreshItem(item){var index=this._model.indexOf(item);if(index===-1){console.error('Item to refresh is not present');return;} -this._itemToElement.delete(item);this.invalidateRange(index,index+1);if(this._selectedIndex!==-1) -this._select(this._selectedIndex,null,null);} -invalidateRange(from,to){this._invalidate(from,to,to-from);} -viewportResized(){if(this._mode===UI.ListMode.NonViewport) -return;var scrollTop=this.element.scrollTop;var viewportHeight=this.element.offsetHeight;this._clearViewport();this._updateViewport(Number.constrain(scrollTop,0,this._totalHeight()-viewportHeight),viewportHeight);} -invalidateItemHeight(){if(this._mode!==UI.ListMode.EqualHeightItems){console.error('Only supported in equal height items mode');return;} -this._fixedHeight=0;if(this._model.length){this._itemToElement.clear();this._invalidate(0,this._model.length,this._model.length);}} -itemForNode(node){while(node&&node.parentNodeOrShadowHost()!==this.element) -node=node.parentNodeOrShadowHost();if(!node) -return null;var element=(node);var index=this._model.findIndex(item=>this._itemToElement.get(item)===element);return index!==-1?this._model.at(index):null;} -scrollItemIntoView(item,center){var index=this._model.indexOf(item);if(index===-1){console.error('Attempt to scroll onto missing item');return;} -this._scrollIntoView(index,center);} -selectedItem(){return this._selectedItem;} -selectedIndex(){return this._selectedIndex;} -selectItem(item,center,dontScroll){var index=-1;if(item!==null){index=this._model.indexOf(item);if(index===-1){console.error('Attempt to select missing item');return;} -if(!this._delegate.isItemSelectable(item)){console.error('Attempt to select non-selectable item');return;}} -if(this._selectedIndex!==index) -this._select(index);if(index!==-1&&!dontScroll) -this._scrollIntoView(index,center);} -selectPreviousItem(canWrap,center){if(this._selectedIndex===-1&&!canWrap) -return false;var index=this._selectedIndex===-1?this._model.length-1:this._selectedIndex-1;index=this._findFirstSelectable(index,-1,!!canWrap);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;} -return false;} -selectNextItem(canWrap,center){if(this._selectedIndex===-1&&!canWrap) -return false;var index=this._selectedIndex===-1?0:this._selectedIndex+1;index=this._findFirstSelectable(index,+1,!!canWrap);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;} -return false;} -selectItemPreviousPage(center){if(this._mode===UI.ListMode.NonViewport) -return false;var index=this._selectedIndex===-1?this._model.length-1:this._selectedIndex;index=this._findPageSelectable(index,-1);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;} -return false;} -selectItemNextPage(center){if(this._mode===UI.ListMode.NonViewport) -return false;var index=this._selectedIndex===-1?0:this._selectedIndex;index=this._findPageSelectable(index,+1);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;} -return false;} -_scrollIntoView(index,center){if(this._mode===UI.ListMode.NonViewport){this._elementAtIndex(index).scrollIntoViewIfNeeded(!!center);return;} -var top=this._offsetAtIndex(index);var bottom=this._offsetAtIndex(index+1);var viewportHeight=this.element.offsetHeight;if(center){var scrollTo=(top+bottom)/2-viewportHeight/2;this._updateViewport(Number.constrain(scrollTo,0,this._totalHeight()-viewportHeight),viewportHeight);return;} -var scrollTop=this.element.scrollTop;if(top<scrollTop) -this._updateViewport(top,viewportHeight);else if(bottom>scrollTop+viewportHeight) -this._updateViewport(bottom-viewportHeight,viewportHeight);} -_onClick(event){var item=this.itemForNode((event.target));if(item&&this._delegate.isItemSelectable(item)) -this.selectItem(item);} -_onKeyDown(event){var selected=false;switch(event.key){case'ArrowUp':selected=this.selectPreviousItem(true,false);break;case'ArrowDown':selected=this.selectNextItem(true,false);break;case'PageUp':selected=this.selectItemPreviousPage(false);break;case'PageDown':selected=this.selectItemNextPage(false);break;} -if(selected) -event.consume();} -_totalHeight(){return this._offsetAtIndex(this._model.length);} -_indexAtOffset(offset){if(this._mode===UI.ListMode.NonViewport) -throw'There should be no offset conversions in non-viewport mode';if(!this._model.length||offset<0) -return 0;if(this._mode===UI.ListMode.VariousHeightItems){return Math.min(this._model.length-1,this._variableOffsets.lowerBound(offset,undefined,0,this._model.length));} -if(!this._fixedHeight) -this._measureHeight();return Math.min(this._model.length-1,Math.floor(offset/this._fixedHeight));} -_elementAtIndex(index){var item=this._model.at(index);var element=this._itemToElement.get(item);if(!element){element=this._delegate.createElementForItem(item);this._itemToElement.set(item,element);} -return element;} -_offsetAtIndex(index){if(this._mode===UI.ListMode.NonViewport) -throw'There should be no offset conversions in non-viewport mode';if(!this._model.length) -return 0;if(this._mode===UI.ListMode.VariousHeightItems) -return this._variableOffsets[index];if(!this._fixedHeight) -this._measureHeight();return index*this._fixedHeight;} -_measureHeight(){this._fixedHeight=this._delegate.heightForItem(this._model.at(0));if(!this._fixedHeight) -this._fixedHeight=UI.measurePreferredSize(this._elementAtIndex(0),this.element).height;} -_select(index,oldItem,oldElement){if(oldItem===undefined) -oldItem=this._selectedItem;if(oldElement===undefined) -oldElement=this._itemToElement.get(oldItem)||null;this._selectedIndex=index;this._selectedItem=index===-1?null:this._model.at(index);var newItem=this._selectedItem;var newElement=this._selectedIndex!==-1?this._elementAtIndex(index):null;this._delegate.selectedItemChanged(oldItem,newItem,(oldElement),newElement);} -_findFirstSelectable(index,direction,canWrap){var length=this._model.length;if(!length) -return-1;for(var step=0;step<=length;step++){if(index<0||index>=length){if(!canWrap) -return-1;index=(index+length)%length;} -if(this._delegate.isItemSelectable(this._model.at(index))) -return index;index+=direction;} -return-1;} -_findPageSelectable(index,direction){var lastSelectable=-1;var startOffset=this._offsetAtIndex(index);var viewportHeight=this.element.offsetHeight-1;while(index>=0&&index<this._model.length){if(this._delegate.isItemSelectable(this._model.at(index))){if(Math.abs(this._offsetAtIndex(index)-startOffset)>=viewportHeight) -return index;lastSelectable=index;} -index+=direction;} -return lastSelectable;} -_reallocateVariableOffsets(length,copyTo){if(this._variableOffsets.length<length){var variableOffsets=new Int32Array(Math.max(length,this._variableOffsets.length*2));variableOffsets.set(this._variableOffsets.slice(0,copyTo),0);this._variableOffsets=variableOffsets;}else if(this._variableOffsets.length>=2*length){var variableOffsets=new Int32Array(length);variableOffsets.set(this._variableOffsets.slice(0,copyTo),0);this._variableOffsets=variableOffsets;}} -_invalidate(from,to,inserted){if(this._mode===UI.ListMode.NonViewport){this._invalidateNonViewportMode(from,to-from,inserted);return;} -if(this._mode===UI.ListMode.VariousHeightItems){this._reallocateVariableOffsets(this._model.length+1,from+1);for(var i=from+1;i<=this._model.length;i++) -this._variableOffsets[i]=this._variableOffsets[i-1]+this._delegate.heightForItem(this._model.at(i-1));} -var viewportHeight=this.element.offsetHeight;var totalHeight=this._totalHeight();var scrollTop=this.element.scrollTop;if(this._renderedHeight<viewportHeight||totalHeight<viewportHeight){this._clearViewport();this._updateViewport(Number.constrain(scrollTop,0,totalHeight-viewportHeight),viewportHeight);return;} -var heightDelta=totalHeight-this._renderedHeight;if(to<=this._firstIndex){var topHeight=this._topHeight+heightDelta;this._topElement.style.height=topHeight+'px';this.element.scrollTop=scrollTop+heightDelta;this._topHeight=topHeight;this._renderedHeight=totalHeight;var indexDelta=inserted-(to-from);this._firstIndex+=indexDelta;this._lastIndex+=indexDelta;return;} -if(from>=this._lastIndex){var bottomHeight=this._bottomHeight+heightDelta;this._bottomElement.style.height=bottomHeight+'px';this._bottomHeight=bottomHeight;this._renderedHeight=totalHeight;return;} -this._clearViewport();this._updateViewport(Number.constrain(scrollTop,0,totalHeight-viewportHeight),viewportHeight);} -_invalidateNonViewportMode(start,remove,add){var startElement=this._topElement;for(var index=0;index<start;index++) -startElement=startElement.nextElementSibling;while(remove--) -startElement.nextElementSibling.remove();while(add--) -this.element.insertBefore(this._elementAtIndex(start+add),startElement.nextElementSibling);} -_clearViewport(){if(this._mode===UI.ListMode.NonViewport){console.error('There should be no viewport updates in non-viewport mode');return;} -this._firstIndex=0;this._lastIndex=0;this._renderedHeight=0;this._topHeight=0;this._bottomHeight=0;this._clearContents();} -_clearContents(){this._topElement.style.height='0';this._bottomElement.style.height='0';this.element.removeChildren();this.element.appendChild(this._topElement);this.element.appendChild(this._bottomElement);} -_updateViewport(scrollTop,viewportHeight){if(this._mode===UI.ListMode.NonViewport){console.error('There should be no viewport updates in non-viewport mode');return;} -var totalHeight=this._totalHeight();if(!totalHeight){this._firstIndex=0;this._lastIndex=0;this._topHeight=0;this._bottomHeight=0;this._renderedHeight=0;this._topElement.style.height='0';this._bottomElement.style.height='0';return;} -var firstIndex=this._indexAtOffset(scrollTop-viewportHeight);var lastIndex=this._indexAtOffset(scrollTop+2*viewportHeight)+1;while(this._firstIndex<Math.min(firstIndex,this._lastIndex)){this._elementAtIndex(this._firstIndex).remove();this._firstIndex++;} -while(this._lastIndex>Math.max(lastIndex,this._firstIndex)){this._elementAtIndex(this._lastIndex-1).remove();this._lastIndex--;} -this._firstIndex=Math.min(this._firstIndex,lastIndex);this._lastIndex=Math.max(this._lastIndex,firstIndex);for(var index=this._firstIndex-1;index>=firstIndex;index--){var element=this._elementAtIndex(index);this.element.insertBefore(element,this._topElement.nextSibling);} -for(var index=this._lastIndex;index<lastIndex;index++){var element=this._elementAtIndex(index);this.element.insertBefore(element,this._bottomElement);} -this._firstIndex=firstIndex;this._lastIndex=lastIndex;this._topHeight=this._offsetAtIndex(firstIndex);this._topElement.style.height=this._topHeight+'px';this._bottomHeight=totalHeight-this._offsetAtIndex(lastIndex);this._bottomElement.style.height=this._bottomHeight+'px';this._renderedHeight=totalHeight;this.element.scrollTop=scrollTop;}};;UI.ListModel=class extends Common.Object{constructor(items){super();this._items=items||[];} -[Symbol.iterator](){return this._items[Symbol.iterator]();} -get length(){return this._items.length;} -at(index){return this._items[index];} -every(callback){return this._items.every(callback);} -filter(callback){return this._items.filter(callback);} -find(callback){return this._items.find(callback);} -findIndex(callback){return this._items.findIndex(callback);} -indexOf(value,fromIndex){return this._items.indexOf(value,fromIndex);} -insert(index,value){this._items.splice(index,0,value);this._replaced(index,[],1);} -insertWithComparator(value,comparator){this.insert(this._items.lowerBound(value,comparator),value);} -join(separator){return this._items.join(separator);} -remove(index){var result=this._items[index];this._items.splice(index,1);this._replaced(index,[result],0);return result;} -replace(index,value){var oldValue=this._items[index];this._items[index]=value;this._replaced(index,[oldValue],1);return oldValue;} -replaceRange(from,to,items){var removed;if(items.length<10000){removed=this._items.splice(from,to-from,...items);}else{removed=this._items.slice(from,to);var before=this._items.slice(0,from);var after=this._items.slice(to);this._items=[].concat(before,items,after);} -this._replaced(from,removed,items.length);return removed;} -replaceAll(items){var oldItems=this._items.slice();this._items=items;this._replaced(0,oldItems,items.length);return oldItems;} -slice(from,to){return this._items.slice(from,to);} -some(callback){return this._items.some(callback);} -_replaced(index,removed,inserted){this.dispatchEventToListeners(UI.ListModel.Events.ItemsReplaced,{index:index,removed:removed,inserted:inserted});}};UI.ListModel.Events={ItemsReplaced:Symbol('ItemsReplaced'),};;UI.ListWidget=class extends UI.VBox{constructor(delegate){super(true);this.registerRequiredCSS('ui/listWidget.css');this._delegate=delegate;this._list=this.contentElement.createChild('div','list');this.element.tabIndex=-1;this._lastSeparator=false;this._focusRestorer=null;this._items=[];this._editable=[];this._elements=[];this._editor=null;this._editItem=null;this._editElement=null;this._emptyPlaceholder=null;this._updatePlaceholder();} -clear(){this._items=[];this._editable=[];this._elements=[];this._lastSeparator=false;this._list.removeChildren();this._updatePlaceholder();this._stopEditing();} -appendItem(item,editable){if(this._lastSeparator&&this._items.length) -this._list.appendChild(createElementWithClass('div','list-separator'));this._lastSeparator=false;this._items.push(item);this._editable.push(editable);var element=this._list.createChild('div','list-item');element.appendChild(this._delegate.renderItem(item,editable));if(editable){element.classList.add('editable');element.appendChild(this._createControls(item,element));} -this._elements.push(element);this._updatePlaceholder();} -appendSeparator(){this._lastSeparator=true;} -removeItem(index){if(this._editItem===this._items[index]) -this._stopEditing();var element=this._elements[index];var previous=element.previousElementSibling;var previousIsSeparator=previous&&previous.classList.contains('list-separator');var next=element.nextElementSibling;var nextIsSeparator=next&&next.classList.contains('list-separator');if(previousIsSeparator&&(nextIsSeparator||!next)) -previous.remove();if(nextIsSeparator&&!previous) -next.remove();element.remove();this._elements.splice(index,1);this._items.splice(index,1);this._editable.splice(index,1);this._updatePlaceholder();} -addNewItem(index,item){this._startEditing(item,null,this._elements[index]||null);} -setEmptyPlaceholder(element){this._emptyPlaceholder=element;this._updatePlaceholder();} -_createControls(item,element){var controls=createElementWithClass('div','controls-container fill');controls.createChild('div','controls-gradient');var buttons=controls.createChild('div','controls-buttons');var toolbar=new UI.Toolbar('',buttons);var editButton=new UI.ToolbarButton(Common.UIString('Edit'),'largeicon-edit');editButton.addEventListener(UI.ToolbarButton.Events.Click,onEditClicked.bind(this));toolbar.appendToolbarItem(editButton);var removeButton=new UI.ToolbarButton(Common.UIString('Remove'),'largeicon-trash-bin');removeButton.addEventListener(UI.ToolbarButton.Events.Click,onRemoveClicked.bind(this));toolbar.appendToolbarItem(removeButton);return controls;function onEditClicked(){var index=this._elements.indexOf(element);var insertionPoint=this._elements[index+1]||null;this._startEditing(item,element,insertionPoint);} -function onRemoveClicked(){var index=this._elements.indexOf(element);this.element.focus();this._delegate.removeItemRequested(this._items[index],index);}} -wasShown(){super.wasShown();this._stopEditing();} -_updatePlaceholder(){if(!this._emptyPlaceholder) -return;if(!this._elements.length&&!this._editor) -this._list.appendChild(this._emptyPlaceholder);else -this._emptyPlaceholder.remove();} -_startEditing(item,element,insertionPoint){if(element&&this._editElement===element) -return;this._stopEditing();this._focusRestorer=new UI.ElementFocusRestorer(this.element);this._list.classList.add('list-editing');this._editItem=item;this._editElement=element;if(element) -element.classList.add('hidden');var index=element?this._elements.indexOf(element):-1;this._editor=this._delegate.beginEdit(item);this._updatePlaceholder();this._list.insertBefore(this._editor.element,insertionPoint);this._editor.beginEdit(item,index,element?Common.UIString('Save'):Common.UIString('Add'),this._commitEditing.bind(this),this._stopEditing.bind(this));} -_commitEditing(){var editItem=this._editItem;var isNew=!this._editElement;var editor=(this._editor);this._stopEditing();this._delegate.commitEdit(editItem,editor,isNew);} -_stopEditing(){this._list.classList.remove('list-editing');if(this._focusRestorer) -this._focusRestorer.restore();if(this._editElement) -this._editElement.classList.remove('hidden');if(this._editor&&this._editor.element.parentElement) -this._editor.element.remove();this._editor=null;this._editItem=null;this._editElement=null;this._updatePlaceholder();}};UI.ListWidget.Delegate=function(){};UI.ListWidget.Delegate.prototype={renderItem(item,editable){},removeItemRequested(item,index){},beginEdit(item){},commitEdit(item,editor,isNew){}};UI.ListWidget.Editor=class{constructor(){this.element=createElementWithClass('div','editor-container');this.element.addEventListener('keydown',onKeyDown.bind(null,isEscKey,this._cancelClicked.bind(this)),false);this.element.addEventListener('keydown',onKeyDown.bind(null,isEnterKey,this._commitClicked.bind(this)),false);this._contentElement=this.element.createChild('div','editor-content');var buttonsRow=this.element.createChild('div','editor-buttons');this._commitButton=UI.createTextButton('',this._commitClicked.bind(this),'',true);buttonsRow.appendChild(this._commitButton);this._cancelButton=UI.createTextButton(Common.UIString('Cancel'),this._cancelClicked.bind(this));this._cancelButton.addEventListener('keydown',onKeyDown.bind(null,isEnterKey,this._cancelClicked.bind(this)),false);buttonsRow.appendChild(this._cancelButton);function onKeyDown(predicate,callback,event){if(predicate(event)){event.consume(true);callback();}} -this._controls=[];this._controlByName=new Map();this._validators=[];this._commit=null;this._cancel=null;this._item=null;this._index=-1;} -contentElement(){return this._contentElement;} -createInput(name,type,title,validator){var input=(UI.createInput('',type));input.placeholder=title;input.addEventListener('input',this._validateControls.bind(this,false),false);input.addEventListener('blur',this._validateControls.bind(this,false),false);this._controlByName.set(name,input);this._controls.push(input);this._validators.push(validator);return input;} -createSelect(name,options,validator){var select=(createElementWithClass('select','chrome-select'));for(var index=0;index<options.length;++index){var option=select.createChild('option');option.value=options[index];option.textContent=options[index];} -select.addEventListener('input',this._validateControls.bind(this,false),false);select.addEventListener('blur',this._validateControls.bind(this,false),false);this._controlByName.set(name,select);this._controls.push(select);this._validators.push(validator);return select;} -control(name){return(this._controlByName.get(name));} -_validateControls(forceValid){var allValid=true;for(var index=0;index<this._controls.length;++index){var input=this._controls[index];var valid=this._validators[index].call(null,this._item,this._index,input);input.classList.toggle('error-input',!valid&&!forceValid);allValid&=valid;} -this._commitButton.disabled=!allValid;} -beginEdit(item,index,commitButtonTitle,commit,cancel){this._commit=commit;this._cancel=cancel;this._item=item;this._index=index;this._commitButton.textContent=commitButtonTitle;this.element.scrollIntoViewIfNeeded(false);if(this._controls.length) -this._controls[0].focus();this._validateControls(true);} -_commitClicked(){if(this._commitButton.disabled) -return;var commit=this._commit;this._commit=null;this._cancel=null;this._item=null;this._index=-1;commit();} -_cancelClicked(){var cancel=this._cancel;this._commit=null;this._cancel=null;this._item=null;this._index=-1;cancel();}};;UI.panels=[];UI.Panel=class extends UI.VBox{constructor(name){super();this.element.classList.add('panel');this.element.setAttribute('aria-label',name);this.element.classList.add(name);this._panelName=name;UI.panels[name]=this;this._shortcuts=({});} -get name(){return this._panelName;} -searchableView(){return null;} -elementsToRestoreScrollPositionsFor(){return[];} -handleShortcut(event){var shortcutKey=UI.KeyboardShortcut.makeKeyFromEvent(event);var handler=this._shortcuts[shortcutKey];if(handler&&handler(event)) -event.handled=true;} -registerShortcuts(keys,handler){for(var i=0;i<keys.length;++i) -this._shortcuts[keys[i].key]=handler;} -showInfobar(infobar){infobar.setCloseCallback(this._onInfobarClosed.bind(this,infobar));if(this.element.firstChild) -this.element.insertBefore(infobar.element,this.element.firstChild);else -this.element.appendChild(infobar.element);infobar.setParentView(this);this.doResize();} -_onInfobarClosed(infobar){infobar.element.remove();this.doResize();}};UI.PanelWithSidebar=class extends UI.Panel{constructor(name,defaultWidth){super(name);this._panelSplitWidget=new UI.SplitWidget(true,false,this._panelName+'PanelSplitViewState',defaultWidth||200);this._panelSplitWidget.show(this.element);this._mainWidget=new UI.VBox();this._panelSplitWidget.setMainWidget(this._mainWidget);this._sidebarWidget=new UI.VBox();this._sidebarWidget.setMinimumSize(100,25);this._panelSplitWidget.setSidebarWidget(this._sidebarWidget);this._sidebarWidget.element.classList.add('panel-sidebar');} -panelSidebarElement(){return this._sidebarWidget.element;} -mainElement(){return this._mainWidget.element;} -splitWidget(){return this._panelSplitWidget;}};;UI.PopoverHelper=class{constructor(container,getRequest){this._disableOnClick=false;this._hasPadding=false;this._getRequest=getRequest;this._scheduledRequest=null;this._hidePopoverCallback=null;container.addEventListener('mousedown',this._mouseDown.bind(this),false);container.addEventListener('mousemove',this._mouseMove.bind(this),false);container.addEventListener('mouseout',this._mouseOut.bind(this),false);this.setTimeout(1000);} -setTimeout(showTimeout,hideTimeout){this._showTimeout=showTimeout;this._hideTimeout=typeof hideTimeout==='number'?hideTimeout:showTimeout/2;} -setHasPadding(hasPadding){this._hasPadding=hasPadding;} -setDisableOnClick(disableOnClick){this._disableOnClick=disableOnClick;} -_eventInScheduledContent(event){return this._scheduledRequest?this._scheduledRequest.box.contains(event.clientX,event.clientY):false;} -_mouseDown(event){if(this._disableOnClick){this.hidePopover();return;} -if(this._eventInScheduledContent(event)) -return;this._startHidePopoverTimer(0);this._stopShowPopoverTimer();this._startShowPopoverTimer((event),0);} -_mouseMove(event){if(this._eventInScheduledContent(event)) -return;this._startHidePopoverTimer(this._hideTimeout);this._stopShowPopoverTimer();if(event.which&&this._disableOnClick) -return;this._startShowPopoverTimer((event),this.isPopoverVisible()?this._showTimeout*0.6:this._showTimeout);} -_popoverMouseMove(event){this._stopHidePopoverTimer();} -_popoverMouseOut(popover,event){if(!popover.isShowing()) -return;if(event.relatedTarget&&!event.relatedTarget.isSelfOrDescendant(popover.contentElement)) -this._startHidePopoverTimer(this._hideTimeout);} -_mouseOut(event){if(!this.isPopoverVisible()) -return;if(!this._eventInScheduledContent(event)) -this._startHidePopoverTimer(this._hideTimeout);} -_startHidePopoverTimer(timeout){if(!this._hidePopoverCallback||this._hidePopoverTimer) -return;this._hidePopoverTimer=setTimeout(()=>{this._hidePopover();delete this._hidePopoverTimer;},timeout);} -_startShowPopoverTimer(event,timeout){this._scheduledRequest=this._getRequest.call(null,event);if(!this._scheduledRequest) -return;this._showPopoverTimer=setTimeout(()=>{delete this._showPopoverTimer;this._stopHidePopoverTimer();this._hidePopover();this._showPopover(event.target.ownerDocument);},timeout);} -_stopShowPopoverTimer(){if(!this._showPopoverTimer) -return;clearTimeout(this._showPopoverTimer);delete this._showPopoverTimer;} -isPopoverVisible(){return!!this._hidePopoverCallback;} -hidePopover(){this._stopShowPopoverTimer();this._hidePopover();} -_hidePopover(){if(!this._hidePopoverCallback) -return;this._hidePopoverCallback.call(null);this._hidePopoverCallback=null;} -_showPopover(document){var popover=new UI.GlassPane();popover.registerRequiredCSS('ui/popover.css');popover.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);popover.setMarginBehavior(UI.GlassPane.MarginBehavior.Arrow);var request=this._scheduledRequest;request.show.call(null,popover).then(success=>{if(!success) -return;if(this._scheduledRequest!==request){if(request.hide) -request.hide.call(null);return;} -if(UI.PopoverHelper._popoverHelper){console.error('One popover is already visible');UI.PopoverHelper._popoverHelper.hidePopover();} -UI.PopoverHelper._popoverHelper=this;popover.contentElement.classList.toggle('has-padding',this._hasPadding);popover.contentElement.addEventListener('mousemove',this._popoverMouseMove.bind(this),true);popover.contentElement.addEventListener('mouseout',this._popoverMouseOut.bind(this,popover),true);popover.setContentAnchorBox(request.box);popover.show(document);this._hidePopoverCallback=()=>{if(request.hide) -request.hide.call(null);popover.hide();delete UI.PopoverHelper._popoverHelper;};});} -_stopHidePopoverTimer(){if(!this._hidePopoverTimer) -return;clearTimeout(this._hidePopoverTimer);delete this._hidePopoverTimer;this._stopShowPopoverTimer();}};UI.PopoverRequest;;UI.ProgressIndicator=class{constructor(){this.element=createElementWithClass('div','progress-indicator');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/progressIndicator.css');this._contentElement=this._shadowRoot.createChild('div','progress-indicator-shadow-container');this._labelElement=this._contentElement.createChild('div','title');this._progressElement=this._contentElement.createChild('progress');this._progressElement.value=0;this._stopButton=this._contentElement.createChild('button','progress-indicator-shadow-stop-button');this._stopButton.addEventListener('click',this.cancel.bind(this));this._isCanceled=false;this._worked=0;} -show(parent){parent.appendChild(this.element);} -done(){if(this._isDone) -return;this._isDone=true;this.element.remove();} -cancel(){this._isCanceled=true;} -isCanceled(){return this._isCanceled;} -setTitle(title){this._labelElement.textContent=title;} -setTotalWork(totalWork){this._progressElement.max=totalWork;} -setWorked(worked,title){this._worked=worked;this._progressElement.value=worked;if(title) -this.setTitle(title);} -worked(worked){this.setWorked(this._worked+(worked||1));}};;UI.ResizerWidget=class extends Common.Object{constructor(){super();this._isEnabled=true;this._elements=[];this._installDragOnMouseDownBound=this._installDragOnMouseDown.bind(this);this._cursor='nwse-resize';} -isEnabled(){return this._isEnabled;} -setEnabled(enabled){this._isEnabled=enabled;this.updateElementCursors();} -elements(){return this._elements.slice();} -addElement(element){if(this._elements.indexOf(element)!==-1) -return;this._elements.push(element);element.addEventListener('mousedown',this._installDragOnMouseDownBound,false);this._updateElementCursor(element);} -removeElement(element){if(this._elements.indexOf(element)===-1) -return;this._elements.remove(element);element.removeEventListener('mousedown',this._installDragOnMouseDownBound,false);element.style.removeProperty('cursor');} -updateElementCursors(){this._elements.forEach(this._updateElementCursor.bind(this));} -_updateElementCursor(element){if(this._isEnabled) -element.style.setProperty('cursor',this.cursor());else -element.style.removeProperty('cursor');} -cursor(){return this._cursor;} -setCursor(cursor){this._cursor=cursor;this.updateElementCursors();} -_installDragOnMouseDown(event){if(this._elements.indexOf(event.target)===-1) -return false;UI.elementDragStart((event.target),this._dragStart.bind(this),this._drag.bind(this),this._dragEnd.bind(this),this.cursor(),event);} -_dragStart(event){if(!this._isEnabled) -return false;this._startX=event.pageX;this._startY=event.pageY;this.sendDragStart(this._startX,this._startY);return true;} -sendDragStart(x,y){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeStart,{startX:x,currentX:x,startY:y,currentY:y});} -_drag(event){if(!this._isEnabled){this._dragEnd(event);return true;} -this.sendDragMove(this._startX,event.pageX,this._startY,event.pageY,event.shiftKey);event.preventDefault();return false;} -sendDragMove(startX,currentX,startY,currentY,shiftKey){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeUpdate,{startX:startX,currentX:currentX,startY:startY,currentY:currentY,shiftKey:shiftKey});} -_dragEnd(event){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeEnd);delete this._startX;delete this._startY;}};UI.ResizerWidget.Events={ResizeStart:Symbol('ResizeStart'),ResizeUpdate:Symbol('ResizeUpdate'),ResizeEnd:Symbol('ResizeEnd')};UI.SimpleResizerWidget=class extends UI.ResizerWidget{constructor(){super();this._isVertical=true;} -isVertical(){return this._isVertical;} -setVertical(vertical){this._isVertical=vertical;this.updateElementCursors();} -cursor(){return this._isVertical?'ns-resize':'ew-resize';} -sendDragStart(x,y){var position=this._isVertical?y:x;this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeStart,{startPosition:position,currentPosition:position});} -sendDragMove(startX,currentX,startY,currentY,shiftKey){if(this._isVertical){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeUpdate,{startPosition:startY,currentPosition:currentY,shiftKey:shiftKey});}else{this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeUpdate,{startPosition:startX,currentPosition:currentX,shiftKey:shiftKey});}}};;UI.ReportView=class extends UI.VBox{constructor(title){super(true);this.registerRequiredCSS('ui/reportView.css');var contentBox=this.contentElement.createChild('div','report-content-box');this._headerElement=contentBox.createChild('div','report-header vbox');this._titleElement=this._headerElement.createChild('div','report-title');this._titleElement.textContent=title;this._sectionList=contentBox.createChild('div','vbox');} -setTitle(title){if(this._titleElement.textContent===title) -return;this._titleElement.textContent=title;} -setSubtitle(subtitle){if(this._subtitleElement&&this._subtitleElement.textContent===subtitle) -return;if(!this._subtitleElement) -this._subtitleElement=this._headerElement.createChild('div','report-subtitle');this._subtitleElement.textContent=subtitle;} -setURL(link){if(!this._urlElement) -this._urlElement=this._headerElement.createChild('div','report-url link');this._urlElement.removeChildren();if(link) -this._urlElement.appendChild(link);} -createToolbar(){var toolbar=new UI.Toolbar('');this._headerElement.appendChild(toolbar.element);return toolbar;} -appendSection(title,className){var section=new UI.ReportView.Section(title,className);section.show(this._sectionList);return section;} -sortSections(comparator){var sections=(this.children().slice());var sorted=sections.every((e,i,a)=>!i||comparator(a[i-1],a[i])<=0);if(sorted) -return;this.detachChildWidgets();sections.sort(comparator);for(var section of sections) -section.show(this._sectionList);}};UI.ReportView.Section=class extends UI.VBox{constructor(title,className){super();this.element.classList.add('report-section');if(className) -this.element.classList.add(className);this._headerElement=this.element.createChild('div','report-section-header');this._titleElement=this._headerElement.createChild('div','report-section-title');this._titleElement.textContent=title;this._fieldList=this.element.createChild('div','vbox');this._fieldMap=new Map();} -title(){return this._titleElement.textContent;} -setTitle(title){if(this._titleElement.textContent!==title) -this._titleElement.textContent=title;} -createToolbar(){var toolbar=new UI.Toolbar('');this._headerElement.appendChild(toolbar.element);return toolbar;} -appendField(title,textValue){var row=this._fieldMap.get(title);if(!row){row=this._fieldList.createChild('div','report-field');row.createChild('div','report-field-name').textContent=title;this._fieldMap.set(title,row);row.createChild('div','report-field-value');} -if(textValue) -row.lastElementChild.textContent=textValue;return(row.lastElementChild);} -removeField(title){var row=this._fieldMap.get(title);if(row) -row.remove();this._fieldMap.delete(title);} -setFieldVisible(title,visible){var row=this._fieldMap.get(title);if(row) -row.classList.toggle('hidden',!visible);} -fieldValue(title){var row=this._fieldMap.get(title);return row?row.lastElementChild:null;} -appendRow(){return this._fieldList.createChild('div','report-row');} -clearContent(){this._fieldList.removeChildren();this._fieldMap.clear();}};;UI.RootView=class extends UI.VBox{constructor(){super();this.markAsRoot();this.element.classList.add('root-view');this.registerRequiredCSS('ui/rootView.css');this.element.setAttribute('spellcheck',false);} -attachToDocument(document){document.defaultView.addEventListener('resize',this.doResize.bind(this),false);this._window=document.defaultView;this.doResize();this.show((document.body));} -doResize(){if(this._window){var size=this.constraints().minimum;var zoom=UI.zoomManager.zoomFactor();var right=Math.min(0,this._window.innerWidth-size.width/zoom);this.element.style.marginRight=right+'px';var bottom=Math.min(0,this._window.innerHeight-size.height/zoom);this.element.style.marginBottom=bottom+'px';} -super.doResize();}};;UI.SearchableView=class extends UI.VBox{constructor(searchable,settingName){super(true);this.registerRequiredCSS('ui/searchableView.css');this.element[UI.SearchableView._symbol]=this;this._searchProvider=searchable;this._setting=settingName?Common.settings.createSetting(settingName,{}):null;this.contentElement.createChild('content');this._footerElementContainer=this.contentElement.createChild('div','search-bar hidden');this._footerElementContainer.style.order=100;var toolbar=new UI.Toolbar('',this._footerElementContainer);if(this._searchProvider.supportsCaseSensitiveSearch()){this._caseSensitiveButton=new UI.ToolbarToggle(Common.UIString('Case sensitive'),'');this._caseSensitiveButton.setText('Aa');this._caseSensitiveButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleCaseSensitiveSearch,this);toolbar.appendToolbarItem(this._caseSensitiveButton);} -if(this._searchProvider.supportsRegexSearch()){this._regexButton=new UI.ToolbarToggle(Common.UIString('Regex'),'');this._regexButton.setText('.*');this._regexButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleRegexSearch,this);toolbar.appendToolbarItem(this._regexButton);} -this._footerElement=this._footerElementContainer.createChild('div','toolbar-search');var searchInputElements=this._footerElement.createChild('div','toolbar-search-inputs');var searchControlElement=searchInputElements.createChild('div','toolbar-search-control');this._searchInputElement=UI.HistoryInput.create();this._searchInputElement.classList.add('search-replace');this._searchInputElement.id='search-input-field';this._searchInputElement.placeholder=Common.UIString('Find');searchControlElement.appendChild(this._searchInputElement);this._matchesElement=searchControlElement.createChild('label','search-results-matches');this._matchesElement.setAttribute('for','search-input-field');var searchNavigationElement=searchControlElement.createChild('div','toolbar-search-navigation-controls');this._searchNavigationPrevElement=searchNavigationElement.createChild('div','toolbar-search-navigation toolbar-search-navigation-prev');this._searchNavigationPrevElement.addEventListener('click',this._onPrevButtonSearch.bind(this),false);this._searchNavigationPrevElement.title=Common.UIString('Search previous');this._searchNavigationNextElement=searchNavigationElement.createChild('div','toolbar-search-navigation toolbar-search-navigation-next');this._searchNavigationNextElement.addEventListener('click',this._onNextButtonSearch.bind(this),false);this._searchNavigationNextElement.title=Common.UIString('Search next');this._searchInputElement.addEventListener('keydown',this._onSearchKeyDown.bind(this),true);this._searchInputElement.addEventListener('input',this._onInput.bind(this),false);this._replaceInputElement=searchInputElements.createChild('input','search-replace toolbar-replace-control hidden');this._replaceInputElement.addEventListener('keydown',this._onReplaceKeyDown.bind(this),true);this._replaceInputElement.placeholder=Common.UIString('Replace');this._buttonsContainer=this._footerElement.createChild('div','toolbar-search-buttons hidden');var findButtonElement=UI.createTextButton(Common.UIString('Find'),this._onFindClick.bind(this),'search-action-button');findButtonElement.tabIndex=-1;this._buttonsContainer.appendChild(findButtonElement);var prevButtonElement=UI.createTextButton(Common.UIString('Previous'),this._onPreviousClick.bind(this),'search-action-button');prevButtonElement.tabIndex=-1;this._buttonsContainer.appendChild(prevButtonElement);this._replaceButtonElement=UI.createTextButton(Common.UIString('Replace'),this._replace.bind(this),'search-action-button');this._replaceButtonElement.disabled=true;this._replaceButtonElement.tabIndex=-1;this._buttonsContainer.appendChild(this._replaceButtonElement);var replaceAllButtonElement=UI.createTextButton(Common.UIString('Replace all'),this._replaceAll.bind(this),'search-action-button');this._buttonsContainer.appendChild(replaceAllButtonElement);this._replaceElement=this._footerElement.createChild('div').createChild('span','toolbar-replace-checkbox');var replaceLabelElement=UI.CheckboxLabel.create(Common.UIString('Replace'));this._replaceCheckboxElement=replaceLabelElement.checkboxElement;this._replaceCheckboxElement.addEventListener('change',this._updateSecondRowVisibility.bind(this),false);this._replaceElement.appendChild(replaceLabelElement);var cancelButtonElement=UI.createTextButton(Common.UIString('Cancel'),this.closeSearch.bind(this),'search-action-button');cancelButtonElement.tabIndex=-1;this._minimalSearchQuerySize=3;this._footerElement.createChild('div').appendChild(cancelButtonElement);this._loadSetting();} -static fromElement(element){var view=null;while(element&&!view){view=element[UI.SearchableView._symbol];element=element.parentElementOrShadowHost();} -return view;} -_toggleCaseSensitiveSearch(){this._caseSensitiveButton.setToggled(!this._caseSensitiveButton.toggled());this._saveSetting();this._performSearch(false,true);} -_toggleRegexSearch(){this._regexButton.setToggled(!this._regexButton.toggled());this._saveSetting();this._performSearch(false,true);} -_saveSetting(){if(!this._setting) -return;var settingValue=this._setting.get()||{};settingValue.caseSensitive=this._caseSensitiveButton.toggled();settingValue.isRegex=this._regexButton.toggled();this._setting.set(settingValue);} -_loadSetting(){var settingValue=this._setting?(this._setting.get()||{}):{};if(this._searchProvider.supportsCaseSensitiveSearch()) -this._caseSensitiveButton.setToggled(!!settingValue.caseSensitive);if(this._searchProvider.supportsRegexSearch()) -this._regexButton.setToggled(!!settingValue.isRegex);} -setMinimalSearchQuerySize(minimalSearchQuerySize){this._minimalSearchQuerySize=minimalSearchQuerySize;} -setPlaceholder(placeholder){this._searchInputElement.placeholder=placeholder;} -setReplaceable(replaceable){this._replaceable=replaceable;} -updateSearchMatchesCount(matches){if(this._searchProvider.currentSearchMatches===matches) -return;this._searchProvider.currentSearchMatches=matches;this._updateSearchMatchesCountAndCurrentMatchIndex(this._searchProvider.currentQuery?matches:0,-1);} -updateCurrentMatchIndex(currentMatchIndex){this._updateSearchMatchesCountAndCurrentMatchIndex(this._searchProvider.currentSearchMatches,currentMatchIndex);} -isSearchVisible(){return this._searchIsVisible;} -closeSearch(){this.cancelSearch();if(this._footerElementContainer.hasFocus()) -this.focus();} -_toggleSearchBar(toggled){this._footerElementContainer.classList.toggle('hidden',!toggled);this.doResize();} -cancelSearch(){if(!this._searchIsVisible) -return;this.resetSearch();delete this._searchIsVisible;this._toggleSearchBar(false);} -resetSearch(){this._clearSearch();this._updateReplaceVisibility();this._matchesElement.textContent='';} -refreshSearch(){if(!this._searchIsVisible) -return;this.resetSearch();this._performSearch(false,false);} -handleFindNextShortcut(){if(!this._searchIsVisible) -return false;this._searchProvider.jumpToNextSearchResult();return true;} -handleFindPreviousShortcut(){if(!this._searchIsVisible) -return false;this._searchProvider.jumpToPreviousSearchResult();return true;} -handleFindShortcut(){this.showSearchField();return true;} -handleCancelSearchShortcut(){if(!this._searchIsVisible) -return false;this.closeSearch();return true;} -_updateSearchNavigationButtonState(enabled){this._replaceButtonElement.disabled=!enabled;if(enabled){this._searchNavigationPrevElement.classList.add('enabled');this._searchNavigationNextElement.classList.add('enabled');}else{this._searchNavigationPrevElement.classList.remove('enabled');this._searchNavigationNextElement.classList.remove('enabled');}} -_updateSearchMatchesCountAndCurrentMatchIndex(matches,currentMatchIndex){if(!this._currentQuery) -this._matchesElement.textContent='';else if(matches===0||currentMatchIndex>=0) -this._matchesElement.textContent=Common.UIString('%d of %d',currentMatchIndex+1,matches);else if(matches===1) -this._matchesElement.textContent=Common.UIString('1 match');else -this._matchesElement.textContent=Common.UIString('%d matches',matches);this._updateSearchNavigationButtonState(matches>0);} -showSearchField(){if(this._searchIsVisible) -this.cancelSearch();var queryCandidate;if(!this._searchInputElement.hasFocus()){var selection=UI.inspectorView.element.window().getSelection();if(selection.rangeCount) -queryCandidate=selection.toString().replace(/\r?\n.*/,'');} -this._toggleSearchBar(true);this._updateReplaceVisibility();if(queryCandidate) -this._searchInputElement.value=queryCandidate;this._performSearch(false,false);this._searchInputElement.focus();this._searchInputElement.select();this._searchIsVisible=true;} -_updateReplaceVisibility(){this._replaceElement.classList.toggle('hidden',!this._replaceable);if(!this._replaceable){this._replaceCheckboxElement.checked=false;this._updateSecondRowVisibility();}} -_onSearchKeyDown(event){if(isEscKey(event)){this.closeSearch();event.consume(true);return;} -if(!isEnterKey(event)) -return;if(!this._currentQuery) -this._performSearch(true,true,event.shiftKey);else -this._jumpToNextSearchResult(event.shiftKey);} -_onReplaceKeyDown(event){if(isEnterKey(event)) -this._replace();} -_jumpToNextSearchResult(isBackwardSearch){if(!this._currentQuery||!this._searchNavigationPrevElement.classList.contains('enabled')) -return;if(isBackwardSearch) -this._searchProvider.jumpToPreviousSearchResult();else -this._searchProvider.jumpToNextSearchResult();} -_onNextButtonSearch(event){if(!this._searchNavigationNextElement.classList.contains('enabled')) -return;this._jumpToNextSearchResult();this._searchInputElement.focus();} -_onPrevButtonSearch(event){if(!this._searchNavigationPrevElement.classList.contains('enabled')) -return;this._jumpToNextSearchResult(true);this._searchInputElement.focus();} -_onFindClick(event){if(!this._currentQuery) -this._performSearch(true,true);else -this._jumpToNextSearchResult();this._searchInputElement.focus();} -_onPreviousClick(event){if(!this._currentQuery) -this._performSearch(true,true,true);else -this._jumpToNextSearchResult(true);this._searchInputElement.focus();} -_clearSearch(){delete this._currentQuery;if(!!this._searchProvider.currentQuery){delete this._searchProvider.currentQuery;this._searchProvider.searchCanceled();} -this._updateSearchMatchesCountAndCurrentMatchIndex(0,-1);} -_performSearch(forceSearch,shouldJump,jumpBackwards){var query=this._searchInputElement.value;if(!query||(!forceSearch&&query.length<this._minimalSearchQuerySize&&!this._currentQuery)){this._clearSearch();return;} -this._currentQuery=query;this._searchProvider.currentQuery=query;var searchConfig=this._currentSearchConfig();this._searchProvider.performSearch(searchConfig,shouldJump,jumpBackwards);} -_currentSearchConfig(){var query=this._searchInputElement.value;var caseSensitive=this._caseSensitiveButton?this._caseSensitiveButton.toggled():false;var isRegex=this._regexButton?this._regexButton.toggled():false;return new UI.SearchableView.SearchConfig(query,caseSensitive,isRegex);} -_updateSecondRowVisibility(){var secondRowVisible=this._replaceCheckboxElement.checked;this._footerElementContainer.classList.toggle('replaceable',secondRowVisible);this._buttonsContainer.classList.toggle('hidden',!secondRowVisible);this._replaceInputElement.classList.toggle('hidden',!secondRowVisible);this._replaceCheckboxElement.tabIndex=secondRowVisible?-1:0;if(secondRowVisible) -this._replaceInputElement.focus();else -this._searchInputElement.focus();this.doResize();} -_replace(){var searchConfig=this._currentSearchConfig();(this._searchProvider).replaceSelectionWith(searchConfig,this._replaceInputElement.value);delete this._currentQuery;this._performSearch(true,true);} -_replaceAll(){var searchConfig=this._currentSearchConfig();(this._searchProvider).replaceAllWith(searchConfig,this._replaceInputElement.value);} -_onInput(event){if(this._valueChangedTimeoutId) -clearTimeout(this._valueChangedTimeoutId);var timeout=this._searchInputElement.value.length<3?200:0;this._valueChangedTimeoutId=setTimeout(this._onValueChanged.bind(this),timeout);} -_onValueChanged(){if(!this._searchIsVisible) -return;delete this._valueChangedTimeoutId;this._performSearch(false,true);}};UI.SearchableView._symbol=Symbol('searchableView');UI.Searchable=function(){};UI.Searchable.prototype={searchCanceled(){},performSearch(searchConfig,shouldJump,jumpBackwards){},jumpToNextSearchResult(){},jumpToPreviousSearchResult(){},supportsCaseSensitiveSearch(){},supportsRegexSearch(){}};UI.Replaceable=function(){};UI.Replaceable.prototype={replaceSelectionWith(searchConfig,replacement){},replaceAllWith(searchConfig,replacement){}};UI.SearchableView.SearchConfig=class{constructor(query,caseSensitive,isRegex){this.query=query;this.caseSensitive=caseSensitive;this.isRegex=isRegex;} -toSearchRegex(global){var modifiers=this.caseSensitive?'':'i';if(global) -modifiers+='g';var query=this.isRegex?'/'+this.query+'/':this.query;var regex;try{if(/^\/.+\/$/.test(query)){regex=new RegExp(query.substring(1,query.length-1),modifiers);regex.__fromRegExpQuery=true;}}catch(e){} -if(!regex) -regex=createPlainTextSearchRegex(query,modifiers);return regex;}};;UI.SettingsUI={};UI.SettingsUI.createSettingCheckbox=function(name,setting,omitParagraphElement,tooltip){var label=UI.CheckboxLabel.create(name);if(tooltip) -label.title=tooltip;var input=label.checkboxElement;input.name=name;UI.SettingsUI.bindCheckbox(input,setting);if(omitParagraphElement) -return label;var p=createElement('p');p.appendChild(label);return p;};UI.SettingsUI.createSettingSelect=function(name,options,setting){var p=createElement('p');p.createChild('label').textContent=name;var select=p.createChild('select','chrome-select');for(var i=0;i<options.length;++i){var option=options[i];var optionName=option.raw?option.text:Common.UIString(option.text);select.add(new Option(optionName,option.value));} -setting.addChangeListener(settingChanged);settingChanged();select.addEventListener('change',selectChanged,false);return p;function settingChanged(){var newValue=setting.get();for(var i=0;i<options.length;i++){if(options[i].value===newValue) -select.selectedIndex=i;}} -function selectChanged(){setting.set(options[select.selectedIndex].value);}};UI.SettingsUI.bindCheckbox=function(input,setting){function settingChanged(){if(input.checked!==setting.get()) -input.checked=setting.get();} -setting.addChangeListener(settingChanged);settingChanged();function inputChanged(){if(setting.get()!==input.checked) -setting.set(input.checked);} -input.addEventListener('change',inputChanged,false);};UI.SettingsUI.createCustomSetting=function(name,element){var p=createElement('p');var fieldsetElement=p.createChild('fieldset');fieldsetElement.createChild('label').textContent=name;fieldsetElement.appendChild(element);return p;};UI.SettingsUI.createControlForSetting=function(setting){if(!setting.extension()) -return null;var descriptor=setting.extension().descriptor();var uiTitle=Common.UIString(setting.title()||'');switch(descriptor['settingType']){case'boolean':return UI.SettingsUI.createSettingCheckbox(uiTitle,setting);case'enum':if(Array.isArray(descriptor['options'])) -return UI.SettingsUI.createSettingSelect(uiTitle,descriptor['options'],setting);console.error('Enum setting defined without options');return null;default:console.error('Invalid setting type: '+descriptor['settingType']);return null;}};UI.SettingUI=function(){};UI.SettingUI.prototype={settingElement(){}};;UI.SoftContextMenu=class{constructor(items,itemSelectedCallback,parentMenu){this._items=items;this._itemSelectedCallback=itemSelectedCallback;this._parentMenu=parentMenu;} -show(document,anchorBox){if(!this._items.length) -return;this._document=document;this._glassPane=new UI.GlassPane();this._glassPane.setPointerEventsBehavior(this._parentMenu?UI.GlassPane.PointerEventsBehavior.PierceGlassPane:UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this._glassPane.registerRequiredCSS('ui/softContextMenu.css');this._glassPane.setContentAnchorBox(anchorBox);this._glassPane.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);this._glassPane.setMarginBehavior(UI.GlassPane.MarginBehavior.NoMargin);this._glassPane.setAnchorBehavior(this._parentMenu?UI.GlassPane.AnchorBehavior.PreferRight:UI.GlassPane.AnchorBehavior.PreferBottom);this._contextMenuElement=this._glassPane.contentElement.createChild('div','soft-context-menu');this._contextMenuElement.tabIndex=0;this._contextMenuElement.addEventListener('mouseup',e=>e.consume(),false);this._contextMenuElement.addEventListener('keydown',this._menuKeyDown.bind(this),false);for(var i=0;i<this._items.length;++i) -this._contextMenuElement.appendChild(this._createMenuItem(this._items[i]));this._glassPane.show(document);this._focusRestorer=new UI.ElementFocusRestorer(this._contextMenuElement);if(!this._parentMenu){this._onBodyMouseDown=event=>{this.discard();event.consume(true);};this._document.body.addEventListener('mousedown',this._onBodyMouseDown,false);}} -discard(){if(this._subMenu) -this._subMenu.discard();if(this._focusRestorer) -this._focusRestorer.restore();if(this._glassPane){this._glassPane.hide();delete this._glassPane;if(this._onBodyMouseDown){this._document.body.removeEventListener('mousedown',this._onBodyMouseDown,false);delete this._onBodyMouseDown;}} -if(this._parentMenu) -delete this._parentMenu._subMenu;} -_createMenuItem(item){if(item.type==='separator') -return this._createSeparator();if(item.type==='subMenu') -return this._createSubMenu(item);var menuItemElement=createElementWithClass('div','soft-context-menu-item');var checkMarkElement=UI.Icon.create('smallicon-checkmark','checkmark');menuItemElement.appendChild(checkMarkElement);if(!item.checked) -checkMarkElement.style.opacity='0';if(item.element){var wrapper=menuItemElement.createChild('div','soft-context-menu-custom-item');wrapper.appendChild(item.element);menuItemElement._isCustom=true;return menuItemElement;} -if(!item.enabled) -menuItemElement.classList.add('soft-context-menu-disabled');menuItemElement.createTextChild(item.label);menuItemElement.createChild('span','soft-context-menu-shortcut').textContent=item.shortcut;menuItemElement.addEventListener('mousedown',this._menuItemMouseDown.bind(this),false);menuItemElement.addEventListener('mouseup',this._menuItemMouseUp.bind(this),false);menuItemElement.addEventListener('mouseover',this._menuItemMouseOver.bind(this),false);menuItemElement.addEventListener('mouseleave',this._menuItemMouseLeave.bind(this),false);menuItemElement._actionId=item.id;return menuItemElement;} -_createSubMenu(item){var menuItemElement=createElementWithClass('div','soft-context-menu-item');menuItemElement._subItems=item.subItems;var checkMarkElement=UI.Icon.create('smallicon-checkmark','soft-context-menu-item-checkmark');checkMarkElement.classList.add('checkmark');menuItemElement.appendChild(checkMarkElement);checkMarkElement.style.opacity='0';menuItemElement.createTextChild(item.label);var subMenuArrowElement=menuItemElement.createChild('span','soft-context-menu-item-submenu-arrow');subMenuArrowElement.textContent='\u25B6';menuItemElement.addEventListener('mousedown',this._menuItemMouseDown.bind(this),false);menuItemElement.addEventListener('mouseup',this._menuItemMouseUp.bind(this),false);menuItemElement.addEventListener('mouseover',this._menuItemMouseOver.bind(this),false);menuItemElement.addEventListener('mouseleave',this._menuItemMouseLeave.bind(this),false);return menuItemElement;} -_createSeparator(){var separatorElement=createElementWithClass('div','soft-context-menu-separator');separatorElement._isSeparator=true;separatorElement.createChild('div','separator-line');return separatorElement;} -_menuItemMouseDown(event){event.consume(true);} -_menuItemMouseUp(event){this._triggerAction(event.target,event);event.consume();} -_root(){var root=this;while(root._parentMenu) -root=root._parentMenu;return root;} -_triggerAction(menuItemElement,event){if(!menuItemElement._subItems){this._root().discard();event.consume(true);if(typeof menuItemElement._actionId!=='undefined'){this._itemSelectedCallback(menuItemElement._actionId);delete menuItemElement._actionId;} -return;} -this._showSubMenu(menuItemElement);event.consume();} -_showSubMenu(menuItemElement){if(menuItemElement._subMenuTimer){clearTimeout(menuItemElement._subMenuTimer);delete menuItemElement._subMenuTimer;} -if(this._subMenu) -return;this._subMenu=new UI.SoftContextMenu(menuItemElement._subItems,this._itemSelectedCallback,this);var anchorBox=menuItemElement.boxInWindow();anchorBox.y-=5;anchorBox.x+=3;anchorBox.width-=6;anchorBox.height+=10;this._subMenu.show(this._document,anchorBox);} -_menuItemMouseOver(event){this._highlightMenuItem(event.target,true);} -_menuItemMouseLeave(event){if(!this._subMenu||!event.relatedTarget){this._highlightMenuItem(null,true);return;} -var relatedTarget=event.relatedTarget;if(relatedTarget===this._contextMenuElement) -this._highlightMenuItem(null,true);} -_highlightMenuItem(menuItemElement,scheduleSubMenu){if(this._highlightedMenuItemElement===menuItemElement) -return;if(this._subMenu) -this._subMenu.discard();if(this._highlightedMenuItemElement){this._highlightedMenuItemElement.classList.remove('force-white-icons');this._highlightedMenuItemElement.classList.remove('soft-context-menu-item-mouse-over');if(this._highlightedMenuItemElement._subItems&&this._highlightedMenuItemElement._subMenuTimer){clearTimeout(this._highlightedMenuItemElement._subMenuTimer);delete this._highlightedMenuItemElement._subMenuTimer;}} -this._highlightedMenuItemElement=menuItemElement;if(this._highlightedMenuItemElement){this._highlightedMenuItemElement.classList.add('force-white-icons');this._highlightedMenuItemElement.classList.add('soft-context-menu-item-mouse-over');this._contextMenuElement.focus();if(scheduleSubMenu&&this._highlightedMenuItemElement._subItems&&!this._highlightedMenuItemElement._subMenuTimer){this._highlightedMenuItemElement._subMenuTimer=setTimeout(this._showSubMenu.bind(this,this._highlightedMenuItemElement),150);}}} -_highlightPrevious(){var menuItemElement=this._highlightedMenuItemElement?this._highlightedMenuItemElement.previousSibling:this._contextMenuElement.lastChild;while(menuItemElement&&(menuItemElement._isSeparator||menuItemElement._isCustom)) -menuItemElement=menuItemElement.previousSibling;if(menuItemElement) -this._highlightMenuItem(menuItemElement,false);} -_highlightNext(){var menuItemElement=this._highlightedMenuItemElement?this._highlightedMenuItemElement.nextSibling:this._contextMenuElement.firstChild;while(menuItemElement&&(menuItemElement._isSeparator||menuItemElement._isCustom)) -menuItemElement=menuItemElement.nextSibling;if(menuItemElement) -this._highlightMenuItem(menuItemElement,false);} -_menuKeyDown(event){switch(event.key){case'ArrowUp':this._highlightPrevious();break;case'ArrowDown':this._highlightNext();break;case'ArrowLeft':if(this._parentMenu){this._highlightMenuItem(null,false);this.discard();} -break;case'ArrowRight':if(!this._highlightedMenuItemElement) -break;if(this._highlightedMenuItemElement._subItems){this._showSubMenu(this._highlightedMenuItemElement);this._subMenu._highlightNext();} -break;case'Escape':this.discard();break;case'Enter':if(!isEnterKey(event)) -break;case' ':if(this._highlightedMenuItemElement) -this._triggerAction(this._highlightedMenuItemElement,event);if(this._highlightedMenuItemElement._subItems) -this._subMenu._highlightNext();break;} -event.consume(true);}};;UI.SoftDropDown=class{constructor(model,delegate){this._delegate=delegate;this._selectedItem=null;this._model=model;this.element=createElementWithClass('button','soft-dropdown');var shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/softDropDownButton.css');this._titleElement=shadowRoot.createChild('span','title');var dropdownArrowIcon=UI.Icon.create('smallicon-triangle-down');shadowRoot.appendChild(dropdownArrowIcon);this._glassPane=new UI.GlassPane();this._glassPane.setMarginBehavior(UI.GlassPane.MarginBehavior.NoMargin);this._glassPane.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferBottom);this._glassPane.setOutsideClickCallback(this._hide.bind(this));this._glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this._list=new UI.ListControl(model,this,UI.ListMode.EqualHeightItems);this._list.element.classList.add('item-list');this._rowHeight=36;this._width=315;UI.createShadowRootWithCoreStyles(this._glassPane.contentElement,'ui/softDropDown.css').appendChild(this._list.element);this._listWasShowing200msAgo=false;this.element.addEventListener('mousedown',event=>{if(this._listWasShowing200msAgo) -this._hide(event);else -this._show(event);},false);this.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this.element.addEventListener('focusout',this._hide.bind(this),false);this._list.element.addEventListener('mousedown',event=>event.consume(true),false);this._list.element.addEventListener('mouseup',event=>{if(event.target===this._list.element) -return;if(!this._listWasShowing200msAgo) -return;this._selectHighlightedItem();this._hide(event);},false);model.addEventListener(UI.ListModel.Events.ItemsReplaced,this._itemsReplaced,this);} -_show(event){if(this._glassPane.isShowing()) -return;this._glassPane.setContentAnchorBox(this.element.boxInWindow());this._glassPane.show((this.element.ownerDocument));this._updateGlasspaneSize();if(this._selectedItem) -this._list.selectItem(this._selectedItem);this.element.focus();event.consume(true);setTimeout(()=>this._listWasShowing200msAgo=true,200);} -_updateGlasspaneSize(){var maxHeight=this._rowHeight*(Math.min(this._model.length,9));this._glassPane.setMaxContentSize(new UI.Size(this._width,maxHeight));this._list.viewportResized();} -_hide(event){setTimeout(()=>this._listWasShowing200msAgo=false,200);this._glassPane.hide();this._list.selectItem(null);event.consume(true);} -_onKeyDown(event){var handled=false;switch(event.key){case'ArrowLeft':case'ArrowUp':handled=this._list.selectPreviousItem(false,false);break;case'ArrowRight':case'ArrowDown':handled=this._list.selectNextItem(false,false);break;case'PageUp':handled=this._list.selectItemPreviousPage(false);break;case'PageDown':handled=this._list.selectItemNextPage(false);break;case'Home':for(var i=0;i<this._model.length;i++){if(this.isItemSelectable(this._model.at(i))){this._list.selectItem(this._model.at(i));handled=true;break;}} -break;case'End':for(var i=this._model.length-1;i>=0;i--){if(this.isItemSelectable(this._model.at(i))){this._list.selectItem(this._model.at(i));handled=true;break;}} -break;case'Escape':this._hide(event);break;case'Tab':if(!this._glassPane.isShowing()) -break;this._selectHighlightedItem();this._hide(event);break;case'Enter':if(!this._glassPane.isShowing()){this._show(event);break;} -this._selectHighlightedItem();this._hide(event);break;case' ':this._show(event);break;default:if(event.key.length===1){var selectedIndex=this._list.selectedIndex();var letter=event.key.toUpperCase();for(var i=0;i<this._model.length;i++){var item=this._model.at((selectedIndex+i+1)%this._model.length);if(this._delegate.titleFor(item).toUpperCase().startsWith(letter)){this._list.selectItem(item);break;}} -handled=true;} -break;} -if(handled){event.consume(true);this._selectHighlightedItem();}} -setWidth(width){this._width=width;this._updateGlasspaneSize();} -setRowHeight(rowHeight){this._rowHeight=rowHeight;} -_itemsReplaced(event){var removed=(event.data.removed);if(removed.indexOf(this._selectedItem)!==-1){this._selectedItem=null;this._selectHighlightedItem();} -this._updateGlasspaneSize();} -selectItem(item){this._selectedItem=item;if(this._selectedItem) -this._titleElement.textContent=this._delegate.titleFor(this._selectedItem);else -this._titleElement.textContent='';this._delegate.itemSelected(this._selectedItem);} -createElementForItem(item){var element=createElementWithClass('div','item');element.addEventListener('mousemove',e=>{if((e.movementX||e.movementY)&&this._delegate.isItemSelectable(item)) -this._list.selectItem(item,false,true);});element.classList.toggle('disabled',!this._delegate.isItemSelectable(item));element.classList.toggle('highlighted',this._list.selectedItem()===item);element.appendChild(this._delegate.createElementForItem(item));return element;} -heightForItem(item){return this._rowHeight;} -isItemSelectable(item){return this._delegate.isItemSelectable(item);} -selectedItemChanged(from,to,fromElement,toElement){if(fromElement) -fromElement.classList.remove('highlighted');if(toElement) -toElement.classList.add('highlighted');this._delegate.highlightedItemChanged(from,to,fromElement&&fromElement.firstElementChild,toElement&&toElement.firstElementChild);} -_selectHighlightedItem(){this.selectItem(this._list.selectedItem());} -refreshItem(item){this._list.refreshItem(item);}};UI.SoftDropDown.Delegate=class{titleFor(item){} -createElementForItem(item){} -isItemSelectable(item){} -itemSelected(item){} -highlightedItemChanged(from,to,fromElement,toElement){}};;UI.SplitWidget=class extends UI.Widget{constructor(isVertical,secondIsSidebar,settingName,defaultSidebarWidth,defaultSidebarHeight,constraintsInDip){super(true);this.element.classList.add('split-widget');this.registerRequiredCSS('ui/splitWidget.css');this.contentElement.classList.add('shadow-split-widget');this._mainElement=this.contentElement.createChild('div','shadow-split-widget-contents shadow-split-widget-main vbox');this._mainElement.createChild('content').select='.insertion-point-main';this._sidebarElement=this.contentElement.createChild('div','shadow-split-widget-contents shadow-split-widget-sidebar vbox');this._sidebarElement.createChild('content').select='.insertion-point-sidebar';this._resizerElement=this.contentElement.createChild('div','shadow-split-widget-resizer');this._resizerElementSize=null;this._resizerWidget=new UI.SimpleResizerWidget();this._resizerWidget.setEnabled(true);this._resizerWidget.addEventListener(UI.ResizerWidget.Events.ResizeStart,this._onResizeStart,this);this._resizerWidget.addEventListener(UI.ResizerWidget.Events.ResizeUpdate,this._onResizeUpdate,this);this._resizerWidget.addEventListener(UI.ResizerWidget.Events.ResizeEnd,this._onResizeEnd,this);this._defaultSidebarWidth=defaultSidebarWidth||200;this._defaultSidebarHeight=defaultSidebarHeight||this._defaultSidebarWidth;this._constraintsInDip=!!constraintsInDip;this._resizeStartSizeDIP=0;this._setting=settingName?Common.settings.createSetting(settingName,{}):null;this._totalSizeCSS=0;this._totalSizeOtherDimensionCSS=0;this._mainWidget=null;this._sidebarWidget=null;this._animationFrameHandle=0;this._animationCallback=null;this._showHideSidebarButtonTitle='';this._showHideSidebarButton=null;this._isVertical=false;this._sidebarMinimized=false;this._detaching=false;this._sidebarSizeDIP=-1;this._savedSidebarSizeDIP=this._sidebarSizeDIP;this._secondIsSidebar=false;this._shouldSaveShowMode=false;this._savedVerticalMainSize=null;this._savedHorizontalMainSize=null;this.setSecondIsSidebar(secondIsSidebar);this._innerSetVertical(isVertical);this._showMode=UI.SplitWidget.ShowMode.Both;this._savedShowMode=this._showMode;this.installResizer(this._resizerElement);} -isVertical(){return this._isVertical;} -setVertical(isVertical){if(this._isVertical===isVertical) -return;this._innerSetVertical(isVertical);if(this.isShowing()) -this._updateLayout();} -_innerSetVertical(isVertical){this.contentElement.classList.toggle('vbox',!isVertical);this.contentElement.classList.toggle('hbox',isVertical);this._isVertical=isVertical;this._resizerElementSize=null;this._sidebarSizeDIP=-1;this._restoreSidebarSizeFromSettings();if(this._shouldSaveShowMode) -this._restoreAndApplyShowModeFromSettings();this._updateShowHideSidebarButton();this._resizerWidget.setVertical(!isVertical);this.invalidateConstraints();} -_updateLayout(animate){this._totalSizeCSS=0;this._totalSizeOtherDimensionCSS=0;this._mainElement.style.removeProperty('width');this._mainElement.style.removeProperty('height');this._sidebarElement.style.removeProperty('width');this._sidebarElement.style.removeProperty('height');this._innerSetSidebarSizeDIP(this._preferredSidebarSizeDIP(),!!animate);} -setMainWidget(widget){if(this._mainWidget===widget) -return;this.suspendInvalidations();if(this._mainWidget) -this._mainWidget.detach();this._mainWidget=widget;if(widget){widget.element.classList.add('insertion-point-main');widget.element.classList.remove('insertion-point-sidebar');if(this._showMode===UI.SplitWidget.ShowMode.OnlyMain||this._showMode===UI.SplitWidget.ShowMode.Both) -widget.show(this.element);} -this.resumeInvalidations();} -setSidebarWidget(widget){if(this._sidebarWidget===widget) -return;this.suspendInvalidations();if(this._sidebarWidget) -this._sidebarWidget.detach();this._sidebarWidget=widget;if(widget){widget.element.classList.add('insertion-point-sidebar');widget.element.classList.remove('insertion-point-main');if(this._showMode===UI.SplitWidget.ShowMode.OnlySidebar||this._showMode===UI.SplitWidget.ShowMode.Both) -widget.show(this.element);} -this.resumeInvalidations();} -mainWidget(){return this._mainWidget;} -sidebarWidget(){return this._sidebarWidget;} -childWasDetached(widget){if(this._detaching) -return;if(this._mainWidget===widget) -this._mainWidget=null;if(this._sidebarWidget===widget) -this._sidebarWidget=null;this.invalidateConstraints();} -isSidebarSecond(){return this._secondIsSidebar;} -enableShowModeSaving(){this._shouldSaveShowMode=true;this._restoreAndApplyShowModeFromSettings();} -showMode(){return this._showMode;} -setSecondIsSidebar(secondIsSidebar){this.contentElement.classList.toggle('shadow-split-widget-first-is-sidebar',!secondIsSidebar);this._secondIsSidebar=secondIsSidebar;} -sidebarSide(){if(this._showMode!==UI.SplitWidget.ShowMode.Both) -return null;return this._isVertical?(this._secondIsSidebar?'right':'left'):(this._secondIsSidebar?'bottom':'top');} -resizerElement(){return this._resizerElement;} -hideMain(animate){this._showOnly(this._sidebarWidget,this._mainWidget,this._sidebarElement,this._mainElement,animate);this._updateShowMode(UI.SplitWidget.ShowMode.OnlySidebar);} -hideSidebar(animate){this._showOnly(this._mainWidget,this._sidebarWidget,this._mainElement,this._sidebarElement,animate);this._updateShowMode(UI.SplitWidget.ShowMode.OnlyMain);} -setSidebarMinimized(minimized){this._sidebarMinimized=minimized;this.invalidateConstraints();} -isSidebarMinimized(){return this._sidebarMinimized;} -_showOnly(sideToShow,sideToHide,shadowToShow,shadowToHide,animate){this._cancelAnimation();function callback(){if(sideToShow){if(sideToShow===this._mainWidget) -this._mainWidget.show(this.element,this._sidebarWidget?this._sidebarWidget.element:null);else -this._sidebarWidget.show(this.element);} -if(sideToHide){this._detaching=true;sideToHide.detach();this._detaching=false;} -this._resizerElement.classList.add('hidden');shadowToShow.classList.remove('hidden');shadowToShow.classList.add('maximized');shadowToHide.classList.add('hidden');shadowToHide.classList.remove('maximized');this._removeAllLayoutProperties();this.doResize();} -if(animate) -this._animate(true,callback.bind(this));else -callback.call(this);this._sidebarSizeDIP=-1;this.setResizable(false);} -_removeAllLayoutProperties(){this._sidebarElement.style.removeProperty('flexBasis');this._mainElement.style.removeProperty('width');this._mainElement.style.removeProperty('height');this._sidebarElement.style.removeProperty('width');this._sidebarElement.style.removeProperty('height');this._resizerElement.style.removeProperty('left');this._resizerElement.style.removeProperty('right');this._resizerElement.style.removeProperty('top');this._resizerElement.style.removeProperty('bottom');this._resizerElement.style.removeProperty('margin-left');this._resizerElement.style.removeProperty('margin-right');this._resizerElement.style.removeProperty('margin-top');this._resizerElement.style.removeProperty('margin-bottom');} -showBoth(animate){if(this._showMode===UI.SplitWidget.ShowMode.Both) -animate=false;this._cancelAnimation();this._mainElement.classList.remove('maximized','hidden');this._sidebarElement.classList.remove('maximized','hidden');this._resizerElement.classList.remove('hidden');this.setResizable(true);this.suspendInvalidations();if(this._sidebarWidget) -this._sidebarWidget.show(this.element);if(this._mainWidget) -this._mainWidget.show(this.element,this._sidebarWidget?this._sidebarWidget.element:null);this.resumeInvalidations();this.setSecondIsSidebar(this._secondIsSidebar);this._sidebarSizeDIP=-1;this._updateShowMode(UI.SplitWidget.ShowMode.Both);this._updateLayout(animate);} -setResizable(resizable){this._resizerWidget.setEnabled(resizable);} -isResizable(){return this._resizerWidget.isEnabled();} -setSidebarSize(size){var sizeDIP=UI.zoomManager.cssToDIP(size);this._savedSidebarSizeDIP=sizeDIP;this._saveSetting();this._innerSetSidebarSizeDIP(sizeDIP,false,true);} -sidebarSize(){var sizeDIP=Math.max(0,this._sidebarSizeDIP);return UI.zoomManager.dipToCSS(sizeDIP);} -_totalSizeDIP(){if(!this._totalSizeCSS){this._totalSizeCSS=this._isVertical?this.contentElement.offsetWidth:this.contentElement.offsetHeight;this._totalSizeOtherDimensionCSS=this._isVertical?this.contentElement.offsetHeight:this.contentElement.offsetWidth;} -return UI.zoomManager.cssToDIP(this._totalSizeCSS);} -_updateShowMode(showMode){this._showMode=showMode;this._saveShowModeToSettings();this._updateShowHideSidebarButton();this.dispatchEventToListeners(UI.SplitWidget.Events.ShowModeChanged,showMode);this.invalidateConstraints();} -_innerSetSidebarSizeDIP(sizeDIP,animate,userAction){if(this._showMode!==UI.SplitWidget.ShowMode.Both||!this.isShowing()) -return;sizeDIP=this._applyConstraints(sizeDIP,userAction);if(this._sidebarSizeDIP===sizeDIP) -return;if(!this._resizerElementSize){this._resizerElementSize=this._isVertical?this._resizerElement.offsetWidth:this._resizerElement.offsetHeight;} -this._removeAllLayoutProperties();var roundSizeCSS=Math.round(UI.zoomManager.dipToCSS(sizeDIP));var sidebarSizeValue=roundSizeCSS+'px';var mainSizeValue=(this._totalSizeCSS-roundSizeCSS)+'px';this._sidebarElement.style.flexBasis=sidebarSizeValue;if(this._isVertical){this._sidebarElement.style.width=sidebarSizeValue;this._mainElement.style.width=mainSizeValue;this._sidebarElement.style.height=this._totalSizeOtherDimensionCSS+'px';this._mainElement.style.height=this._totalSizeOtherDimensionCSS+'px';}else{this._sidebarElement.style.height=sidebarSizeValue;this._mainElement.style.height=mainSizeValue;this._sidebarElement.style.width=this._totalSizeOtherDimensionCSS+'px';this._mainElement.style.width=this._totalSizeOtherDimensionCSS+'px';} -if(this._isVertical){if(this._secondIsSidebar){this._resizerElement.style.right=sidebarSizeValue;this._resizerElement.style.marginRight=-this._resizerElementSize/2+'px';}else{this._resizerElement.style.left=sidebarSizeValue;this._resizerElement.style.marginLeft=-this._resizerElementSize/2+'px';}}else{if(this._secondIsSidebar){this._resizerElement.style.bottom=sidebarSizeValue;this._resizerElement.style.marginBottom=-this._resizerElementSize/2+'px';}else{this._resizerElement.style.top=sidebarSizeValue;this._resizerElement.style.marginTop=-this._resizerElementSize/2+'px';}} -this._sidebarSizeDIP=sizeDIP;if(animate){this._animate(false);}else{this.doResize();this.dispatchEventToListeners(UI.SplitWidget.Events.SidebarSizeChanged,this.sidebarSize());}} -_animate(reverse,callback){var animationTime=50;this._animationCallback=callback||null;var animatedMarginPropertyName;if(this._isVertical) -animatedMarginPropertyName=this._secondIsSidebar?'margin-right':'margin-left';else -animatedMarginPropertyName=this._secondIsSidebar?'margin-bottom':'margin-top';var marginFrom=reverse?'0':'-'+UI.zoomManager.dipToCSS(this._sidebarSizeDIP)+'px';var marginTo=reverse?'-'+UI.zoomManager.dipToCSS(this._sidebarSizeDIP)+'px':'0';this.contentElement.style.setProperty(animatedMarginPropertyName,marginFrom);if(!reverse){suppressUnused(this._mainElement.offsetWidth);suppressUnused(this._sidebarElement.offsetWidth);} -if(!reverse) -this._sidebarWidget.doResize();this.contentElement.style.setProperty('transition',animatedMarginPropertyName+' '+animationTime+'ms linear');var boundAnimationFrame;var startTime;function animationFrame(){this._animationFrameHandle=0;if(!startTime){this.contentElement.style.setProperty(animatedMarginPropertyName,marginTo);startTime=window.performance.now();}else if(window.performance.now()<startTime+animationTime){if(this._mainWidget) -this._mainWidget.doResize();}else{this._cancelAnimation();if(this._mainWidget) -this._mainWidget.doResize();this.dispatchEventToListeners(UI.SplitWidget.Events.SidebarSizeChanged,this.sidebarSize());return;} -this._animationFrameHandle=this.contentElement.window().requestAnimationFrame(boundAnimationFrame);} -boundAnimationFrame=animationFrame.bind(this);this._animationFrameHandle=this.contentElement.window().requestAnimationFrame(boundAnimationFrame);} -_cancelAnimation(){this.contentElement.style.removeProperty('margin-top');this.contentElement.style.removeProperty('margin-right');this.contentElement.style.removeProperty('margin-bottom');this.contentElement.style.removeProperty('margin-left');this.contentElement.style.removeProperty('transition');if(this._animationFrameHandle){this.contentElement.window().cancelAnimationFrame(this._animationFrameHandle);this._animationFrameHandle=0;} -if(this._animationCallback){this._animationCallback();this._animationCallback=null;}} -_applyConstraints(sidebarSize,userAction){var totalSize=this._totalSizeDIP();var zoomFactor=this._constraintsInDip?1:UI.zoomManager.zoomFactor();var constraints=this._sidebarWidget?this._sidebarWidget.constraints():new UI.Constraints();var minSidebarSize=this.isVertical()?constraints.minimum.width:constraints.minimum.height;if(!minSidebarSize) -minSidebarSize=UI.SplitWidget.MinPadding;minSidebarSize*=zoomFactor;if(this._sidebarMinimized) -sidebarSize=minSidebarSize;var preferredSidebarSize=this.isVertical()?constraints.preferred.width:constraints.preferred.height;if(!preferredSidebarSize) -preferredSidebarSize=UI.SplitWidget.MinPadding;preferredSidebarSize*=zoomFactor;if(sidebarSize<preferredSidebarSize) -preferredSidebarSize=Math.max(sidebarSize,minSidebarSize);preferredSidebarSize+=zoomFactor;constraints=this._mainWidget?this._mainWidget.constraints():new UI.Constraints();var minMainSize=this.isVertical()?constraints.minimum.width:constraints.minimum.height;if(!minMainSize) -minMainSize=UI.SplitWidget.MinPadding;minMainSize*=zoomFactor;var preferredMainSize=this.isVertical()?constraints.preferred.width:constraints.preferred.height;if(!preferredMainSize) -preferredMainSize=UI.SplitWidget.MinPadding;preferredMainSize*=zoomFactor;var savedMainSize=this.isVertical()?this._savedVerticalMainSize:this._savedHorizontalMainSize;if(savedMainSize!==null) -preferredMainSize=Math.min(preferredMainSize,savedMainSize*zoomFactor);if(userAction) -preferredMainSize=minMainSize;var totalPreferred=preferredMainSize+preferredSidebarSize;if(totalPreferred<=totalSize) -return Number.constrain(sidebarSize,preferredSidebarSize,totalSize-preferredMainSize);if(minMainSize+minSidebarSize<=totalSize){var delta=totalPreferred-totalSize;var sidebarDelta=delta*preferredSidebarSize/totalPreferred;sidebarSize=preferredSidebarSize-sidebarDelta;return Number.constrain(sidebarSize,minSidebarSize,totalSize-minMainSize);} -return Math.max(0,totalSize-minMainSize);} -wasShown(){this._forceUpdateLayout();UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._onZoomChanged,this);} -willHide(){UI.zoomManager.removeEventListener(UI.ZoomManager.Events.ZoomChanged,this._onZoomChanged,this);} -onResize(){this._updateLayout();} -onLayout(){this._updateLayout();} -calculateConstraints(){if(this._showMode===UI.SplitWidget.ShowMode.OnlyMain) -return this._mainWidget?this._mainWidget.constraints():new UI.Constraints();if(this._showMode===UI.SplitWidget.ShowMode.OnlySidebar) -return this._sidebarWidget?this._sidebarWidget.constraints():new UI.Constraints();var mainConstraints=this._mainWidget?this._mainWidget.constraints():new UI.Constraints();var sidebarConstraints=this._sidebarWidget?this._sidebarWidget.constraints():new UI.Constraints();var min=UI.SplitWidget.MinPadding;if(this._isVertical){mainConstraints=mainConstraints.widthToMax(min).addWidth(1);sidebarConstraints=sidebarConstraints.widthToMax(min);return mainConstraints.addWidth(sidebarConstraints).heightToMax(sidebarConstraints);}else{mainConstraints=mainConstraints.heightToMax(min).addHeight(1);sidebarConstraints=sidebarConstraints.heightToMax(min);return mainConstraints.widthToMax(sidebarConstraints).addHeight(sidebarConstraints);}} -_onResizeStart(event){this._resizeStartSizeDIP=this._sidebarSizeDIP;} -_onResizeUpdate(event){var offset=event.data.currentPosition-event.data.startPosition;var offsetDIP=UI.zoomManager.cssToDIP(offset);var newSizeDIP=this._secondIsSidebar?this._resizeStartSizeDIP-offsetDIP:this._resizeStartSizeDIP+offsetDIP;var constrainedSizeDIP=this._applyConstraints(newSizeDIP,true);this._savedSidebarSizeDIP=constrainedSizeDIP;this._saveSetting();this._innerSetSidebarSizeDIP(constrainedSizeDIP,false,true);if(this.isVertical()) -this._savedVerticalMainSize=this._totalSizeDIP()-this._sidebarSizeDIP;else -this._savedHorizontalMainSize=this._totalSizeDIP()-this._sidebarSizeDIP;} -_onResizeEnd(event){this._resizeStartSizeDIP=0;} -hideDefaultResizer(noSplitter){this.uninstallResizer(this._resizerElement);this._sidebarElement.classList.toggle('no-default-splitter',noSplitter);} -installResizer(resizerElement){this._resizerWidget.addElement(resizerElement);} -uninstallResizer(resizerElement){this._resizerWidget.removeElement(resizerElement);} -hasCustomResizer(){var elements=this._resizerWidget.elements();return elements.length>1||(elements.length===1&&elements[0]!==this._resizerElement);} -toggleResizer(resizer,on){if(on) -this.installResizer(resizer);else -this.uninstallResizer(resizer);} -_settingForOrientation(){var state=this._setting?this._setting.get():{};return this._isVertical?state.vertical:state.horizontal;} -_preferredSidebarSizeDIP(){var size=this._savedSidebarSizeDIP;if(!size){size=this._isVertical?this._defaultSidebarWidth:this._defaultSidebarHeight;if(0<size&&size<1) -size*=this._totalSizeDIP();} -return size;} -_restoreSidebarSizeFromSettings(){var settingForOrientation=this._settingForOrientation();this._savedSidebarSizeDIP=settingForOrientation?settingForOrientation.size:0;} -_restoreAndApplyShowModeFromSettings(){var orientationState=this._settingForOrientation();this._savedShowMode=orientationState&&orientationState.showMode?orientationState.showMode:this._showMode;this._showMode=this._savedShowMode;switch(this._savedShowMode){case UI.SplitWidget.ShowMode.Both:this.showBoth();break;case UI.SplitWidget.ShowMode.OnlyMain:this.hideSidebar();break;case UI.SplitWidget.ShowMode.OnlySidebar:this.hideMain();break;}} -_saveShowModeToSettings(){this._savedShowMode=this._showMode;this._saveSetting();} -_saveSetting(){if(!this._setting) -return;var state=this._setting.get();var orientationState=(this._isVertical?state.vertical:state.horizontal)||{};orientationState.size=this._savedSidebarSizeDIP;if(this._shouldSaveShowMode) -orientationState.showMode=this._savedShowMode;if(this._isVertical) -state.vertical=orientationState;else -state.horizontal=orientationState;this._setting.set(state);} -_forceUpdateLayout(){this._sidebarSizeDIP=-1;this._updateLayout();} -_onZoomChanged(event){this._forceUpdateLayout();} -createShowHideSidebarButton(title){this._showHideSidebarButtonTitle=Common.UIString(title);this._showHideSidebarButton=new UI.ToolbarButton('','');this._showHideSidebarButton.addEventListener(UI.ToolbarButton.Events.Click,buttonClicked,this);this._updateShowHideSidebarButton();function buttonClicked(event){if(this._showMode!==UI.SplitWidget.ShowMode.Both) -this.showBoth(true);else -this.hideSidebar(true);} -return this._showHideSidebarButton;} -_updateShowHideSidebarButton(){if(!this._showHideSidebarButton) -return;var sidebarHidden=this._showMode===UI.SplitWidget.ShowMode.OnlyMain;var glyph='';if(sidebarHidden){glyph=this.isVertical()?(this.isSidebarSecond()?'largeicon-show-right-sidebar':'largeicon-show-left-sidebar'):(this.isSidebarSecond()?'largeicon-show-bottom-sidebar':'largeicon-show-top-sidebar');}else{glyph=this.isVertical()?(this.isSidebarSecond()?'largeicon-hide-right-sidebar':'largeicon-hide-left-sidebar'):(this.isSidebarSecond()?'largeicon-hide-bottom-sidebar':'largeicon-hide-top-sidebar');} -this._showHideSidebarButton.setGlyph(glyph);this._showHideSidebarButton.setTitle(sidebarHidden?Common.UIString('Show %s',this._showHideSidebarButtonTitle):Common.UIString('Hide %s',this._showHideSidebarButtonTitle));}};UI.SplitWidget.SettingForOrientation;UI.SplitWidget.ShowMode={Both:'Both',OnlyMain:'OnlyMain',OnlySidebar:'OnlySidebar'};UI.SplitWidget.Events={SidebarSizeChanged:Symbol('SidebarSizeChanged'),ShowModeChanged:Symbol('ShowModeChanged')};UI.SplitWidget.MinPadding=20;;UI.TextPrompt=class extends Common.Object{constructor(){super();this._proxyElement;this._proxyElementDisplay='inline-block';this._autocompletionTimeout=UI.TextPrompt.DefaultAutocompletionTimeout;this._title='';this._queryRange=null;this._previousText='';this._currentSuggestion='';this._completionRequestId=0;this._ghostTextElement=createElementWithClass('span','auto-complete-text');this._ghostTextElement.setAttribute('contenteditable','false');} -initialize(completions,stopCharacters){this._loadCompletions=completions;this._completionStopCharacters=stopCharacters||' =:[({;,!+-*/&|^<>.';} -setAutocompletionTimeout(timeout){this._autocompletionTimeout=timeout;} -renderAsBlock(){this._proxyElementDisplay='block';} -attach(element){return this._attachInternal(element);} -attachAndStartEditing(element,blurListener){var proxyElement=this._attachInternal(element);this._startEditing(blurListener);return proxyElement;} -_attachInternal(element){if(this._proxyElement) -throw'Cannot attach an attached TextPrompt';this._element=element;this._boundOnKeyDown=this.onKeyDown.bind(this);this._boundOnInput=this.onInput.bind(this);this._boundOnMouseWheel=this.onMouseWheel.bind(this);this._boundClearAutocomplete=this.clearAutocomplete.bind(this);this._proxyElement=element.ownerDocument.createElement('span');var shadowRoot=UI.createShadowRootWithCoreStyles(this._proxyElement,'ui/textPrompt.css');this._contentElement=shadowRoot.createChild('div','text-prompt-root');this._contentElement.createChild('content');this._proxyElement.style.display=this._proxyElementDisplay;element.parentElement.insertBefore(this._proxyElement,element);this._proxyElement.appendChild(element);this._element.classList.add('text-prompt');this._element.setAttribute('contenteditable','plaintext-only');this._element.addEventListener('keydown',this._boundOnKeyDown,false);this._element.addEventListener('input',this._boundOnInput,false);this._element.addEventListener('mousewheel',this._boundOnMouseWheel,false);this._element.addEventListener('selectstart',this._boundClearAutocomplete,false);this._element.addEventListener('blur',this._boundClearAutocomplete,false);this._suggestBox=new UI.SuggestBox(this,20,true);if(this._title) -this._proxyElement.title=this._title;return this._proxyElement;} -detach(){this._removeFromElement();this._focusRestorer.restore();this._proxyElement.parentElement.insertBefore(this._element,this._proxyElement);this._proxyElement.remove();delete this._proxyElement;this._element.classList.remove('text-prompt');this._element.removeAttribute('contenteditable');} -textWithCurrentSuggestion(){var text=this.text();if(!this._queryRange) -return text;return text.substring(0,this._queryRange.startColumn)+this._currentSuggestion+ -text.substring(this._queryRange.endColumn);} -text(){var text=this._element.textContent;if(this._ghostTextElement.parentNode){var addition=this._ghostTextElement.textContent;text=text.substring(0,text.length-addition.length);} -return text;} -setText(text){this.clearAutocomplete();this._element.textContent=text;this._previousText=this.text();this.moveCaretToEndOfPrompt();this._element.scrollIntoView();} -title(){return this._title;} -setTitle(title){this._title=title;if(this._proxyElement) -this._proxyElement.title=title;} -setPlaceholder(placeholder){if(placeholder) -this._element.setAttribute('data-placeholder',placeholder);else -this._element.removeAttribute('data-placeholder');} -setEnabled(enabled){if(enabled) -this._element.setAttribute('contenteditable','plaintext-only');else -this._element.removeAttribute('contenteditable');} -_removeFromElement(){this.clearAutocomplete();this._element.removeEventListener('keydown',this._boundOnKeyDown,false);this._element.removeEventListener('input',this._boundOnInput,false);this._element.removeEventListener('selectstart',this._boundClearAutocomplete,false);this._element.removeEventListener('blur',this._boundClearAutocomplete,false);if(this._isEditing) -this._stopEditing();if(this._suggestBox) -this._suggestBox.hide();} -_startEditing(blurListener){this._isEditing=true;this._contentElement.classList.add('text-prompt-editing');if(blurListener){this._blurListener=blurListener;this._element.addEventListener('blur',this._blurListener,false);} -this._oldTabIndex=this._element.tabIndex;if(this._element.tabIndex<0) -this._element.tabIndex=0;this._focusRestorer=new UI.ElementFocusRestorer(this._element);if(!this.text()) -this.autoCompleteSoon();} -_stopEditing(){this._element.tabIndex=this._oldTabIndex;if(this._blurListener) -this._element.removeEventListener('blur',this._blurListener,false);this._contentElement.classList.remove('text-prompt-editing');delete this._isEditing;} -onMouseWheel(event){} -onKeyDown(event){var handled=false;switch(event.key){case'Tab':handled=this.tabKeyPressed(event);break;case'ArrowLeft':case'Home':this.clearAutocomplete();break;case'ArrowRight':case'End':if(this._isCaretAtEndOfPrompt()) -handled=this.acceptAutoComplete();else -this.clearAutocomplete();break;case'Escape':if(this._isSuggestBoxVisible()){this.clearAutocomplete();handled=true;} -break;case' ':if(event.ctrlKey&&!event.metaKey&&!event.altKey&&!event.shiftKey){this.autoCompleteSoon(true);handled=true;} -break;case'Alt':case'Meta':case'Shift':case'Control':break;} -if(isEnterKey(event)) -event.preventDefault();if(!handled&&this._isSuggestBoxVisible()) -handled=this._suggestBox.keyPressed(event);if(handled) -event.consume(true);} -onInput(event){var text=this.text();var hasCommonPrefix=text.startsWith(this._previousText)||this._previousText.startsWith(text);if(this._queryRange&&hasCommonPrefix) -this._queryRange.endColumn+=text.length-this._previousText.length;this._refreshGhostText();this._previousText=text;this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);this.autoCompleteSoon();} -acceptAutoComplete(){var result=false;if(this._isSuggestBoxVisible()) -result=this._suggestBox.acceptSuggestion();if(!result) -result=this._acceptSuggestionInternal();return result;} -clearAutocomplete(){var beforeText=this.textWithCurrentSuggestion();if(this._isSuggestBoxVisible()) -this._suggestBox.hide();this._clearAutocompleteTimeout();this._queryRange=null;this._refreshGhostText();if(beforeText!==this.textWithCurrentSuggestion()) -this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);} -_refreshGhostText(){if(this._queryRange&&this._isCaretAtEndOfPrompt()&&this._currentSuggestion.startsWith(this.text().substring(this._queryRange.startColumn))){this._ghostTextElement.textContent=this._currentSuggestion.substring(this._queryRange.endColumn-this._queryRange.startColumn);this._element.appendChild(this._ghostTextElement);}else{this._ghostTextElement.remove();}} -_clearAutocompleteTimeout(){if(this._completeTimeout){clearTimeout(this._completeTimeout);delete this._completeTimeout;} -this._completionRequestId++;} -autoCompleteSoon(force){var immediately=this._isSuggestBoxVisible()||force;if(!this._completeTimeout){this._completeTimeout=setTimeout(this.complete.bind(this,force),immediately?0:this._autocompletionTimeout);}} -complete(force,reverse){this._clearAutocompleteTimeout();var selection=this._element.getComponentSelection();var selectionRange=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!selectionRange) -return;var shouldExit;if(!force&&!this._isCaretAtEndOfPrompt()&&!this._isSuggestBoxVisible()){shouldExit=true;}else if(!selection.isCollapsed){shouldExit=true;}else if(!force){var wordSuffixRange=selectionRange.startContainer.rangeOfWord(selectionRange.endOffset,this._completionStopCharacters,this._element,'forward');var autocompleteTextLength=this._ghostTextElement.parentNode?this._ghostTextElement.textContent.length:0;if(wordSuffixRange.toString().length!==autocompleteTextLength) -shouldExit=true;} -if(shouldExit){this.clearAutocomplete();return;} -var wordQueryRange=selectionRange.startContainer.rangeOfWord(selectionRange.startOffset,this._completionStopCharacters,this._element,'backward');var expressionRange=wordQueryRange.cloneRange();expressionRange.collapse(true);expressionRange.setStartBefore(this._proxyElement);this._loadCompletions(expressionRange.toString(),wordQueryRange.toString(),!!force).then(this._completionsReady.bind(this,++this._completionRequestId,selection,wordQueryRange,!!reverse,!!force));} -disableDefaultSuggestionForEmptyInput(){this._disableDefaultSuggestionForEmptyInput=true;} -_boxForAnchorAtStart(selection,textRange){var rangeCopy=selection.getRangeAt(0).cloneRange();var anchorElement=createElement('span');anchorElement.textContent='\u200B';textRange.insertNode(anchorElement);var box=anchorElement.boxInWindow(window);anchorElement.remove();selection.removeAllRanges();selection.addRange(rangeCopy);return box;} -_createRange(){return document.createRange();} -additionalCompletions(query){return[];} -_completionsReady(completionRequestId,selection,originalWordQueryRange,reverse,force,completions){if(this._completionRequestId!==completionRequestId) -return;var query=originalWordQueryRange.toString();var store=new Set();completions=completions.filter(item=>!store.has(item.text)&&!!store.add(item.text));if(query||force){if(query) -completions=completions.concat(this.additionalCompletions(query));else -completions=this.additionalCompletions(query).concat(completions);} -if(!completions.length){this.clearAutocomplete();return;} -var selectionRange=selection.getRangeAt(0);var fullWordRange=this._createRange();fullWordRange.setStart(originalWordQueryRange.startContainer,originalWordQueryRange.startOffset);fullWordRange.setEnd(selectionRange.endContainer,selectionRange.endOffset);if(query+selectionRange.toString()!==fullWordRange.toString()) -return;var beforeRange=this._createRange();beforeRange.setStart(this._element,0);beforeRange.setEnd(fullWordRange.startContainer,fullWordRange.startOffset);this._queryRange=new TextUtils.TextRange(0,beforeRange.toString().length,0,beforeRange.toString().length+fullWordRange.toString().length);var shouldSelect=!this._disableDefaultSuggestionForEmptyInput||!!this.text();if(this._suggestBox){this._suggestBox.updateSuggestions(this._boxForAnchorAtStart(selection,fullWordRange),completions,shouldSelect,!this._isCaretAtEndOfPrompt(),this.text());}} -applySuggestion(suggestion,isIntermediateSuggestion){if(!this._queryRange) -return;this._currentSuggestion=suggestion;this._refreshGhostText();if(isIntermediateSuggestion) -this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);} -acceptSuggestion(){this._acceptSuggestionInternal();} -_acceptSuggestionInternal(){if(!this._queryRange) -return false;this._element.textContent=this.textWithCurrentSuggestion();this.setDOMSelection(this._queryRange.startColumn+this._currentSuggestion.length,this._queryRange.startColumn+this._currentSuggestion.length);this.clearAutocomplete();this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);return true;} -setDOMSelection(startColumn,endColumn){this._element.normalize();var node=this._element.childNodes[0];if(!node||node===this._ghostTextElement) -return;var range=this._createRange();range.setStart(node,startColumn);range.setEnd(node,endColumn);var selection=this._element.getComponentSelection();selection.removeAllRanges();selection.addRange(range);} -_isSuggestBoxVisible(){return this._suggestBox&&this._suggestBox.visible();} -isCaretInsidePrompt(){var selection=this._element.getComponentSelection();var selectionRange=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!selectionRange||!selection.isCollapsed) -return false;return selectionRange.startContainer.isSelfOrDescendant(this._element);} -_isCaretAtEndOfPrompt(){var selection=this._element.getComponentSelection();var selectionRange=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!selectionRange||!selection.isCollapsed) -return false;var node=selectionRange.startContainer;if(!node.isSelfOrDescendant(this._element)) -return false;if(this._ghostTextElement.isAncestor(node)) -return true;if(node.nodeType===Node.TEXT_NODE&&selectionRange.startOffset<node.nodeValue.length) -return false;var foundNextText=false;while(node){if(node.nodeType===Node.TEXT_NODE&&node.nodeValue.length){if(foundNextText&&!this._ghostTextElement.isAncestor(node)) -return false;foundNextText=true;} -node=node.traverseNextNode(this._element);} -return true;} -moveCaretToEndOfPrompt(){var selection=this._element.getComponentSelection();var selectionRange=this._createRange();var container=this._element;while(container.childNodes.length) -container=container.lastChild;var offset=container.nodeType===Node.TEXT_NODE?container.textContent.length:0;selectionRange.setStart(container,offset);selectionRange.setEnd(container,offset);selection.removeAllRanges();selection.addRange(selectionRange);} -tabKeyPressed(event){return this.acceptAutoComplete();} -proxyElementForTests(){return this._proxyElement||null;}};UI.TextPrompt.DefaultAutocompletionTimeout=250;UI.TextPrompt.Events={TextChanged:Symbol('TextChanged')};;UI.ThrottledWidget=class extends UI.VBox{constructor(isWebComponent,timeout){super(isWebComponent);this._updateThrottler=new Common.Throttler(timeout===undefined?100:timeout);this._updateWhenVisible=false;} -doUpdate(){return Promise.resolve();} -update(){this._updateWhenVisible=!this.isShowing();if(this._updateWhenVisible) -return;this._updateThrottler.schedule(innerUpdate.bind(this));function innerUpdate(){if(this.isShowing()) -return this.doUpdate();this._updateWhenVisible=true;return Promise.resolve();}} -wasShown(){super.wasShown();if(this._updateWhenVisible) -this.update();}};;UI.Toolbar=class{constructor(className,parentElement){this._items=[];this._reverse=false;this.element=parentElement?parentElement.createChild('div'):createElement('div');this.element.className=className;this.element.classList.add('toolbar');this._enabled=true;this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/toolbar.css');this._contentElement=this._shadowRoot.createChild('div','toolbar-shadow');this._insertionPoint=this._contentElement.createChild('content');} -static createActionButton(action,toggledOptions,untoggledOptions){var button=new UI.ToolbarToggle(action.title(),action.icon(),action.toggledIcon());button.setToggleWithRedColor(action.toggleWithRedColor());button.addEventListener(UI.ToolbarButton.Events.Click,action.execute,action);action.addEventListener(UI.Action.Events.Enabled,enabledChanged);action.addEventListener(UI.Action.Events.Toggled,toggled);var longClickController=null;var longClickButtons=null;var longClickGlyph=null;toggled();button.setEnabled(action.enabled());return button;function enabledChanged(event){button.setEnabled((event.data));} -function toggled(){button.setToggled(action.toggled());if(action.title()) -UI.Tooltip.install(button.element,action.title(),action.id());updateOptions();} -function updateOptions(){var buttons=action.toggled()?(toggledOptions||null):(untoggledOptions||null);if(buttons&&buttons.length){if(!longClickController){longClickController=new UI.LongClickController(button.element,showOptions);longClickGlyph=UI.Icon.create('largeicon-longclick-triangle','long-click-glyph');button.element.appendChild(longClickGlyph);longClickButtons=buttons;}}else{if(longClickController){longClickController.dispose();longClickController=null;longClickGlyph.remove();longClickGlyph=null;longClickButtons=null;}}} -function showOptions(){var buttons=longClickButtons.slice();var mainButtonClone=new UI.ToolbarToggle(action.title(),action.icon(),action.toggledIcon());mainButtonClone.addEventListener(UI.ToolbarButton.Events.Click,clicked);function clicked(event){button._clicked((event.data));} -mainButtonClone.setToggled(action.toggled());buttons.push(mainButtonClone);var document=button.element.ownerDocument;document.documentElement.addEventListener('mouseup',mouseUp,false);var optionsGlassPane=new UI.GlassPane();optionsGlassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);optionsGlassPane.show(document);var optionsBar=new UI.Toolbar('fill',optionsGlassPane.contentElement);optionsBar._contentElement.classList.add('floating');const buttonHeight=26;var hostButtonPosition=button.element.boxInWindow().relativeToElement(UI.GlassPane.container(document));var topNotBottom=hostButtonPosition.y+buttonHeight*buttons.length<document.documentElement.offsetHeight;if(topNotBottom) -buttons=buttons.reverse();optionsBar.element.style.height=(buttonHeight*buttons.length)+'px';if(topNotBottom) -optionsBar.element.style.top=(hostButtonPosition.y-5)+'px';else -optionsBar.element.style.top=(hostButtonPosition.y-(buttonHeight*(buttons.length-1))-6)+'px';optionsBar.element.style.left=(hostButtonPosition.x-5)+'px';for(var i=0;i<buttons.length;++i){buttons[i].element.addEventListener('mousemove',mouseOver,false);buttons[i].element.addEventListener('mouseout',mouseOut,false);optionsBar.appendToolbarItem(buttons[i]);} -var hostButtonIndex=topNotBottom?0:buttons.length-1;buttons[hostButtonIndex].element.classList.add('emulate-active');function mouseOver(e){if(e.which!==1) -return;var buttonElement=e.target.enclosingNodeOrSelfWithClass('toolbar-item');buttonElement.classList.add('emulate-active');} -function mouseOut(e){if(e.which!==1) -return;var buttonElement=e.target.enclosingNodeOrSelfWithClass('toolbar-item');buttonElement.classList.remove('emulate-active');} -function mouseUp(e){if(e.which!==1) -return;optionsGlassPane.hide();document.documentElement.removeEventListener('mouseup',mouseUp,false);for(var i=0;i<buttons.length;++i){if(buttons[i].element.classList.contains('emulate-active')){buttons[i].element.classList.remove('emulate-active');buttons[i]._clicked(e);break;}}}}} -static createActionButtonForId(actionId){const action=UI.actionRegistry.action(actionId);return UI.Toolbar.createActionButton((action));} -gripElementForResize(){return this._contentElement;} -makeWrappable(reverse,growVertically){this._contentElement.classList.add('wrappable');this._reverse=!!reverse;if(reverse) -this._contentElement.classList.add('wrappable-reverse');if(growVertically) -this._contentElement.classList.add('toolbar-grow-vertical');} -makeVertical(){this._contentElement.classList.add('vertical');} -makeBlueOnHover(){this._contentElement.classList.add('toolbar-blue-on-hover');} -makeToggledGray(){this._contentElement.classList.add('toolbar-toggled-gray');} -renderAsLinks(){this._contentElement.classList.add('toolbar-render-as-links');} -setEnabled(enabled){this._enabled=enabled;for(var item of this._items) -item._applyEnabledState(this._enabled&&item._enabled);} -appendToolbarItem(item){this._items.push(item);item._toolbar=this;if(!this._enabled) -item._applyEnabledState(false);if(this._reverse) -this._contentElement.insertBefore(item.element,this._insertionPoint.nextSibling);else -this._contentElement.insertBefore(item.element,this._insertionPoint);this._hideSeparatorDupes();} -appendSeparator(){this.appendToolbarItem(new UI.ToolbarSeparator());} -appendSpacer(){this.appendToolbarItem(new UI.ToolbarSeparator(true));} -appendText(text){this.appendToolbarItem(new UI.ToolbarText(text));} -removeToolbarItems(){for(var item of this._items) -delete item._toolbar;this._items=[];this._contentElement.removeChildren();this._insertionPoint=this._contentElement.createChild('content');} -setColor(color){var style=createElement('style');style.textContent='.toolbar-glyph { background-color: '+color+' !important }';this._shadowRoot.appendChild(style);} -setToggledColor(color){var style=createElement('style');style.textContent='.toolbar-button.toolbar-state-on .toolbar-glyph { background-color: '+color+' !important }';this._shadowRoot.appendChild(style);} -_hideSeparatorDupes(){if(!this._items.length) -return;var previousIsSeparator=false;var lastSeparator;var nonSeparatorVisible=false;for(var i=0;i<this._items.length;++i){if(this._items[i]instanceof UI.ToolbarSeparator){this._items[i].setVisible(!previousIsSeparator);previousIsSeparator=true;lastSeparator=this._items[i];continue;} -if(this._items[i].visible()){previousIsSeparator=false;lastSeparator=null;nonSeparatorVisible=true;}} -if(lastSeparator&&lastSeparator!==this._items.peekLast()) -lastSeparator.setVisible(false);this.element.classList.toggle('hidden',!!lastSeparator&&lastSeparator.visible()&&!nonSeparatorVisible);} -appendLocationItems(location){var extensions=self.runtime.extensions(UI.ToolbarItem.Provider);var promises=[];for(var i=0;i<extensions.length;++i){if(extensions[i].descriptor()['location']===location) -promises.push(resolveItem(extensions[i]));} -Promise.all(promises).then(appendItemsInOrder.bind(this));function resolveItem(extension){var descriptor=extension.descriptor();if(descriptor['separator']) -return Promise.resolve((new UI.ToolbarSeparator()));if(descriptor['actionId']){return Promise.resolve((UI.Toolbar.createActionButtonForId(descriptor['actionId'])));} -return extension.instance().then(fetchItemFromProvider);function fetchItemFromProvider(provider){return(provider).item();}} -function appendItemsInOrder(items){for(var i=0;i<items.length;++i){var item=items[i];if(item) -this.appendToolbarItem(item);}}}};UI.ToolbarItem=class extends Common.Object{constructor(element){super();this.element=element;this.element.classList.add('toolbar-item');this._visible=true;this._enabled=true;} -setTitle(title){if(this._title===title) -return;this._title=title;UI.Tooltip.install(this.element,title);} -setEnabled(value){if(this._enabled===value) -return;this._enabled=value;this._applyEnabledState(this._enabled&&(!this._toolbar||this._toolbar._enabled));} -_applyEnabledState(enabled){this.element.disabled=!enabled;} -visible(){return this._visible;} -setVisible(x){if(this._visible===x) -return;this.element.classList.toggle('hidden',!x);this._visible=x;if(this._toolbar&&!(this instanceof UI.ToolbarSeparator)) -this._toolbar._hideSeparatorDupes();} -setRightAligned(alignRight){this.element.classList.toggle('toolbar-item-right-aligned',alignRight);}};UI.ToolbarText=class extends UI.ToolbarItem{constructor(text){super(createElementWithClass('div','toolbar-text'));this.element.classList.add('toolbar-text');this.setText(text||'');} -text(){return this.element.textContent;} -setText(text){this.element.textContent=text;}};UI.ToolbarButton=class extends UI.ToolbarItem{constructor(title,glyph,text){super(createElementWithClass('button','toolbar-button'));this.element.addEventListener('click',this._clicked.bind(this),false);this.element.addEventListener('mousedown',this._mouseDown.bind(this),false);this.element.addEventListener('mouseup',this._mouseUp.bind(this),false);this._glyphElement=UI.Icon.create('','toolbar-glyph hidden');this.element.appendChild(this._glyphElement);this._textElement=this.element.createChild('div','toolbar-text hidden');this.setTitle(title);if(glyph) -this.setGlyph(glyph);this.setText(text||'');this._title='';} -setText(text){if(this._text===text) -return;this._textElement.textContent=text;this._textElement.classList.toggle('hidden',!text);this._text=text;} -setGlyph(glyph){if(this._glyph===glyph) -return;this._glyphElement.setIconType(glyph);this._glyphElement.classList.toggle('hidden',!glyph);this.element.classList.toggle('toolbar-has-glyph',!!glyph);this._glyph=glyph;} -setBackgroundImage(iconURL){this.element.style.backgroundImage='url('+iconURL+')';} -setDarkText(){this.element.classList.add('dark-text');} -turnIntoSelect(width){this.element.classList.add('toolbar-has-dropdown');var dropdownArrowIcon=UI.Icon.create('smallicon-triangle-down','toolbar-dropdown-arrow');this.element.appendChild(dropdownArrowIcon);if(width) -this.element.style.width=width+'px';} -_clicked(event){if(!this._enabled) -return;this.dispatchEventToListeners(UI.ToolbarButton.Events.Click,event);event.consume();} -_mouseDown(event){if(!this._enabled) -return;this.dispatchEventToListeners(UI.ToolbarButton.Events.MouseDown,event);} -_mouseUp(event){if(!this._enabled) -return;this.dispatchEventToListeners(UI.ToolbarButton.Events.MouseUp,event);}};UI.ToolbarButton.Events={Click:Symbol('Click'),MouseDown:Symbol('MouseDown'),MouseUp:Symbol('MouseUp')};UI.ToolbarInput=class extends UI.ToolbarItem{constructor(placeholder,growFactor,shrinkFactor,tooltip,completions){super(createElementWithClass('div','toolbar-input'));var internalPromptElement=this.element.createChild('div','toolbar-input-prompt');internalPromptElement.addEventListener('focus',()=>this.element.classList.add('focused'));internalPromptElement.addEventListener('blur',()=>this.element.classList.remove('focused'));this._prompt=new UI.TextPrompt();this._proxyElement=this._prompt.attach(internalPromptElement);this._proxyElement.classList.add('toolbar-prompt-proxy');this._proxyElement.addEventListener('keydown',event=>this._onKeydownCallback(event));this._prompt.initialize(completions||(()=>Promise.resolve([])),' ');if(tooltip) -this._prompt.setTitle(tooltip);this._prompt.setPlaceholder(placeholder);this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged,this._onChangeCallback.bind(this));if(growFactor) -this.element.style.flexGrow=growFactor;if(shrinkFactor) -this.element.style.flexShrink=shrinkFactor;var clearButton=this.element.createChild('div','toolbar-input-clear-button');clearButton.appendChild(UI.Icon.create('mediumicon-gray-cross-hover','search-cancel-button'));clearButton.addEventListener('click',()=>this._internalSetValue('',true));this._updateEmptyStyles();} -_applyEnabledState(enabled){this._prompt.setEnabled(enabled);} -setValue(value){this._internalSetValue(value,false);} -_internalSetValue(value,notify){this._prompt.setText(value);if(notify) -this._onChangeCallback();this._updateEmptyStyles();} -value(){return this._prompt.textWithCurrentSuggestion();} -_onKeydownCallback(event){if(!isEscKey(event)||!this._prompt.text()) -return;this._internalSetValue('',true);event.consume(true);} -_onChangeCallback(){this._updateEmptyStyles();this.dispatchEventToListeners(UI.ToolbarInput.Event.TextChanged,this._prompt.text());} -_updateEmptyStyles(){this.element.classList.toggle('toolbar-input-empty',!this._prompt.text());}};UI.ToolbarInput.Event={TextChanged:Symbol('TextChanged')};UI.ToolbarToggle=class extends UI.ToolbarButton{constructor(title,glyph,toggledGlyph){super(title,glyph,'');this._toggled=false;this._untoggledGlyph=glyph;this._toggledGlyph=toggledGlyph;this.element.classList.add('toolbar-state-off');UI.ARIAUtils.setPressed(this.element,false);} -toggled(){return this._toggled;} -setToggled(toggled){if(this._toggled===toggled) -return;this._toggled=toggled;this.element.classList.toggle('toolbar-state-on',toggled);this.element.classList.toggle('toolbar-state-off',!toggled);UI.ARIAUtils.setPressed(this.element,toggled);if(this._toggledGlyph&&this._untoggledGlyph) -this.setGlyph(toggled?this._toggledGlyph:this._untoggledGlyph);} -setDefaultWithRedColor(withRedColor){this.element.classList.toggle('toolbar-default-with-red-color',withRedColor);} -setToggleWithRedColor(toggleWithRedColor){this.element.classList.toggle('toolbar-toggle-with-red-color',toggleWithRedColor);}};UI.ToolbarMenuButton=class extends UI.ToolbarButton{constructor(contextMenuHandler,useSoftMenu){super('','largeicon-menu');this._contextMenuHandler=contextMenuHandler;this._useSoftMenu=!!useSoftMenu;} -_mouseDown(event){if(event.buttons!==1){super._mouseDown(event);return;} -if(!this._triggerTimeout) -this._triggerTimeout=setTimeout(this._trigger.bind(this,event),200);} -_trigger(event){delete this._triggerTimeout;if(this._lastTriggerTime&&Date.now()-this._lastTriggerTime<300) -return;var contextMenu=new UI.ContextMenu(event,this._useSoftMenu,this.element.totalOffsetLeft(),this.element.totalOffsetTop()+this.element.offsetHeight);this._contextMenuHandler(contextMenu);contextMenu.show();this._lastTriggerTime=Date.now();} -_clicked(event){if(this._triggerTimeout) -clearTimeout(this._triggerTimeout);this._trigger(event);}};UI.ToolbarSettingToggle=class extends UI.ToolbarToggle{constructor(setting,glyph,title,toggledTitle){super(title,glyph);this._defaultTitle=title;this._toggledTitle=toggledTitle||title;this._setting=setting;this._settingChanged();this._setting.addChangeListener(this._settingChanged,this);} -_settingChanged(){var toggled=this._setting.get();this.setToggled(toggled);this.setTitle(toggled?this._toggledTitle:this._defaultTitle);} -_clicked(event){this._setting.set(!this.toggled());super._clicked(event);}};UI.ToolbarSeparator=class extends UI.ToolbarItem{constructor(spacer){super(createElementWithClass('div',spacer?'toolbar-spacer':'toolbar-divider'));}};UI.ToolbarItem.Provider=function(){};UI.ToolbarItem.Provider.prototype={item(){}};UI.ToolbarItem.ItemsProvider=function(){};UI.ToolbarItem.ItemsProvider.prototype={toolbarItems(){}};UI.ToolbarComboBox=class extends UI.ToolbarItem{constructor(changeHandler,className){super(createElementWithClass('span','toolbar-select-container'));this._selectElement=this.element.createChild('select','toolbar-item');var dropdownArrowIcon=UI.Icon.create('smallicon-triangle-down','toolbar-dropdown-arrow');this.element.appendChild(dropdownArrowIcon);if(changeHandler) -this._selectElement.addEventListener('change',changeHandler,false);if(className) -this._selectElement.classList.add(className);} -selectElement(){return(this._selectElement);} -size(){return this._selectElement.childElementCount;} -options(){return Array.prototype.slice.call(this._selectElement.children,0);} -addOption(option){this._selectElement.appendChild(option);} -createOption(label,title,value){var option=this._selectElement.createChild('option');option.text=label;if(title) -option.title=title;if(typeof value!=='undefined') -option.value=value;return option;} -_applyEnabledState(enabled){super._applyEnabledState(enabled);this._selectElement.disabled=!enabled;} -removeOption(option){this._selectElement.removeChild(option);} -removeOptions(){this._selectElement.removeChildren();} -selectedOption(){if(this._selectElement.selectedIndex>=0) -return this._selectElement[this._selectElement.selectedIndex];return null;} -select(option){this._selectElement.selectedIndex=Array.prototype.indexOf.call((this._selectElement),option);} -setSelectedIndex(index){this._selectElement.selectedIndex=index;} -selectedIndex(){return this._selectElement.selectedIndex;} -setMaxWidth(width){this._selectElement.style.maxWidth=width+'px';} -setMinWidth(width){this._selectElement.style.minWidth=width+'px';}};UI.ToolbarSettingComboBox=class extends UI.ToolbarComboBox{constructor(options,setting,optGroup){super(null);this._setting=setting;this._options=options;this._selectElement.addEventListener('change',this._valueChanged.bind(this),false);var optionContainer=this._selectElement;var optGroupElement=optGroup?this._selectElement.createChild('optgroup'):null;if(optGroupElement){optGroupElement.label=optGroup;optionContainer=optGroupElement;} -for(var i=0;i<options.length;++i){var dataOption=options[i];var option=this.createOption(dataOption.label,dataOption.title,dataOption.value);optionContainer.appendChild(option);if(setting.get()===dataOption.value) -this.setSelectedIndex(i);} -setting.addChangeListener(this._settingChanged,this);} -value(){return this._options[this.selectedIndex()].value;} -_settingChanged(){if(this._muteSettingListener) -return;var value=this._setting.get();for(var i=0;i<this._options.length;++i){if(value===this._options[i].value){this.setSelectedIndex(i);break;}}} -_valueChanged(event){var option=this._options[this.selectedIndex()];this._muteSettingListener=true;this._setting.set(option.value);this._muteSettingListener=false;}};UI.ToolbarCheckbox=class extends UI.ToolbarItem{constructor(text,tooltip,listener){super(UI.CheckboxLabel.create(text));this.element.classList.add('checkbox');this.inputElement=this.element.checkboxElement;if(tooltip) -this.element.title=tooltip;if(listener) -this.inputElement.addEventListener('click',listener,false);} -checked(){return this.inputElement.checked;} -setChecked(value){this.inputElement.checked=value;} -_applyEnabledState(enabled){super._applyEnabledState(enabled);this.inputElement.disabled=!enabled;}};UI.ToolbarSettingCheckbox=class extends UI.ToolbarCheckbox{constructor(setting,tooltip,alternateTitle){super(alternateTitle||setting.title()||'',tooltip);UI.SettingsUI.bindCheckbox(this.inputElement,setting);}};;UI.Tooltip=class{constructor(doc){this.element=doc.body.createChild('div');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/tooltip.css');this._tooltipElement=this._shadowRoot.createChild('div','tooltip');doc.addEventListener('mousemove',this._mouseMove.bind(this),true);doc.addEventListener('mousedown',this._hide.bind(this,true),true);doc.addEventListener('mouseleave',this._hide.bind(this,false),true);doc.addEventListener('keydown',this._hide.bind(this,true),true);UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._reset,this);doc.defaultView.addEventListener('resize',this._reset.bind(this),false);} -static installHandler(doc){new UI.Tooltip(doc);} -static install(element,tooltipContent,actionId,options){if(!tooltipContent){delete element[UI.Tooltip._symbol];return;} -element[UI.Tooltip._symbol]={content:tooltipContent,actionId:actionId,options:options||{}};} -static addNativeOverrideContainer(element){UI.Tooltip._nativeOverrideContainer.push(element);} -_mouseMove(event){var mouseEvent=(event);var path=mouseEvent.path;if(!path||mouseEvent.buttons!==0||(mouseEvent.movementX===0&&mouseEvent.movementY===0)) -return;if(this._anchorElement&&path.indexOf(this._anchorElement)===-1) -this._hide(false);for(var element of path){if(element===this._anchorElement){return;}else if(element[UI.Tooltip._symbol]){this._show(element,mouseEvent);return;}}} -_show(anchorElement,event){var tooltip=anchorElement[UI.Tooltip._symbol];this._anchorElement=anchorElement;this._tooltipElement.removeChildren();for(var element of UI.Tooltip._nativeOverrideContainer){if(this._anchorElement.isSelfOrDescendant(element)){Object.defineProperty(this._anchorElement,'title',UI.Tooltip._nativeTitle);this._anchorElement.title=tooltip.content;return;}} -if(typeof tooltip.content==='string') -this._tooltipElement.setTextContentTruncatedIfNeeded(tooltip.content);else -this._tooltipElement.appendChild(tooltip.content);if(tooltip.actionId){var shortcuts=UI.shortcutRegistry.shortcutDescriptorsForAction(tooltip.actionId);for(var shortcut of shortcuts){var shortcutElement=this._tooltipElement.createChild('div','tooltip-shortcut');shortcutElement.textContent=shortcut.name;}} -this._tooltipElement.classList.add('shown');this._tooltipElement.positionAt(0,0);var now=Date.now();var instant=(this._tooltipLastClosed&&now-this._tooltipLastClosed<UI.Tooltip.Timing.InstantThreshold);this._tooltipElement.classList.toggle('instant',instant);this._tooltipLastOpened=instant?now:now+UI.Tooltip.Timing.OpeningDelay;var container=UI.GlassPane.container((anchorElement.ownerDocument));var containerBox=container.boxInWindow(this.element.window());var anchorBox=this._anchorElement.boxInWindow(this.element.window());const anchorOffset=2;const pageMargin=2;var cursorOffset=10;this._tooltipElement.classList.toggle('tooltip-breakword',!this._tooltipElement.textContent.match('\\s'));this._tooltipElement.style.maxWidth=(containerBox.width-pageMargin*2)+'px';this._tooltipElement.style.maxHeight='';var tooltipWidth=this._tooltipElement.offsetWidth;var tooltipHeight=this._tooltipElement.offsetHeight;var anchorTooltipAtElement=this._anchorElement.nodeName==='BUTTON'||this._anchorElement.nodeName==='LABEL';var tooltipX=anchorTooltipAtElement?anchorBox.x:event.x+cursorOffset;tooltipX=Number.constrain(tooltipX,containerBox.x+pageMargin,containerBox.x+containerBox.width-tooltipWidth-pageMargin);var tooltipY;if(!anchorTooltipAtElement){tooltipY=event.y+cursorOffset+tooltipHeight<containerBox.y+containerBox.height?event.y+cursorOffset:event.y-tooltipHeight;}else{var onBottom=anchorBox.y+anchorOffset+anchorBox.height+tooltipHeight<containerBox.y+containerBox.height;tooltipY=onBottom?anchorBox.y+anchorBox.height+anchorOffset:anchorBox.y-tooltipHeight-anchorOffset;} -this._tooltipElement.positionAt(tooltipX,tooltipY);} -_hide(removeInstant){delete this._anchorElement;this._tooltipElement.classList.remove('shown');if(Date.now()>this._tooltipLastOpened) -this._tooltipLastClosed=Date.now();if(removeInstant) -delete this._tooltipLastClosed;} -_reset(){this._hide(true);this._tooltipElement.positionAt(0,0);this._tooltipElement.style.maxWidth='0';this._tooltipElement.style.maxHeight='0';}};UI.Tooltip.Timing={'InstantThreshold':300,'OpeningDelay':600};UI.Tooltip._symbol=Symbol('Tooltip');UI.Tooltip._nativeOverrideContainer=[];UI.Tooltip._nativeTitle=(Object.getOwnPropertyDescriptor(HTMLElement.prototype,'title'));Object.defineProperty(HTMLElement.prototype,'title',{get:function(){var tooltip=this[UI.Tooltip._symbol];return tooltip?tooltip.content:'';},set:function(x){UI.Tooltip.install(this,x);}});;UI.SuggestBoxDelegate=function(){};UI.SuggestBoxDelegate.prototype={applySuggestion(suggestion,isIntermediateSuggestion){},acceptSuggestion(){},};UI.SuggestBox=class{constructor(suggestBoxDelegate,maxItemsHeight,captureEnter){this._suggestBoxDelegate=suggestBoxDelegate;this._maxItemsHeight=maxItemsHeight;this._captureEnter=captureEnter;this._rowHeight=17;this._userInteracted=false;this._userEnteredText='';this._defaultSelectionIsDimmed=false;this._onlyCompletion=null;this._items=new UI.ListModel();this._list=new UI.ListControl(this._items,this,UI.ListMode.EqualHeightItems);this._element=this._list.element;this._element.classList.add('suggest-box');this._element.addEventListener('mousedown',event=>event.preventDefault(),true);this._element.addEventListener('click',this._onClick.bind(this),false);this._glassPane=new UI.GlassPane();this._glassPane.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferBottom);this._glassPane.setOutsideClickCallback(this.hide.bind(this));var shadowRoot=UI.createShadowRootWithCoreStyles(this._glassPane.contentElement,'ui/suggestBox.css');shadowRoot.appendChild(this._element);} -setDefaultSelectionIsDimmed(value){this._defaultSelectionIsDimmed=value;this._element.classList.toggle('default-selection-is-dimmed',value);} -_setUserInteracted(value){this._userInteracted=value;this._element.classList.toggle('user-has-interacted',value);} -visible(){return this._glassPane.isShowing();} -setPosition(anchorBox){this._glassPane.setContentAnchorBox(anchorBox);} -_updateMaxSize(items){var maxWidth=this._maxWidth(items);var length=this._maxItemsHeight?Math.min(this._maxItemsHeight,items.length):items.length;var maxHeight=length*this._rowHeight;this._glassPane.setMaxContentSize(new UI.Size(maxWidth,maxHeight));} -_maxWidth(items){var kMaxWidth=300;if(!items.length) -return kMaxWidth;var maxItem;var maxLength=-Infinity;for(var i=0;i<items.length;i++){var length=(items[i].title||items[i].text).length+(items[i].subtitle||'').length;if(length>maxLength){maxLength=length;maxItem=items[i];}} -var element=this.createElementForItem((maxItem));return Math.min(kMaxWidth,UI.measurePreferredSize(element,this._element).width);} -_show(){if(this.visible()) -return;this._glassPane.show(document);this._rowHeight=UI.measurePreferredSize(this.createElementForItem({text:'1',subtitle:'12'}),this._element).height;} -hide(){if(!this.visible()) -return;this._setUserInteracted(false);this._glassPane.hide();} -_applySuggestion(isIntermediateSuggestion){if(this._onlyCompletion){this._suggestBoxDelegate.applySuggestion(this._onlyCompletion,isIntermediateSuggestion);return true;} -if(!this.visible()||!this._list.selectedItem()) -return false;var suggestion=this._list.selectedItem().text;if(!suggestion) -return false;this._suggestBoxDelegate.applySuggestion(suggestion,isIntermediateSuggestion);return true;} -acceptSuggestion(){var result=this._applySuggestion();this.hide();if(!result) -return false;this._suggestBoxDelegate.acceptSuggestion();return true;} -createElementForItem(item){var query=this._userEnteredText;var element=createElementWithClass('div','suggest-box-content-item source-code');if(item.iconType){var icon=UI.Icon.create(item.iconType,'suggestion-icon');element.appendChild(icon);} -if(item.isSecondary) -element.classList.add('secondary');element.tabIndex=-1;var maxTextLength=50+query.length;var displayText=(item.title||item.text).trimEnd(maxTextLength);var titleElement=element.createChild('span','suggestion-title');var index=displayText.toLowerCase().indexOf(query.toLowerCase());if(index>0) -titleElement.createChild('span').textContent=displayText.substring(0,index);if(index>-1) -titleElement.createChild('span','query').textContent=displayText.substring(index,index+query.length);titleElement.createChild('span').textContent=displayText.substring(index>-1?index+query.length:0);titleElement.createChild('span','spacer');if(item.subtitle){var subtitleElement=element.createChild('span','suggestion-subtitle');subtitleElement.textContent=item.subtitle.trimEnd(maxTextLength-displayText.length);} -return element;} -heightForItem(item){return this._rowHeight;} -isItemSelectable(item){return true;} -selectedItemChanged(from,to,fromElement,toElement){if(fromElement) -fromElement.classList.remove('selected','force-white-icons');if(toElement){toElement.classList.add('selected');if(fromElement||this._userInteracted||!this._defaultSelectionIsDimmed) -toElement.classList.add('force-white-icons');} -if(!to) -return;this._applySuggestion(true);} -_onClick(event){var item=this._list.itemForNode((event.target));if(!item) -return;this._list.selectItem(item);this._setUserInteracted(true);this.acceptSuggestion();event.consume(true);} -_canShowBox(completions,canShowForSingleItem,userEnteredText){if(!completions||!completions.length) -return false;if(completions.length>1) -return true;if(!completions[0].text.startsWith(userEnteredText)) -return true;return canShowForSingleItem&&completions[0].text!==userEnteredText;} -updateSuggestions(anchorBox,completions,selectHighestPriority,canShowForSingleItem,userEnteredText){this._onlyCompletion=null;if(this._canShowBox(completions,canShowForSingleItem,userEnteredText)){this._userEnteredText=userEnteredText;this._show();this._updateMaxSize(completions);this._glassPane.setContentAnchorBox(anchorBox);this._list.invalidateItemHeight();this._items.replaceAll(completions);if(selectHighestPriority){var highestPriorityItem=completions[0];var highestPriority=completions[0].priority||0;for(var i=0;i<completions.length;i++){var priority=completions[i].priority||0;if(highestPriority<priority){highestPriority=priority;highestPriorityItem=completions[i];}} -this._list.selectItem(highestPriorityItem,true);}}else{if(completions.length===1){this._onlyCompletion=completions[0].text;this._applySuggestion(true);} -this.hide();}} -keyPressed(event){var selected=false;switch(event.key){case'Enter':return this.enterKeyPressed();case'ArrowUp':selected=this._list.selectPreviousItem(true,false);break;case'ArrowDown':selected=this._list.selectNextItem(true,false);break;case'PageUp':selected=this._list.selectItemPreviousPage(false);break;case'PageDown':selected=this._list.selectItemNextPage(false);break;default:return false;} -if(selected){this._setUserInteracted(true);return true;} -return false;} -enterKeyPressed(){if(!this._userInteracted&&this._captureEnter) -return false;var hasSelectedItem=!!this._list.selectedItem()||!!this._onlyCompletion;this.acceptSuggestion();return hasSelectedItem;}};UI.SuggestBox.Suggestion;UI.SuggestBox.Suggestions;;UI.TabbedPane=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('ui/tabbedPane.css');this.element.classList.add('tabbed-pane');this.contentElement.classList.add('tabbed-pane-shadow');this.contentElement.tabIndex=-1;this._headerElement=this.contentElement.createChild('div','tabbed-pane-header');this._headerContentsElement=this._headerElement.createChild('div','tabbed-pane-header-contents');this._tabSlider=createElementWithClass('div','tabbed-pane-tab-slider');this._tabsElement=this._headerContentsElement.createChild('div','tabbed-pane-header-tabs');this._tabsElement.setAttribute('role','tablist');this._tabsElement.addEventListener('keydown',this._keyDown.bind(this),false);this._contentElement=this.contentElement.createChild('div','tabbed-pane-content');this._contentElement.setAttribute('role','tabpanel');this._contentElement.createChild('content');this._tabs=[];this._tabsHistory=[];this._tabsById=new Map();this._currentTabLocked=false;this._autoSelectFirstItemOnShow=true;this._dropDownButton=this._createDropDownButton();UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._zoomChanged,this);} -setAccessibleName(name){UI.ARIAUtils.setAccessibleName(this._tabsElement,name);} -setCurrentTabLocked(locked){this._currentTabLocked=locked;this._headerElement.classList.toggle('locked',this._currentTabLocked);} -setAutoSelectFirstItemOnShow(autoSelect){this._autoSelectFirstItemOnShow=autoSelect;} -get visibleView(){return this._currentTab?this._currentTab.view:null;} -tabIds(){return this._tabs.map(tab=>tab._id);} -tabIndex(tabId){return this._tabs.findIndex(tab=>tab.id===tabId);} -tabViews(){return this._tabs.map(tab=>tab.view);} -tabView(tabId){return this._tabsById.has(tabId)?this._tabsById.get(tabId).view:null;} -get selectedTabId(){return this._currentTab?this._currentTab.id:null;} -setShrinkableTabs(shrinkableTabs){this._shrinkableTabs=shrinkableTabs;} -setVerticalTabLayout(verticalTabLayout){this._verticalTabLayout=verticalTabLayout;this.contentElement.classList.add('vertical-tab-layout');this.invalidateConstraints();} -setCloseableTabs(closeableTabs){this._closeableTabs=closeableTabs;} -focus(){if(this.visibleView) -this.visibleView.focus();else -this.contentElement.focus();} -headerElement(){return this._headerElement;} -isTabCloseable(id){var tab=this._tabsById.get(id);return tab?tab.isCloseable():false;} -setTabDelegate(delegate){var tabs=this._tabs.slice();for(var i=0;i<tabs.length;++i) -tabs[i].setDelegate(delegate);this._delegate=delegate;} -appendTab(id,tabTitle,view,tabTooltip,userGesture,isCloseable,index){isCloseable=typeof isCloseable==='boolean'?isCloseable:this._closeableTabs;var tab=new UI.TabbedPaneTab(this,id,tabTitle,isCloseable,view,tabTooltip);tab.setDelegate(this._delegate);console.assert(!this._tabsById.has(id),`Tabbed pane already contains a tab with id '${id}'`);this._tabsById.set(id,tab);if(index!==undefined) -this._tabs.splice(index,0,tab);else -this._tabs.push(tab);this._tabsHistory.push(tab);if(this._tabsHistory[0]===tab&&this.isShowing()) -this.selectTab(tab.id,userGesture);this._updateTabElements();} -closeTab(id,userGesture){this.closeTabs([id],userGesture);} -closeTabs(ids,userGesture){var focused=this.hasFocus();for(var i=0;i<ids.length;++i) -this._innerCloseTab(ids[i],userGesture);this._updateTabElements();if(this._tabsHistory.length) -this.selectTab(this._tabsHistory[0].id,false);if(focused) -this.focus();} -_innerCloseTab(id,userGesture){if(!this._tabsById.has(id)) -return;if(userGesture&&!this._tabsById.get(id)._closeable) -return;if(this._currentTab&&this._currentTab.id===id) -this._hideCurrentTab();var tab=this._tabsById.get(id);this._tabsById.delete(id);this._tabsHistory.splice(this._tabsHistory.indexOf(tab),1);this._tabs.splice(this._tabs.indexOf(tab),1);if(tab._shown) -this._hideTabElement(tab);var eventData={tabId:id,view:tab.view,isUserGesture:userGesture};this.dispatchEventToListeners(UI.TabbedPane.Events.TabClosed,eventData);return true;} -hasTab(tabId){return this._tabsById.has(tabId);} -allTabs(){return this._tabs.map(function(tab){return tab.id;});} -otherTabs(id){var result=[];for(var i=0;i<this._tabs.length;++i){if(this._tabs[i].id!==id) -result.push(this._tabs[i].id);} -return result;} -_tabsToTheRight(id){var index=-1;for(var i=0;i<this._tabs.length;++i){if(this._tabs[i].id===id){index=i;break;}} -if(index===-1) -return[];return this._tabs.slice(index+1).map(function(tab){return tab.id;});} -_viewHasFocus(){if(this.visibleView) -return this.visibleView.hasFocus();return this.contentElement===this.contentElement.getComponentRoot().activeElement;} -selectTab(id,userGesture){if(this._currentTabLocked) -return false;var focused=this._viewHasFocus();var tab=this._tabsById.get(id);if(!tab) -return false;if(this._currentTab&&this._currentTab.id===id) -return true;this.suspendInvalidations();this._hideCurrentTab();this._showTab(tab);this.resumeInvalidations();this._currentTab=tab;this._tabsHistory.splice(this._tabsHistory.indexOf(tab),1);this._tabsHistory.splice(0,0,tab);this._updateTabElements();if(focused) -this.focus();var eventData={tabId:id,view:tab.view,isUserGesture:userGesture};this.dispatchEventToListeners(UI.TabbedPane.Events.TabSelected,eventData);return true;} -selectNextTab(){var index=this._tabs.indexOf(this._currentTab);var nextIndex=mod(index+1,this._tabs.length);this.selectTab(this._tabs[nextIndex].id,true);} -selectPrevTab(){var index=this._tabs.indexOf(this._currentTab);var nextIndex=mod(index-1,this._tabs.length);this.selectTab(this._tabs[nextIndex].id,true);} -lastOpenedTabIds(tabsCount){function tabToTabId(tab){return tab.id;} -return this._tabsHistory.slice(0,tabsCount).map(tabToTabId);} -setTabIcon(id,icon){var tab=this._tabsById.get(id);tab._setIcon(icon);this._updateTabElements();} -setTabEnabled(id,enabled){var tab=this._tabsById.get(id);tab.tabElement.classList.toggle('disabled',!enabled);} -toggleTabClass(id,className,force){var tab=this._tabsById.get(id);if(tab._toggleClass(className,force)) -this._updateTabElements();} -_zoomChanged(event){for(var i=0;i<this._tabs.length;++i) -delete this._tabs[i]._measuredWidth;if(this.isShowing()) -this._updateTabElements();} -changeTabTitle(id,tabTitle,tabTooltip){var tab=this._tabsById.get(id);if(tabTooltip!==undefined) -tab.tooltip=tabTooltip;if(tab.title!==tabTitle){tab.title=tabTitle;this._updateTabElements();}} -changeTabView(id,view){var tab=this._tabsById.get(id);if(tab.view===view) -return;this.suspendInvalidations();var isSelected=this._currentTab&&this._currentTab.id===id;var shouldFocus=tab.view.hasFocus();if(isSelected) -this._hideTab(tab);tab.view=view;if(isSelected) -this._showTab(tab);if(shouldFocus) -tab.view.focus();this.resumeInvalidations();} -onResize(){this._updateTabElements();} -headerResized(){this._updateTabElements();} -wasShown(){var effectiveTab=this._currentTab||this._tabsHistory[0];if(effectiveTab&&this._autoSelectFirstItemOnShow) -this.selectTab(effectiveTab.id);} -setTabSlider(enable){this._sliderEnabled=enable;this._tabSlider.classList.toggle('enabled',enable);this._headerElement.classList.add('tabbed-pane-no-tab-borders');} -calculateConstraints(){var constraints=super.calculateConstraints();var minContentConstraints=new UI.Constraints(new UI.Size(0,0),new UI.Size(50,50));constraints=constraints.widthToMax(minContentConstraints).heightToMax(minContentConstraints);if(this._verticalTabLayout) -constraints=constraints.addWidth(new UI.Constraints(new UI.Size(120,0)));else -constraints=constraints.addHeight(new UI.Constraints(new UI.Size(0,30)));return constraints;} -_updateTabElements(){UI.invokeOnceAfterBatchUpdate(this,this._innerUpdateTabElements);} -setPlaceholderElement(element){this._placeholderElement=element;if(this._placeholderContainerElement){this._placeholderContainerElement.removeChildren();this._placeholderContainerElement.appendChild(element);}} -_innerUpdateTabElements(){if(!this.isShowing()) -return;if(!this._tabs.length){this._contentElement.classList.add('has-no-tabs');if(this._placeholderElement&&!this._placeholderContainerElement){this._placeholderContainerElement=this._contentElement.createChild('div','tabbed-pane-placeholder fill');this._placeholderContainerElement.appendChild(this._placeholderElement);}}else{this._contentElement.classList.remove('has-no-tabs');if(this._placeholderContainerElement){this._placeholderContainerElement.remove();delete this._placeholderContainerElement;}} -this._measureDropDownButton();this._updateWidths();this._updateTabsDropDown();this._updateTabSlider();} -_showTabElement(index,tab){if(index>=this._tabsElement.children.length) -this._tabsElement.appendChild(tab.tabElement);else -this._tabsElement.insertBefore(tab.tabElement,this._tabsElement.children[index]);tab._shown=true;} -_hideTabElement(tab){this._tabsElement.removeChild(tab.tabElement);tab._shown=false;} -_createDropDownButton(){var dropDownContainer=createElementWithClass('div','tabbed-pane-header-tabs-drop-down-container');var chevronIcon=UI.Icon.create('largeicon-chevron','chevron-icon');dropDownContainer.appendChild(chevronIcon);dropDownContainer.addEventListener('click',this._onDropDownMouseDown.bind(this));dropDownContainer.addEventListener('mousedown',this._onDropDownMouseDown.bind(this));return dropDownContainer;} -_onDropDownMouseDown(event){if(event.which!==1) -return;var rect=this._dropDownButton.getBoundingClientRect();var menu=new UI.ContextMenu(event,false,rect.left,rect.bottom);for(var i=0;i<this._tabs.length;++i){var tab=this._tabs[i];if(tab._shown) -continue;menu.defaultSection().appendCheckboxItem(tab.title,this._dropDownMenuItemSelected.bind(this,tab),this._tabsHistory[0]===tab);} -menu.show();} -_dropDownMenuItemSelected(tab){this._lastSelectedOverflowTab=tab;this.selectTab(tab.id,true);} -_totalWidth(){return this._headerContentsElement.getBoundingClientRect().width;} -_numberOfTabsShown(){var numTabsShown=0;for(var tab of this._tabs){if(tab._shown) -numTabsShown++;} -return numTabsShown;} -disableOverflowMenu(){this._overflowDisabled=true;} -_updateTabsDropDown(){var tabsToShowIndexes=this._tabsToShowIndexes(this._tabs,this._tabsHistory,this._totalWidth(),this._measuredDropDownButtonWidth||0);if(this._lastSelectedOverflowTab&&this._numberOfTabsShown()!==tabsToShowIndexes.length){delete this._lastSelectedOverflowTab;this._updateTabsDropDown();return;} -for(var i=0;i<this._tabs.length;++i){if(this._tabs[i]._shown&&tabsToShowIndexes.indexOf(i)===-1) -this._hideTabElement(this._tabs[i]);} -for(var i=0;i<tabsToShowIndexes.length;++i){var tab=this._tabs[tabsToShowIndexes[i]];if(!tab._shown) -this._showTabElement(i,tab);} -if(!this._overflowDisabled) -this._maybeShowDropDown(tabsToShowIndexes.length!==this._tabs.length);} -_maybeShowDropDown(hasMoreTabs){if(hasMoreTabs&&!this._dropDownButton.parentElement) -this._headerContentsElement.appendChild(this._dropDownButton);else if(!hasMoreTabs&&this._dropDownButton.parentElement) -this._headerContentsElement.removeChild(this._dropDownButton);} -_measureDropDownButton(){if(this._overflowDisabled||this._measuredDropDownButtonWidth) -return;this._dropDownButton.classList.add('measuring');this._headerContentsElement.appendChild(this._dropDownButton);this._measuredDropDownButtonWidth=this._dropDownButton.getBoundingClientRect().width;this._headerContentsElement.removeChild(this._dropDownButton);this._dropDownButton.classList.remove('measuring');} -_updateWidths(){var measuredWidths=this._measureWidths();var maxWidth=this._shrinkableTabs?this._calculateMaxWidth(measuredWidths.slice(),this._totalWidth()):Number.MAX_VALUE;var i=0;for(var tab of this._tabs) -tab.setWidth(this._verticalTabLayout?-1:Math.min(maxWidth,measuredWidths[i++]));} -_measureWidths(){this._tabsElement.style.setProperty('width','2000px');var measuringTabElements=[];for(var tab of this._tabs){if(typeof tab._measuredWidth==='number') -continue;var measuringTabElement=tab._createTabElement(true);measuringTabElement.__tab=tab;measuringTabElements.push(measuringTabElement);this._tabsElement.appendChild(measuringTabElement);} -for(var i=0;i<measuringTabElements.length;++i){var width=measuringTabElements[i].getBoundingClientRect().width;measuringTabElements[i].__tab._measuredWidth=Math.ceil(width);} -for(var i=0;i<measuringTabElements.length;++i) -measuringTabElements[i].remove();var measuredWidths=[];for(var tab of this._tabs) -measuredWidths.push(tab._measuredWidth);this._tabsElement.style.removeProperty('width');return measuredWidths;} -_calculateMaxWidth(measuredWidths,totalWidth){if(!measuredWidths.length) -return 0;measuredWidths.sort(function(x,y){return x-y;});var totalMeasuredWidth=0;for(var i=0;i<measuredWidths.length;++i) -totalMeasuredWidth+=measuredWidths[i];if(totalWidth>=totalMeasuredWidth) -return measuredWidths[measuredWidths.length-1];var totalExtraWidth=0;for(var i=measuredWidths.length-1;i>0;--i){var extraWidth=measuredWidths[i]-measuredWidths[i-1];totalExtraWidth+=(measuredWidths.length-i)*extraWidth;if(totalWidth+totalExtraWidth>=totalMeasuredWidth){return measuredWidths[i-1]+ -(totalWidth+totalExtraWidth-totalMeasuredWidth)/(measuredWidths.length-i);}} -return totalWidth/measuredWidths.length;} -_tabsToShowIndexes(tabsOrdered,tabsHistory,totalWidth,measuredDropDownButtonWidth){var tabsToShowIndexes=[];var totalTabsWidth=0;var tabCount=tabsOrdered.length;var tabsToLookAt=tabsOrdered.slice(0);if(this._currentTab!==undefined) -tabsToLookAt.unshift(tabsToLookAt.splice(tabsToLookAt.indexOf(this._currentTab),1)[0]);if(this._lastSelectedOverflowTab!==undefined) -tabsToLookAt.unshift(tabsToLookAt.splice(tabsToLookAt.indexOf(this._lastSelectedOverflowTab),1)[0]);for(var i=0;i<tabCount;++i){var tab=this._automaticReorder?tabsHistory[i]:tabsToLookAt[i];totalTabsWidth+=tab.width();var minimalRequiredWidth=totalTabsWidth;if(i!==tabCount-1) -minimalRequiredWidth+=measuredDropDownButtonWidth;if(!this._verticalTabLayout&&minimalRequiredWidth>totalWidth) -break;tabsToShowIndexes.push(tabsOrdered.indexOf(tab));} -tabsToShowIndexes.sort(function(x,y){return x-y;});return tabsToShowIndexes;} -_hideCurrentTab(){if(!this._currentTab) -return;this._hideTab(this._currentTab);delete this._currentTab;} -_showTab(tab){tab.tabElement.tabIndex=0;tab.tabElement.classList.add('selected');UI.ARIAUtils.setSelected(tab.tabElement,true);tab.view.show(this.element);this._updateTabSlider();} -_updateTabSlider(){if(!this._currentTab||!this._sliderEnabled) -return;var left=0;for(var i=0;i<this._tabs.length&&this._currentTab!==this._tabs[i];i++){if(this._tabs[i]._shown) -left+=this._tabs[i]._measuredWidth;} -var sliderWidth=this._currentTab._shown?this._currentTab._measuredWidth:this._dropDownButton.offsetWidth;var scaleFactor=window.devicePixelRatio>=1.5?' scaleY(0.75)':'';this._tabSlider.style.transform='translateX('+left+'px)'+scaleFactor;this._tabSlider.style.width=sliderWidth+'px';if(this._tabSlider.parentElement!==this._headerContentsElement) -this._headerContentsElement.appendChild(this._tabSlider);} -_hideTab(tab){tab.tabElement.removeAttribute('tabIndex');tab.tabElement.classList.remove('selected');tab.tabElement.setAttribute('aria-selected','false');tab.view.detach();} -elementsToRestoreScrollPositionsFor(){return[this._contentElement];} -_insertBefore(tab,index){this._tabsElement.insertBefore(tab.tabElement,this._tabsElement.childNodes[index]);var oldIndex=this._tabs.indexOf(tab);this._tabs.splice(oldIndex,1);if(oldIndex<index) ---index;this._tabs.splice(index,0,tab);this.dispatchEventToListeners(UI.TabbedPane.Events.TabOrderChanged,this._tabs);} -leftToolbar(){if(!this._leftToolbar){this._leftToolbar=new UI.Toolbar('tabbed-pane-left-toolbar');this._headerElement.insertBefore(this._leftToolbar.element,this._headerElement.firstChild);} -return this._leftToolbar;} -rightToolbar(){if(!this._rightToolbar){this._rightToolbar=new UI.Toolbar('tabbed-pane-right-toolbar');this._headerElement.appendChild(this._rightToolbar.element);} -return this._rightToolbar;} -renderWithNoHeaderBackground(){this._headerElement.classList.add('tabbed-pane-no-header-background');} -setAllowTabReorder(allow,automatic){this._allowTabReorder=allow;this._automaticReorder=automatic;} -_keyDown(event){if(!this._currentTab) -return;var nextTabElement=null;switch(event.key){case'ArrowUp':case'ArrowLeft':nextTabElement=this._currentTab.tabElement.previousElementSibling;if(!nextTabElement&&!this._dropDownButton.parentElement) -nextTabElement=this._currentTab.tabElement.parentElement.lastElementChild;break;case'ArrowDown':case'ArrowRight':nextTabElement=this._currentTab.tabElement.nextElementSibling;if(!nextTabElement&&!this._dropDownButton.parentElement) -nextTabElement=this._currentTab.tabElement.parentElement.firstElementChild;break;case'Enter':case'Space':this._currentTab.view.focus();return;default:return;} -if(!nextTabElement){this._dropDownButton.click();return;} -var tab=this._tabs.find(tab=>tab.tabElement===nextTabElement);this.selectTab(tab.id,true);nextTabElement.focus();}};UI.TabbedPane.Events={TabSelected:Symbol('TabSelected'),TabClosed:Symbol('TabClosed'),TabOrderChanged:Symbol('TabOrderChanged')};UI.TabbedPaneTab=class{constructor(tabbedPane,id,title,closeable,view,tooltip){this._closeable=closeable;this._tabbedPane=tabbedPane;this._id=id;this._title=title;this._tooltip=tooltip;this._view=view;this._shown=false;this._measuredWidth;this._tabElement;this._iconContainer=null;} -get id(){return this._id;} -get title(){return this._title;} -set title(title){if(title===this._title) -return;this._title=title;if(this._titleElement) -this._titleElement.textContent=title;delete this._measuredWidth;} -isCloseable(){return this._closeable;} -_setIcon(icon){this._icon=icon;if(this._tabElement) -this._createIconElement(this._tabElement,this._titleElement,false);delete this._measuredWidth;} -_toggleClass(className,force){var element=this.tabElement;var hasClass=element.classList.contains(className);if(hasClass===force) -return false;element.classList.toggle(className,force);delete this._measuredWidth;return true;} -get view(){return this._view;} -set view(view){this._view=view;} -get tooltip(){return this._tooltip;} -set tooltip(tooltip){this._tooltip=tooltip;if(this._titleElement) -this._titleElement.title=tooltip||'';} -get tabElement(){if(!this._tabElement) -this._tabElement=this._createTabElement(false);return this._tabElement;} -width(){return this._width;} -setWidth(width){this.tabElement.style.width=width===-1?'':(width+'px');this._width=width;} -setDelegate(delegate){this._delegate=delegate;} -_createIconElement(tabElement,titleElement,measuring){if(tabElement.__iconElement){tabElement.__iconElement.remove();tabElement.__iconElement=null;} -if(!this._icon) -return;var iconContainer=createElementWithClass('span','tabbed-pane-header-tab-icon');var iconNode=measuring?this._icon.cloneNode(true):this._icon;iconContainer.appendChild(iconNode);tabElement.insertBefore(iconContainer,titleElement);tabElement.__iconElement=iconContainer;} -_createTabElement(measuring){var tabElement=createElementWithClass('div','tabbed-pane-header-tab');tabElement.id='tab-'+this._id;UI.ARIAUtils.markAsTab(tabElement);UI.ARIAUtils.setSelected(tabElement,false);var titleElement=tabElement.createChild('span','tabbed-pane-header-tab-title');titleElement.textContent=this.title;titleElement.title=this.tooltip||'';this._createIconElement(tabElement,titleElement,measuring);if(!measuring) -this._titleElement=titleElement;if(this._closeable) -tabElement.createChild('div','tabbed-pane-close-button','dt-close-button').gray=true;if(measuring){tabElement.classList.add('measuring');}else{tabElement.addEventListener('click',this._tabClicked.bind(this),false);tabElement.addEventListener('auxclick',this._tabClicked.bind(this),false);tabElement.addEventListener('mousedown',this._tabMouseDown.bind(this),false);tabElement.addEventListener('mouseup',this._tabMouseUp.bind(this),false);tabElement.addEventListener('contextmenu',this._tabContextMenu.bind(this),false);if(this._tabbedPane._allowTabReorder){UI.installDragHandle(tabElement,this._startTabDragging.bind(this),this._tabDragging.bind(this),this._endTabDragging.bind(this),'-webkit-grabbing','pointer',200);}} -return tabElement;} -_tabClicked(event){var middleButton=event.button===1;var shouldClose=this._closeable&&(middleButton||event.target.classList.contains('tabbed-pane-close-button'));if(!shouldClose){this._tabbedPane.focus();return;} -this._closeTabs([this.id]);event.consume(true);} -_tabMouseDown(event){if(event.target.classList.contains('tabbed-pane-close-button')||event.button===1) -return;this._tabbedPane.selectTab(this.id,true);} -_tabMouseUp(event){if(event.button===1) -event.consume(true);} -_closeTabs(ids){if(this._delegate){this._delegate.closeTabs(this._tabbedPane,ids);return;} -this._tabbedPane.closeTabs(ids,true);} -_tabContextMenu(event){function close(){this._closeTabs([this.id]);} -function closeOthers(){this._closeTabs(this._tabbedPane.otherTabs(this.id));} -function closeAll(){this._closeTabs(this._tabbedPane.allTabs());} -function closeToTheRight(){this._closeTabs(this._tabbedPane._tabsToTheRight(this.id));} -var contextMenu=new UI.ContextMenu(event);if(this._closeable){contextMenu.defaultSection().appendItem(Common.UIString('Close'),close.bind(this));contextMenu.defaultSection().appendItem(Common.UIString('Close others'),closeOthers.bind(this));contextMenu.defaultSection().appendItem(Common.UIString('Close tabs to the right'),closeToTheRight.bind(this));contextMenu.defaultSection().appendItem(Common.UIString('Close all'),closeAll.bind(this));} -if(this._delegate) -this._delegate.onContextMenu(this.id,contextMenu);contextMenu.show();} -_startTabDragging(event){if(event.target.classList.contains('tabbed-pane-close-button')) -return false;this._dragStartX=event.pageX;this._tabElement.classList.add('dragging');this._tabbedPane._tabSlider.remove();return true;} -_tabDragging(event){var tabElements=this._tabbedPane._tabsElement.childNodes;for(var i=0;i<tabElements.length;++i){var tabElement=tabElements[i];if(tabElement===this._tabElement) -continue;var intersects=tabElement.offsetLeft+tabElement.clientWidth>this._tabElement.offsetLeft&&this._tabElement.offsetLeft+this._tabElement.clientWidth>tabElement.offsetLeft;if(!intersects) -continue;if(Math.abs(event.pageX-this._dragStartX)<tabElement.clientWidth/2+5) -break;if(event.pageX-this._dragStartX>0){tabElement=tabElement.nextSibling;++i;} -var oldOffsetLeft=this._tabElement.offsetLeft;this._tabbedPane._insertBefore(this,i);this._dragStartX+=this._tabElement.offsetLeft-oldOffsetLeft;break;} -if(!this._tabElement.previousSibling&&event.pageX-this._dragStartX<0){this._tabElement.style.setProperty('left','0px');return;} -if(!this._tabElement.nextSibling&&event.pageX-this._dragStartX>0){this._tabElement.style.setProperty('left','0px');return;} -this._tabElement.style.setProperty('left',(event.pageX-this._dragStartX)+'px');} -_endTabDragging(event){this._tabElement.classList.remove('dragging');this._tabElement.style.removeProperty('left');delete this._dragStartX;this._tabbedPane._updateTabSlider();}};UI.TabbedPaneTabDelegate=function(){};UI.TabbedPaneTabDelegate.prototype={closeTabs(tabbedPane,ids){},onContextMenu(tabId,contextMenu){}};;UI.highlightedSearchResultClassName='highlighted-search-result';UI.highlightedCurrentSearchResultClassName='current-search-result';UI.installDragHandle=function(element,elementDragStart,elementDrag,elementDragEnd,cursor,hoverCursor,startDelay){function onMouseDown(event){var dragHandler=new UI.DragHandler();var dragStart=dragHandler.elementDragStart.bind(dragHandler,element,elementDragStart,elementDrag,elementDragEnd,cursor,event);if(startDelay) -startTimer=setTimeout(dragStart,startDelay);else -dragStart();} -function onMouseUp(){if(startTimer) -clearTimeout(startTimer);startTimer=null;} -var startTimer;element.addEventListener('mousedown',onMouseDown,false);if(startDelay) -element.addEventListener('mouseup',onMouseUp,false);if(hoverCursor!==null) -element.style.cursor=hoverCursor||cursor||'';};UI.elementDragStart=function(targetElement,elementDragStart,elementDrag,elementDragEnd,cursor,event){var dragHandler=new UI.DragHandler();dragHandler.elementDragStart(targetElement,elementDragStart,elementDrag,elementDragEnd,cursor,event);};UI.DragHandler=class{constructor(){this._elementDragMove=this._elementDragMove.bind(this);this._elementDragEnd=this._elementDragEnd.bind(this);this._mouseOutWhileDragging=this._mouseOutWhileDragging.bind(this);} -_createGlassPane(){this._glassPaneInUse=true;if(!UI.DragHandler._glassPaneUsageCount++){UI.DragHandler._glassPane=new UI.GlassPane();UI.DragHandler._glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);UI.DragHandler._glassPane.show(UI.DragHandler._documentForMouseOut);}} -_disposeGlassPane(){if(!this._glassPaneInUse) -return;this._glassPaneInUse=false;if(--UI.DragHandler._glassPaneUsageCount) -return;UI.DragHandler._glassPane.hide();delete UI.DragHandler._glassPane;delete UI.DragHandler._documentForMouseOut;} -elementDragStart(targetElement,elementDragStart,elementDrag,elementDragEnd,cursor,event){if(event.button||(Host.isMac()&&event.ctrlKey)) -return;if(this._elementDraggingEventListener) -return;if(elementDragStart&&!elementDragStart((event))) -return;var targetDocument=event.target.ownerDocument;this._elementDraggingEventListener=elementDrag;this._elementEndDraggingEventListener=elementDragEnd;console.assert((UI.DragHandler._documentForMouseOut||targetDocument)===targetDocument,'Dragging on multiple documents.');UI.DragHandler._documentForMouseOut=targetDocument;this._dragEventsTargetDocument=targetDocument;this._dragEventsTargetDocumentTop=targetDocument.defaultView.top.document;targetDocument.addEventListener('mousemove',this._elementDragMove,true);targetDocument.addEventListener('mouseup',this._elementDragEnd,true);targetDocument.addEventListener('mouseout',this._mouseOutWhileDragging,true);if(targetDocument!==this._dragEventsTargetDocumentTop) -this._dragEventsTargetDocumentTop.addEventListener('mouseup',this._elementDragEnd,true);if(typeof cursor==='string'){this._restoreCursorAfterDrag=restoreCursor.bind(this,targetElement.style.cursor);targetElement.style.cursor=cursor;targetDocument.body.style.cursor=cursor;} -function restoreCursor(oldCursor){targetDocument.body.style.removeProperty('cursor');targetElement.style.cursor=oldCursor;this._restoreCursorAfterDrag=null;} -event.preventDefault();} -_mouseOutWhileDragging(){this._unregisterMouseOutWhileDragging();this._createGlassPane();} -_unregisterMouseOutWhileDragging(){if(!UI.DragHandler._documentForMouseOut) -return;UI.DragHandler._documentForMouseOut.removeEventListener('mouseout',this._mouseOutWhileDragging,true);} -_unregisterDragEvents(){if(!this._dragEventsTargetDocument) -return;this._dragEventsTargetDocument.removeEventListener('mousemove',this._elementDragMove,true);this._dragEventsTargetDocument.removeEventListener('mouseup',this._elementDragEnd,true);if(this._dragEventsTargetDocument!==this._dragEventsTargetDocumentTop) -this._dragEventsTargetDocumentTop.removeEventListener('mouseup',this._elementDragEnd,true);delete this._dragEventsTargetDocument;delete this._dragEventsTargetDocumentTop;} -_elementDragMove(event){if(event.buttons!==1){this._elementDragEnd(event);return;} -if(this._elementDraggingEventListener((event))) -this._cancelDragEvents(event);} -_cancelDragEvents(event){this._unregisterDragEvents();this._unregisterMouseOutWhileDragging();if(this._restoreCursorAfterDrag) -this._restoreCursorAfterDrag();this._disposeGlassPane();delete this._elementDraggingEventListener;delete this._elementEndDraggingEventListener;} -_elementDragEnd(event){var elementDragEnd=this._elementEndDraggingEventListener;this._cancelDragEvents((event));event.preventDefault();if(elementDragEnd) -elementDragEnd((event));}};UI.DragHandler._glassPaneUsageCount=0;UI.isBeingEdited=function(node){if(!node||node.nodeType!==Node.ELEMENT_NODE) -return false;var element=(node);if(element.classList.contains('text-prompt')||element.nodeName==='INPUT'||element.nodeName==='TEXTAREA') -return true;if(!UI.__editingCount) -return false;while(element){if(element.__editing) -return true;element=element.parentElementOrShadowHost();} -return false;};UI.isEditing=function(){if(UI.__editingCount) -return true;var focused=document.deepActiveElement();if(!focused) -return false;return focused.classList.contains('text-prompt')||focused.nodeName==='INPUT'||focused.nodeName==='TEXTAREA';};UI.markBeingEdited=function(element,value){if(value){if(element.__editing) -return false;element.classList.add('being-edited');element.__editing=true;UI.__editingCount=(UI.__editingCount||0)+1;}else{if(!element.__editing) -return false;element.classList.remove('being-edited');delete element.__editing;--UI.__editingCount;} -return true;};UI.CSSNumberRegex=/^(-?(?:\d+(?:\.\d+)?|\.\d+))$/;UI.StyleValueDelimiters=' \xA0\t\n"\':;,/()';UI._valueModificationDirection=function(event){var direction=null;if(event.type==='mousewheel'){if(event.wheelDeltaY>0||event.wheelDeltaX>0) -direction='Up';else if(event.wheelDeltaY<0||event.wheelDeltaX<0) -direction='Down';}else{if(event.key==='ArrowUp'||event.key==='PageUp') -direction='Up';else if(event.key==='ArrowDown'||event.key==='PageDown') -direction='Down';} -return direction;};UI._modifiedHexValue=function(hexString,event){var direction=UI._valueModificationDirection(event);if(!direction) -return null;var mouseEvent=(event);var number=parseInt(hexString,16);if(isNaN(number)||!isFinite(number)) -return null;var hexStrLen=hexString.length;var channelLen=hexStrLen/3;if(channelLen!==1&&channelLen!==2) -return null;var delta=0;if(UI.KeyboardShortcut.eventHasCtrlOrMeta(mouseEvent)) -delta+=Math.pow(16,channelLen*2);if(mouseEvent.shiftKey) -delta+=Math.pow(16,channelLen);if(mouseEvent.altKey) -delta+=1;if(delta===0) -delta=1;if(direction==='Down') -delta*=-1;var maxValue=Math.pow(16,hexStrLen)-1;var result=Number.constrain(number+delta,0,maxValue);var resultString=result.toString(16).toUpperCase();for(var i=0,lengthDelta=hexStrLen-resultString.length;i<lengthDelta;++i) -resultString='0'+resultString;return resultString;};UI._modifiedFloatNumber=function(number,event){var direction=UI._valueModificationDirection(event);if(!direction) -return null;var mouseEvent=(event);var delta=1;if(UI.KeyboardShortcut.eventHasCtrlOrMeta(mouseEvent)) -delta=100;else if(mouseEvent.shiftKey) -delta=10;else if(mouseEvent.altKey) -delta=0.1;if(direction==='Down') -delta*=-1;var result=Number((number+delta).toFixed(6));if(!String(result).match(UI.CSSNumberRegex)) -return null;return result;};UI.createReplacementString=function(wordString,event,customNumberHandler){var prefix;var suffix;var number;var replacementString=null;var matches=/(.*#)([\da-fA-F]+)(.*)/.exec(wordString);if(matches&&matches.length){prefix=matches[1];suffix=matches[3];number=UI._modifiedHexValue(matches[2],event);if(number!==null) -replacementString=prefix+number+suffix;}else{matches=/(.*?)(-?(?:\d+(?:\.\d+)?|\.\d+))(.*)/.exec(wordString);if(matches&&matches.length){prefix=matches[1];suffix=matches[3];number=UI._modifiedFloatNumber(parseFloat(matches[2]),event);if(number!==null){replacementString=customNumberHandler?customNumberHandler(prefix,number,suffix):prefix+number+suffix;}}} -return replacementString;};UI.handleElementValueModifications=function(event,element,finishHandler,suggestionHandler,customNumberHandler){function createRange(){return document.createRange();} -var arrowKeyOrMouseWheelEvent=(event.key==='ArrowUp'||event.key==='ArrowDown'||event.type==='mousewheel');var pageKeyPressed=(event.key==='PageUp'||event.key==='PageDown');if(!arrowKeyOrMouseWheelEvent&&!pageKeyPressed) -return false;var selection=element.getComponentSelection();if(!selection.rangeCount) -return false;var selectionRange=selection.getRangeAt(0);if(!selectionRange.commonAncestorContainer.isSelfOrDescendant(element)) -return false;var originalValue=element.textContent;var wordRange=selectionRange.startContainer.rangeOfWord(selectionRange.startOffset,UI.StyleValueDelimiters,element);var wordString=wordRange.toString();if(suggestionHandler&&suggestionHandler(wordString)) -return false;var replacementString=UI.createReplacementString(wordString,event,customNumberHandler);if(replacementString){var replacementTextNode=createTextNode(replacementString);wordRange.deleteContents();wordRange.insertNode(replacementTextNode);var finalSelectionRange=createRange();finalSelectionRange.setStart(replacementTextNode,0);finalSelectionRange.setEnd(replacementTextNode,replacementString.length);selection.removeAllRanges();selection.addRange(finalSelectionRange);event.handled=true;event.preventDefault();if(finishHandler) -finishHandler(originalValue,replacementString);return true;} -return false;};Number.preciseMillisToString=function(ms,precision){precision=precision||0;var format='%.'+precision+'f\xa0ms';return Common.UIString(format,ms);};UI._microsFormat=new Common.UIStringFormat('%.0f\xa0\u03bcs');UI._subMillisFormat=new Common.UIStringFormat('%.2f\xa0ms');UI._millisFormat=new Common.UIStringFormat('%.0f\xa0ms');UI._secondsFormat=new Common.UIStringFormat('%.2f\xa0s');UI._minutesFormat=new Common.UIStringFormat('%.1f\xa0min');UI._hoursFormat=new Common.UIStringFormat('%.1f\xa0hrs');UI._daysFormat=new Common.UIStringFormat('%.1f\xa0days');Number.millisToString=function(ms,higherResolution){if(!isFinite(ms)) -return'-';if(ms===0) -return'0';if(higherResolution&&ms<0.1) -return UI._microsFormat.format(ms*1000);if(higherResolution&&ms<1000) -return UI._subMillisFormat.format(ms);if(ms<1000) -return UI._millisFormat.format(ms);var seconds=ms/1000;if(seconds<60) -return UI._secondsFormat.format(seconds);var minutes=seconds/60;if(minutes<60) -return UI._minutesFormat.format(minutes);var hours=minutes/60;if(hours<24) -return UI._hoursFormat.format(hours);var days=hours/24;return UI._daysFormat.format(days);};Number.secondsToString=function(seconds,higherResolution){if(!isFinite(seconds)) -return'-';return Number.millisToString(seconds*1000,higherResolution);};Number.bytesToString=function(bytes){if(bytes<1024) -return Common.UIString('%.0f\xa0B',bytes);var kilobytes=bytes/1024;if(kilobytes<100) -return Common.UIString('%.1f\xa0KB',kilobytes);if(kilobytes<1024) -return Common.UIString('%.0f\xa0KB',kilobytes);var megabytes=kilobytes/1024;if(megabytes<100) -return Common.UIString('%.1f\xa0MB',megabytes);else -return Common.UIString('%.0f\xa0MB',megabytes);};Number.withThousandsSeparator=function(num){var str=num+'';var re=/(\d+)(\d{3})/;while(str.match(re)) -str=str.replace(re,'$1\xa0$2');return str;};UI.formatLocalized=function(format,substitutions){var formatters={s:substitution=>substitution};function append(a,b){a.appendChild(typeof b==='string'?createTextNode(b):b);return a;} -return String.format(Common.UIString(format),substitutions,formatters,createElement('span'),append).formattedResult;};UI.openLinkExternallyLabel=function(){return Common.UIString('Open in new tab');};UI.copyLinkAddressLabel=function(){return Common.UIString('Copy link address');};UI.anotherProfilerActiveLabel=function(){return Common.UIString('Another profiler is already active');};UI.asyncStackTraceLabel=function(description){if(description){if(description==='Promise.resolve') -description=Common.UIString('Promise resolved');else if(description==='Promise.reject') -description=Common.UIString('Promise rejected');return description+' '+Common.UIString('(async)');} -return Common.UIString('Async Call');};UI.installComponentRootStyles=function(element){UI.appendStyle(element,'ui/inspectorCommon.css');UI.themeSupport.injectHighlightStyleSheets(element);UI.themeSupport.injectCustomStyleSheets(element);element.classList.add('platform-'+Host.platform());function overlayScrollbarEnabled(document){var scrollDiv=document.createElement('div');scrollDiv.setAttribute('style','width: 100px; height: 100px; overflow: scroll;');document.body.appendChild(scrollDiv);var scrollbarWidth=scrollDiv.offsetWidth-scrollDiv.clientWidth;document.body.removeChild(scrollDiv);return scrollbarWidth===0;} -if(!Host.isMac()&&overlayScrollbarEnabled(element.ownerDocument)) -element.classList.add('overlay-scrollbar-enabled');};UI.createShadowRootWithCoreStyles=function(element,cssFile){var shadowRoot=element.createShadowRoot();UI.appendStyle(shadowRoot,'ui/inspectorCommon.css');UI.themeSupport.injectHighlightStyleSheets(shadowRoot);UI.themeSupport.injectCustomStyleSheets(shadowRoot);if(cssFile) -UI.appendStyle(shadowRoot,cssFile);shadowRoot.addEventListener('focus',UI._focusChanged.bind(UI),true);return shadowRoot;};UI._windowFocused=function(document,event){if(event.target.document.nodeType===Node.DOCUMENT_NODE) -document.body.classList.remove('inactive');UI._keyboardFocus=true;var listener=()=>{var activeElement=document.deepActiveElement();if(activeElement) -activeElement.removeAttribute('data-keyboard-focus');UI._keyboardFocus=false;};document.defaultView.requestAnimationFrame(()=>{UI._keyboardFocus=false;document.removeEventListener('mousedown',listener,true);});document.addEventListener('mousedown',listener,true);};UI._windowBlurred=function(document,event){if(event.target.document.nodeType===Node.DOCUMENT_NODE) -document.body.classList.add('inactive');};UI._focusChanged=function(event){var document=event.target&&event.target.ownerDocument;var element=document?document.deepActiveElement():null;UI.Widget.focusWidgetForNode(element);if(!UI._keyboardFocus) -return;element.setAttribute('data-keyboard-focus','true');element.addEventListener('blur',()=>element.removeAttribute('data-keyboard-focus'),{once:true,capture:true});};UI.ElementFocusRestorer=class{constructor(element){this._element=element;this._previous=element.ownerDocument.deepActiveElement();element.focus();} -restore(){if(!this._element) -return;if(this._element.hasFocus()&&this._previous) -this._previous.focus();this._previous=null;this._element=null;}};UI.highlightSearchResult=function(element,offset,length,domChanges){var result=UI.highlightSearchResults(element,[new TextUtils.SourceRange(offset,length)],domChanges);return result.length?result[0]:null;};UI.highlightSearchResults=function(element,resultRanges,changes){return UI.highlightRangesWithStyleClass(element,resultRanges,UI.highlightedSearchResultClassName,changes);};UI.runCSSAnimationOnce=function(element,className){function animationEndCallback(){element.classList.remove(className);element.removeEventListener('webkitAnimationEnd',animationEndCallback,false);} -if(element.classList.contains(className)) -element.classList.remove(className);element.addEventListener('webkitAnimationEnd',animationEndCallback,false);element.classList.add(className);};UI.highlightRangesWithStyleClass=function(element,resultRanges,styleClass,changes){changes=changes||[];var highlightNodes=[];var textNodes=element.childTextNodes();var lineText=textNodes.map(function(node){return node.textContent;}).join('');var ownerDocument=element.ownerDocument;if(textNodes.length===0) -return highlightNodes;var nodeRanges=[];var rangeEndOffset=0;for(var i=0;i<textNodes.length;++i){var range={};range.offset=rangeEndOffset;range.length=textNodes[i].textContent.length;rangeEndOffset=range.offset+range.length;nodeRanges.push(range);} -var startIndex=0;for(var i=0;i<resultRanges.length;++i){var startOffset=resultRanges[i].offset;var endOffset=startOffset+resultRanges[i].length;while(startIndex<textNodes.length&&nodeRanges[startIndex].offset+nodeRanges[startIndex].length<=startOffset) -startIndex++;var endIndex=startIndex;while(endIndex<textNodes.length&&nodeRanges[endIndex].offset+nodeRanges[endIndex].length<endOffset) -endIndex++;if(endIndex===textNodes.length) -break;var highlightNode=ownerDocument.createElement('span');highlightNode.className=styleClass;highlightNode.textContent=lineText.substring(startOffset,endOffset);var lastTextNode=textNodes[endIndex];var lastText=lastTextNode.textContent;lastTextNode.textContent=lastText.substring(endOffset-nodeRanges[endIndex].offset);changes.push({node:lastTextNode,type:'changed',oldText:lastText,newText:lastTextNode.textContent});if(startIndex===endIndex){lastTextNode.parentElement.insertBefore(highlightNode,lastTextNode);changes.push({node:highlightNode,type:'added',nextSibling:lastTextNode,parent:lastTextNode.parentElement});highlightNodes.push(highlightNode);var prefixNode=ownerDocument.createTextNode(lastText.substring(0,startOffset-nodeRanges[startIndex].offset));lastTextNode.parentElement.insertBefore(prefixNode,highlightNode);changes.push({node:prefixNode,type:'added',nextSibling:highlightNode,parent:lastTextNode.parentElement});}else{var firstTextNode=textNodes[startIndex];var firstText=firstTextNode.textContent;var anchorElement=firstTextNode.nextSibling;firstTextNode.parentElement.insertBefore(highlightNode,anchorElement);changes.push({node:highlightNode,type:'added',nextSibling:anchorElement,parent:firstTextNode.parentElement});highlightNodes.push(highlightNode);firstTextNode.textContent=firstText.substring(0,startOffset-nodeRanges[startIndex].offset);changes.push({node:firstTextNode,type:'changed',oldText:firstText,newText:firstTextNode.textContent});for(var j=startIndex+1;j<endIndex;j++){var textNode=textNodes[j];var text=textNode.textContent;textNode.textContent='';changes.push({node:textNode,type:'changed',oldText:text,newText:textNode.textContent});}} -startIndex=endIndex;nodeRanges[startIndex].offset=endOffset;nodeRanges[startIndex].length=lastTextNode.textContent.length;} -return highlightNodes;};UI.applyDomChanges=function(domChanges){for(var i=0,size=domChanges.length;i<size;++i){var entry=domChanges[i];switch(entry.type){case'added':entry.parent.insertBefore(entry.node,entry.nextSibling);break;case'changed':entry.node.textContent=entry.newText;break;}}};UI.revertDomChanges=function(domChanges){for(var i=domChanges.length-1;i>=0;--i){var entry=domChanges[i];switch(entry.type){case'added':entry.node.remove();break;case'changed':entry.node.textContent=entry.oldText;break;}}};UI.measurePreferredSize=function(element,containerElement){var oldParent=element.parentElement;var oldNextSibling=element.nextSibling;containerElement=containerElement||element.ownerDocument.body;containerElement.appendChild(element);element.positionAt(0,0);var result=element.getBoundingClientRect();element.positionAt(undefined,undefined);if(oldParent) -oldParent.insertBefore(element,oldNextSibling);else -element.remove();return new UI.Size(result.width,result.height);};UI.InvokeOnceHandlers=class{constructor(autoInvoke){this._handlers=null;this._autoInvoke=autoInvoke;} -add(object,method){if(!this._handlers){this._handlers=new Map();if(this._autoInvoke) -this.scheduleInvoke();} -var methods=this._handlers.get(object);if(!methods){methods=new Set();this._handlers.set(object,methods);} -methods.add(method);} -scheduleInvoke(){if(this._handlers) -requestAnimationFrame(this._invoke.bind(this));} -_invoke(){var handlers=this._handlers;this._handlers=null;var keys=handlers.keysArray();for(var i=0;i<keys.length;++i){var object=keys[i];var methods=handlers.get(object).valuesArray();for(var j=0;j<methods.length;++j) -methods[j].call(object);}}};UI._coalescingLevel=0;UI._postUpdateHandlers=null;UI.startBatchUpdate=function(){if(!UI._coalescingLevel++) -UI._postUpdateHandlers=new UI.InvokeOnceHandlers(false);};UI.endBatchUpdate=function(){if(--UI._coalescingLevel) -return;UI._postUpdateHandlers.scheduleInvoke();UI._postUpdateHandlers=null;};UI.invokeOnceAfterBatchUpdate=function(object,method){if(!UI._postUpdateHandlers) -UI._postUpdateHandlers=new UI.InvokeOnceHandlers(true);UI._postUpdateHandlers.add(object,method);};UI.animateFunction=function(window,func,params,frames,animationComplete){var values=new Array(params.length);var deltas=new Array(params.length);for(var i=0;i<params.length;++i){values[i]=params[i].from;deltas[i]=(params[i].to-params[i].from)/frames;} -var raf=window.requestAnimationFrame(animationStep);var framesLeft=frames;function animationStep(){if(--framesLeft<0){if(animationComplete) -animationComplete();return;} -for(var i=0;i<params.length;++i){if(params[i].to>params[i].from) -values[i]=Number.constrain(values[i]+deltas[i],params[i].from,params[i].to);else -values[i]=Number.constrain(values[i]+deltas[i],params[i].to,params[i].from);} -func.apply(null,values);raf=window.requestAnimationFrame(animationStep);} -function cancelAnimation(){window.cancelAnimationFrame(raf);} -return cancelAnimation;};UI.LongClickController=class extends Common.Object{constructor(element,callback){super();this._element=element;this._callback=callback;this._enable();} -reset(){if(this._longClickInterval){clearInterval(this._longClickInterval);delete this._longClickInterval;}} -_enable(){if(this._longClickData) -return;var boundMouseDown=mouseDown.bind(this);var boundMouseUp=mouseUp.bind(this);var boundReset=this.reset.bind(this);this._element.addEventListener('mousedown',boundMouseDown,false);this._element.addEventListener('mouseout',boundReset,false);this._element.addEventListener('mouseup',boundMouseUp,false);this._element.addEventListener('click',boundReset,true);this._longClickData={mouseUp:boundMouseUp,mouseDown:boundMouseDown,reset:boundReset};function mouseDown(e){if(e.which!==1) -return;var callback=this._callback;this._longClickInterval=setTimeout(callback.bind(null,e),200);} -function mouseUp(e){if(e.which!==1) -return;this.reset();}} -dispose(){if(!this._longClickData) -return;this._element.removeEventListener('mousedown',this._longClickData.mouseDown,false);this._element.removeEventListener('mouseout',this._longClickData.reset,false);this._element.removeEventListener('mouseup',this._longClickData.mouseUp,false);this._element.addEventListener('click',this._longClickData.reset,true);delete this._longClickData;}};UI.initializeUIUtils=function(document,themeSetting){document.body.classList.toggle('inactive',!document.hasFocus());document.defaultView.addEventListener('focus',UI._windowFocused.bind(UI,document),false);document.defaultView.addEventListener('blur',UI._windowBlurred.bind(UI,document),false);document.addEventListener('focus',UI._focusChanged.bind(UI),true);document.addEventListener('keydown',event=>{UI._keyboardFocus=true;document.defaultView.requestAnimationFrame(()=>UI._keyboardFocus=false);},true);if(!UI.themeSupport) -UI.themeSupport=new UI.ThemeSupport(themeSetting);UI.themeSupport.applyTheme(document);var body=(document.body);UI.appendStyle(body,'ui/inspectorStyle.css');UI.GlassPane.setContainer((document.body));};UI.beautifyFunctionName=function(name){return name||Common.UIString('(anonymous)');};UI.registerCustomElement=function(localName,typeExtension,prototype){return document.registerElement(typeExtension,{prototype:Object.create(prototype),extends:localName});};UI.createTextButton=function(text,clickHandler,className,primary){var element=createElementWithClass('button',className||'','text-button');element.textContent=text;if(primary) -element.classList.add('primary-button');if(clickHandler) -element.addEventListener('click',clickHandler,false);return element;};UI.createInput=function(className,type){var element=createElementWithClass('input',className||'');element.spellcheck=false;element.classList.add('harmony-input');if(type) -element.type=type;return element;};UI.createRadioLabel=function(name,title,checked){var element=createElement('label','dt-radio');element.radioElement.name=name;element.radioElement.checked=!!checked;element.createTextChild(title);return element;};UI.createLabel=function(title,iconClass){var element=createElement('label','dt-icon-label');element.createChild('span').textContent=title;element.type=iconClass;return element;};UI.createSliderLabel=function(min,max,tabIndex){var element=createElement('label','dt-slider');element.sliderElement.min=min;element.sliderElement.max=max;element.sliderElement.step=1;element.sliderElement.tabIndex=tabIndex;return element;};UI.appendStyle=function(node,cssFile){var content=Runtime.cachedResources[cssFile]||'';if(!content) -console.error(cssFile+' not preloaded. Check module.json');var styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=content;node.appendChild(styleElement);var themeStyleSheet=UI.themeSupport.themeStyleSheet(cssFile,content);if(themeStyleSheet){styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=themeStyleSheet+'\n'+Runtime.resolveSourceURL(cssFile+'.theme');node.appendChild(styleElement);}};UI.CheckboxLabel=class extends HTMLLabelElement{constructor(){super();this._shadowRoot;this.checkboxElement;this.textElement;throw new Error('Checkbox must be created via factory method.');} -createdCallback(){UI.CheckboxLabel._lastId=(UI.CheckboxLabel._lastId||0)+1;var id='ui-checkbox-label'+UI.CheckboxLabel._lastId;this._shadowRoot=UI.createShadowRootWithCoreStyles(this,'ui/checkboxTextLabel.css');this.checkboxElement=(this._shadowRoot.createChild('input'));this.checkboxElement.type='checkbox';this.checkboxElement.setAttribute('id',id);this.textElement=this._shadowRoot.createChild('label','dt-checkbox-text');this.textElement.setAttribute('for',id);this._shadowRoot.createChild('content');} -static create(title,checked,subtitle){if(!UI.CheckboxLabel._constructor) -UI.CheckboxLabel._constructor=UI.registerCustomElement('label','dt-checkbox',UI.CheckboxLabel.prototype);var element=(new UI.CheckboxLabel._constructor());element.checkboxElement.checked=!!checked;if(title!==undefined){element.textElement.textContent=title;if(subtitle!==undefined) -element.textElement.createChild('div','dt-checkbox-subtitle').textContent=subtitle;} -return element;} -set backgroundColor(color){this.checkboxElement.classList.add('dt-checkbox-themed');this.checkboxElement.style.backgroundColor=color;} -set checkColor(color){this.checkboxElement.classList.add('dt-checkbox-themed');var stylesheet=createElement('style');stylesheet.textContent='input.dt-checkbox-themed:checked:after { background-color: '+color+'}';this._shadowRoot.appendChild(stylesheet);} -set borderColor(color){this.checkboxElement.classList.add('dt-checkbox-themed');this.checkboxElement.style.borderColor=color;}};(function(){UI.registerCustomElement('button','text-button',{createdCallback:function(){this.type='button';var root=UI.createShadowRootWithCoreStyles(this,'ui/textButton.css');root.createChild('content');},__proto__:HTMLButtonElement.prototype});UI.registerCustomElement('label','dt-radio',{createdCallback:function(){this.radioElement=this.createChild('input','dt-radio-button');this.radioElement.type='radio';var root=UI.createShadowRootWithCoreStyles(this,'ui/radioButton.css');root.createChild('content').select='.dt-radio-button';root.createChild('content');this.addEventListener('click',radioClickHandler,false);},__proto__:HTMLLabelElement.prototype});function radioClickHandler(event){if(this.radioElement.checked||this.radioElement.disabled) -return;this.radioElement.checked=true;this.radioElement.dispatchEvent(new Event('change'));} -UI.registerCustomElement('label','dt-icon-label',{createdCallback:function(){var root=UI.createShadowRootWithCoreStyles(this);this._iconElement=UI.Icon.create();this._iconElement.style.setProperty('margin-right','4px');root.appendChild(this._iconElement);root.createChild('content');},set type(type){this._iconElement.setIconType(type);},__proto__:HTMLLabelElement.prototype});UI.registerCustomElement('label','dt-slider',{createdCallback:function(){var root=UI.createShadowRootWithCoreStyles(this,'ui/slider.css');this.sliderElement=createElementWithClass('input','dt-range-input');this.sliderElement.type='range';root.appendChild(this.sliderElement);},set value(amount){this.sliderElement.value=amount;},get value(){return this.sliderElement.value;},__proto__:HTMLLabelElement.prototype});UI.registerCustomElement('label','dt-small-bubble',{createdCallback:function(){var root=UI.createShadowRootWithCoreStyles(this,'ui/smallBubble.css');this._textElement=root.createChild('div');this._textElement.className='info';this._textElement.createChild('content');},set type(type){this._textElement.className=type;},__proto__:HTMLLabelElement.prototype});UI.registerCustomElement('div','dt-close-button',{createdCallback:function(){var root=UI.createShadowRootWithCoreStyles(this,'ui/closeButton.css');this._buttonElement=root.createChild('div','close-button');var regularIcon=UI.Icon.create('smallicon-cross','default-icon');this._hoverIcon=UI.Icon.create('mediumicon-red-cross-hover','hover-icon');this._activeIcon=UI.Icon.create('mediumicon-red-cross-active','active-icon');this._buttonElement.appendChild(regularIcon);this._buttonElement.appendChild(this._hoverIcon);this._buttonElement.appendChild(this._activeIcon);},set gray(gray){if(gray){this._hoverIcon.setIconType('mediumicon-gray-cross-hover');this._activeIcon.setIconType('mediumicon-gray-cross-active');}else{this._hoverIcon.setIconType('mediumicon-red-cross-hover');this._activeIcon.setIconType('mediumicon-red-cross-active');}},__proto__:HTMLDivElement.prototype});})();UI.bindInput=function(input,apply,validate,numeric){input.addEventListener('change',onChange,false);input.addEventListener('input',onInput,false);input.addEventListener('keydown',onKeyDown,false);input.addEventListener('focus',input.select.bind(input),false);function onInput(){input.classList.toggle('error-input',!validate(input.value));} -function onChange(){var valid=validate(input.value);input.classList.toggle('error-input',!valid);if(valid) -apply(input.value);} -function onKeyDown(event){if(isEnterKey(event)){if(validate(input.value)) -apply(input.value);event.preventDefault();return;} -if(!numeric) -return;var increment=event.key==='ArrowUp'?1:event.key==='ArrowDown'?-1:0;if(!increment) -return;if(event.shiftKey) -increment*=10;var value=input.value;if(!validate(value)||!value) -return;value=(value?Number(value):0)+increment;var stringValue=value?String(value):'';if(!validate(stringValue)||!value) -return;input.value=stringValue;apply(input.value);event.preventDefault();} -function setValue(value){if(value===input.value) -return;var valid=validate(value);input.classList.toggle('error-input',!valid);input.value=value;} -return setValue;};UI.trimText=function(context,text,maxWidth,trimFunction){const maxLength=200;if(maxWidth<=10) -return'';if(text.length>maxLength) -text=trimFunction(text,maxLength);const textWidth=UI.measureTextWidth(context,text);if(textWidth<=maxWidth) -return text;var l=0;var r=text.length;var lv=0;var rv=textWidth;while(l<r&&lv!==rv&&lv!==maxWidth){const m=Math.ceil(l+(r-l)*(maxWidth-lv)/(rv-lv));const mv=UI.measureTextWidth(context,trimFunction(text,m));if(mv<=maxWidth){l=m;lv=mv;}else{r=m-1;rv=mv;}} -text=trimFunction(text,l);return text!=='\u2026'?text:'';};UI.trimTextMiddle=function(context,text,maxWidth){return UI.trimText(context,text,maxWidth,(text,width)=>text.trimMiddle(width));};UI.trimTextEnd=function(context,text,maxWidth){return UI.trimText(context,text,maxWidth,(text,width)=>text.trimEnd(width));};UI.measureTextWidth=function(context,text){const maxCacheableLength=200;if(text.length>maxCacheableLength) -return context.measureText(text).width;var widthCache=UI.measureTextWidth._textWidthCache;if(!widthCache){widthCache=new Map();UI.measureTextWidth._textWidthCache=widthCache;} -const font=context.font;var textWidths=widthCache.get(font);if(!textWidths){textWidths=new Map();widthCache.set(font,textWidths);} -var width=textWidths.get(text);if(!width){width=context.measureText(text).width;textWidths.set(text,width);} -return width;};UI.ThemeSupport=class{constructor(setting){this._themeName=setting.get()||'default';this._themableProperties=new Set(['color','box-shadow','text-shadow','outline-color','background-image','background-color','border-left-color','border-right-color','border-top-color','border-bottom-color','-webkit-border-image']);this._cachedThemePatches=new Map();this._setting=setting;this._customSheets=new Set();} -hasTheme(){return this._themeName!=='default';} -themeName(){return this._themeName;} -injectHighlightStyleSheets(element){this._injectingStyleSheet=true;UI.appendStyle(element,'ui/inspectorSyntaxHighlight.css');if(this._themeName==='dark') -UI.appendStyle(element,'ui/inspectorSyntaxHighlightDark.css');this._injectingStyleSheet=false;} -injectCustomStyleSheets(element){for(const sheet of this._customSheets){var styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=sheet;element.appendChild(styleElement);}} -addCustomStylesheet(sheetText){this._customSheets.add(sheetText);} -applyTheme(document){if(!this.hasTheme()) -return;if(this._themeName==='dark') -document.body.classList.add('-theme-with-dark-background');var styleSheets=document.styleSheets;var result=[];for(var i=0;i<styleSheets.length;++i) -result.push(this._patchForTheme(styleSheets[i].href,styleSheets[i]));result.push('/*# sourceURL=inspector.css.theme */');var styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=result.join('\n');document.head.appendChild(styleElement);} -themeStyleSheet(id,text){if(!this.hasTheme()||this._injectingStyleSheet) -return'';var patch=this._cachedThemePatches.get(id);if(!patch){var styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=text;document.body.appendChild(styleElement);patch=this._patchForTheme(id,styleElement.sheet);document.body.removeChild(styleElement);} -return patch;} -_patchForTheme(id,styleSheet){var cached=this._cachedThemePatches.get(id);if(cached) -return cached;try{var rules=styleSheet.cssRules;var result=[];for(var j=0;j<rules.length;++j){if(rules[j]instanceof CSSImportRule){result.push(this._patchForTheme(rules[j].styleSheet.href,rules[j].styleSheet));continue;} -var output=[];var style=rules[j].style;var selectorText=rules[j].selectorText;for(var i=0;style&&i<style.length;++i) -this._patchProperty(selectorText,style,style[i],output);if(output.length) -result.push(rules[j].selectorText+'{'+output.join('')+'}');} -var fullText=result.join('\n');this._cachedThemePatches.set(id,fullText);return fullText;}catch(e){this._setting.set('default');return'';}} -_patchProperty(selectorText,style,name,output){if(!this._themableProperties.has(name)) -return;var value=style.getPropertyValue(name);if(!value||value==='none'||value==='inherit'||value==='initial'||value==='transparent') -return;if(name==='background-image'&&value.indexOf('gradient')===-1) -return;var isSelection=selectorText.indexOf('.-theme-selection-color')!==-1;if(selectorText.indexOf('-theme-')!==-1&&!isSelection) -return;if(name==='-webkit-border-image'){output.push('-webkit-filter: invert(100%)');return;} -isSelection=isSelection||selectorText.indexOf('selected')!==-1||selectorText.indexOf('.selection')!==-1;var colorUsage=UI.ThemeSupport.ColorUsage.Unknown;if(isSelection) -colorUsage|=UI.ThemeSupport.ColorUsage.Selection;if(name.indexOf('background')===0||name.indexOf('border')===0) -colorUsage|=UI.ThemeSupport.ColorUsage.Background;if(name.indexOf('background')===-1) -colorUsage|=UI.ThemeSupport.ColorUsage.Foreground;output.push(name);output.push(':');var items=value.replace(Common.Color.Regex,'\0$1\0').split('\0');for(var i=0;i<items.length;++i) -output.push(this.patchColorText(items[i],colorUsage));if(style.getPropertyPriority(name)) -output.push(' !important');output.push(';');} -patchColorText(text,colorUsage){var color=Common.Color.parse(text);if(!color) -return text;var outColor=this.patchColor(color,colorUsage);var outText=outColor.asString(null);if(!outText) -outText=outColor.asString(outColor.hasAlpha()?Common.Color.Format.RGBA:Common.Color.Format.RGB);return outText||text;} -patchColor(color,colorUsage){var hsla=color.hsla();this._patchHSLA(hsla,colorUsage);var rgba=[];Common.Color.hsl2rgb(hsla,rgba);return new Common.Color(rgba,color.format());} -_patchHSLA(hsla,colorUsage){var hue=hsla[0];var sat=hsla[1];var lit=hsla[2];var alpha=hsla[3];switch(this._themeName){case'dark':if(colorUsage&UI.ThemeSupport.ColorUsage.Selection) -hue=(hue+0.5)%1;var minCap=colorUsage&UI.ThemeSupport.ColorUsage.Background?0.14:0;var maxCap=colorUsage&UI.ThemeSupport.ColorUsage.Foreground?0.9:1;lit=1-lit;if(lit<minCap*2) -lit=minCap+lit/2;else if(lit>2*maxCap-1) -lit=maxCap-1/2+lit/2;break;} -hsla[0]=Number.constrain(hue,0,1);hsla[1]=Number.constrain(sat,0,1);hsla[2]=Number.constrain(lit,0,1);hsla[3]=Number.constrain(alpha,0,1);}};UI.ThemeSupport.ColorUsage={Unknown:0,Foreground:1<<0,Background:1<<1,Selection:1<<2,};UI.createExternalLink=function(url,linkText,className,preventClick){if(!linkText) -linkText=url;var a=createElementWithClass('span',className);UI.ARIAUtils.markAsLink(a);var href=url;if(url.trim().toLowerCase().startsWith('javascript:')) -href=null;if(Common.ParsedURL.isRelativeURL(url)) -href=null;if(href!==null){a.href=href;a.classList.add('devtools-link');if(!preventClick){a.addEventListener('click',event=>{event.consume(true);InspectorFrontendHost.openInNewTab((href));},false);}else{a.classList.add('devtools-link-prevent-click');} -a[UI._externalLinkSymbol]=true;} -if(linkText!==url) -a.title=url;a.textContent=linkText.trimMiddle(UI.MaxLengthForDisplayedURLs);a.setAttribute('target','_blank');return a;};UI._externalLinkSymbol=Symbol('UI._externalLink');UI.ExternaLinkContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){var targetNode=(target);while(targetNode&&!targetNode[UI._externalLinkSymbol]) -targetNode=targetNode.parentNodeOrShadowHost();if(!targetNode||!targetNode.href) -return;contextMenu.revealSection().appendItem(UI.openLinkExternallyLabel(),()=>InspectorFrontendHost.openInNewTab(targetNode.href));contextMenu.revealSection().appendItem(UI.copyLinkAddressLabel(),()=>InspectorFrontendHost.copyText(targetNode.href));}};UI.createDocumentationLink=function(article,title){return UI.createExternalLink('https://developers.google.com/web/tools/chrome-devtools/'+article,title);};UI.loadImage=function(url){return new Promise(fulfill=>{var image=new Image();image.addEventListener('load',()=>fulfill(image));image.addEventListener('error',()=>fulfill(null));image.src=url;});};UI.loadImageFromData=function(data){return data?UI.loadImage('data:image/jpg;base64,'+data):Promise.resolve(null);};UI.themeSupport;UI.createFileSelectorElement=function(callback){var fileSelectorElement=createElement('input');fileSelectorElement.type='file';fileSelectorElement.style.display='none';fileSelectorElement.setAttribute('tabindex',-1);fileSelectorElement.onchange=onChange;function onChange(event){callback(fileSelectorElement.files[0]);} -return fileSelectorElement;};UI.MaxLengthForDisplayedURLs=150;UI.MessageDialog=class{static async show(message,where){var dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.setDimmed(true);var shadowRoot=UI.createShadowRootWithCoreStyles(dialog.contentElement,'ui/confirmDialog.css');var content=shadowRoot.createChild('div','widget');await new Promise(resolve=>{var okButton=UI.createTextButton(Common.UIString('OK'),resolve,'',true);content.createChild('div','message').createChild('span').textContent=message;content.createChild('div','button').appendChild(okButton);dialog.setOutsideClickCallback(event=>{event.consume();resolve();});dialog.show(where);okButton.focus();});dialog.hide();}};UI.ConfirmDialog=class{static async show(message,where){var dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.setDimmed(true);var shadowRoot=UI.createShadowRootWithCoreStyles(dialog.contentElement,'ui/confirmDialog.css');var content=shadowRoot.createChild('div','widget');content.createChild('div','message').createChild('span').textContent=message;var buttonsBar=content.createChild('div','button');var result=await new Promise(resolve=>{buttonsBar.appendChild(UI.createTextButton(Common.UIString('OK'),()=>resolve(true),'',true));buttonsBar.appendChild(UI.createTextButton(Common.UIString('Cancel'),()=>resolve(false)));dialog.setOutsideClickCallback(event=>{event.consume();resolve(false);});dialog.show(where);});dialog.hide();return result;}};UI.createInlineButton=function(toolbarButton){var element=createElement('span');var shadowRoot=UI.createShadowRootWithCoreStyles(element,'ui/inlineButton.css');element.classList.add('inline-button');var toolbar=new UI.Toolbar('');toolbar.appendToolbarItem(toolbarButton);shadowRoot.appendChild(toolbar.element);return element;};;UI.ARIAUtils={};UI.ARIAUtils.markAsButton=function(element){element.setAttribute('role','button');};UI.ARIAUtils.markAsGroup=function(element){element.setAttribute('role','group');};UI.ARIAUtils.markAsLink=function(element){element.setAttribute('role','link');};UI.ARIAUtils.markAsTab=function(element){element.setAttribute('role','tab');};UI.ARIAUtils.markAsTree=function(element){element.setAttribute('role','tree');};UI.ARIAUtils.markAsTreeitem=function(element){element.setAttribute('role','treeitem');};UI.ARIAUtils.markAsPresentation=function(element){element.setAttribute('role','presentation');};UI.ARIAUtils.setControls=function(element,controlledElement){if(!controlledElement){element.removeAttribute('aria-controls');return;} -if(controlledElement.id==='') -throw new Error('Controlled element must have ID');element.setAttribute('aria-controls',controlledElement.id);};UI.ARIAUtils.setExpanded=function(element,value){element.setAttribute('aria-expanded',!!value);};UI.ARIAUtils.unsetExpanded=function(element){element.removeAttribute('aria-expanded');};UI.ARIAUtils.setSelected=function(element,value){element.setAttribute('aria-selected',!!value);};UI.ARIAUtils.setPressed=function(element,value){element.setAttribute('aria-pressed',!!value);};UI.ARIAUtils.setAccessibleName=function(element,name){element.setAttribute('aria-label',name);};;UI.ZoomManager=class extends Common.Object{constructor(window,frontendHost){super();this._frontendHost=frontendHost;this._zoomFactor=this._frontendHost.zoomFactor();window.addEventListener('resize',this._onWindowResize.bind(this),true);} -zoomFactor(){return this._zoomFactor;} -cssToDIP(value){return value*this._zoomFactor;} -dipToCSS(valueDIP){return valueDIP/this._zoomFactor;} -_onWindowResize(){var oldZoomFactor=this._zoomFactor;this._zoomFactor=this._frontendHost.zoomFactor();if(oldZoomFactor!==this._zoomFactor) -this.dispatchEventToListeners(UI.ZoomManager.Events.ZoomChanged,{from:oldZoomFactor,to:this._zoomFactor});}};UI.ZoomManager.Events={ZoomChanged:Symbol('ZoomChanged')};UI.zoomManager;;UI.ShortcutsScreen=class{constructor(){this._sections={};} -static registerShortcuts(){var elementsSection=UI.shortcutsScreen.section(Common.UIString('Elements Panel'));var navigate=UI.ShortcutsScreen.ElementsPanelShortcuts.NavigateUp.concat(UI.ShortcutsScreen.ElementsPanelShortcuts.NavigateDown);elementsSection.addRelatedKeys(navigate,Common.UIString('Navigate elements'));var expandCollapse=UI.ShortcutsScreen.ElementsPanelShortcuts.Expand.concat(UI.ShortcutsScreen.ElementsPanelShortcuts.Collapse);elementsSection.addRelatedKeys(expandCollapse,Common.UIString('Expand/collapse'));elementsSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.EditAttribute,Common.UIString('Edit attribute'));elementsSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.HideElement,Common.UIString('Hide element'));elementsSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.ToggleEditAsHTML,Common.UIString('Toggle edit as HTML'));var stylesPaneSection=UI.shortcutsScreen.section(Common.UIString('Styles Pane'));var nextPreviousProperty=UI.ShortcutsScreen.ElementsPanelShortcuts.NextProperty.concat(UI.ShortcutsScreen.ElementsPanelShortcuts.PreviousProperty);stylesPaneSection.addRelatedKeys(nextPreviousProperty,Common.UIString('Next/previous property'));stylesPaneSection.addRelatedKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementValue,Common.UIString('Increment value'));stylesPaneSection.addRelatedKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementValue,Common.UIString('Decrement value'));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy10,Common.UIString('Increment by %f',10));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy10,Common.UIString('Decrement by %f',10));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy100,Common.UIString('Increment by %f',100));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy100,Common.UIString('Decrement by %f',100));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy01,Common.UIString('Increment by %f',0.1));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy01,Common.UIString('Decrement by %f',0.1));var section=UI.shortcutsScreen.section(Common.UIString('Debugger'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-pause'),Common.UIString('Pause/ Continue'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-over'),Common.UIString('Step over'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-into'),Common.UIString('Step into'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-out'),Common.UIString('Step out'));var nextAndPrevFrameKeys=UI.ShortcutsScreen.SourcesPanelShortcuts.NextCallFrame.concat(UI.ShortcutsScreen.SourcesPanelShortcuts.PrevCallFrame);section.addRelatedKeys(nextAndPrevFrameKeys,Common.UIString('Next/previous call frame'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.EvaluateSelectionInConsole,Common.UIString('Evaluate selection in console'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.AddSelectionToWatch,Common.UIString('Add selection to watch'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.ToggleBreakpoint,Common.UIString('Toggle breakpoint'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.ToggleBreakpointEnabled,Common.UIString('Toggle breakpoint enabled'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-breakpoints-active'),Common.UIString('Toggle all breakpoints'));section=UI.shortcutsScreen.section(Common.UIString('Text Editor'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.GoToMember,Common.UIString('Go to member'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.ToggleAutocompletion,Common.UIString('Autocompletion'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.GoToLine,Common.UIString('Go to line'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.JumpToPreviousLocation,Common.UIString('Jump to previous editing location'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.JumpToNextLocation,Common.UIString('Jump to next editing location'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.ToggleComment,Common.UIString('Toggle comment'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.IncreaseCSSUnitByOne,Common.UIString('Increment CSS unit by 1'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.DecreaseCSSUnitByOne,Common.UIString('Decrement CSS unit by 1'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.IncreaseCSSUnitByTen,Common.UIString('Increment CSS unit by 10'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.DecreaseCSSUnitByTen,Common.UIString('Decrement CSS unit by 10'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.SelectNextOccurrence,Common.UIString('Select next occurrence'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.SoftUndo,Common.UIString('Soft undo'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.GotoMatchingBracket,Common.UIString('Go to matching bracket'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.CloseEditorTab,Common.UIString('Close editor tab'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.switch-file'),Common.UIString('Switch between files with the same name and different extensions.'));section=UI.shortcutsScreen.section(Common.UIString('Performance Panel'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.toggle-recording'),Common.UIString('Start/stop recording'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.record-reload'),Common.UIString('Record page reload'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.save-to-file'),Common.UIString('Save profile'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.load-from-file'),Common.UIString('Load profile'));section.addRelatedKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.jump-to-previous-frame').concat(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.jump-to-next-frame')),Common.UIString('Jump to previous/next frame'));if(Runtime.experiments.isEnabled('timelineKeepHistory')){section.addRelatedKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.show-history'),Common.UIString('Pick a recording from history'));section.addRelatedKeys(UI.ShortcutsScreen.PerformancePanelShortcuts.PreviousRecording.concat(UI.ShortcutsScreen.PerformancePanelShortcuts.NextRecording),Common.UIString('Show previous/next recording'));} -section=UI.shortcutsScreen.section(Common.UIString('Memory Panel'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('profiler.heap-toggle-recording'),Common.UIString('Start/stop recording'));section=UI.shortcutsScreen.section(Common.UIString('Layers Panel'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.ResetView,Common.UIString('Reset view'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.PanMode,Common.UIString('Switch to pan mode'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.RotateMode,Common.UIString('Switch to rotate mode'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.TogglePanRotate,Common.UIString('Temporarily toggle pan/rotate mode while held'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.ZoomIn,Common.UIString('Zoom in'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.ZoomOut,Common.UIString('Zoom out'));section.addRelatedKeys(UI.ShortcutsScreen.LayersPanelShortcuts.Up.concat(UI.ShortcutsScreen.LayersPanelShortcuts.Down),Common.UIString('Pan or rotate up/down'));section.addRelatedKeys(UI.ShortcutsScreen.LayersPanelShortcuts.Left.concat(UI.ShortcutsScreen.LayersPanelShortcuts.Right),Common.UIString('Pan or rotate left/right'));} -section(name){var section=this._sections[name];if(!section) -this._sections[name]=section=new UI.ShortcutsSection(name);return section;} -createShortcutsTabView(){var orderedSections=[];for(var section in this._sections) -orderedSections.push(this._sections[section]);function compareSections(a,b){return a.order-b.order;} -orderedSections.sort(compareSections);var widget=new UI.Widget();widget.element.className='settings-tab-container';widget.element.createChild('header').createChild('h3').createTextChild(Common.UIString('Shortcuts'));var scrollPane=widget.element.createChild('div','help-container-wrapper');var container=scrollPane.createChild('div');container.className='help-content help-container';for(var i=0;i<orderedSections.length;++i) -orderedSections[i].renderSection(container);var note=scrollPane.createChild('p','help-footnote');note.appendChild(UI.createDocumentationLink('iterate/inspect-styles/shortcuts',Common.UIString('Full list of DevTools keyboard shortcuts and gestures')));return widget;}};UI.shortcutsScreen;UI.ShortcutsSection=class{constructor(name){this.name=name;this._lines=([]);this.order=++UI.ShortcutsSection._sequenceNumber;} -addKey(key,description){this._addLine(this._renderKey(key),description);} -addRelatedKeys(keys,description){this._addLine(this._renderSequence(keys,'/'),description);} -addAlternateKeys(keys,description){this._addLine(this._renderSequence(keys,Common.UIString('or')),description);} -_addLine(keyElement,description){this._lines.push({key:keyElement,text:description});} -renderSection(container){var parent=container.createChild('div','help-block');var headLine=parent.createChild('div','help-line');headLine.createChild('div','help-key-cell');headLine.createChild('div','help-section-title help-cell').textContent=this.name;for(var i=0;i<this._lines.length;++i){var line=parent.createChild('div','help-line');var keyCell=line.createChild('div','help-key-cell');keyCell.appendChild(this._lines[i].key);keyCell.appendChild(this._createSpan('help-key-delimiter',':'));line.createChild('div','help-cell').textContent=this._lines[i].text;}} -_renderSequence(sequence,delimiter){var delimiterSpan=this._createSpan('help-key-delimiter',delimiter);return this._joinNodes(sequence.map(this._renderKey.bind(this)),delimiterSpan);} -_renderKey(key){var keyName=key.name;var plus=this._createSpan('help-combine-keys','+');return this._joinNodes(keyName.split(' + ').map(this._createSpan.bind(this,'help-key')),plus);} -_createSpan(className,textContent){var node=createElement('span');node.className=className;node.textContent=textContent;return node;} -_joinNodes(nodes,delimiter){var result=createDocumentFragment();for(var i=0;i<nodes.length;++i){if(i>0) -result.appendChild(delimiter.cloneNode(true));result.appendChild(nodes[i]);} -return result;}};UI.ShortcutsSection._sequenceNumber=0;UI.ShortcutsScreen.ElementsPanelShortcuts={NavigateUp:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up)],NavigateDown:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down)],Expand:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Right)],Collapse:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Left)],EditAttribute:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Enter)],HideElement:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.H)],ToggleEditAsHTML:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.F2)],NextProperty:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Tab)],PreviousProperty:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Tab,UI.KeyboardShortcut.Modifiers.Shift)],IncrementValue:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up)],DecrementValue:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down)],IncrementBy10:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up,UI.KeyboardShortcut.Modifiers.Shift)],DecrementBy10:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down,UI.KeyboardShortcut.Modifiers.Shift)],IncrementBy100:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp,UI.KeyboardShortcut.Modifiers.Shift)],DecrementBy100:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown,UI.KeyboardShortcut.Modifiers.Shift)],IncrementBy01:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up,UI.KeyboardShortcut.Modifiers.Alt)],DecrementBy01:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down,UI.KeyboardShortcut.Modifiers.Alt)]};UI.ShortcutsScreen.SourcesPanelShortcuts={SelectNextOccurrence:[UI.KeyboardShortcut.makeDescriptor('d',UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],SoftUndo:[UI.KeyboardShortcut.makeDescriptor('u',UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],GotoMatchingBracket:[UI.KeyboardShortcut.makeDescriptor('m',UI.KeyboardShortcut.Modifiers.Ctrl)],ToggleAutocompletion:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Space,UI.KeyboardShortcut.Modifiers.Ctrl)],IncreaseCSSUnitByOne:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up,UI.KeyboardShortcut.Modifiers.Alt)],DecreaseCSSUnitByOne:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down,UI.KeyboardShortcut.Modifiers.Alt)],IncreaseCSSUnitByTen:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp,UI.KeyboardShortcut.Modifiers.Alt)],DecreaseCSSUnitByTen:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown,UI.KeyboardShortcut.Modifiers.Alt)],EvaluateSelectionInConsole:[UI.KeyboardShortcut.makeDescriptor('e',UI.KeyboardShortcut.Modifiers.Shift|UI.KeyboardShortcut.Modifiers.Ctrl)],AddSelectionToWatch:[UI.KeyboardShortcut.makeDescriptor('a',UI.KeyboardShortcut.Modifiers.Shift|UI.KeyboardShortcut.Modifiers.Ctrl)],GoToMember:[UI.KeyboardShortcut.makeDescriptor('o',UI.KeyboardShortcut.Modifiers.CtrlOrMeta|UI.KeyboardShortcut.Modifiers.Shift)],GoToLine:[UI.KeyboardShortcut.makeDescriptor('g',UI.KeyboardShortcut.Modifiers.Ctrl)],ToggleBreakpoint:[UI.KeyboardShortcut.makeDescriptor('b',UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],ToggleBreakpointEnabled:[UI.KeyboardShortcut.makeDescriptor('b',UI.KeyboardShortcut.Modifiers.CtrlOrMeta|UI.KeyboardShortcut.Modifiers.Shift)],NextCallFrame:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Period,UI.KeyboardShortcut.Modifiers.Ctrl)],PrevCallFrame:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Comma,UI.KeyboardShortcut.Modifiers.Ctrl)],ToggleComment:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Slash,UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],JumpToPreviousLocation:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Minus,UI.KeyboardShortcut.Modifiers.Alt)],JumpToNextLocation:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Plus,UI.KeyboardShortcut.Modifiers.Alt)],CloseEditorTab:[UI.KeyboardShortcut.makeDescriptor('w',UI.KeyboardShortcut.Modifiers.Alt)],Save:[UI.KeyboardShortcut.makeDescriptor('s',UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],SaveAll:[UI.KeyboardShortcut.makeDescriptor('s',UI.KeyboardShortcut.Modifiers.CtrlOrMeta|UI.KeyboardShortcut.Modifiers.ShiftOrOption)],};UI.ShortcutsScreen.LayersPanelShortcuts={ResetView:[UI.KeyboardShortcut.makeDescriptor('0')],PanMode:[UI.KeyboardShortcut.makeDescriptor('x')],RotateMode:[UI.KeyboardShortcut.makeDescriptor('v')],TogglePanRotate:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Shift)],ZoomIn:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Plus,UI.KeyboardShortcut.Modifiers.Shift),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.NumpadPlus)],ZoomOut:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Minus,UI.KeyboardShortcut.Modifiers.Shift),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.NumpadMinus)],Up:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up),UI.KeyboardShortcut.makeDescriptor('w')],Down:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down),UI.KeyboardShortcut.makeDescriptor('s')],Left:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Left),UI.KeyboardShortcut.makeDescriptor('a')],Right:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Right),UI.KeyboardShortcut.makeDescriptor('d')]};UI.ShortcutsScreen.PerformancePanelShortcuts={PreviousRecording:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Left,Host.isMac()?UI.KeyboardShortcut.Modifiers.Meta:UI.KeyboardShortcut.Modifiers.Alt)],NextRecording:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Right,Host.isMac()?UI.KeyboardShortcut.Modifiers.Meta:UI.KeyboardShortcut.Modifiers.Alt)],};;UI.Geometry={};UI.Geometry._Eps=1e-5;UI.Geometry.Vector=class{constructor(x,y,z){this.x=x;this.y=y;this.z=z;} -length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);} -normalize(){var length=this.length();if(length<=UI.Geometry._Eps) -return;this.x/=length;this.y/=length;this.z/=length;}};UI.Geometry.Point=class{constructor(x,y){this.x=x;this.y=y;} -distanceTo(p){return Math.sqrt(Math.pow(p.x-this.x,2)+Math.pow(p.y-this.y,2));} -projectOn(line){if(line.x===0&&line.y===0) -return new UI.Geometry.Point(0,0);return line.scale((this.x*line.x+this.y*line.y)/(Math.pow(line.x,2)+Math.pow(line.y,2)));} -scale(scalar){return new UI.Geometry.Point(this.x*scalar,this.y*scalar);} -toString(){return Math.round(this.x*100)/100+', '+Math.round(this.y*100)/100;}};UI.Geometry.CubicBezier=class{constructor(point1,point2){this.controlPoints=[point1,point2];} -static parse(text){var keywordValues=UI.Geometry.CubicBezier.KeywordValues;var value=text.toLowerCase().replace(/\s+/g,'');if(Object.keys(keywordValues).indexOf(value)!==-1) -return UI.Geometry.CubicBezier.parse(keywordValues[value]);var bezierRegex=/^cubic-bezier\(([^,]+),([^,]+),([^,]+),([^,]+)\)$/;var match=value.match(bezierRegex);if(match){var control1=new UI.Geometry.Point(parseFloat(match[1]),parseFloat(match[2]));var control2=new UI.Geometry.Point(parseFloat(match[3]),parseFloat(match[4]));return new UI.Geometry.CubicBezier(control1,control2);} -return null;} -evaluateAt(t){function evaluate(v1,v2,t){return 3*(1-t)*(1-t)*t*v1+3*(1-t)*t*t*v2+Math.pow(t,3);} -var x=evaluate(this.controlPoints[0].x,this.controlPoints[1].x,t);var y=evaluate(this.controlPoints[0].y,this.controlPoints[1].y,t);return new UI.Geometry.Point(x,y);} -asCSSText(){var raw='cubic-bezier('+this.controlPoints.join(', ')+')';var keywordValues=UI.Geometry.CubicBezier.KeywordValues;for(var keyword in keywordValues){if(raw===keywordValues[keyword]) -return keyword;} -return raw;}};UI.Geometry.CubicBezier.Regex=/((cubic-bezier\([^)]+\))|\b(linear|ease-in-out|ease-in|ease-out|ease)\b)/g;UI.Geometry.CubicBezier.KeywordValues={'linear':'cubic-bezier(0, 0, 1, 1)','ease':'cubic-bezier(0.25, 0.1, 0.25, 1)','ease-in':'cubic-bezier(0.42, 0, 1, 1)','ease-in-out':'cubic-bezier(0.42, 0, 0.58, 1)','ease-out':'cubic-bezier(0, 0, 0.58, 1)'};UI.Geometry.EulerAngles=class{constructor(alpha,beta,gamma){this.alpha=alpha;this.beta=beta;this.gamma=gamma;} -static fromRotationMatrix(rotationMatrix){var beta=Math.atan2(rotationMatrix.m23,rotationMatrix.m33);var gamma=Math.atan2(-rotationMatrix.m13,Math.sqrt(rotationMatrix.m11*rotationMatrix.m11+rotationMatrix.m12*rotationMatrix.m12));var alpha=Math.atan2(rotationMatrix.m12,rotationMatrix.m11);return new UI.Geometry.EulerAngles(UI.Geometry.radiansToDegrees(alpha),UI.Geometry.radiansToDegrees(beta),UI.Geometry.radiansToDegrees(gamma));} -toRotate3DString(){var gammaAxisY=-Math.sin(UI.Geometry.degreesToRadians(this.beta));var gammaAxisZ=Math.cos(UI.Geometry.degreesToRadians(this.beta));var axis={alpha:[0,1,0],beta:[-1,0,0],gamma:[0,gammaAxisY,gammaAxisZ]};return'rotate3d('+axis.alpha.join(',')+','+this.alpha+'deg) '+'rotate3d('+axis.beta.join(',')+','+this.beta+'deg) '+'rotate3d('+axis.gamma.join(',')+','+this.gamma+'deg)';}};UI.Geometry.scalarProduct=function(u,v){return u.x*v.x+u.y*v.y+u.z*v.z;};UI.Geometry.crossProduct=function(u,v){var x=u.y*v.z-u.z*v.y;var y=u.z*v.x-u.x*v.z;var z=u.x*v.y-u.y*v.x;return new UI.Geometry.Vector(x,y,z);};UI.Geometry.subtract=function(u,v){var x=u.x-v.x;var y=u.y-v.y;var z=u.z-v.z;return new UI.Geometry.Vector(x,y,z);};UI.Geometry.multiplyVectorByMatrixAndNormalize=function(v,m){var t=v.x*m.m14+v.y*m.m24+v.z*m.m34+m.m44;var x=(v.x*m.m11+v.y*m.m21+v.z*m.m31+m.m41)/t;var y=(v.x*m.m12+v.y*m.m22+v.z*m.m32+m.m42)/t;var z=(v.x*m.m13+v.y*m.m23+v.z*m.m33+m.m43)/t;return new UI.Geometry.Vector(x,y,z);};UI.Geometry.calculateAngle=function(u,v){var uLength=u.length();var vLength=v.length();if(uLength<=UI.Geometry._Eps||vLength<=UI.Geometry._Eps) -return 0;var cos=UI.Geometry.scalarProduct(u,v)/uLength/vLength;if(Math.abs(cos)>1) -return 0;return UI.Geometry.radiansToDegrees(Math.acos(cos));};UI.Geometry.degreesToRadians=function(deg){return deg*Math.PI/180;};UI.Geometry.radiansToDegrees=function(rad){return rad*180/Math.PI;};UI.Geometry.boundsForTransformedPoints=function(matrix,points,aggregateBounds){if(!aggregateBounds) -aggregateBounds={minX:Infinity,maxX:-Infinity,minY:Infinity,maxY:-Infinity};if(points.length%3) -console.assert('Invalid size of points array');for(var p=0;p<points.length;p+=3){var vector=new UI.Geometry.Vector(points[p],points[p+1],points[p+2]);vector=UI.Geometry.multiplyVectorByMatrixAndNormalize(vector,matrix);aggregateBounds.minX=Math.min(aggregateBounds.minX,vector.x);aggregateBounds.maxX=Math.max(aggregateBounds.maxX,vector.x);aggregateBounds.minY=Math.min(aggregateBounds.minY,vector.y);aggregateBounds.maxY=Math.max(aggregateBounds.maxY,vector.y);} -return aggregateBounds;};UI.Size=class{constructor(width,height){this.width=width;this.height=height;} -clipTo(size){if(!size) -return this;return new UI.Size(Math.min(this.width,size.width),Math.min(this.height,size.height));} -scale(scale){return new UI.Size(this.width*scale,this.height*scale);}};UI.Size.prototype.isEqual=function(size){return!!size&&this.width===size.width&&this.height===size.height;};UI.Size.prototype.widthToMax=function(size){return new UI.Size(Math.max(this.width,(typeof size==='number'?size:size.width)),this.height);};UI.Size.prototype.addWidth=function(size){return new UI.Size(this.width+(typeof size==='number'?size:size.width),this.height);};UI.Size.prototype.heightToMax=function(size){return new UI.Size(this.width,Math.max(this.height,(typeof size==='number'?size:size.height)));};UI.Size.prototype.addHeight=function(size){return new UI.Size(this.width,this.height+(typeof size==='number'?size:size.height));};UI.Insets=class{constructor(left,top,right,bottom){this.left=left;this.top=top;this.right=right;this.bottom=bottom;} -isEqual(insets){return!!insets&&this.left===insets.left&&this.top===insets.top&&this.right===insets.right&&this.bottom===insets.bottom;}};UI.Rect=class{constructor(left,top,width,height){this.left=left;this.top=top;this.width=width;this.height=height;} -isEqual(rect){return!!rect&&this.left===rect.left&&this.top===rect.top&&this.width===rect.width&&this.height===rect.height;} -scale(scale){return new UI.Rect(this.left*scale,this.top*scale,this.width*scale,this.height*scale);} -size(){return new UI.Size(this.width,this.height);} -relativeTo(origin){return new UI.Rect(this.left-origin.left,this.top-origin.top,this.width,this.height);} -rebaseTo(origin){return new UI.Rect(this.left+origin.left,this.top+origin.top,this.width,this.height);}};UI.Constraints=class{constructor(minimum,preferred){this.minimum=minimum||new UI.Size(0,0);this.preferred=preferred||this.minimum;if(this.minimum.width>this.preferred.width||this.minimum.height>this.preferred.height) -throw new Error('Minimum size is greater than preferred.');}};UI.Constraints.prototype.isEqual=function(constraints){return!!constraints&&this.minimum.isEqual(constraints.minimum)&&this.preferred.isEqual(constraints.preferred);};UI.Constraints.prototype.widthToMax=function(value){if(typeof value==='number') -return new UI.Constraints(this.minimum.widthToMax(value),this.preferred.widthToMax(value));return new UI.Constraints(this.minimum.widthToMax(value.minimum),this.preferred.widthToMax(value.preferred));};UI.Constraints.prototype.addWidth=function(value){if(typeof value==='number') -return new UI.Constraints(this.minimum.addWidth(value),this.preferred.addWidth(value));return new UI.Constraints(this.minimum.addWidth(value.minimum),this.preferred.addWidth(value.preferred));};UI.Constraints.prototype.heightToMax=function(value){if(typeof value==='number') -return new UI.Constraints(this.minimum.heightToMax(value),this.preferred.heightToMax(value));return new UI.Constraints(this.minimum.heightToMax(value.minimum),this.preferred.heightToMax(value.preferred));};UI.Constraints.prototype.addHeight=function(value){if(typeof value==='number') -return new UI.Constraints(this.minimum.addHeight(value),this.preferred.addHeight(value));return new UI.Constraints(this.minimum.addHeight(value.minimum),this.preferred.addHeight(value.preferred));};;self['Protocol']=self['Protocol']||{};Protocol.Error=Symbol('Protocol.Error');Protocol.InspectorBackend=class{constructor(){this._agentPrototypes={};this._dispatcherPrototypes={};this._initialized=false;} -static reportProtocolError(error,messageObject){console.error(error+': '+JSON.stringify(messageObject));} -isInitialized(){return this._initialized;} -_addAgentGetterMethodToProtocolTargetPrototype(domain){var upperCaseLength=0;while(upperCaseLength<domain.length&&domain[upperCaseLength].toLowerCase()!==domain[upperCaseLength]) -++upperCaseLength;var methodName=domain.substr(0,upperCaseLength).toLowerCase()+domain.slice(upperCaseLength)+'Agent';function agentGetter(){return this._agents[domain];} -Protocol.TargetBase.prototype[methodName]=agentGetter;function registerDispatcher(dispatcher){this.registerDispatcher(domain,dispatcher);} -Protocol.TargetBase.prototype['register'+domain+'Dispatcher']=registerDispatcher;} -_agentPrototype(domain){if(!this._agentPrototypes[domain]){this._agentPrototypes[domain]=new Protocol.InspectorBackend._AgentPrototype(domain);this._addAgentGetterMethodToProtocolTargetPrototype(domain);} -return this._agentPrototypes[domain];} -_dispatcherPrototype(domain){if(!this._dispatcherPrototypes[domain]) -this._dispatcherPrototypes[domain]=new Protocol.InspectorBackend._DispatcherPrototype();return this._dispatcherPrototypes[domain];} -registerCommand(method,signature,replyArgs,hasErrorData){var domainAndMethod=method.split('.');this._agentPrototype(domainAndMethod[0]).registerCommand(domainAndMethod[1],signature,replyArgs,hasErrorData);this._initialized=true;} -registerEnum(type,values){var domainAndName=type.split('.');var domain=domainAndName[0];if(!Protocol[domain]) -Protocol[domain]={};Protocol[domain][domainAndName[1]]=values;this._initialized=true;} -registerEvent(eventName,params){var domain=eventName.split('.')[0];this._dispatcherPrototype(domain).registerEvent(eventName,params);this._initialized=true;} -wrapClientCallback(clientCallback,errorPrefix,constructor,defaultValue){function callbackWrapper(error,value){if(error){console.error(errorPrefix+error);clientCallback(defaultValue);return;} -if(constructor) -clientCallback(new constructor(value));else -clientCallback(value);} -return callbackWrapper;}};Protocol.InspectorBackend._ConnectionClosedErrorCode=-32000;Protocol.InspectorBackend.DevToolsStubErrorCode=-32015;Protocol.inspectorBackend=new Protocol.InspectorBackend();Protocol.InspectorBackend.Connection=function(){};Protocol.InspectorBackend.Connection.prototype={sendMessage(message){},disconnect(){},};Protocol.InspectorBackend.Connection.Params;Protocol.InspectorBackend.Connection.Factory;Protocol.TargetBase=class{constructor(connectionFactory){this._connection=connectionFactory({onMessage:this._onMessage.bind(this),onDisconnect:this._onDisconnect.bind(this)});this._lastMessageId=1;this._pendingResponsesCount=0;this._agents={};this._dispatchers={};this._callbacks={};this._initialize(Protocol.inspectorBackend._agentPrototypes,Protocol.inspectorBackend._dispatcherPrototypes);this._domainToLogger=new Map();if(!Protocol.InspectorBackend.deprecatedRunAfterPendingDispatches){Protocol.InspectorBackend.deprecatedRunAfterPendingDispatches=this._deprecatedRunAfterPendingDispatches.bind(this);} -if(!Protocol.InspectorBackend.sendRawMessageForTesting) -Protocol.InspectorBackend.sendRawMessageForTesting=this._sendRawMessageForTesting.bind(this);} -_initialize(agentPrototypes,dispatcherPrototypes){for(var domain in agentPrototypes){this._agents[domain]=Object.create(agentPrototypes[domain]);this._agents[domain].setTarget(this);} -for(var domain in dispatcherPrototypes){this._dispatchers[domain]=Object.create(dispatcherPrototypes[domain]);this._dispatchers[domain].initialize();}} -_nextMessageId(){return this._lastMessageId++;} -_agent(domain){return this._agents[domain];} -_wrapCallbackAndSendMessageObject(domain,method,params,callback){if(!this._connection){if(callback) -this._dispatchConnectionErrorResponse(domain,method,callback);return;} -var messageObject={};var messageId=this._nextMessageId();messageObject.id=messageId;messageObject.method=method;if(params) -messageObject.params=params;var wrappedCallback=this._wrap(callback,domain,method);var message=JSON.stringify(messageObject);if(Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages) -this._dumpProtocolMessage('frontend: '+message,'[FE] '+domain);this._connection.sendMessage(message);++this._pendingResponsesCount;this._callbacks[messageId]=wrappedCallback;} -_wrap(callback,domain,method){if(!callback) -callback=function(){};callback.methodName=method;callback.domain=domain;if(Protocol.InspectorBackend.Options.dumpInspectorTimeStats) -callback.sendRequestTime=Date.now();return callback;} -_sendRawMessageForTesting(method,params,callback){var domain=method.split('.')[0];this._wrapCallbackAndSendMessageObject(domain,method,params,callback);} -_onMessage(message){if(Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages){this._dumpProtocolMessage('backend: '+((typeof message==='string')?message:JSON.stringify(message)),'Backend');} -var messageObject=((typeof message==='string')?JSON.parse(message):message);if('id'in messageObject){var callback=this._callbacks[messageObject.id];if(!callback){Protocol.InspectorBackend.reportProtocolError('Protocol Error: the message with wrong id',messageObject);return;} -var timingLabel='time-stats: '+callback.methodName;if(Protocol.InspectorBackend.Options.dumpInspectorTimeStats) -Protocol.InspectorBackend._timeLogger.time(timingLabel);this._agent(callback.domain).dispatchResponse(messageObject,callback.methodName,callback);--this._pendingResponsesCount;delete this._callbacks[messageObject.id];if(Protocol.InspectorBackend.Options.dumpInspectorTimeStats) -Protocol.InspectorBackend._timeLogger.timeEnd(timingLabel);if(this._scripts&&!this._pendingResponsesCount) -this._deprecatedRunAfterPendingDispatches();}else{if(!('method'in messageObject)){Protocol.InspectorBackend.reportProtocolError('Protocol Error: the message without method',messageObject);return;} -var method=messageObject.method.split('.');var domainName=method[0];if(!(domainName in this._dispatchers)){Protocol.InspectorBackend.reportProtocolError(`Protocol Error: the message ${messageObject.method} is for non-existing domain '${domainName}'`,messageObject);return;} -this._dispatchers[domainName].dispatch(method[1],messageObject);}} -registerDispatcher(domain,dispatcher){if(!this._dispatchers[domain]) -return;this._dispatchers[domain].addDomainDispatcher(dispatcher);} -_deprecatedRunAfterPendingDispatches(script){if(!this._scripts) -this._scripts=[];if(script) -this._scripts.push(script);setTimeout(function(){if(!this._pendingResponsesCount) -this._executeAfterPendingDispatches();else -this._deprecatedRunAfterPendingDispatches();}.bind(this),0);} -_executeAfterPendingDispatches(){if(!this._pendingResponsesCount){var scripts=this._scripts;this._scripts=[];for(var id=0;id<scripts.length;++id) -scripts[id].call(this);}} -_dumpProtocolMessage(message,context){if(!this._domainToLogger.get(context)) -this._domainToLogger.set(context,console.context?console.context(context):console);var logger=this._domainToLogger.get(context);logger.log(message);} -_onDisconnect(reason){this._connection=null;this._runPendingCallbacks();this.dispose();} -dispose(){} -isDisposed(){return!this._connection;} -_runPendingCallbacks(){var keys=Object.keys(this._callbacks).map(function(num){return parseInt(num,10);});for(var i=0;i<keys.length;++i){var callback=this._callbacks[keys[i]];this._dispatchConnectionErrorResponse(callback.domain,callback.methodName,callback);} -this._callbacks={};} -_dispatchConnectionErrorResponse(domain,methodName,callback){var error={message:'Connection is closed, can\'t dispatch pending '+methodName,code:Protocol.InspectorBackend._ConnectionClosedErrorCode,data:null};var messageObject={error:error};setTimeout(Protocol.InspectorBackend._AgentPrototype.prototype.dispatchResponse.bind(this._agent(domain),messageObject,methodName,callback),0);}};Protocol.InspectorBackend._AgentPrototype=class{constructor(domain){this._replyArgs={};this._hasErrorData={};this._domain=domain;} -setTarget(target){this._target=target;} -registerCommand(methodName,signature,replyArgs,hasErrorData){var domainAndMethod=this._domain+'.'+methodName;function sendMessagePromise(vararg){var params=Array.prototype.slice.call(arguments);return Protocol.InspectorBackend._AgentPrototype.prototype._sendMessageToBackendPromise.call(this,domainAndMethod,signature,params);} -this[methodName]=sendMessagePromise;function invoke(request){return this._invoke(domainAndMethod,request);} -this['invoke_'+methodName]=invoke;this._replyArgs[domainAndMethod]=replyArgs;if(hasErrorData) -this._hasErrorData[domainAndMethod]=true;} -_prepareParameters(method,signature,args,errorCallback){var params={};var hasParams=false;for(var param of signature){var paramName=param['name'];var typeName=param['type'];var optionalFlag=param['optional'];if(!args.length&&!optionalFlag){errorCallback(`Protocol Error: Invalid number of arguments for method '${method}' call. `+`It must have the following arguments ${JSON.stringify(signature)}'.`);return null;} -var value=args.shift();if(optionalFlag&&typeof value==='undefined') -continue;if(typeof value!==typeName){errorCallback(`Protocol Error: Invalid type of argument '${paramName}' for method '${method}' call. `+`It must be '${typeName}' but it is '${typeof value}'.`);return null;} -params[paramName]=value;hasParams=true;} -if(args.length){errorCallback(`Protocol Error: Extra ${args.length} arguments in a call to method '${method}'.`);return null;} -return hasParams?params:null;} -_sendMessageToBackendPromise(method,signature,args){var errorMessage;function onError(message){console.error(message);errorMessage=message;} -var params=this._prepareParameters(method,signature,args,onError);if(errorMessage) -return Promise.resolve(null);return new Promise(resolve=>{this._target._wrapCallbackAndSendMessageObject(this._domain,method,params,(error,result)=>{if(error){resolve(null);return;} -var args=this._replyArgs[method];resolve(result&&args.length?result[args[0]]:undefined);});});} -_invoke(method,request){return new Promise(fulfill=>{this._target._wrapCallbackAndSendMessageObject(this._domain,method,request,(error,result)=>{if(!result) -result={};if(error) -result[Protocol.Error]=error.message;fulfill(result);});});} -dispatchResponse(messageObject,methodName,callback){if(messageObject.error&&messageObject.error.code!==Protocol.InspectorBackend._ConnectionClosedErrorCode&&messageObject.error.code!==Protocol.InspectorBackend.DevToolsStubErrorCode&&!Protocol.InspectorBackend.Options.suppressRequestErrors){var id=Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages?' with id = '+messageObject.id:'';console.error('Request '+methodName+id+' failed. '+JSON.stringify(messageObject.error));} -callback(messageObject.error,messageObject.result);}};Protocol.InspectorBackend._DispatcherPrototype=class{constructor(){this._eventArgs={};} -registerEvent(eventName,params){this._eventArgs[eventName]=params;} -initialize(){this._dispatchers=[];} -addDomainDispatcher(dispatcher){this._dispatchers.push(dispatcher);} -dispatch(functionName,messageObject){if(!this._dispatchers.length) -return;if(!this._eventArgs[messageObject.method]){Protocol.InspectorBackend.reportProtocolError(`Protocol Error: Attempted to dispatch an unspecified method '${messageObject.method}'`,messageObject);return;} -var params=[];if(messageObject.params){var paramNames=this._eventArgs[messageObject.method];for(var i=0;i<paramNames.length;++i) -params.push(messageObject.params[paramNames[i]]);} -var timingLabel='time-stats: '+messageObject.method;if(Protocol.InspectorBackend.Options.dumpInspectorTimeStats) -Protocol.InspectorBackend._timeLogger.time(timingLabel);for(var index=0;index<this._dispatchers.length;++index){var dispatcher=this._dispatchers[index];if(functionName in dispatcher) -dispatcher[functionName].apply(dispatcher,params);} -if(Protocol.InspectorBackend.Options.dumpInspectorTimeStats) -Protocol.InspectorBackend._timeLogger.timeEnd(timingLabel);}};Protocol.InspectorBackend.Options={dumpInspectorTimeStats:false,dumpInspectorProtocolMessages:false,suppressRequestErrors:false};Protocol.InspectorBackend._timeLogger=console.context?console.context('Protocol timing'):console;;Protocol.inspectorBackend.registerEvent("Inspector.detached",["reason"]);Protocol.inspectorBackend.registerEvent("Inspector.targetCrashed",[]);Protocol.inspectorBackend.registerCommand("Inspector.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Inspector.disable",[],[],false);Protocol.inspectorBackend.registerEnum("Memory.PressureLevel",{Moderate:"moderate",Critical:"critical"});Protocol.inspectorBackend.registerCommand("Memory.getDOMCounters",[],["documents","nodes","jsEventListeners"],false);Protocol.inspectorBackend.registerCommand("Memory.prepareForLeakDetection",[],[],false);Protocol.inspectorBackend.registerCommand("Memory.setPressureNotificationsSuppressed",[{"name":"suppressed","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Memory.simulatePressureNotification",[{"name":"level","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerEvent("Performance.metrics",["metrics","title"]);Protocol.inspectorBackend.registerCommand("Performance.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Performance.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Performance.getMetrics",[],["metrics"],false);Protocol.inspectorBackend.registerEnum("Page.ResourceType",{Document:"Document",Stylesheet:"Stylesheet",Image:"Image",Media:"Media",Font:"Font",Script:"Script",TextTrack:"TextTrack",XHR:"XHR",Fetch:"Fetch",EventSource:"EventSource",WebSocket:"WebSocket",Manifest:"Manifest",Other:"Other"});Protocol.inspectorBackend.registerEnum("Page.TransitionType",{Link:"link",Typed:"typed",Auto_bookmark:"auto_bookmark",Auto_subframe:"auto_subframe",Manual_subframe:"manual_subframe",Generated:"generated",Auto_toplevel:"auto_toplevel",Form_submit:"form_submit",Reload:"reload",Keyword:"keyword",Keyword_generated:"keyword_generated",Other:"other"});Protocol.inspectorBackend.registerEnum("Page.DialogType",{Alert:"alert",Confirm:"confirm",Prompt:"prompt",Beforeunload:"beforeunload"});Protocol.inspectorBackend.registerEnum("Page.NavigationResponse",{Proceed:"Proceed",Cancel:"Cancel",CancelAndIgnore:"CancelAndIgnore"});Protocol.inspectorBackend.registerEvent("Page.domContentEventFired",["timestamp"]);Protocol.inspectorBackend.registerEvent("Page.loadEventFired",["timestamp"]);Protocol.inspectorBackend.registerEvent("Page.lifecycleEvent",["frameId","name","timestamp"]);Protocol.inspectorBackend.registerEvent("Page.frameAttached",["frameId","parentFrameId","stack"]);Protocol.inspectorBackend.registerEvent("Page.frameNavigated",["frame"]);Protocol.inspectorBackend.registerEvent("Page.frameDetached",["frameId"]);Protocol.inspectorBackend.registerEvent("Page.frameStartedLoading",["frameId"]);Protocol.inspectorBackend.registerEvent("Page.frameStoppedLoading",["frameId"]);Protocol.inspectorBackend.registerEvent("Page.frameScheduledNavigation",["frameId","delay","reason","url"]);Protocol.inspectorBackend.registerEvent("Page.frameClearedScheduledNavigation",["frameId"]);Protocol.inspectorBackend.registerEvent("Page.frameResized",[]);Protocol.inspectorBackend.registerEvent("Page.javascriptDialogOpening",["url","message","type","defaultPrompt"]);Protocol.inspectorBackend.registerEvent("Page.javascriptDialogClosed",["result","userInput"]);Protocol.inspectorBackend.registerEvent("Page.screencastFrame",["data","metadata","sessionId"]);Protocol.inspectorBackend.registerEvent("Page.screencastVisibilityChanged",["visible"]);Protocol.inspectorBackend.registerEvent("Page.interstitialShown",[]);Protocol.inspectorBackend.registerEvent("Page.interstitialHidden",[]);Protocol.inspectorBackend.registerEvent("Page.windowOpen",["url","windowName","windowFeatures","userGesture"]);Protocol.inspectorBackend.registerCommand("Page.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Page.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Page.addScriptToEvaluateOnLoad",[{"name":"scriptSource","type":"string","optional":false}],["identifier"],false);Protocol.inspectorBackend.registerCommand("Page.removeScriptToEvaluateOnLoad",[{"name":"identifier","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.addScriptToEvaluateOnNewDocument",[{"name":"source","type":"string","optional":false}],["identifier"],false);Protocol.inspectorBackend.registerCommand("Page.removeScriptToEvaluateOnNewDocument",[{"name":"identifier","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.setAutoAttachToCreatedPages",[{"name":"autoAttach","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.reload",[{"name":"ignoreCache","type":"boolean","optional":true},{"name":"scriptToEvaluateOnLoad","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.setAdBlockingEnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.navigate",[{"name":"url","type":"string","optional":false},{"name":"referrer","type":"string","optional":true},{"name":"transitionType","type":"string","optional":true}],["frameId"],false);Protocol.inspectorBackend.registerCommand("Page.stopLoading",[],[],false);Protocol.inspectorBackend.registerCommand("Page.getNavigationHistory",[],["currentIndex","entries"],false);Protocol.inspectorBackend.registerCommand("Page.navigateToHistoryEntry",[{"name":"entryId","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.getCookies",[],["cookies"],false);Protocol.inspectorBackend.registerCommand("Page.deleteCookie",[{"name":"cookieName","type":"string","optional":false},{"name":"url","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.getResourceTree",[],["frameTree"],false);Protocol.inspectorBackend.registerCommand("Page.getResourceContent",[{"name":"frameId","type":"string","optional":false},{"name":"url","type":"string","optional":false}],["content","base64Encoded"],false);Protocol.inspectorBackend.registerCommand("Page.searchInResource",[{"name":"frameId","type":"string","optional":false},{"name":"url","type":"string","optional":false},{"name":"query","type":"string","optional":false},{"name":"caseSensitive","type":"boolean","optional":true},{"name":"isRegex","type":"boolean","optional":true}],["result"],false);Protocol.inspectorBackend.registerCommand("Page.setDocumentContent",[{"name":"frameId","type":"string","optional":false},{"name":"html","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.setDeviceMetricsOverride",[{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"deviceScaleFactor","type":"number","optional":false},{"name":"mobile","type":"boolean","optional":false},{"name":"scale","type":"number","optional":true},{"name":"screenWidth","type":"number","optional":true},{"name":"screenHeight","type":"number","optional":true},{"name":"positionX","type":"number","optional":true},{"name":"positionY","type":"number","optional":true},{"name":"dontSetVisibleSize","type":"boolean","optional":true},{"name":"screenOrientation","type":"object","optional":true},{"name":"viewport","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.clearDeviceMetricsOverride",[],[],false);Protocol.inspectorBackend.registerCommand("Page.setGeolocationOverride",[{"name":"latitude","type":"number","optional":true},{"name":"longitude","type":"number","optional":true},{"name":"accuracy","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.clearGeolocationOverride",[],[],false);Protocol.inspectorBackend.registerCommand("Page.setDeviceOrientationOverride",[{"name":"alpha","type":"number","optional":false},{"name":"beta","type":"number","optional":false},{"name":"gamma","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.clearDeviceOrientationOverride",[],[],false);Protocol.inspectorBackend.registerCommand("Page.setTouchEmulationEnabled",[{"name":"enabled","type":"boolean","optional":false},{"name":"configuration","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.captureScreenshot",[{"name":"format","type":"string","optional":true},{"name":"quality","type":"number","optional":true},{"name":"clip","type":"object","optional":true},{"name":"fromSurface","type":"boolean","optional":true}],["data"],false);Protocol.inspectorBackend.registerCommand("Page.printToPDF",[{"name":"landscape","type":"boolean","optional":true},{"name":"displayHeaderFooter","type":"boolean","optional":true},{"name":"printBackground","type":"boolean","optional":true},{"name":"scale","type":"number","optional":true},{"name":"paperWidth","type":"number","optional":true},{"name":"paperHeight","type":"number","optional":true},{"name":"marginTop","type":"number","optional":true},{"name":"marginBottom","type":"number","optional":true},{"name":"marginLeft","type":"number","optional":true},{"name":"marginRight","type":"number","optional":true},{"name":"pageRanges","type":"string","optional":true},{"name":"ignoreInvalidPageRanges","type":"boolean","optional":true}],["data"],false);Protocol.inspectorBackend.registerCommand("Page.startScreencast",[{"name":"format","type":"string","optional":true},{"name":"quality","type":"number","optional":true},{"name":"maxWidth","type":"number","optional":true},{"name":"maxHeight","type":"number","optional":true},{"name":"everyNthFrame","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.stopScreencast",[],[],false);Protocol.inspectorBackend.registerCommand("Page.screencastFrameAck",[{"name":"sessionId","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.handleJavaScriptDialog",[{"name":"accept","type":"boolean","optional":false},{"name":"promptText","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.getAppManifest",[],["url","errors","data"],false);Protocol.inspectorBackend.registerCommand("Page.requestAppBanner",[],[],false);Protocol.inspectorBackend.registerCommand("Page.getLayoutMetrics",[],["layoutViewport","visualViewport","contentSize"],false);Protocol.inspectorBackend.registerCommand("Page.createIsolatedWorld",[{"name":"frameId","type":"string","optional":false},{"name":"worldName","type":"string","optional":true},{"name":"grantUniveralAccess","type":"boolean","optional":true}],["executionContextId"],false);Protocol.inspectorBackend.registerCommand("Page.bringToFront",[],[],false);Protocol.inspectorBackend.registerCommand("Page.setDownloadBehavior",[{"name":"behavior","type":"string","optional":false},{"name":"downloadPath","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerEnum("Overlay.InspectMode",{SearchForNode:"searchForNode",SearchForUAShadowDOM:"searchForUAShadowDOM",None:"none"});Protocol.inspectorBackend.registerEvent("Overlay.nodeHighlightRequested",["nodeId"]);Protocol.inspectorBackend.registerEvent("Overlay.inspectNodeRequested",["backendNodeId"]);Protocol.inspectorBackend.registerEvent("Overlay.screenshotRequested",["viewport"]);Protocol.inspectorBackend.registerCommand("Overlay.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Overlay.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setShowPaintRects",[{"name":"result","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setShowDebugBorders",[{"name":"show","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setShowFPSCounter",[{"name":"show","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setShowScrollBottleneckRects",[{"name":"show","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setShowViewportSizeOnResize",[{"name":"show","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setPausedInDebuggerMessage",[{"name":"message","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setSuspended",[{"name":"suspended","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setInspectMode",[{"name":"mode","type":"string","optional":false},{"name":"highlightConfig","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.highlightRect",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"color","type":"object","optional":true},{"name":"outlineColor","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.highlightQuad",[{"name":"quad","type":"object","optional":false},{"name":"color","type":"object","optional":true},{"name":"outlineColor","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.highlightNode",[{"name":"highlightConfig","type":"object","optional":false},{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.highlightFrame",[{"name":"frameId","type":"string","optional":false},{"name":"contentColor","type":"object","optional":true},{"name":"contentOutlineColor","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.hideHighlight",[],[],false);Protocol.inspectorBackend.registerCommand("Overlay.getHighlightObjectForTest",[{"name":"nodeId","type":"number","optional":false}],["highlight"],false);Protocol.inspectorBackend.registerEnum("Emulation.ScreenOrientationType",{PortraitPrimary:"portraitPrimary",PortraitSecondary:"portraitSecondary",LandscapePrimary:"landscapePrimary",LandscapeSecondary:"landscapeSecondary"});Protocol.inspectorBackend.registerEnum("Emulation.VirtualTimePolicy",{Advance:"advance",Pause:"pause",PauseIfNetworkFetchesPending:"pauseIfNetworkFetchesPending"});Protocol.inspectorBackend.registerEvent("Emulation.virtualTimeBudgetExpired",[]);Protocol.inspectorBackend.registerEvent("Emulation.virtualTimeAdvanced",["virtualTimeElapsed"]);Protocol.inspectorBackend.registerEvent("Emulation.virtualTimePaused",["virtualTimeElapsed"]);Protocol.inspectorBackend.registerCommand("Emulation.setDeviceMetricsOverride",[{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"deviceScaleFactor","type":"number","optional":false},{"name":"mobile","type":"boolean","optional":false},{"name":"scale","type":"number","optional":true},{"name":"screenWidth","type":"number","optional":true},{"name":"screenHeight","type":"number","optional":true},{"name":"positionX","type":"number","optional":true},{"name":"positionY","type":"number","optional":true},{"name":"dontSetVisibleSize","type":"boolean","optional":true},{"name":"screenOrientation","type":"object","optional":true},{"name":"viewport","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.clearDeviceMetricsOverride",[],[],false);Protocol.inspectorBackend.registerCommand("Emulation.resetPageScaleFactor",[],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setPageScaleFactor",[{"name":"pageScaleFactor","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setVisibleSize",[{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setScriptExecutionDisabled",[{"name":"value","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setGeolocationOverride",[{"name":"latitude","type":"number","optional":true},{"name":"longitude","type":"number","optional":true},{"name":"accuracy","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.clearGeolocationOverride",[],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setTouchEmulationEnabled",[{"name":"enabled","type":"boolean","optional":false},{"name":"maxTouchPoints","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setEmitTouchEventsForMouse",[{"name":"enabled","type":"boolean","optional":false},{"name":"configuration","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setEmulatedMedia",[{"name":"media","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setCPUThrottlingRate",[{"name":"rate","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.canEmulate",[],["result"],false);Protocol.inspectorBackend.registerCommand("Emulation.setVirtualTimePolicy",[{"name":"policy","type":"string","optional":false},{"name":"budget","type":"number","optional":true},{"name":"maxVirtualTimeTaskStarvationCount","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setNavigatorOverrides",[{"name":"platform","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setDefaultBackgroundColorOverride",[{"name":"color","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerEnum("Security.MixedContentType",{Blockable:"blockable",OptionallyBlockable:"optionally-blockable",None:"none"});Protocol.inspectorBackend.registerEnum("Security.SecurityState",{Unknown:"unknown",Neutral:"neutral",Insecure:"insecure",Secure:"secure",Info:"info"});Protocol.inspectorBackend.registerEnum("Security.CertificateErrorAction",{Continue:"continue",Cancel:"cancel"});Protocol.inspectorBackend.registerEvent("Security.securityStateChanged",["securityState","schemeIsCryptographic","explanations","insecureContentStatus","summary"]);Protocol.inspectorBackend.registerEvent("Security.certificateError",["eventId","errorType","requestURL"]);Protocol.inspectorBackend.registerCommand("Security.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Security.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Security.handleCertificateError",[{"name":"eventId","type":"number","optional":false},{"name":"action","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Security.setOverrideCertificateErrors",[{"name":"override","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Audits.getEncodedResponse",[{"name":"requestId","type":"string","optional":false},{"name":"encoding","type":"string","optional":false},{"name":"quality","type":"number","optional":true},{"name":"sizeOnly","type":"boolean","optional":true}],["body","originalSize","encodedSize"],false);Protocol.inspectorBackend.registerEnum("Network.ErrorReason",{Failed:"Failed",Aborted:"Aborted",TimedOut:"TimedOut",AccessDenied:"AccessDenied",ConnectionClosed:"ConnectionClosed",ConnectionReset:"ConnectionReset",ConnectionRefused:"ConnectionRefused",ConnectionAborted:"ConnectionAborted",ConnectionFailed:"ConnectionFailed",NameNotResolved:"NameNotResolved",InternetDisconnected:"InternetDisconnected",AddressUnreachable:"AddressUnreachable"});Protocol.inspectorBackend.registerEnum("Network.ConnectionType",{None:"none",Cellular2g:"cellular2g",Cellular3g:"cellular3g",Cellular4g:"cellular4g",Bluetooth:"bluetooth",Ethernet:"ethernet",Wifi:"wifi",Wimax:"wimax",Other:"other"});Protocol.inspectorBackend.registerEnum("Network.CookieSameSite",{Strict:"Strict",Lax:"Lax"});Protocol.inspectorBackend.registerEnum("Network.ResourcePriority",{VeryLow:"VeryLow",Low:"Low",Medium:"Medium",High:"High",VeryHigh:"VeryHigh"});Protocol.inspectorBackend.registerEnum("Network.RequestReferrerPolicy",{UnsafeUrl:"unsafe-url",NoReferrerWhenDowngrade:"no-referrer-when-downgrade",NoReferrer:"no-referrer",Origin:"origin",OriginWhenCrossOrigin:"origin-when-cross-origin",SameOrigin:"same-origin",StrictOrigin:"strict-origin",StrictOriginWhenCrossOrigin:"strict-origin-when-cross-origin"});Protocol.inspectorBackend.registerEnum("Network.BlockedReason",{Csp:"csp",MixedContent:"mixed-content",Origin:"origin",Inspector:"inspector",SubresourceFilter:"subresource-filter",Other:"other"});Protocol.inspectorBackend.registerEnum("Network.InitiatorType",{Parser:"parser",Script:"script",Preload:"preload",Other:"other"});Protocol.inspectorBackend.registerEnum("Network.AuthChallengeSource",{Server:"Server",Proxy:"Proxy"});Protocol.inspectorBackend.registerEnum("Network.AuthChallengeResponseResponse",{Default:"Default",CancelAuth:"CancelAuth",ProvideCredentials:"ProvideCredentials"});Protocol.inspectorBackend.registerEvent("Network.resourceChangedPriority",["requestId","newPriority","timestamp"]);Protocol.inspectorBackend.registerEvent("Network.requestWillBeSent",["requestId","loaderId","documentURL","request","timestamp","wallTime","initiator","redirectResponse","type","frameId"]);Protocol.inspectorBackend.registerEvent("Network.requestServedFromCache",["requestId"]);Protocol.inspectorBackend.registerEvent("Network.responseReceived",["requestId","loaderId","timestamp","type","response","frameId"]);Protocol.inspectorBackend.registerEvent("Network.dataReceived",["requestId","timestamp","dataLength","encodedDataLength"]);Protocol.inspectorBackend.registerEvent("Network.loadingFinished",["requestId","timestamp","encodedDataLength"]);Protocol.inspectorBackend.registerEvent("Network.loadingFailed",["requestId","timestamp","type","errorText","canceled","blockedReason"]);Protocol.inspectorBackend.registerEvent("Network.webSocketWillSendHandshakeRequest",["requestId","timestamp","wallTime","request"]);Protocol.inspectorBackend.registerEvent("Network.webSocketHandshakeResponseReceived",["requestId","timestamp","response"]);Protocol.inspectorBackend.registerEvent("Network.webSocketCreated",["requestId","url","initiator"]);Protocol.inspectorBackend.registerEvent("Network.webSocketClosed",["requestId","timestamp"]);Protocol.inspectorBackend.registerEvent("Network.webSocketFrameReceived",["requestId","timestamp","response"]);Protocol.inspectorBackend.registerEvent("Network.webSocketFrameError",["requestId","timestamp","errorMessage"]);Protocol.inspectorBackend.registerEvent("Network.webSocketFrameSent",["requestId","timestamp","response"]);Protocol.inspectorBackend.registerEvent("Network.eventSourceMessageReceived",["requestId","timestamp","eventName","eventId","data"]);Protocol.inspectorBackend.registerEvent("Network.requestIntercepted",["interceptionId","request","frameId","resourceType","isNavigationRequest","redirectHeaders","redirectStatusCode","redirectUrl","authChallenge"]);Protocol.inspectorBackend.registerCommand("Network.enable",[{"name":"maxTotalBufferSize","type":"number","optional":true},{"name":"maxResourceBufferSize","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Network.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Network.setUserAgentOverride",[{"name":"userAgent","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.setExtraHTTPHeaders",[{"name":"headers","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.getResponseBody",[{"name":"requestId","type":"string","optional":false}],["body","base64Encoded"],false);Protocol.inspectorBackend.registerCommand("Network.setBlockedURLs",[{"name":"urls","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.replayXHR",[{"name":"requestId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.canClearBrowserCache",[],["result"],false);Protocol.inspectorBackend.registerCommand("Network.clearBrowserCache",[],[],false);Protocol.inspectorBackend.registerCommand("Network.canClearBrowserCookies",[],["result"],false);Protocol.inspectorBackend.registerCommand("Network.clearBrowserCookies",[],[],false);Protocol.inspectorBackend.registerCommand("Network.getCookies",[{"name":"urls","type":"object","optional":true}],["cookies"],false);Protocol.inspectorBackend.registerCommand("Network.getAllCookies",[],["cookies"],false);Protocol.inspectorBackend.registerCommand("Network.deleteCookies",[{"name":"name","type":"string","optional":false},{"name":"url","type":"string","optional":true},{"name":"domain","type":"string","optional":true},{"name":"path","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Network.setCookie",[{"name":"name","type":"string","optional":false},{"name":"value","type":"string","optional":false},{"name":"url","type":"string","optional":true},{"name":"domain","type":"string","optional":true},{"name":"path","type":"string","optional":true},{"name":"secure","type":"boolean","optional":true},{"name":"httpOnly","type":"boolean","optional":true},{"name":"sameSite","type":"string","optional":true},{"name":"expires","type":"number","optional":true}],["success"],false);Protocol.inspectorBackend.registerCommand("Network.setCookies",[{"name":"cookies","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.canEmulateNetworkConditions",[],["result"],false);Protocol.inspectorBackend.registerCommand("Network.emulateNetworkConditions",[{"name":"offline","type":"boolean","optional":false},{"name":"latency","type":"number","optional":false},{"name":"downloadThroughput","type":"number","optional":false},{"name":"uploadThroughput","type":"number","optional":false},{"name":"connectionType","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Network.setCacheDisabled",[{"name":"cacheDisabled","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.setBypassServiceWorker",[{"name":"bypass","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.setDataSizeLimitsForTest",[{"name":"maxTotalSize","type":"number","optional":false},{"name":"maxResourceSize","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.getCertificate",[{"name":"origin","type":"string","optional":false}],["tableNames"],false);Protocol.inspectorBackend.registerCommand("Network.setRequestInterception",[{"name":"patterns","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.continueInterceptedRequest",[{"name":"interceptionId","type":"string","optional":false},{"name":"errorReason","type":"string","optional":true},{"name":"rawResponse","type":"string","optional":true},{"name":"url","type":"string","optional":true},{"name":"method","type":"string","optional":true},{"name":"postData","type":"string","optional":true},{"name":"headers","type":"object","optional":true},{"name":"authChallengeResponse","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerEvent("Database.addDatabase",["database"]);Protocol.inspectorBackend.registerCommand("Database.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Database.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Database.getDatabaseTableNames",[{"name":"databaseId","type":"string","optional":false}],["tableNames"],false);Protocol.inspectorBackend.registerCommand("Database.executeSQL",[{"name":"databaseId","type":"string","optional":false},{"name":"query","type":"string","optional":false}],["columnNames","values","sqlError"],false);Protocol.inspectorBackend.registerEnum("IndexedDB.KeyType",{Number:"number",String:"string",Date:"date",Array:"array"});Protocol.inspectorBackend.registerEnum("IndexedDB.KeyPathType",{Null:"null",String:"string",Array:"array"});Protocol.inspectorBackend.registerCommand("IndexedDB.enable",[],[],false);Protocol.inspectorBackend.registerCommand("IndexedDB.disable",[],[],false);Protocol.inspectorBackend.registerCommand("IndexedDB.requestDatabaseNames",[{"name":"securityOrigin","type":"string","optional":false}],["databaseNames"],false);Protocol.inspectorBackend.registerCommand("IndexedDB.requestDatabase",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false}],["databaseWithObjectStores"],false);Protocol.inspectorBackend.registerCommand("IndexedDB.requestData",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false},{"name":"objectStoreName","type":"string","optional":false},{"name":"indexName","type":"string","optional":false},{"name":"skipCount","type":"number","optional":false},{"name":"pageSize","type":"number","optional":false},{"name":"keyRange","type":"object","optional":true}],["objectStoreDataEntries","hasMore"],false);Protocol.inspectorBackend.registerCommand("IndexedDB.clearObjectStore",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false},{"name":"objectStoreName","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("IndexedDB.deleteDatabase",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("CacheStorage.requestCacheNames",[{"name":"securityOrigin","type":"string","optional":false}],["caches"],false);Protocol.inspectorBackend.registerCommand("CacheStorage.requestEntries",[{"name":"cacheId","type":"string","optional":false},{"name":"skipCount","type":"number","optional":false},{"name":"pageSize","type":"number","optional":false}],["cacheDataEntries","hasMore"],false);Protocol.inspectorBackend.registerCommand("CacheStorage.deleteCache",[{"name":"cacheId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("CacheStorage.deleteEntry",[{"name":"cacheId","type":"string","optional":false},{"name":"request","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("CacheStorage.requestCachedResponse",[{"name":"cacheId","type":"string","optional":false},{"name":"requestURL","type":"string","optional":false}],["response"],false);Protocol.inspectorBackend.registerEvent("DOMStorage.domStorageItemsCleared",["storageId"]);Protocol.inspectorBackend.registerEvent("DOMStorage.domStorageItemRemoved",["storageId","key"]);Protocol.inspectorBackend.registerEvent("DOMStorage.domStorageItemAdded",["storageId","key","newValue"]);Protocol.inspectorBackend.registerEvent("DOMStorage.domStorageItemUpdated",["storageId","key","oldValue","newValue"]);Protocol.inspectorBackend.registerCommand("DOMStorage.enable",[],[],false);Protocol.inspectorBackend.registerCommand("DOMStorage.disable",[],[],false);Protocol.inspectorBackend.registerCommand("DOMStorage.clear",[{"name":"storageId","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMStorage.getDOMStorageItems",[{"name":"storageId","type":"object","optional":false}],["entries"],false);Protocol.inspectorBackend.registerCommand("DOMStorage.setDOMStorageItem",[{"name":"storageId","type":"object","optional":false},{"name":"key","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMStorage.removeDOMStorageItem",[{"name":"storageId","type":"object","optional":false},{"name":"key","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerEvent("ApplicationCache.applicationCacheStatusUpdated",["frameId","manifestURL","status"]);Protocol.inspectorBackend.registerEvent("ApplicationCache.networkStateUpdated",["isNowOnline"]);Protocol.inspectorBackend.registerCommand("ApplicationCache.getFramesWithManifests",[],["frameIds"],false);Protocol.inspectorBackend.registerCommand("ApplicationCache.enable",[],[],false);Protocol.inspectorBackend.registerCommand("ApplicationCache.getManifestForFrame",[{"name":"frameId","type":"string","optional":false}],["manifestURL"],false);Protocol.inspectorBackend.registerCommand("ApplicationCache.getApplicationCacheForFrame",[{"name":"frameId","type":"string","optional":false}],["applicationCache"],false);Protocol.inspectorBackend.registerEnum("DOM.PseudoType",{FirstLine:"first-line",FirstLetter:"first-letter",Before:"before",After:"after",Backdrop:"backdrop",Selection:"selection",FirstLineInherited:"first-line-inherited",Scrollbar:"scrollbar",ScrollbarThumb:"scrollbar-thumb",ScrollbarButton:"scrollbar-button",ScrollbarTrack:"scrollbar-track",ScrollbarTrackPiece:"scrollbar-track-piece",ScrollbarCorner:"scrollbar-corner",Resizer:"resizer",InputListButton:"input-list-button"});Protocol.inspectorBackend.registerEnum("DOM.ShadowRootType",{UserAgent:"user-agent",Open:"open",Closed:"closed"});Protocol.inspectorBackend.registerEvent("DOM.documentUpdated",[]);Protocol.inspectorBackend.registerEvent("DOM.setChildNodes",["parentId","nodes"]);Protocol.inspectorBackend.registerEvent("DOM.attributeModified",["nodeId","name","value"]);Protocol.inspectorBackend.registerEvent("DOM.attributeRemoved",["nodeId","name"]);Protocol.inspectorBackend.registerEvent("DOM.inlineStyleInvalidated",["nodeIds"]);Protocol.inspectorBackend.registerEvent("DOM.characterDataModified",["nodeId","characterData"]);Protocol.inspectorBackend.registerEvent("DOM.childNodeCountUpdated",["nodeId","childNodeCount"]);Protocol.inspectorBackend.registerEvent("DOM.childNodeInserted",["parentNodeId","previousNodeId","node"]);Protocol.inspectorBackend.registerEvent("DOM.childNodeRemoved",["parentNodeId","nodeId"]);Protocol.inspectorBackend.registerEvent("DOM.shadowRootPushed",["hostId","root"]);Protocol.inspectorBackend.registerEvent("DOM.shadowRootPopped",["hostId","rootId"]);Protocol.inspectorBackend.registerEvent("DOM.pseudoElementAdded",["parentId","pseudoElement"]);Protocol.inspectorBackend.registerEvent("DOM.pseudoElementRemoved",["parentId","pseudoElementId"]);Protocol.inspectorBackend.registerEvent("DOM.distributedNodesUpdated",["insertionPointId","distributedNodes"]);Protocol.inspectorBackend.registerCommand("DOM.enable",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.disable",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.getDocument",[{"name":"depth","type":"number","optional":true},{"name":"pierce","type":"boolean","optional":true}],["root"],false);Protocol.inspectorBackend.registerCommand("DOM.getFlattenedDocument",[{"name":"depth","type":"number","optional":true},{"name":"pierce","type":"boolean","optional":true}],["nodes"],false);Protocol.inspectorBackend.registerCommand("DOM.collectClassNamesFromSubtree",[{"name":"nodeId","type":"number","optional":false}],["classNames"],false);Protocol.inspectorBackend.registerCommand("DOM.requestChildNodes",[{"name":"nodeId","type":"number","optional":false},{"name":"depth","type":"number","optional":true},{"name":"pierce","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOM.querySelector",[{"name":"nodeId","type":"number","optional":false},{"name":"selector","type":"string","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.querySelectorAll",[{"name":"nodeId","type":"number","optional":false},{"name":"selector","type":"string","optional":false}],["nodeIds"],false);Protocol.inspectorBackend.registerCommand("DOM.setNodeName",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.setNodeValue",[{"name":"nodeId","type":"number","optional":false},{"name":"value","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.removeNode",[{"name":"nodeId","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.setAttributeValue",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.setAttributesAsText",[{"name":"nodeId","type":"number","optional":false},{"name":"text","type":"string","optional":false},{"name":"name","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOM.removeAttribute",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.getOuterHTML",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],["outerHTML"],false);Protocol.inspectorBackend.registerCommand("DOM.setOuterHTML",[{"name":"nodeId","type":"number","optional":false},{"name":"outerHTML","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.performSearch",[{"name":"query","type":"string","optional":false},{"name":"includeUserAgentShadowDOM","type":"boolean","optional":true}],["searchId","resultCount"],false);Protocol.inspectorBackend.registerCommand("DOM.getSearchResults",[{"name":"searchId","type":"string","optional":false},{"name":"fromIndex","type":"number","optional":false},{"name":"toIndex","type":"number","optional":false}],["nodeIds"],false);Protocol.inspectorBackend.registerCommand("DOM.discardSearchResults",[{"name":"searchId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.requestNode",[{"name":"objectId","type":"string","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.highlightRect",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.highlightNode",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.hideHighlight",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.pushNodeByPathToFrontend",[{"name":"path","type":"string","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.pushNodesByBackendIdsToFrontend",[{"name":"backendNodeIds","type":"object","optional":false}],["nodeIds"],false);Protocol.inspectorBackend.registerCommand("DOM.setInspectedNode",[{"name":"nodeId","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.resolveNode",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectGroup","type":"string","optional":true}],["object"],false);Protocol.inspectorBackend.registerCommand("DOM.getAttributes",[{"name":"nodeId","type":"number","optional":false}],["attributes"],false);Protocol.inspectorBackend.registerCommand("DOM.copyTo",[{"name":"nodeId","type":"number","optional":false},{"name":"targetNodeId","type":"number","optional":false},{"name":"insertBeforeNodeId","type":"number","optional":true}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.moveTo",[{"name":"nodeId","type":"number","optional":false},{"name":"targetNodeId","type":"number","optional":false},{"name":"insertBeforeNodeId","type":"number","optional":true}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.undo",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.redo",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.markUndoableState",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.focus",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOM.setFileInputFiles",[{"name":"files","type":"object","optional":false},{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOM.getBoxModel",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],["model"],false);Protocol.inspectorBackend.registerCommand("DOM.getNodeForLocation",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"includeUserAgentShadowDOM","type":"boolean","optional":true}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.getRelayoutBoundary",[{"name":"nodeId","type":"number","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.describeNode",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true},{"name":"depth","type":"number","optional":true},{"name":"pierce","type":"boolean","optional":true}],["node"],false);Protocol.inspectorBackend.registerEnum("CSS.StyleSheetOrigin",{Injected:"injected",UserAgent:"user-agent",Inspector:"inspector",Regular:"regular"});Protocol.inspectorBackend.registerEnum("CSS.CSSMediaSource",{MediaRule:"mediaRule",ImportRule:"importRule",LinkedSheet:"linkedSheet",InlineSheet:"inlineSheet"});Protocol.inspectorBackend.registerEvent("CSS.mediaQueryResultChanged",[]);Protocol.inspectorBackend.registerEvent("CSS.fontsUpdated",[]);Protocol.inspectorBackend.registerEvent("CSS.styleSheetChanged",["styleSheetId"]);Protocol.inspectorBackend.registerEvent("CSS.styleSheetAdded",["header"]);Protocol.inspectorBackend.registerEvent("CSS.styleSheetRemoved",["styleSheetId"]);Protocol.inspectorBackend.registerCommand("CSS.enable",[],[],false);Protocol.inspectorBackend.registerCommand("CSS.disable",[],[],false);Protocol.inspectorBackend.registerCommand("CSS.getMatchedStylesForNode",[{"name":"nodeId","type":"number","optional":false}],["inlineStyle","attributesStyle","matchedCSSRules","pseudoElements","inherited","cssKeyframesRules"],false);Protocol.inspectorBackend.registerCommand("CSS.getInlineStylesForNode",[{"name":"nodeId","type":"number","optional":false}],["inlineStyle","attributesStyle"],false);Protocol.inspectorBackend.registerCommand("CSS.getComputedStyleForNode",[{"name":"nodeId","type":"number","optional":false}],["computedStyle"],false);Protocol.inspectorBackend.registerCommand("CSS.getPlatformFontsForNode",[{"name":"nodeId","type":"number","optional":false}],["fonts"],false);Protocol.inspectorBackend.registerCommand("CSS.getStyleSheetText",[{"name":"styleSheetId","type":"string","optional":false}],["text"],false);Protocol.inspectorBackend.registerCommand("CSS.collectClassNames",[{"name":"styleSheetId","type":"string","optional":false}],["classNames"],false);Protocol.inspectorBackend.registerCommand("CSS.setStyleSheetText",[{"name":"styleSheetId","type":"string","optional":false},{"name":"text","type":"string","optional":false}],["sourceMapURL"],false);Protocol.inspectorBackend.registerCommand("CSS.setRuleSelector",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"selector","type":"string","optional":false}],["selectorList"],false);Protocol.inspectorBackend.registerCommand("CSS.setKeyframeKey",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"keyText","type":"string","optional":false}],["keyText"],false);Protocol.inspectorBackend.registerCommand("CSS.setStyleTexts",[{"name":"edits","type":"object","optional":false}],["styles"],false);Protocol.inspectorBackend.registerCommand("CSS.setMediaText",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"text","type":"string","optional":false}],["media"],false);Protocol.inspectorBackend.registerCommand("CSS.createStyleSheet",[{"name":"frameId","type":"string","optional":false}],["styleSheetId"],false);Protocol.inspectorBackend.registerCommand("CSS.addRule",[{"name":"styleSheetId","type":"string","optional":false},{"name":"ruleText","type":"string","optional":false},{"name":"location","type":"object","optional":false}],["rule"],false);Protocol.inspectorBackend.registerCommand("CSS.forcePseudoState",[{"name":"nodeId","type":"number","optional":false},{"name":"forcedPseudoClasses","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("CSS.getMediaQueries",[],["medias"],false);Protocol.inspectorBackend.registerCommand("CSS.setEffectivePropertyValueForNode",[{"name":"nodeId","type":"number","optional":false},{"name":"propertyName","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("CSS.getBackgroundColors",[{"name":"nodeId","type":"number","optional":false}],["backgroundColors","computedFontSize","computedFontWeight","computedBodyFontSize"],false);Protocol.inspectorBackend.registerCommand("CSS.startRuleUsageTracking",[],[],false);Protocol.inspectorBackend.registerCommand("CSS.takeCoverageDelta",[],["coverage"],false);Protocol.inspectorBackend.registerCommand("CSS.stopRuleUsageTracking",[],["ruleUsage"],false);Protocol.inspectorBackend.registerCommand("DOMSnapshot.getSnapshot",[{"name":"computedStyleWhitelist","type":"object","optional":false}],["domNodes","layoutTreeNodes","computedStyles"],false);Protocol.inspectorBackend.registerCommand("IO.read",[{"name":"handle","type":"string","optional":false},{"name":"offset","type":"number","optional":true},{"name":"size","type":"number","optional":true}],["base64Encoded","data","eof"],false);Protocol.inspectorBackend.registerCommand("IO.close",[{"name":"handle","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("IO.resolveBlob",[{"name":"objectId","type":"string","optional":false}],["uuid"],false);Protocol.inspectorBackend.registerEnum("DOMDebugger.DOMBreakpointType",{SubtreeModified:"subtree-modified",AttributeModified:"attribute-modified",NodeRemoved:"node-removed"});Protocol.inspectorBackend.registerCommand("DOMDebugger.setDOMBreakpoint",[{"name":"nodeId","type":"number","optional":false},{"name":"type","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.removeDOMBreakpoint",[{"name":"nodeId","type":"number","optional":false},{"name":"type","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.setEventListenerBreakpoint",[{"name":"eventName","type":"string","optional":false},{"name":"targetName","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.removeEventListenerBreakpoint",[{"name":"eventName","type":"string","optional":false},{"name":"targetName","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.setInstrumentationBreakpoint",[{"name":"eventName","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.removeInstrumentationBreakpoint",[{"name":"eventName","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.setXHRBreakpoint",[{"name":"url","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.removeXHRBreakpoint",[{"name":"url","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.getEventListeners",[{"name":"objectId","type":"string","optional":false},{"name":"depth","type":"number","optional":true},{"name":"pierce","type":"boolean","optional":true}],["listeners"],false);Protocol.inspectorBackend.registerEvent("Target.targetCreated",["targetInfo"]);Protocol.inspectorBackend.registerEvent("Target.targetInfoChanged",["targetInfo"]);Protocol.inspectorBackend.registerEvent("Target.targetDestroyed",["targetId"]);Protocol.inspectorBackend.registerEvent("Target.attachedToTarget",["sessionId","targetInfo","waitingForDebugger"]);Protocol.inspectorBackend.registerEvent("Target.detachedFromTarget",["sessionId","targetId"]);Protocol.inspectorBackend.registerEvent("Target.receivedMessageFromTarget",["sessionId","message","targetId"]);Protocol.inspectorBackend.registerCommand("Target.setDiscoverTargets",[{"name":"discover","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Target.setAutoAttach",[{"name":"autoAttach","type":"boolean","optional":false},{"name":"waitForDebuggerOnStart","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Target.setAttachToFrames",[{"name":"value","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Target.setRemoteLocations",[{"name":"locations","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Target.sendMessageToTarget",[{"name":"message","type":"string","optional":false},{"name":"sessionId","type":"string","optional":true},{"name":"targetId","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Target.getTargetInfo",[{"name":"targetId","type":"string","optional":false}],["targetInfo"],false);Protocol.inspectorBackend.registerCommand("Target.activateTarget",[{"name":"targetId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Target.closeTarget",[{"name":"targetId","type":"string","optional":false}],["success"],false);Protocol.inspectorBackend.registerCommand("Target.attachToTarget",[{"name":"targetId","type":"string","optional":false}],["sessionId"],false);Protocol.inspectorBackend.registerCommand("Target.detachFromTarget",[{"name":"sessionId","type":"string","optional":true},{"name":"targetId","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Target.createBrowserContext",[],["browserContextId"],false);Protocol.inspectorBackend.registerCommand("Target.disposeBrowserContext",[{"name":"browserContextId","type":"string","optional":false}],["success"],false);Protocol.inspectorBackend.registerCommand("Target.createTarget",[{"name":"url","type":"string","optional":false},{"name":"width","type":"number","optional":true},{"name":"height","type":"number","optional":true},{"name":"browserContextId","type":"string","optional":true},{"name":"enableBeginFrameControl","type":"boolean","optional":true}],["targetId"],false);Protocol.inspectorBackend.registerCommand("Target.getTargets",[],["targetInfos"],false);Protocol.inspectorBackend.registerEnum("HeadlessExperimental.ScreenshotParamsFormat",{Jpeg:"jpeg",Png:"png"});Protocol.inspectorBackend.registerEvent("HeadlessExperimental.needsBeginFramesChanged",["needsBeginFrames"]);Protocol.inspectorBackend.registerEvent("HeadlessExperimental.mainFrameReadyForScreenshots",[]);Protocol.inspectorBackend.registerCommand("HeadlessExperimental.enable",[],[],false);Protocol.inspectorBackend.registerCommand("HeadlessExperimental.disable",[],[],false);Protocol.inspectorBackend.registerCommand("HeadlessExperimental.beginFrame",[{"name":"frameTime","type":"number","optional":true},{"name":"deadline","type":"number","optional":true},{"name":"interval","type":"number","optional":true},{"name":"screenshot","type":"object","optional":true}],["hasDamage","mainFrameContentUpdated","screenshotData"],false);Protocol.inspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionRunningStatus",{Stopped:"stopped",Starting:"starting",Running:"running",Stopping:"stopping"});Protocol.inspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionStatus",{New:"new",Installing:"installing",Installed:"installed",Activating:"activating",Activated:"activated",Redundant:"redundant"});Protocol.inspectorBackend.registerEvent("ServiceWorker.workerRegistrationUpdated",["registrations"]);Protocol.inspectorBackend.registerEvent("ServiceWorker.workerVersionUpdated",["versions"]);Protocol.inspectorBackend.registerEvent("ServiceWorker.workerErrorReported",["errorMessage"]);Protocol.inspectorBackend.registerCommand("ServiceWorker.enable",[],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.disable",[],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.unregister",[{"name":"scopeURL","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.updateRegistration",[{"name":"scopeURL","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.startWorker",[{"name":"scopeURL","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.skipWaiting",[{"name":"scopeURL","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.stopWorker",[{"name":"versionId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.stopAllWorkers",[],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.inspectWorker",[{"name":"versionId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.setForceUpdateOnPageLoad",[{"name":"forceUpdateOnPageLoad","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.deliverPushMessage",[{"name":"origin","type":"string","optional":false},{"name":"registrationId","type":"string","optional":false},{"name":"data","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.dispatchSyncEvent",[{"name":"origin","type":"string","optional":false},{"name":"registrationId","type":"string","optional":false},{"name":"tag","type":"string","optional":false},{"name":"lastChance","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("Input.GestureSourceType",{Default:"default",Touch:"touch",Mouse:"mouse"});Protocol.inspectorBackend.registerCommand("Input.setIgnoreInputEvents",[{"name":"ignore","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Input.dispatchKeyEvent",[{"name":"type","type":"string","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true},{"name":"text","type":"string","optional":true},{"name":"unmodifiedText","type":"string","optional":true},{"name":"key","type":"string","optional":true},{"name":"code","type":"string","optional":true},{"name":"key","type":"string","optional":true},{"name":"windowsVirtualKeyCode","type":"number","optional":true},{"name":"nativeVirtualKeyCode","type":"number","optional":true},{"name":"autoRepeat","type":"boolean","optional":true},{"name":"isKeypad","type":"boolean","optional":true},{"name":"isSystemKey","type":"boolean","optional":true},{"name":"location","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.dispatchMouseEvent",[{"name":"type","type":"string","optional":false},{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true},{"name":"button","type":"string","optional":true},{"name":"clickCount","type":"number","optional":true},{"name":"deltaX","type":"number","optional":true},{"name":"deltaY","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.dispatchTouchEvent",[{"name":"type","type":"string","optional":false},{"name":"touchPoints","type":"object","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.emulateTouchFromMouseEvent",[{"name":"type","type":"string","optional":false},{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"timestamp","type":"number","optional":false},{"name":"button","type":"string","optional":false},{"name":"deltaX","type":"number","optional":true},{"name":"deltaY","type":"number","optional":true},{"name":"modifiers","type":"number","optional":true},{"name":"clickCount","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.synthesizePinchGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"scaleFactor","type":"number","optional":false},{"name":"relativeSpeed","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.synthesizeScrollGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"xDistance","type":"number","optional":true},{"name":"yDistance","type":"number","optional":true},{"name":"xOverscroll","type":"number","optional":true},{"name":"yOverscroll","type":"number","optional":true},{"name":"preventFling","type":"boolean","optional":true},{"name":"speed","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true},{"name":"repeatCount","type":"number","optional":true},{"name":"repeatDelayMs","type":"number","optional":true},{"name":"interactionMarkerName","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.synthesizeTapGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"duration","type":"number","optional":true},{"name":"tapCount","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerEnum("LayerTree.ScrollRectType",{RepaintsOnScroll:"RepaintsOnScroll",TouchEventHandler:"TouchEventHandler",WheelEventHandler:"WheelEventHandler"});Protocol.inspectorBackend.registerEvent("LayerTree.layerTreeDidChange",["layers"]);Protocol.inspectorBackend.registerEvent("LayerTree.layerPainted",["layerId","clip"]);Protocol.inspectorBackend.registerCommand("LayerTree.enable",[],[],false);Protocol.inspectorBackend.registerCommand("LayerTree.disable",[],[],false);Protocol.inspectorBackend.registerCommand("LayerTree.compositingReasons",[{"name":"layerId","type":"string","optional":false}],["compositingReasons"],false);Protocol.inspectorBackend.registerCommand("LayerTree.makeSnapshot",[{"name":"layerId","type":"string","optional":false}],["snapshotId"],false);Protocol.inspectorBackend.registerCommand("LayerTree.loadSnapshot",[{"name":"tiles","type":"object","optional":false}],["snapshotId"],false);Protocol.inspectorBackend.registerCommand("LayerTree.releaseSnapshot",[{"name":"snapshotId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("LayerTree.profileSnapshot",[{"name":"snapshotId","type":"string","optional":false},{"name":"minRepeatCount","type":"number","optional":true},{"name":"minDuration","type":"number","optional":true},{"name":"clipRect","type":"object","optional":true}],["timings"],false);Protocol.inspectorBackend.registerCommand("LayerTree.replaySnapshot",[{"name":"snapshotId","type":"string","optional":false},{"name":"fromStep","type":"number","optional":true},{"name":"toStep","type":"number","optional":true},{"name":"scale","type":"number","optional":true}],["dataURL"],false);Protocol.inspectorBackend.registerCommand("LayerTree.snapshotCommandLog",[{"name":"snapshotId","type":"string","optional":false}],["commandLog"],false);Protocol.inspectorBackend.registerCommand("DeviceOrientation.setDeviceOrientationOverride",[{"name":"alpha","type":"number","optional":false},{"name":"beta","type":"number","optional":false},{"name":"gamma","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DeviceOrientation.clearDeviceOrientationOverride",[],[],false);Protocol.inspectorBackend.registerEnum("Tracing.TraceConfigRecordMode",{RecordUntilFull:"recordUntilFull",RecordContinuously:"recordContinuously",RecordAsMuchAsPossible:"recordAsMuchAsPossible",EchoToConsole:"echoToConsole"});Protocol.inspectorBackend.registerEvent("Tracing.dataCollected",["value"]);Protocol.inspectorBackend.registerEvent("Tracing.tracingComplete",["stream"]);Protocol.inspectorBackend.registerEvent("Tracing.bufferUsage",["percentFull","eventCount","value"]);Protocol.inspectorBackend.registerCommand("Tracing.start",[{"name":"categories","type":"string","optional":true},{"name":"options","type":"string","optional":true},{"name":"bufferUsageReportingInterval","type":"number","optional":true},{"name":"transferMode","type":"string","optional":true},{"name":"traceConfig","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Tracing.end",[],[],false);Protocol.inspectorBackend.registerCommand("Tracing.getCategories",[],["categories"],false);Protocol.inspectorBackend.registerCommand("Tracing.requestMemoryDump",[],["dumpGuid","success"],false);Protocol.inspectorBackend.registerCommand("Tracing.recordClockSyncMarker",[{"name":"syncId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("Animation.AnimationType",{CSSTransition:"CSSTransition",CSSAnimation:"CSSAnimation",WebAnimation:"WebAnimation"});Protocol.inspectorBackend.registerEvent("Animation.animationCreated",["id"]);Protocol.inspectorBackend.registerEvent("Animation.animationStarted",["animation"]);Protocol.inspectorBackend.registerEvent("Animation.animationCanceled",["id"]);Protocol.inspectorBackend.registerCommand("Animation.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Animation.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Animation.getPlaybackRate",[],["playbackRate"],false);Protocol.inspectorBackend.registerCommand("Animation.setPlaybackRate",[{"name":"playbackRate","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.getCurrentTime",[{"name":"id","type":"string","optional":false}],["currentTime"],false);Protocol.inspectorBackend.registerCommand("Animation.setPaused",[{"name":"animations","type":"object","optional":false},{"name":"paused","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.setTiming",[{"name":"animationId","type":"string","optional":false},{"name":"duration","type":"number","optional":false},{"name":"delay","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.seekAnimations",[{"name":"animations","type":"object","optional":false},{"name":"currentTime","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.releaseAnimations",[{"name":"animations","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.resolveAnimation",[{"name":"animationId","type":"string","optional":false}],["remoteObject"],false);Protocol.inspectorBackend.registerEnum("Accessibility.AXValueType",{Boolean:"boolean",Tristate:"tristate",BooleanOrUndefined:"booleanOrUndefined",Idref:"idref",IdrefList:"idrefList",Integer:"integer",Node:"node",NodeList:"nodeList",Number:"number",String:"string",ComputedString:"computedString",Token:"token",TokenList:"tokenList",DomRelation:"domRelation",Role:"role",InternalRole:"internalRole",ValueUndefined:"valueUndefined"});Protocol.inspectorBackend.registerEnum("Accessibility.AXValueSourceType",{Attribute:"attribute",Implicit:"implicit",Style:"style",Contents:"contents",Placeholder:"placeholder",RelatedElement:"relatedElement"});Protocol.inspectorBackend.registerEnum("Accessibility.AXValueNativeSourceType",{Figcaption:"figcaption",Label:"label",Labelfor:"labelfor",Labelwrapped:"labelwrapped",Legend:"legend",Tablecaption:"tablecaption",Title:"title",Other:"other"});Protocol.inspectorBackend.registerEnum("Accessibility.AXGlobalStates",{Busy:"busy",Disabled:"disabled",Hidden:"hidden",HiddenRoot:"hiddenRoot",Invalid:"invalid",Keyshortcuts:"keyshortcuts",Roledescription:"roledescription"});Protocol.inspectorBackend.registerEnum("Accessibility.AXLiveRegionAttributes",{Live:"live",Atomic:"atomic",Relevant:"relevant",Root:"root"});Protocol.inspectorBackend.registerEnum("Accessibility.AXWidgetAttributes",{Autocomplete:"autocomplete",Haspopup:"haspopup",Level:"level",Multiselectable:"multiselectable",Orientation:"orientation",Multiline:"multiline",Readonly:"readonly",Required:"required",Valuemin:"valuemin",Valuemax:"valuemax",Valuetext:"valuetext"});Protocol.inspectorBackend.registerEnum("Accessibility.AXWidgetStates",{Checked:"checked",Expanded:"expanded",Modal:"modal",Pressed:"pressed",Selected:"selected"});Protocol.inspectorBackend.registerEnum("Accessibility.AXRelationshipAttributes",{Activedescendant:"activedescendant",Controls:"controls",Describedby:"describedby",Details:"details",Errormessage:"errormessage",Flowto:"flowto",Labelledby:"labelledby",Owns:"owns"});Protocol.inspectorBackend.registerCommand("Accessibility.getPartialAXTree",[{"name":"nodeId","type":"number","optional":false},{"name":"fetchRelatives","type":"boolean","optional":true}],["nodes"],false);Protocol.inspectorBackend.registerEnum("Storage.StorageType",{Appcache:"appcache",Cookies:"cookies",File_systems:"file_systems",Indexeddb:"indexeddb",Local_storage:"local_storage",Shader_cache:"shader_cache",Websql:"websql",Service_workers:"service_workers",Cache_storage:"cache_storage",All:"all",Other:"other"});Protocol.inspectorBackend.registerEvent("Storage.cacheStorageListUpdated",["origin"]);Protocol.inspectorBackend.registerEvent("Storage.cacheStorageContentUpdated",["origin","cacheName"]);Protocol.inspectorBackend.registerEvent("Storage.indexedDBListUpdated",["origin"]);Protocol.inspectorBackend.registerEvent("Storage.indexedDBContentUpdated",["origin","databaseName","objectStoreName"]);Protocol.inspectorBackend.registerCommand("Storage.clearDataForOrigin",[{"name":"origin","type":"string","optional":false},{"name":"storageTypes","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Storage.getUsageAndQuota",[{"name":"origin","type":"string","optional":false}],["usage","quota","usageBreakdown"],false);Protocol.inspectorBackend.registerCommand("Storage.trackCacheStorageForOrigin",[{"name":"origin","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Storage.untrackCacheStorageForOrigin",[{"name":"origin","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Storage.trackIndexedDBForOrigin",[{"name":"origin","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Storage.untrackIndexedDBForOrigin",[{"name":"origin","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("Log.LogEntrySource",{XML:"xml",Javascript:"javascript",Network:"network",Storage:"storage",Appcache:"appcache",Rendering:"rendering",Security:"security",Deprecation:"deprecation",Worker:"worker",Violation:"violation",Intervention:"intervention",Recommendation:"recommendation",Other:"other"});Protocol.inspectorBackend.registerEnum("Log.LogEntryLevel",{Verbose:"verbose",Info:"info",Warning:"warning",Error:"error"});Protocol.inspectorBackend.registerEnum("Log.ViolationSettingName",{LongTask:"longTask",LongLayout:"longLayout",BlockedEvent:"blockedEvent",BlockedParser:"blockedParser",DiscouragedAPIUse:"discouragedAPIUse",Handler:"handler",RecurringHandler:"recurringHandler"});Protocol.inspectorBackend.registerEvent("Log.entryAdded",["entry"]);Protocol.inspectorBackend.registerCommand("Log.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Log.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Log.clear",[],[],false);Protocol.inspectorBackend.registerCommand("Log.startViolationsReport",[{"name":"config","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Log.stopViolationsReport",[],[],false);Protocol.inspectorBackend.registerCommand("SystemInfo.getInfo",[],["gpu","modelName","modelVersion","commandLine"],false);Protocol.inspectorBackend.registerEvent("Tethering.accepted",["port","connectionId"]);Protocol.inspectorBackend.registerCommand("Tethering.bind",[{"name":"port","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Tethering.unbind",[{"name":"port","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("Browser.WindowState",{Normal:"normal",Minimized:"minimized",Maximized:"maximized",Fullscreen:"fullscreen"});Protocol.inspectorBackend.registerCommand("Browser.close",[],[],false);Protocol.inspectorBackend.registerCommand("Browser.getWindowForTarget",[{"name":"targetId","type":"string","optional":false}],["windowId","bounds"],false);Protocol.inspectorBackend.registerCommand("Browser.getVersion",[],["protocolVersion","product","revision","userAgent","jsVersion"],false);Protocol.inspectorBackend.registerCommand("Browser.setWindowBounds",[{"name":"windowId","type":"number","optional":false},{"name":"bounds","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Browser.getWindowBounds",[{"name":"windowId","type":"number","optional":false}],["bounds"],false);Protocol.inspectorBackend.registerCommand("Schema.getDomains",[],["domains"],false);Protocol.inspectorBackend.registerEnum("Runtime.UnserializableValue",{Infinity:"Infinity",NaN:"NaN",NegativeInfinity:"-Infinity",Negative0:"-0"});Protocol.inspectorBackend.registerEnum("Runtime.RemoteObjectType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol"});Protocol.inspectorBackend.registerEnum("Runtime.RemoteObjectSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Weakmap:"weakmap",Weakset:"weakset",Iterator:"iterator",Generator:"generator",Error:"error",Proxy:"proxy",Promise:"promise",Typedarray:"typedarray"});Protocol.inspectorBackend.registerEnum("Runtime.ObjectPreviewType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol"});Protocol.inspectorBackend.registerEnum("Runtime.ObjectPreviewSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Weakmap:"weakmap",Weakset:"weakset",Iterator:"iterator",Generator:"generator",Error:"error"});Protocol.inspectorBackend.registerEnum("Runtime.PropertyPreviewType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol",Accessor:"accessor"});Protocol.inspectorBackend.registerEnum("Runtime.PropertyPreviewSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Weakmap:"weakmap",Weakset:"weakset",Iterator:"iterator",Generator:"generator",Error:"error"});Protocol.inspectorBackend.registerEvent("Runtime.executionContextCreated",["context"]);Protocol.inspectorBackend.registerEvent("Runtime.executionContextDestroyed",["executionContextId"]);Protocol.inspectorBackend.registerEvent("Runtime.executionContextsCleared",[]);Protocol.inspectorBackend.registerEvent("Runtime.exceptionThrown",["timestamp","exceptionDetails"]);Protocol.inspectorBackend.registerEvent("Runtime.exceptionRevoked",["reason","exceptionId"]);Protocol.inspectorBackend.registerEvent("Runtime.consoleAPICalled",["type","args","executionContextId","timestamp","stackTrace","context"]);Protocol.inspectorBackend.registerEvent("Runtime.inspectRequested",["object","hints"]);Protocol.inspectorBackend.registerCommand("Runtime.evaluate",[{"name":"expression","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true},{"name":"includeCommandLineAPI","type":"boolean","optional":true},{"name":"silent","type":"boolean","optional":true},{"name":"contextId","type":"number","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true},{"name":"userGesture","type":"boolean","optional":true},{"name":"awaitPromise","type":"boolean","optional":true}],["result","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.awaitPromise",[{"name":"promiseObjectId","type":"string","optional":false},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.callFunctionOn",[{"name":"functionDeclaration","type":"string","optional":false},{"name":"objectId","type":"string","optional":true},{"name":"arguments","type":"object","optional":true},{"name":"silent","type":"boolean","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true},{"name":"userGesture","type":"boolean","optional":true},{"name":"awaitPromise","type":"boolean","optional":true},{"name":"executionContextId","type":"number","optional":true},{"name":"objectGroup","type":"string","optional":true}],["result","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.getProperties",[{"name":"objectId","type":"string","optional":false},{"name":"ownProperties","type":"boolean","optional":true},{"name":"accessorPropertiesOnly","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","internalProperties","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.releaseObject",[{"name":"objectId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Runtime.releaseObjectGroup",[{"name":"objectGroup","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Runtime.runIfWaitingForDebugger",[],[],false);Protocol.inspectorBackend.registerCommand("Runtime.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Runtime.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Runtime.discardConsoleEntries",[],[],false);Protocol.inspectorBackend.registerCommand("Runtime.setCustomObjectFormatterEnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Runtime.compileScript",[{"name":"expression","type":"string","optional":false},{"name":"sourceURL","type":"string","optional":false},{"name":"persistScript","type":"boolean","optional":false},{"name":"executionContextId","type":"number","optional":true}],["scriptId","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.runScript",[{"name":"scriptId","type":"string","optional":false},{"name":"executionContextId","type":"number","optional":true},{"name":"objectGroup","type":"string","optional":true},{"name":"silent","type":"boolean","optional":true},{"name":"includeCommandLineAPI","type":"boolean","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true},{"name":"awaitPromise","type":"boolean","optional":true}],["result","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.queryObjects",[{"name":"prototypeObjectId","type":"string","optional":false}],["objects"],false);Protocol.inspectorBackend.registerCommand("Runtime.globalLexicalScopeNames",[{"name":"executionContextId","type":"number","optional":true}],["names"],false);Protocol.inspectorBackend.registerEnum("Debugger.ScopeType",{Global:"global",Local:"local",With:"with",Closure:"closure",Catch:"catch",Block:"block",Script:"script",Eval:"eval",Module:"module"});Protocol.inspectorBackend.registerEnum("Debugger.BreakLocationType",{DebuggerStatement:"debuggerStatement",Call:"call",Return:"return"});Protocol.inspectorBackend.registerEvent("Debugger.scriptParsed",["scriptId","url","startLine","startColumn","endLine","endColumn","executionContextId","hash","executionContextAuxData","isLiveEdit","sourceMapURL","hasSourceURL","isModule","length","stackTrace"]);Protocol.inspectorBackend.registerEvent("Debugger.scriptFailedToParse",["scriptId","url","startLine","startColumn","endLine","endColumn","executionContextId","hash","executionContextAuxData","sourceMapURL","hasSourceURL","isModule","length","stackTrace"]);Protocol.inspectorBackend.registerEvent("Debugger.breakpointResolved",["breakpointId","location"]);Protocol.inspectorBackend.registerEvent("Debugger.paused",["callFrames","reason","data","hitBreakpoints","asyncStackTrace"]);Protocol.inspectorBackend.registerEvent("Debugger.resumed",[]);Protocol.inspectorBackend.registerCommand("Debugger.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setBreakpointsActive",[{"name":"active","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setSkipAllPauses",[{"name":"skip","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setBreakpointByUrl",[{"name":"lineNumber","type":"number","optional":false},{"name":"url","type":"string","optional":true},{"name":"urlRegex","type":"string","optional":true},{"name":"scriptHash","type":"string","optional":true},{"name":"columnNumber","type":"number","optional":true},{"name":"condition","type":"string","optional":true}],["breakpointId","locations"],false);Protocol.inspectorBackend.registerCommand("Debugger.setBreakpoint",[{"name":"location","type":"object","optional":false},{"name":"condition","type":"string","optional":true}],["breakpointId","actualLocation"],false);Protocol.inspectorBackend.registerCommand("Debugger.removeBreakpoint",[{"name":"breakpointId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.getPossibleBreakpoints",[{"name":"start","type":"object","optional":false},{"name":"end","type":"object","optional":true},{"name":"restrictToFunction","type":"boolean","optional":true}],["locations"],false);Protocol.inspectorBackend.registerCommand("Debugger.continueToLocation",[{"name":"location","type":"object","optional":false},{"name":"targetCallFrames","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.stepOver",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.stepInto",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.stepOut",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.pause",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.scheduleStepIntoAsync",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.resume",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.searchInContent",[{"name":"scriptId","type":"string","optional":false},{"name":"query","type":"string","optional":false},{"name":"caseSensitive","type":"boolean","optional":true},{"name":"isRegex","type":"boolean","optional":true}],["result"],false);Protocol.inspectorBackend.registerCommand("Debugger.setScriptSource",[{"name":"scriptId","type":"string","optional":false},{"name":"scriptSource","type":"string","optional":false},{"name":"dryRun","type":"boolean","optional":true}],["callFrames","stackChanged","asyncStackTrace","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Debugger.restartFrame",[{"name":"callFrameId","type":"string","optional":false}],["callFrames","asyncStackTrace"],false);Protocol.inspectorBackend.registerCommand("Debugger.getScriptSource",[{"name":"scriptId","type":"string","optional":false}],["scriptSource"],false);Protocol.inspectorBackend.registerCommand("Debugger.setPauseOnExceptions",[{"name":"state","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.evaluateOnCallFrame",[{"name":"callFrameId","type":"string","optional":false},{"name":"expression","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true},{"name":"includeCommandLineAPI","type":"boolean","optional":true},{"name":"silent","type":"boolean","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true},{"name":"throwOnSideEffect","type":"boolean","optional":true}],["result","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Debugger.setVariableValue",[{"name":"scopeNumber","type":"number","optional":false},{"name":"variableName","type":"string","optional":false},{"name":"newValue","type":"object","optional":false},{"name":"callFrameId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setAsyncCallStackDepth",[{"name":"maxDepth","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setBlackboxPatterns",[{"name":"patterns","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setBlackboxedRanges",[{"name":"scriptId","type":"string","optional":false},{"name":"positions","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerEvent("Profiler.consoleProfileStarted",["id","location","title"]);Protocol.inspectorBackend.registerEvent("Profiler.consoleProfileFinished",["id","location","profile","title"]);Protocol.inspectorBackend.registerCommand("Profiler.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.setSamplingInterval",[{"name":"interval","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Profiler.start",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.stop",[],["profile"],false);Protocol.inspectorBackend.registerCommand("Profiler.startPreciseCoverage",[{"name":"callCount","type":"boolean","optional":true},{"name":"detailed","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Profiler.stopPreciseCoverage",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.takePreciseCoverage",[],["result"],false);Protocol.inspectorBackend.registerCommand("Profiler.getBestEffortCoverage",[],["result"],false);Protocol.inspectorBackend.registerCommand("Profiler.startTypeProfile",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.stopTypeProfile",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.takeTypeProfile",[],["result"],false);Protocol.inspectorBackend.registerEvent("HeapProfiler.addHeapSnapshotChunk",["chunk"]);Protocol.inspectorBackend.registerEvent("HeapProfiler.resetProfiles",[]);Protocol.inspectorBackend.registerEvent("HeapProfiler.reportHeapSnapshotProgress",["done","total","finished"]);Protocol.inspectorBackend.registerEvent("HeapProfiler.lastSeenObjectId",["lastSeenObjectId","timestamp"]);Protocol.inspectorBackend.registerEvent("HeapProfiler.heapStatsUpdate",["statsUpdate"]);Protocol.inspectorBackend.registerCommand("HeapProfiler.enable",[],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.disable",[],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.startTrackingHeapObjects",[{"name":"trackAllocations","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.stopTrackingHeapObjects",[{"name":"reportProgress","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.takeHeapSnapshot",[{"name":"reportProgress","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.collectGarbage",[],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.getObjectByHeapObjectId",[{"name":"objectId","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true}],["result"],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.addInspectedHeapObject",[{"name":"heapObjectId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.getHeapObjectId",[{"name":"objectId","type":"string","optional":false}],["heapSnapshotObjectId"],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.startSampling",[{"name":"samplingInterval","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.stopSampling",[],["profile"],false);;self['Help']=self['Help']||{};Help.latestReleaseNote=function(){if(!Help._latestReleaseNote){Help._latestReleaseNote=Help.releaseNoteText.reduce((acc,note)=>note.version>acc.version?note:acc);} -return Help._latestReleaseNote;};Help.releaseNoteVersionSetting=function(){if(!Help._releaseNoteVersionSetting){Help._releaseNoteVersionSetting=Common.settings.createSetting('releaseNoteVersionSeen',0);} -return Help._releaseNoteVersionSetting;};Help.showReleaseNoteIfNeeded=function(){Help._showReleaseNoteIfNeeded(Help.releaseNoteVersionSetting().get(),Help.latestReleaseNote().version);};Help._showReleaseNoteIfNeeded=function(lastSeenVersion,latestVersion){if(!lastSeenVersion){Help.releaseNoteVersionSetting().set(latestVersion);return;} -if(lastSeenVersion>=latestVersion) -return;Help.releaseNoteVersionSetting().set(latestVersion);UI.viewManager.showView(Help.releaseNoteViewId,true);};Help.releaseNoteViewId='release-note';Help.ReleaseNoteHighlight;Help.ReleaseNote;;Help.ReleaseNoteView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('help/releaseNote.css');var releaseNoteElement=this._createReleaseNoteElement(Help.latestReleaseNote());var topSection=this.contentElement.createChild('div','release-note-top-section');topSection.textContent=Common.UIString(Help.latestReleaseNote().header);this.contentElement.appendChild(releaseNoteElement);} -_createReleaseNoteElement(releaseNote){var hbox=createElementWithClass('div','hbox');var container=hbox.createChild('div','release-note-container');var contentContainer=container.createChild('ul');for(var highlight of releaseNote.highlights){var listItem=contentContainer.createChild('li');var title=UI.createExternalLink(highlight.link,highlight.title+' ','release-note-title');title.title='';listItem.appendChild(title);var subtitle=UI.createExternalLink(highlight.link,highlight.subtitle+' ','release-note-subtitle');subtitle.title='';listItem.appendChild(subtitle);} -var actionContainer=container.createChild('div','release-note-action-container');actionContainer.appendChild(UI.createTextButton(Common.UIString('Learn more'),event=>{event.consume(true);InspectorFrontendHost.openInNewTab(releaseNote.link);}));actionContainer.appendChild(UI.createTextButton(Common.UIString('Close'),event=>{event.consume(true);UI.inspectorView.closeDrawerTab(Help.releaseNoteViewId,true);},'close-release-note'));var imageLink=UI.createExternalLink(releaseNote.link,' ');imageLink.classList.add('release-note-image');imageLink.title='';hbox.appendChild(imageLink);var image=imageLink.createChild('img');image.src='Images/whatsnew.png';return hbox;}};;var continueToHereShortcut=Host.isMac()?'Command':'Control';var commandMenuShortcut=Host.isMac()?'Command + Shift + P':'Control + Shift + P';Help.releaseNoteText=[{version:6,header:'Highlights from the Chrome 63 update',highlights:[{title:'Multi-client remote debugging',subtitle:'Use DevTools while debugging your app from an IDE or testing framework.',link:'https://developers.google.com/web/updates/2017/10/devtools-release-notes#multi-client',},{title:'Workspaces 2.0',subtitle:'Save changes made in DevTools to disk, now with more helpful UI and better auto-mapping.',link:'https://developers.google.com/web/updates/2017/10/devtools-release-notes#workspaces',},{title:'Four new audits',subtitle:'Including "Appropriate aspect ratios for images", "Avoid JS libraries with known vulnerabilities", and more.',link:'https://developers.google.com/web/updates/2017/10/devtools-release-notes#audits',},{title:'Custom push notifications',subtitle:'Simulate push notifications with custom data.',link:'https://developers.google.com/web/updates/2017/10/devtools-release-notes#push',},{title:'Custom background sync events',subtitle:'Trigger background sync events with custom tags.',link:'https://developers.google.com/web/updates/2017/10/devtools-release-notes#sync',},],link:'https://developers.google.com/web/updates/2017/10/devtools-release-notes',},{version:5,header:'Highlights from the Chrome 62 update',highlights:[{title:'Top-level await operators in the Console',subtitle:'Use await to conveniently experiment with asynchronous functions in the Console.',link:'https://developers.google.com/web/updates/2017/08/devtools-release-notes#await',},{title:'New screenshot workflows',subtitle:'Take screenshots of a portion of the viewport, or of specific HTML nodes.',link:'https://developers.google.com/web/updates/2017/08/devtools-release-notes#screenshots',},{title:'CSS Grid highlighting',subtitle:'Hover over an element to see the CSS Grid that\'s affecting it.',link:'https://developers.google.com/web/updates/2017/08/devtools-release-notes#css-grid-highlighting',},{title:'A new Console API for querying objects',subtitle:'Call queryObjects(Constructor) to get an array of objects instantiated with that constructor.',link:'https://developers.google.com/web/updates/2017/08/devtools-release-notes#query-objects',},{title:'New Console filters',subtitle:'Filter out logging noise with the new negative and URL filters.',link:'https://developers.google.com/web/updates/2017/08/devtools-release-notes#console-filters',},{title:'HAR imports in the Network panel',subtitle:'Drag-and-drop a HAR file to analyze a previous network recording.',link:'https://developers.google.com/web/updates/2017/08/devtools-release-notes#har-imports',},{title:'Previewable cache resources in the Application panel',subtitle:'Click a row in a Cache Storage table to see a preview of that resource.',link:'https://developers.google.com/web/updates/2017/08/devtools-release-notes#cache-preview',}],link:'https://developers.google.com/web/updates/2017/08/devtools-release-notes',},{version:4,header:'Highlights from the Chrome 61 update',highlights:[{title:'Mobile device throttling',subtitle:'Simulate a mobile device\'s CPU and network throttling from Device Mode.',link:'https://developers.google.com/web/updates/2017/07/devtools-release-notes#throttling',},{title:'Storage usage',subtitle:'See how much storage (IndexedDB, local, session, cache, etc.) an origin is using.',link:'https://developers.google.com/web/updates/2017/07/devtools-release-notes#storage',},{title:'Cache timestamps',subtitle:'View when a service worker cached a response.',link:'https://developers.google.com/web/updates/2017/07/devtools-release-notes#time-cached',},{title:'ES6 Modules support',subtitle:'Debug ES6 Modules natively from the Sources panel.',link:'https://developers.google.com/web/updates/2017/07/devtools-release-notes#modules',}],link:'https://developers.google.com/web/updates/2017/07/devtools-release-notes',},{version:3,header:'Highlights from the Chrome 60 update',highlights:[{title:'New Audits panel, powered by Lighthouse',subtitle:'Find out whether your site qualifies as a Progressive Web App, measure the accessibility and performance of a page, and discover best practices.',link:'https://developers.google.com/web/updates/2017/05/devtools-release-notes#lighthouse',},{title:'Third-party badges',subtitle:'See what third-party entities are logging to the Console, making network requests, and causing work during performance recordings.',link:'https://developers.google.com/web/updates/2017/05/devtools-release-notes#badges',},{title:'New "Continue to Here" gesture',subtitle:'While paused on a line of code, hold '+continueToHereShortcut+' and then click to continue to another line of code.',link:'https://developers.google.com/web/updates/2017/05/devtools-release-notes#continue',},{title:'Step into async',subtitle:'Predictably step into a promise resolution or other asynchronous code with a single gesture.',link:'https://developers.google.com/web/updates/2017/05/devtools-release-notes#step-into-async',},{title:'More informative object previews',subtitle:'Get a better idea of the contents of objects when logging them to the Console.',link:'https://developers.google.com/web/updates/2017/05/devtools-release-notes#object-previews',},{title:'Real-time Coverage tab updates',subtitle:'See what code is being used in real-time.',link:'https://developers.google.com/web/updates/2017/05/devtools-release-notes#coverage',}],link:'https://developers.google.com/web/updates/2017/05/devtools-release-notes',},{version:2,header:'Highlights from Chrome 59 update',highlights:[{title:'CSS and JS code coverage',subtitle:'Find unused CSS and JS with the new Coverage drawer.',link:'https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage',},{title:'Full-page screenshots',subtitle:'Take a screenshot of the entire page, from the top of the viewport to the bottom.',link:'https://developers.google.com/web/updates/2017/04/devtools-release-notes#screenshots',},{title:'Block requests',subtitle:'Manually disable individual requests in the Network panel.',link:'https://developers.google.com/web/updates/2017/04/devtools-release-notes#block-requests',},{title:'Step over async await',subtitle:'Step through async functions predictably.',link:'https://developers.google.com/web/updates/2017/04/devtools-release-notes#async',},{title:'Unified Command Menu',subtitle:'Execute commands and open files from the newly-unified Command Menu ('+commandMenuShortcut+').',link:'https://developers.google.com/web/updates/2017/04/devtools-release-notes#command-menu',}],link:'https://developers.google.com/web/updates/2017/04/devtools-release-notes',},{version:1,header:'Highlights from Chrome 58 update',highlights:[{title:'New Performance and Memory panels',subtitle:'Head to Performance for JavaScript profiling',link:'https://developers.google.com/web/updates/2017/03/devtools-release-notes#performance-panel',},{title:'Editable cookies',subtitle:'You can edit any existing cookies and create new ones in the Application panel',link:'https://developers.google.com/web/updates/2017/03/devtools-release-notes#cookies',},{title:'Console filtering & settings',subtitle:'Use the text filter or click the Console settings icon to touch up your preferences',link:'https://developers.google.com/web/updates/2017/03/devtools-release-notes#console',},{title:'Debugger catches out-of-memory errors',subtitle:'See the stack or grab a heap snapshot to see why the app may crash',link:'https://developers.google.com/web/updates/2017/03/devtools-release-notes#out-of-memory-breakpoints',},],link:'https://developers.google.com/web/updates/2017/03/devtools-release-notes',}];;self['SDK']=self['SDK']||{};SDK.Target=class extends Protocol.TargetBase{constructor(targetManager,id,name,capabilitiesMask,connectionFactory,parentTarget){super(connectionFactory);this._targetManager=targetManager;this._name=name;this._inspectedURL='';this._capabilitiesMask=capabilitiesMask;this._parentTarget=parentTarget;this._id=id;this._modelByConstructor=new Map();} -createModels(required){this._creatingModels=true;this.model(SDK.ResourceTreeModel);var registered=Array.from(SDK.SDKModel._registeredModels.keys());for(var modelClass of registered){var info=SDK.SDKModel._registeredModels.get(modelClass);if(info.autostart||required.has(modelClass)) -this.model(modelClass);} -this._creatingModels=false;} -isNodeJS(){return this._capabilitiesMask===SDK.Target.Capability.JS||this._isNodeJSForTest;} -setIsNodeJSForTest(){this._isNodeJSForTest=true;} -id(){return this._id;} -name(){return this._name||this._inspectedURLName;} -targetManager(){return this._targetManager;} -hasAllCapabilities(capabilitiesMask){return(this._capabilitiesMask&capabilitiesMask)===capabilitiesMask;} -decorateLabel(label){return!this.hasBrowserCapability()?'\u2699 '+label:label;} -hasBrowserCapability(){return this.hasAllCapabilities(SDK.Target.Capability.Browser);} -hasJSCapability(){return this.hasAllCapabilities(SDK.Target.Capability.JS);} -hasLogCapability(){return this.hasAllCapabilities(SDK.Target.Capability.Log);} -hasNetworkCapability(){return this.hasAllCapabilities(SDK.Target.Capability.Network);} -hasTargetCapability(){return this.hasAllCapabilities(SDK.Target.Capability.Target);} -hasDOMCapability(){return this.hasAllCapabilities(SDK.Target.Capability.DOM);} -parentTarget(){return this._parentTarget;} -dispose(){this._targetManager.removeTarget(this);for(var model of this._modelByConstructor.valuesArray()) -model.dispose();} -model(modelClass){if(!this._modelByConstructor.get(modelClass)){var info=SDK.SDKModel._registeredModels.get(modelClass);if(info===undefined) -throw'Model class is not registered @'+new Error().stack;if((this._capabilitiesMask&info.capabilities)===info.capabilities){var model=new modelClass(this);this._modelByConstructor.set(modelClass,model);if(!this._creatingModels) -this._targetManager.modelAdded(this,modelClass,model);}} -return this._modelByConstructor.get(modelClass)||null;} -models(){return this._modelByConstructor;} -inspectedURL(){return this._inspectedURL;} -setInspectedURL(inspectedURL){this._inspectedURL=inspectedURL;var parsedURL=inspectedURL.asParsedURL();this._inspectedURLName=parsedURL?parsedURL.lastPathComponentWithFragment():'#'+this._id;if(!this.parentTarget()) -InspectorFrontendHost.inspectedURLChanged(inspectedURL||'');this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.InspectedURLChanged,this);if(!this._name) -this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.NameChanged,this);}};SDK.Target.Capability={Browser:1<<0,DOM:1<<1,JS:1<<2,Log:1<<3,Network:1<<4,Target:1<<5,ScreenCapture:1<<6,Tracing:1<<7,Emulation:1<<8,Security:1<<9,Input:1<<10,Inspector:1<<11,DeviceEmulation:1<<12,None:0,AllForTests:(1<<13)-1};SDK.SDKModel=class extends Common.Object{constructor(target){super();this._target=target;} -target(){return this._target;} -suspendModel(){return Promise.resolve();} -resumeModel(){return Promise.resolve();} -dispose(){}};SDK.SDKModel.register=function(modelClass,capabilities,autostart){if(!SDK.SDKModel._registeredModels) -SDK.SDKModel._registeredModels=new Map();SDK.SDKModel._registeredModels.set(modelClass,{capabilities:capabilities,autostart:autostart});};SDK.SDKModel._registeredModels;;SDK.TargetManager=class extends Common.Object{constructor(){super();this._targets=[];this._observers=[];this._observerCapabiliesMaskSymbol=Symbol('observerCapabilitiesMask');this._modelListeners=new Map();this._modelObservers=new Map();this._isSuspended=false;this._lastAnonymousTargetId=0;this._childTargetManagers=new Map();this._nodeTargetIds=new Set();this._mainConnection;this._webSocketConnectionLostCallback;} -suspendAllTargets(){if(this._isSuspended) -return Promise.resolve();this._isSuspended=true;this.dispatchEventToListeners(SDK.TargetManager.Events.SuspendStateChanged);var promises=[];for(var target of this._targets){var childTargetManager=this._childTargetManagers.get(target);if(childTargetManager) -promises.push(childTargetManager.suspend());for(var model of target.models().values()) -promises.push(model.suspendModel());} -return Promise.all(promises);} -resumeAllTargets(){if(!this._isSuspended) -return Promise.resolve();this._isSuspended=false;this.dispatchEventToListeners(SDK.TargetManager.Events.SuspendStateChanged);var promises=[];for(var target of this._targets){var childTargetManager=this._childTargetManagers.get(target);if(childTargetManager) -promises.push(childTargetManager.resume());for(var model of target.models().values()) -promises.push(model.resumeModel());} -return Promise.all(promises);} -allTargetsSuspended(){return this._isSuspended;} -models(modelClass){var result=[];for(var i=0;i<this._targets.length;++i){var model=this._targets[i].model(modelClass);if(model) -result.push(model);} -return result;} -inspectedURL(){return this._targets[0]?this._targets[0].inspectedURL():'';} -observeModels(modelClass,observer){if(!this._modelObservers.has(modelClass)) -this._modelObservers.set(modelClass,[]);this._modelObservers.get(modelClass).push(observer);for(var model of this.models(modelClass)) -observer.modelAdded(model);} -unobserveModels(modelClass,observer){if(!this._modelObservers.has(modelClass)) -return;var observers=this._modelObservers.get(modelClass);observers.remove(observer);if(!observers.length) -this._modelObservers.delete(modelClass);} -modelAdded(target,modelClass,model){if(!this._modelObservers.has(modelClass)) -return;for(var observer of this._modelObservers.get(modelClass).slice()) -observer.modelAdded(model);} -_modelRemoved(target,modelClass,model){if(!this._modelObservers.has(modelClass)) -return;for(var observer of this._modelObservers.get(modelClass).slice()) -observer.modelRemoved(model);} -addModelListener(modelClass,eventType,listener,thisObject){for(var i=0;i<this._targets.length;++i){var model=this._targets[i].model(modelClass);if(model) -model.addEventListener(eventType,listener,thisObject);} -if(!this._modelListeners.has(eventType)) -this._modelListeners.set(eventType,[]);this._modelListeners.get(eventType).push({modelClass:modelClass,thisObject:thisObject,listener:listener});} -removeModelListener(modelClass,eventType,listener,thisObject){if(!this._modelListeners.has(eventType)) -return;for(var i=0;i<this._targets.length;++i){var model=this._targets[i].model(modelClass);if(model) -model.removeEventListener(eventType,listener,thisObject);} -var listeners=this._modelListeners.get(eventType);for(var i=0;i<listeners.length;++i){if(listeners[i].modelClass===modelClass&&listeners[i].listener===listener&&listeners[i].thisObject===thisObject) -listeners.splice(i--,1);} -if(!listeners.length) -this._modelListeners.delete(eventType);} -observeTargets(targetObserver,capabilitiesMask){if(this._observerCapabiliesMaskSymbol in targetObserver) -throw new Error('Observer can only be registered once');targetObserver[this._observerCapabiliesMaskSymbol]=capabilitiesMask||0;this.targets(capabilitiesMask).forEach(targetObserver.targetAdded.bind(targetObserver));this._observers.push(targetObserver);} -unobserveTargets(targetObserver){delete targetObserver[this._observerCapabiliesMaskSymbol];this._observers.remove(targetObserver);} -createTarget(id,name,capabilitiesMask,connectionFactory,parentTarget){var target=new SDK.Target(this,id,name,capabilitiesMask,connectionFactory,parentTarget);target.createModels(new Set(this._modelObservers.keys()));if(target.hasTargetCapability()) -this._childTargetManagers.set(target,new SDK.ChildTargetManager(this,target));this._targets.push(target);var copy=this._observersForTarget(target);for(var i=0;i<copy.length;++i) -copy[i].targetAdded(target);for(var modelClass of target.models().keys()) -this.modelAdded(target,modelClass,target.models().get(modelClass));for(var pair of this._modelListeners){var listeners=pair[1];for(var i=0;i<listeners.length;++i){var model=target.model(listeners[i].modelClass);if(model) -model.addEventListener((pair[0]),listeners[i].listener,listeners[i].thisObject);}} -return target;} -_observersForTarget(target){return this._observers.filter(observer=>target.hasAllCapabilities(observer[this._observerCapabiliesMaskSymbol]||0));} -removeTarget(target){if(!this._targets.includes(target)) -return;var childTargetManager=this._childTargetManagers.get(target);this._childTargetManagers.delete(target);if(childTargetManager) -childTargetManager.dispose();this._targets.remove(target);for(var modelClass of target.models().keys()) -this._modelRemoved(target,modelClass,target.models().get(modelClass));var copy=this._observersForTarget(target);for(var i=0;i<copy.length;++i) -copy[i].targetRemoved(target);for(var pair of this._modelListeners){var listeners=pair[1];for(var i=0;i<listeners.length;++i){var model=target.model(listeners[i].modelClass);if(model) -model.removeEventListener((pair[0]),listeners[i].listener,listeners[i].thisObject);}}} -targets(capabilitiesMask){if(!capabilitiesMask) -return this._targets.slice();else -return this._targets.filter(target=>target.hasAllCapabilities(capabilitiesMask||0));} -targetById(id){for(var i=0;i<this._targets.length;++i){if(this._targets[i].id()===id) -return this._targets[i];} -return null;} -mainTarget(){return this._targets[0]||null;} -connectToMainTarget(webSocketConnectionLostCallback){this._webSocketConnectionLostCallback=webSocketConnectionLostCallback;this._connectAndCreateMainTarget();} -_connectAndCreateMainTarget(){if(Runtime.queryParam('nodeFrontend')){var target=new SDK.Target(this,'main',Common.UIString('Node.js'),SDK.Target.Capability.Target,this._createMainConnection.bind(this),null);target.setInspectedURL('Node.js');this._childTargetManagers.set(target,new SDK.ChildTargetManager(this,target));Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConnectToNodeJSFromFrontend);return;} -var capabilities=SDK.Target.Capability.Browser|SDK.Target.Capability.DOM|SDK.Target.Capability.JS|SDK.Target.Capability.Log|SDK.Target.Capability.Network|SDK.Target.Capability.Target|SDK.Target.Capability.ScreenCapture|SDK.Target.Capability.Tracing|SDK.Target.Capability.Emulation|SDK.Target.Capability.Security|SDK.Target.Capability.Input|SDK.Target.Capability.Inspector|SDK.Target.Capability.DeviceEmulation;if(Runtime.queryParam('isSharedWorker')){capabilities=SDK.Target.Capability.Browser|SDK.Target.Capability.Log|SDK.Target.Capability.Network|SDK.Target.Capability.Target|SDK.Target.Capability.Inspector;}else if(Runtime.queryParam('v8only')){capabilities=SDK.Target.Capability.JS;Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConnectToNodeJSDirectly);} -var target=this.createTarget('main',Common.UIString('Main'),capabilities,this._createMainConnection.bind(this),null);target.runtimeAgent().runIfWaitingForDebugger();} -_createMainConnection(params){var wsParam=Runtime.queryParam('ws');var wssParam=Runtime.queryParam('wss');if(wsParam||wssParam){var ws=wsParam?`ws://${wsParam}`:`wss://${wssParam}`;this._mainConnection=new SDK.WebSocketConnection(ws,this._webSocketConnectionLostCallback,params);}else if(InspectorFrontendHost.isHostedMode()){this._mainConnection=new SDK.StubConnection(params);}else{this._mainConnection=new SDK.MainConnection(params);} -return this._mainConnection;} -availableNodeTargetsCount(){return this._nodeTargetIds.size;} -interceptMainConnection(onMessage){var params={onMessage:onMessage,onDisconnect:this._connectAndCreateMainTarget.bind(this)};return this._mainConnection.disconnect().then(this._createMainConnection.bind(this,params));}};SDK.ChildTargetManager=class{constructor(targetManager,parentTarget){this._targetManager=targetManager;this._parentTarget=parentTarget;this._targetAgent=parentTarget.targetAgent();this._childConnections=new Map();parentTarget.registerTargetDispatcher(this);this._targetAgent.invoke_setAutoAttach({autoAttach:true,waitForDebuggerOnStart:true});if(Runtime.experiments.isEnabled('autoAttachToCrossProcessSubframes')) -this._targetAgent.setAttachToFrames(true);if(!parentTarget.parentTarget()){this._targetAgent.setDiscoverTargets(true);if(Runtime.queryParam('nodeFrontend')){InspectorFrontendHost.setDevicesUpdatesEnabled(true);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged,this._devicesDiscoveryConfigChanged,this);}else{this._targetAgent.setRemoteLocations([{host:'localhost',port:9229}]);}}} -_devicesDiscoveryConfigChanged(event){var config=(event.data);var locations=[];for(var address of config.networkDiscoveryConfig){var parts=address.split(':');var port=parseInt(parts[1],10);if(parts[0]&&port) -locations.push({host:parts[0],port:port});} -this._targetAgent.setRemoteLocations(locations);} -suspend(){return this._targetAgent.invoke_setAutoAttach({autoAttach:true,waitForDebuggerOnStart:false});} -resume(){return this._targetAgent.invoke_setAutoAttach({autoAttach:true,waitForDebuggerOnStart:true});} -dispose(){if(Runtime.queryParam('nodeFrontend')&&!this._parentTarget.parentTarget()){InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged,this._devicesDiscoveryConfigChanged,this);} -for(var sessionId of this._childConnections.keys()) -this.detachedFromTarget(sessionId,undefined);} -_capabilitiesForType(type){if(type==='worker') -return SDK.Target.Capability.JS|SDK.Target.Capability.Log|SDK.Target.Capability.Network;if(type==='service_worker') -return SDK.Target.Capability.Log|SDK.Target.Capability.Network|SDK.Target.Capability.Target;if(type==='iframe'){return SDK.Target.Capability.Browser|SDK.Target.Capability.DOM|SDK.Target.Capability.JS|SDK.Target.Capability.Log|SDK.Target.Capability.Network|SDK.Target.Capability.Target|SDK.Target.Capability.Tracing|SDK.Target.Capability.Emulation|SDK.Target.Capability.Input;} -if(type==='node') -return SDK.Target.Capability.JS;return 0;} -targetCreated(targetInfo){if(targetInfo.type!=='node') -return;if(Runtime.queryParam('nodeFrontend')){if(!targetInfo.attached) -this._targetAgent.attachToTarget(targetInfo.targetId);return;} -if(targetInfo.attached) -return;this._targetManager._nodeTargetIds.add(targetInfo.targetId);this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.AvailableNodeTargetsChanged);} -targetInfoChanged(targetInfo){if(targetInfo.type!=='node'||Runtime.queryParam('nodeFrontend')) -return;var availableIds=this._targetManager._nodeTargetIds;if(!availableIds.has(targetInfo.targetId)&&!targetInfo.attached){availableIds.add(targetInfo.targetId);this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.AvailableNodeTargetsChanged);}else if(availableIds.has(targetInfo.targetId)&&targetInfo.attached){availableIds.delete(targetInfo.targetId);this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.AvailableNodeTargetsChanged);}} -targetDestroyed(targetId){if(Runtime.queryParam('nodeFrontend')||!this._targetManager._nodeTargetIds.has(targetId)) -return;this._targetManager._nodeTargetIds.delete(targetId);this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.AvailableNodeTargetsChanged);} -attachedToTarget(sessionId,targetInfo,waitingForDebugger){var targetName='';if(targetInfo.type==='node'){targetName=Common.UIString('Node.js: %s',targetInfo.url);}else if(targetInfo.type!=='iframe'){var parsedURL=targetInfo.url.asParsedURL();targetName=parsedURL?parsedURL.lastPathComponentWithFragment():'#'+(++this._targetManager._lastAnonymousTargetId);} -var target=this._targetManager.createTarget(targetInfo.targetId,targetName,this._capabilitiesForType(targetInfo.type),this._createChildConnection.bind(this,this._targetAgent,sessionId),this._parentTarget);if(!this._parentTarget.parentTarget()&&Runtime.queryParam('isSharedWorker')&&waitingForDebugger){var debuggerModel=target.model(SDK.DebuggerModel);if(debuggerModel) -debuggerModel.pause();} -target.runtimeAgent().runIfWaitingForDebugger();if(Runtime.queryParam('nodeFrontend')) -InspectorFrontendHost.bringToFront();} -detachedFromTarget(sessionId,childTargetId){this._childConnections.get(sessionId)._onDisconnect.call(null,'target terminated');this._childConnections.delete(sessionId);} -receivedMessageFromTarget(sessionId,message,childTargetId){var connection=this._childConnections.get(sessionId);if(connection) -connection._onMessage.call(null,message);} -_createChildConnection(agent,sessionId,params){var connection=new SDK.ChildConnection(agent,sessionId,params);this._childConnections.set(sessionId,connection);return connection;}};SDK.ChildConnection=class{constructor(agent,sessionId,params){this._agent=agent;this._sessionId=sessionId;this._onMessage=params.onMessage;this._onDisconnect=params.onDisconnect;} -sendMessage(message){this._agent.sendMessageToTarget(message,this._sessionId);} -disconnect(){throw'Not implemented';}};SDK.TargetManager.Events={InspectedURLChanged:Symbol('InspectedURLChanged'),NameChanged:Symbol('NameChanged'),SuspendStateChanged:Symbol('SuspendStateChanged'),AvailableNodeTargetsChanged:Symbol('AvailableNodeTargetsChanged')};SDK.TargetManager.Observer=function(){};SDK.TargetManager.Observer.prototype={targetAdded(target){},targetRemoved(target){},};SDK.SDKModelObserver=function(){};SDK.SDKModelObserver.prototype={modelAdded(model){},modelRemoved(model){},};SDK.targetManager=new SDK.TargetManager();;SDK.MainConnection=class{constructor(params){this._onMessage=params.onMessage;this._onDisconnect=params.onDisconnect;this._disconnected=false;this._eventListeners=[InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DispatchMessage,this._dispatchMessage,this),InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DispatchMessageChunk,this._dispatchMessageChunk,this),InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.EvaluateForTestInFrontend,this._evaluateForTestInFrontend,this),];} -sendMessage(message){if(!this._disconnected) -InspectorFrontendHost.sendMessageToBackend(message);} -_dispatchMessage(event){this._onMessage.call(null,(event.data));} -_dispatchMessageChunk(event){var messageChunk=(event.data['messageChunk']);var messageSize=(event.data['messageSize']);if(messageSize){this._messageBuffer='';this._messageSize=messageSize;} -this._messageBuffer+=messageChunk;if(this._messageBuffer.length===this._messageSize){this._onMessage.call(null,this._messageBuffer);this._messageBuffer='';this._messageSize=0;}} -_evaluateForTestInFrontend(event){if(!Host.isUnderTest()) -return;var callId=(event.data['callId']);var script=(event.data['script']);function invokeMethod(){try{script=script+'//# sourceURL=evaluateInWebInspector'+callId+'.js';window.eval(script);}catch(e){console.error(e.stack);}} -Protocol.InspectorBackend.deprecatedRunAfterPendingDispatches(invokeMethod);} -disconnect(){var onDisconnect=this._onDisconnect;Common.EventTarget.removeEventListeners(this._eventListeners);this._onDisconnect=null;this._onMessage=null;this._disconnected=true;var fulfill;var promise=new Promise(f=>fulfill=f);InspectorFrontendHost.reattach(()=>{onDisconnect.call(null,'force disconnect');fulfill();});return promise;}};SDK.WebSocketConnection=class{constructor(url,onWebSocketDisconnect,params){this._socket=new WebSocket(url);this._socket.onerror=this._onError.bind(this);this._socket.onopen=this._onOpen.bind(this);this._socket.onmessage=messageEvent=>params.onMessage.call(null,(messageEvent.data));this._socket.onclose=this._onClose.bind(this);this._onDisconnect=params.onDisconnect;this._onWebSocketDisconnect=onWebSocketDisconnect;this._connected=false;this._messages=[];} -_onError(){this._onWebSocketDisconnect.call(null);this._onDisconnect.call(null,'connection failed');this._close();} -_onOpen(){this._socket.onerror=console.error;this._connected=true;for(var message of this._messages) -this._socket.send(message);this._messages=[];} -_onClose(){this._onWebSocketDisconnect.call(null);this._onDisconnect.call(null,'websocket closed');this._close();} -_close(callback){this._socket.onerror=null;this._socket.onopen=null;this._socket.onclose=callback||null;this._socket.onmessage=null;this._socket.close();this._socket=null;this._onWebSocketDisconnect=null;} -sendMessage(message){if(this._connected) -this._socket.send(message);else -this._messages.push(message);} -disconnect(){var fulfill;var promise=new Promise(f=>fulfill=f);this._close(()=>{this._onDisconnect.call(null,'force disconnect');fulfill();});return promise;}};SDK.StubConnection=class{constructor(params){this._onMessage=params.onMessage;this._onDisconnect=params.onDisconnect;} -sendMessage(message){setTimeout(this._respondWithError.bind(this,message),0);} -_respondWithError(message){var messageObject=JSON.parse(message);var error={message:'This is a stub connection, can\'t dispatch message.',code:Protocol.InspectorBackend.DevToolsStubErrorCode,data:messageObject};this._onMessage.call(null,{id:messageObject.id,error:error});} -disconnect(){this._onDisconnect.call(null,'force disconnect');this._onDisconnect=null;this._onMessage=null;return Promise.resolve();}};;SDK.CompilerSourceMappingContentProvider=class{constructor(sourceURL,contentType){this._sourceURL=sourceURL;this._contentType=contentType;} -contentURL(){return this._sourceURL;} -contentType(){return this._contentType;} -contentEncoded(){return Promise.resolve(false);} -requestContent(){var callback;var promise=new Promise(fulfill=>callback=fulfill);SDK.multitargetNetworkManager.loadResource(this._sourceURL,contentLoaded.bind(this));return promise;function contentLoaded(statusCode,headers,content){if(statusCode>=400){console.error('Could not load content for '+this._sourceURL+' : '+'HTTP status code: '+statusCode);callback(null);return;} -callback(content);}} -async searchInContent(query,caseSensitive,isRegex){var content=await this.requestContent();if(typeof content!=='string') -return[];return Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex);}};;SDK.CookieModel=class extends SDK.SDKModel{constructor(target){super(target);} -static _parseProtocolCookie(protocolCookie){var cookie=new SDK.Cookie(protocolCookie.name,protocolCookie.value,null);cookie.addAttribute('domain',protocolCookie['domain']);cookie.addAttribute('path',protocolCookie['path']);cookie.addAttribute('port',protocolCookie['port']);if(protocolCookie['expires']) -cookie.addAttribute('expires',protocolCookie['expires']*1000);if(protocolCookie['httpOnly']) -cookie.addAttribute('httpOnly');if(protocolCookie['secure']) -cookie.addAttribute('secure');if(protocolCookie['sameSite']) -cookie.addAttribute('sameSite',protocolCookie['sameSite']);cookie.setSize(protocolCookie['size']);return cookie;} -static cookieMatchesResourceURL(cookie,resourceURL){var url=resourceURL.asParsedURL();if(!url||!SDK.CookieModel.cookieDomainMatchesResourceDomain(cookie.domain(),url.host)) -return false;return(url.path.startsWith(cookie.path())&&(!cookie.port()||url.port===cookie.port())&&(!cookie.secure()||url.scheme==='https'));} -static cookieDomainMatchesResourceDomain(cookieDomain,resourceDomain){if(cookieDomain.charAt(0)!=='.') -return resourceDomain===cookieDomain;return!!resourceDomain.match(new RegExp('^([^\\.]+\\.)*'+cookieDomain.substring(1).escapeForRegExp()+'$','i'));} -getCookies(urls){return this.target().networkAgent().getCookies(urls).then(cookies=>(cookies||[]).map(cookie=>SDK.CookieModel._parseProtocolCookie(cookie)));} -deleteCookie(cookie,callback){this._deleteAll([cookie],callback);} -clear(domain,callback){this.getCookiesForDomain(domain||null).then(cookies=>this._deleteAll(cookies,callback));} -saveCookie(cookie){var domain=cookie.domain();if(!domain.startsWith('.')) -domain='';var expires=undefined;if(cookie.expires()) -expires=Math.floor(Date.parse(cookie.expires())/1000);return this.target().networkAgent().setCookie(cookie.name(),cookie.value(),cookie.url(),domain,cookie.path(),cookie.secure(),cookie.httpOnly(),cookie.sameSite(),expires).then(success=>!!success);} -getCookiesForDomain(domain){var resourceURLs=[];function populateResourceURLs(resource){var url=resource.documentURL.asParsedURL();if(url&&(!domain||url.securityOrigin()===domain)) -resourceURLs.push(resource.url);} -var resourceTreeModel=this.target().model(SDK.ResourceTreeModel);if(resourceTreeModel) -resourceTreeModel.forAllResources(populateResourceURLs);return this.getCookies(resourceURLs);} -_deleteAll(cookies,callback){var networkAgent=this.target().networkAgent();Promise.all(cookies.map(cookie=>networkAgent.deleteCookies(cookie.name(),undefined,cookie.domain(),cookie.path()))).then(callback||function(){});}};SDK.SDKModel.register(SDK.CookieModel,SDK.Target.Capability.Network,false);;SDK.CookieParser=class{constructor(){} -static parseCookie(header){return(new SDK.CookieParser()).parseCookie(header);} -static parseSetCookie(header){return(new SDK.CookieParser()).parseSetCookie(header);} -cookies(){return this._cookies;} -parseCookie(cookieHeader){if(!this._initialize(cookieHeader)) -return null;for(var kv=this._extractKeyValue();kv;kv=this._extractKeyValue()){if(kv.key.charAt(0)==='$'&&this._lastCookie) -this._lastCookie.addAttribute(kv.key.slice(1),kv.value);else if(kv.key.toLowerCase()!=='$version'&&typeof kv.value==='string') -this._addCookie(kv,SDK.Cookie.Type.Request);this._advanceAndCheckCookieDelimiter();} -this._flushCookie();return this._cookies;} -parseSetCookie(setCookieHeader){if(!this._initialize(setCookieHeader)) -return null;for(var kv=this._extractKeyValue();kv;kv=this._extractKeyValue()){if(this._lastCookie) -this._lastCookie.addAttribute(kv.key,kv.value);else -this._addCookie(kv,SDK.Cookie.Type.Response);if(this._advanceAndCheckCookieDelimiter()) -this._flushCookie();} -this._flushCookie();return this._cookies;} -_initialize(headerValue){this._input=headerValue;if(typeof headerValue!=='string') -return false;this._cookies=[];this._lastCookie=null;this._originalInputLength=this._input.length;return true;} -_flushCookie(){if(this._lastCookie) -this._lastCookie.setSize(this._originalInputLength-this._input.length-this._lastCookiePosition);this._lastCookie=null;} -_extractKeyValue(){if(!this._input||!this._input.length) -return null;var keyValueMatch=/^[ \t]*([^\s=;]+)[ \t]*(?:=[ \t]*([^;\n]*))?/.exec(this._input);if(!keyValueMatch){console.error('Failed parsing cookie header before: '+this._input);return null;} -var result=new SDK.CookieParser.KeyValue(keyValueMatch[1],keyValueMatch[2]&&keyValueMatch[2].trim(),this._originalInputLength-this._input.length);this._input=this._input.slice(keyValueMatch[0].length);return result;} -_advanceAndCheckCookieDelimiter(){var match=/^\s*[\n;]\s*/.exec(this._input);if(!match) -return false;this._input=this._input.slice(match[0].length);return match[0].match('\n')!==null;} -_addCookie(keyValue,type){if(this._lastCookie) -this._lastCookie.setSize(keyValue.position-this._lastCookiePosition);this._lastCookie=typeof keyValue.value==='string'?new SDK.Cookie(keyValue.key,keyValue.value,type):new SDK.Cookie('',keyValue.key,type);this._lastCookiePosition=keyValue.position;this._cookies.push(this._lastCookie);}};SDK.CookieParser.KeyValue=class{constructor(key,value,position){this.key=key;this.value=value;this.position=position;}};SDK.Cookie=class{constructor(name,value,type){this._name=name;this._value=value;this._type=type;this._attributes={};this._size=0;} -name(){return this._name;} -value(){return this._value;} -type(){return this._type;} -httpOnly(){return'httponly'in this._attributes;} -secure(){return'secure'in this._attributes;} -sameSite(){return(this._attributes['samesite']);} -session(){return!('expires'in this._attributes||'max-age'in this._attributes);} -path(){return this._attributes['path'];} -port(){return this._attributes['port'];} -domain(){return this._attributes['domain'];} -expires(){return this._attributes['expires'];} -maxAge(){return this._attributes['max-age'];} -size(){return this._size;} -url(){return(this.secure()?'https://':'http://')+this.domain()+this.path();} -setSize(size){this._size=size;} -expiresDate(requestDate){if(this.maxAge()){var targetDate=requestDate===null?new Date():requestDate;return new Date(targetDate.getTime()+1000*this.maxAge());} -if(this.expires()) -return new Date(this.expires());return null;} -attributes(){return this._attributes;} -addAttribute(key,value){this._attributes[key.toLowerCase()]=value;}};SDK.Cookie.Type={Request:0,Response:1};;SDK.ProfileNode=class{constructor(callFrame){this.callFrame=callFrame;this.callUID=`${this.callFrame.functionName}@${this.callFrame.scriptId}:${this.callFrame.lineNumber}`;this.self=0;this.total=0;this.id=0;this.parent=null;this.children=[];} -get functionName(){return this.callFrame.functionName;} -get scriptId(){return this.callFrame.scriptId;} -get url(){return this.callFrame.url;} -get lineNumber(){return this.callFrame.lineNumber;} -get columnNumber(){return this.callFrame.columnNumber;}};SDK.ProfileTreeModel=class{initialize(root){this.root=root;this._assignDepthsAndParents();this.total=this._calculateTotals(this.root);} -_assignDepthsAndParents(){var root=this.root;root.depth=-1;root.parent=null;this.maxDepth=0;var nodesToTraverse=[root];while(nodesToTraverse.length){var parent=nodesToTraverse.pop();var depth=parent.depth+1;if(depth>this.maxDepth) -this.maxDepth=depth;var children=parent.children;var length=children.length;for(var i=0;i<length;++i){var child=children[i];child.depth=depth;child.parent=parent;if(child.children.length) -nodesToTraverse.push(child);}}} -_calculateTotals(root){var nodesToTraverse=[root];var dfsList=[];while(nodesToTraverse.length){var node=nodesToTraverse.pop();node.total=node.self;dfsList.push(node);nodesToTraverse.push(...node.children);} -while(dfsList.length>1){var node=dfsList.pop();node.parent.total+=node.total;} -return root.total;}};;SDK.ServerTiming=class{constructor(metric,value,description){this.metric=metric;this.value=value;this.description=description;} -static parseHeaders(headers){var rawServerTimingHeaders=headers.filter(item=>item.name.toLowerCase()==='server-timing');if(!rawServerTimingHeaders.length) -return null;function createFromHeaderValue(valueString){var serverTimingMetricRegExp=/[ \t]*([\!\#\$\%\&\'\*\+\-\.\^\_\`\|\~0-9A-Za-z]+)[ \t]*(?:=[ \t]*(\d+(?:\.\d+)?))?[ \t]*(?:;[ \t]*(?:"([^"]+)"|([\!\#\$\%\&\'\*\+\-\.\^\_\`\|\~0-9A-Za-z]+)))?[ \t]*(?:,(.*))?/;var metricMatch;var result=[];while(valueString&&(metricMatch=serverTimingMetricRegExp.exec(valueString))){var metric=metricMatch[1];var value=metricMatch[2];var description=metricMatch[3]||metricMatch[4];if(value!==undefined) -value=Math.abs(parseFloat(metricMatch[2]));valueString=metricMatch[5];if(value===undefined||isNaN(value)) -value=null;result.push(new SDK.ServerTiming(metric,value,description));} -return result;} -var serverTimings=rawServerTimingHeaders.reduce((memo,header)=>{var timing=createFromHeaderValue(header.value);Array.prototype.push.apply(memo,timing);return memo;},[]);serverTimings.sort((a,b)=>a.metric.toLowerCase().compareTo(b.metric.toLowerCase()));return serverTimings;}};;SDK.CPUProfileNode=class extends SDK.ProfileNode{constructor(node,sampleTime){var callFrame=node.callFrame||({functionName:node['functionName'],scriptId:node['scriptId'],url:node['url'],lineNumber:node['lineNumber']-1,columnNumber:node['columnNumber']-1});super(callFrame);this.id=node.id;this.self=node.hitCount*sampleTime;this.positionTicks=node.positionTicks;this.deoptReason=node.deoptReason&&node.deoptReason!=='no reason'?node.deoptReason:null;}};SDK.CPUProfileDataModel=class extends SDK.ProfileTreeModel{constructor(profile){super();var isLegacyFormat=!!profile['head'];if(isLegacyFormat){this.profileStartTime=profile.startTime*1000;this.profileEndTime=profile.endTime*1000;this.timestamps=profile.timestamps;this._compatibilityConversionHeadToNodes(profile);}else{this.profileStartTime=profile.startTime/1000;this.profileEndTime=profile.endTime/1000;this.timestamps=this._convertTimeDeltas(profile);} -this.samples=profile.samples;this.totalHitCount=0;this.profileHead=this._translateProfileTree(profile.nodes);this.initialize(this.profileHead);this._extractMetaNodes();if(this.samples){this._buildIdToNodeMap();this._sortSamples();this._normalizeTimestamps();}} -_compatibilityConversionHeadToNodes(profile){if(!profile.head||profile.nodes) -return;var nodes=[];convertNodesTree(profile.head);profile.nodes=nodes;delete profile.head;function convertNodesTree(node){nodes.push(node);node.children=((node.children)).map(convertNodesTree);return node.id;}} -_convertTimeDeltas(profile){if(!profile.timeDeltas) -return null;var lastTimeUsec=profile.startTime;var timestamps=new Array(profile.timeDeltas.length);for(var i=0;i<timestamps.length;++i){lastTimeUsec+=profile.timeDeltas[i];timestamps[i]=lastTimeUsec;} -return timestamps;} -_translateProfileTree(nodes){function isNativeNode(node){if(node.callFrame) -return!!node.callFrame.url&&node.callFrame.url.startsWith('native ');return!!node['url']&&node['url'].startsWith('native ');} -function buildChildrenFromParents(nodes){if(nodes[0].children) -return;nodes[0].children=[];for(var i=1;i<nodes.length;++i){var node=nodes[i];var parentNode=nodeByIdMap.get(node.parent);if(parentNode.children) -parentNode.children.push(node.id);else -parentNode.children=[node.id];}} -var nodeByIdMap=new Map();for(var i=0;i<nodes.length;++i){var node=nodes[i];nodeByIdMap.set(node.id,node);} -buildChildrenFromParents(nodes);this.totalHitCount=nodes.reduce((acc,node)=>acc+node.hitCount,0);var sampleTime=(this.profileEndTime-this.profileStartTime)/this.totalHitCount;var keepNatives=!!Common.moduleSetting('showNativeFunctionsInJSProfile').get();var root=nodes[0];var idMap=new Map([[root.id,root.id]]);var resultRoot=new SDK.CPUProfileNode(root,sampleTime);var parentNodeStack=root.children.map(()=>resultRoot);var sourceNodeStack=root.children.map(id=>nodeByIdMap.get(id));while(sourceNodeStack.length){var parentNode=parentNodeStack.pop();var sourceNode=sourceNodeStack.pop();if(!sourceNode.children) -sourceNode.children=[];var targetNode=new SDK.CPUProfileNode(sourceNode,sampleTime);if(keepNatives||!isNativeNode(sourceNode)){parentNode.children.push(targetNode);parentNode=targetNode;}else{parentNode.self+=targetNode.self;} -idMap.set(sourceNode.id,parentNode.id);parentNodeStack.push.apply(parentNodeStack,sourceNode.children.map(()=>parentNode));sourceNodeStack.push.apply(sourceNodeStack,sourceNode.children.map(id=>nodeByIdMap.get(id)));} -if(this.samples) -this.samples=this.samples.map(id=>idMap.get(id));return resultRoot;} -_sortSamples(){var timestamps=this.timestamps;if(!timestamps) -return;var samples=this.samples;var indices=timestamps.map((x,index)=>index);indices.sort((a,b)=>timestamps[a]-timestamps[b]);for(var i=0;i<timestamps.length;++i){var index=indices[i];if(index===i) -continue;var savedTimestamp=timestamps[i];var savedSample=samples[i];var currentIndex=i;while(index!==i){samples[currentIndex]=samples[index];timestamps[currentIndex]=timestamps[index];currentIndex=index;index=indices[index];indices[currentIndex]=currentIndex;} -samples[currentIndex]=savedSample;timestamps[currentIndex]=savedTimestamp;}} -_normalizeTimestamps(){var timestamps=this.timestamps;if(!timestamps){var profileStartTime=this.profileStartTime;var interval=(this.profileEndTime-profileStartTime)/this.samples.length;timestamps=new Float64Array(this.samples.length+1);for(var i=0;i<timestamps.length;++i) -timestamps[i]=profileStartTime+i*interval;this.timestamps=timestamps;return;} -for(var i=0;i<timestamps.length;++i) -timestamps[i]/=1000;var averageSample=(timestamps.peekLast()-timestamps[0])/(timestamps.length-1);this.timestamps.push(timestamps.peekLast()+averageSample);this.profileStartTime=timestamps[0];this.profileEndTime=timestamps.peekLast();} -_buildIdToNodeMap(){this._idToNode=new Map();var idToNode=this._idToNode;var stack=[this.profileHead];while(stack.length){var node=stack.pop();idToNode.set(node.id,node);stack.push.apply(stack,node.children);}} -_extractMetaNodes(){var topLevelNodes=this.profileHead.children;for(var i=0;i<topLevelNodes.length&&!(this.gcNode&&this.programNode&&this.idleNode);i++){var node=topLevelNodes[i];if(node.functionName==='(garbage collector)') -this.gcNode=node;else if(node.functionName==='(program)') -this.programNode=node;else if(node.functionName==='(idle)') -this.idleNode=node;}} -forEachFrame(openFrameCallback,closeFrameCallback,startTime,stopTime){if(!this.profileHead||!this.samples) -return;startTime=startTime||0;stopTime=stopTime||Infinity;var samples=this.samples;var timestamps=this.timestamps;var idToNode=this._idToNode;var gcNode=this.gcNode;var samplesCount=samples.length;var startIndex=timestamps.lowerBound(startTime);var stackTop=0;var stackNodes=[];var prevId=this.profileHead.id;var sampleTime=timestamps[samplesCount];var gcParentNode=null;if(!this._stackStartTimes) -this._stackStartTimes=new Float64Array(this.maxDepth+2);var stackStartTimes=this._stackStartTimes;if(!this._stackChildrenDuration) -this._stackChildrenDuration=new Float64Array(this.maxDepth+2);var stackChildrenDuration=this._stackChildrenDuration;for(var sampleIndex=startIndex;sampleIndex<samplesCount;sampleIndex++){sampleTime=timestamps[sampleIndex];if(sampleTime>=stopTime) -break;var id=samples[sampleIndex];if(id===prevId) -continue;var node=idToNode.get(id);var prevNode=idToNode.get(prevId);if(node===gcNode){gcParentNode=prevNode;openFrameCallback(gcParentNode.depth+1,gcNode,sampleTime);stackStartTimes[++stackTop]=sampleTime;stackChildrenDuration[stackTop]=0;prevId=id;continue;} -if(prevNode===gcNode){var start=stackStartTimes[stackTop];var duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(gcParentNode.depth+1,gcNode,start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;prevNode=gcParentNode;prevId=prevNode.id;gcParentNode=null;} -while(node.depth>prevNode.depth){stackNodes.push(node);node=node.parent;} -while(prevNode!==node){var start=stackStartTimes[stackTop];var duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(prevNode.depth,(prevNode),start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;if(node.depth===prevNode.depth){stackNodes.push(node);node=node.parent;} -prevNode=prevNode.parent;} -while(stackNodes.length){node=stackNodes.pop();openFrameCallback(node.depth,node,sampleTime);stackStartTimes[++stackTop]=sampleTime;stackChildrenDuration[stackTop]=0;} -prevId=id;} -if(idToNode.get(prevId)===gcNode){var start=stackStartTimes[stackTop];var duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(gcParentNode.depth+1,node,start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;} -for(var node=idToNode.get(prevId);node.parent;node=node.parent){var start=stackStartTimes[stackTop];var duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(node.depth,(node),start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;}} -nodeByIndex(index){return this._idToNode.get(this.samples[index])||null;}};;SDK.CPUProfilerModel=class extends SDK.SDKModel{constructor(target){super(target);this._isRecording=false;this._nextAnonymousConsoleProfileNumber=1;this._anonymousConsoleProfileIdToTitle=new Map();this._profilerAgent=target.profilerAgent();target.registerProfilerDispatcher(this);this._profilerAgent.enable();this._debuggerModel=(target.model(SDK.DebuggerModel));} -runtimeModel(){return this._debuggerModel.runtimeModel();} -debuggerModel(){return this._debuggerModel;} -consoleProfileStarted(id,scriptLocation,title){if(!title){title=Common.UIString('Profile %d',this._nextAnonymousConsoleProfileNumber++);this._anonymousConsoleProfileIdToTitle.set(id,title);} -this._dispatchProfileEvent(SDK.CPUProfilerModel.Events.ConsoleProfileStarted,id,scriptLocation,title);} -consoleProfileFinished(id,scriptLocation,cpuProfile,title){if(!title){title=this._anonymousConsoleProfileIdToTitle.get(id);this._anonymousConsoleProfileIdToTitle.delete(id);} -self.runtime.loadModulePromise('profiler').then(()=>{this._dispatchProfileEvent(SDK.CPUProfilerModel.Events.ConsoleProfileFinished,id,scriptLocation,title,cpuProfile);});} -_dispatchProfileEvent(eventName,id,scriptLocation,title,cpuProfile){var debuggerLocation=SDK.DebuggerModel.Location.fromPayload(this._debuggerModel,scriptLocation);var globalId=this.target().id()+'.'+id;var data=({id:globalId,scriptLocation:debuggerLocation,cpuProfile:cpuProfile,title:title,cpuProfilerModel:this});this.dispatchEventToListeners(eventName,data);} -isRecordingProfile(){return this._isRecording;} -startRecording(){this._isRecording=true;var intervalUs=Common.moduleSetting('highResolutionCpuProfiling').get()?100:1000;this._profilerAgent.setSamplingInterval(intervalUs);return this._profilerAgent.start();} -stopRecording(){this._isRecording=false;return this._profilerAgent.stop();} -startPreciseCoverage(){var callCount=false;var detailed=true;return this._profilerAgent.startPreciseCoverage(callCount,detailed);} -takePreciseCoverage(){return this._profilerAgent.takePreciseCoverage().then(result=>result||[]);} -stopPreciseCoverage(){return this._profilerAgent.stopPreciseCoverage();} -bestEffortCoverage(){return this._profilerAgent.getBestEffortCoverage().then(result=>result||[]);}};SDK.SDKModel.register(SDK.CPUProfilerModel,SDK.Target.Capability.JS,true);SDK.CPUProfilerModel.Events={ConsoleProfileStarted:Symbol('ConsoleProfileStarted'),ConsoleProfileFinished:Symbol('ConsoleProfileFinished')};SDK.CPUProfilerModel.EventData;;SDK.CSSMatchedStyles=class{constructor(cssModel,node,inlinePayload,attributesPayload,matchedPayload,pseudoPayload,inheritedPayload,animationsPayload){this._cssModel=cssModel;this._node=node;this._nodeStyles=[];this._nodeForStyle=new Map();this._inheritedStyles=new Set();this._keyframes=[];this._matchingSelectors=new Map();function addAttributesStyle(){if(!attributesPayload) -return;var style=new SDK.CSSStyleDeclaration(cssModel,null,attributesPayload,SDK.CSSStyleDeclaration.Type.Attributes);this._nodeForStyle.set(style,this._node);this._nodeStyles.push(style);} -if(inlinePayload&&this._node.nodeType()===Node.ELEMENT_NODE){var style=new SDK.CSSStyleDeclaration(cssModel,null,inlinePayload,SDK.CSSStyleDeclaration.Type.Inline);this._nodeForStyle.set(style,this._node);this._nodeStyles.push(style);} -var addedAttributesStyle;for(var i=matchedPayload.length-1;i>=0;--i){var rule=new SDK.CSSStyleRule(cssModel,matchedPayload[i].rule);if((rule.isInjected()||rule.isUserAgent())&&!addedAttributesStyle){addedAttributesStyle=true;addAttributesStyle.call(this);} -this._nodeForStyle.set(rule.style,this._node);this._nodeStyles.push(rule.style);addMatchingSelectors.call(this,this._node,rule,matchedPayload[i].matchingSelectors);} -if(!addedAttributesStyle) -addAttributesStyle.call(this);var parentNode=this._node.parentNode;for(var i=0;parentNode&&inheritedPayload&&i<inheritedPayload.length;++i){var entryPayload=inheritedPayload[i];var inheritedInlineStyle=entryPayload.inlineStyle?new SDK.CSSStyleDeclaration(cssModel,null,entryPayload.inlineStyle,SDK.CSSStyleDeclaration.Type.Inline):null;if(inheritedInlineStyle&&this._containsInherited(inheritedInlineStyle)){this._nodeForStyle.set(inheritedInlineStyle,parentNode);this._nodeStyles.push(inheritedInlineStyle);this._inheritedStyles.add(inheritedInlineStyle);} -var inheritedMatchedCSSRules=entryPayload.matchedCSSRules||[];for(var j=inheritedMatchedCSSRules.length-1;j>=0;--j){var inheritedRule=new SDK.CSSStyleRule(cssModel,inheritedMatchedCSSRules[j].rule);addMatchingSelectors.call(this,parentNode,inheritedRule,inheritedMatchedCSSRules[j].matchingSelectors);if(!this._containsInherited(inheritedRule.style)) -continue;this._nodeForStyle.set(inheritedRule.style,parentNode);this._nodeStyles.push(inheritedRule.style);this._inheritedStyles.add(inheritedRule.style);} -parentNode=parentNode.parentNode;} -this._pseudoStyles=new Map();if(pseudoPayload){for(var i=0;i<pseudoPayload.length;++i){var entryPayload=pseudoPayload[i];var pseudoElement=this._node.pseudoElements().get(entryPayload.pseudoType)||null;var pseudoStyles=[];var rules=entryPayload.matches||[];for(var j=rules.length-1;j>=0;--j){var pseudoRule=new SDK.CSSStyleRule(cssModel,rules[j].rule);pseudoStyles.push(pseudoRule.style);this._nodeForStyle.set(pseudoRule.style,pseudoElement);if(pseudoElement) -addMatchingSelectors.call(this,pseudoElement,pseudoRule,rules[j].matchingSelectors);} -this._pseudoStyles.set(entryPayload.pseudoType,pseudoStyles);}} -if(animationsPayload) -this._keyframes=animationsPayload.map(rule=>new SDK.CSSKeyframesRule(cssModel,rule));this.resetActiveProperties();function addMatchingSelectors(node,rule,matchingSelectorIndices){for(var matchingSelectorIndex of matchingSelectorIndices){var selector=rule.selectors[matchingSelectorIndex];this._setSelectorMatches(node,selector.text,true);}}} -node(){return this._node;} -cssModel(){return this._cssModel;} -hasMatchingSelectors(rule){var matchingSelectors=this.matchingSelectors(rule);return matchingSelectors.length>0&&this.mediaMatches(rule.style);} -matchingSelectors(rule){var node=this.nodeForStyle(rule.style);if(!node) -return[];var map=this._matchingSelectors.get(node.id);if(!map) -return[];var result=[];for(var i=0;i<rule.selectors.length;++i){if(map.get(rule.selectors[i].text)) -result.push(i);} -return result;} -recomputeMatchingSelectors(rule){var node=this.nodeForStyle(rule.style);if(!node) -return Promise.resolve();var promises=[];for(var selector of rule.selectors) -promises.push(querySelector.call(this,node,selector.text));return Promise.all(promises);async function querySelector(node,selectorText){var ownerDocument=node.ownerDocument||null;var map=this._matchingSelectors.get(node.id);if((map&&map.has(selectorText))||!ownerDocument) -return;var matchingNodeIds=await this._node.domModel().querySelectorAll(ownerDocument.id,selectorText);if(matchingNodeIds) -this._setSelectorMatches(node,selectorText,matchingNodeIds.indexOf(node.id)!==-1);}} -addNewRule(rule,node){this._nodeForStyle.set(rule.style,node);return this.recomputeMatchingSelectors(rule);} -_setSelectorMatches(node,selectorText,value){var map=this._matchingSelectors.get(node.id);if(!map){map=new Map();this._matchingSelectors.set(node.id,map);} -map.set(selectorText,value);} -mediaMatches(style){var media=style.parentRule?style.parentRule.media:[];for(var i=0;media&&i<media.length;++i){if(!media[i].active()) -return false;} -return true;} -nodeStyles(){return this._nodeStyles;} -keyframes(){return this._keyframes;} -pseudoStyles(){return this._pseudoStyles;} -_containsInherited(style){var properties=style.allProperties();for(var i=0;i<properties.length;++i){var property=properties[i];if(property.activeInStyle()&&SDK.cssMetadata().isPropertyInherited(property.name)) -return true;} -return false;} -nodeForStyle(style){return this._nodeForStyle.get(style)||null;} -cssVariables(){var cssVariables=[];for(var style of this.nodeStyles()){for(var property of style.allProperties()){if(property.name.startsWith('--')) -cssVariables.push(property.name);}} -return cssVariables;} -isInherited(style){return this._inheritedStyles.has(style);} -propertyState(property){if(this._propertiesState.size===0){this._computeActiveProperties(this._nodeStyles,this._propertiesState);for(var pseudoElementStyles of this._pseudoStyles.valuesArray()) -this._computeActiveProperties(pseudoElementStyles,this._propertiesState);} -return this._propertiesState.get(property)||null;} -resetActiveProperties(){this._propertiesState=new Map();} -_computeActiveProperties(styles,result){var foundImportantProperties=new Set();var propertyToEffectiveRule=new Map();var inheritedPropertyToNode=new Map();var allUsedProperties=new Set();for(var i=0;i<styles.length;++i){var style=styles[i];var rule=style.parentRule;if(rule&&!(rule instanceof SDK.CSSStyleRule)) -continue;if(rule&&!this.hasMatchingSelectors(rule)) -continue;var styleActiveProperties=new Map();var allProperties=style.allProperties();for(var j=0;j<allProperties.length;++j){var property=allProperties[j];var inherited=this.isInherited(style);if(inherited&&!SDK.cssMetadata().isPropertyInherited(property.name)) -continue;if(!property.activeInStyle()){result.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;} -var canonicalName=SDK.cssMetadata().canonicalPropertyName(property.name);if(foundImportantProperties.has(canonicalName)){result.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;} -if(!property.important&&allUsedProperties.has(canonicalName)){result.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;} -var isKnownProperty=propertyToEffectiveRule.has(canonicalName);var inheritedFromNode=inherited?this.nodeForStyle(style):null;if(!isKnownProperty&&inheritedFromNode&&!inheritedPropertyToNode.has(canonicalName)) -inheritedPropertyToNode.set(canonicalName,inheritedFromNode);if(property.important){if(inherited&&isKnownProperty&&inheritedFromNode!==inheritedPropertyToNode.get(canonicalName)){result.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;} -foundImportantProperties.add(canonicalName);if(isKnownProperty){var overloaded=(propertyToEffectiveRule.get(canonicalName).get(canonicalName));result.set(overloaded,SDK.CSSMatchedStyles.PropertyState.Overloaded);propertyToEffectiveRule.get(canonicalName).delete(canonicalName);}} -styleActiveProperties.set(canonicalName,property);allUsedProperties.add(canonicalName);propertyToEffectiveRule.set(canonicalName,styleActiveProperties);result.set(property,SDK.CSSMatchedStyles.PropertyState.Active);} -for(var property of style.leadingProperties()){var canonicalName=SDK.cssMetadata().canonicalPropertyName(property.name);if(!styleActiveProperties.has(canonicalName)) -continue;var longhands=style.longhandProperties(property.name);if(!longhands.length) -continue;var notUsed=true;for(var longhand of longhands){var longhandCanonicalName=SDK.cssMetadata().canonicalPropertyName(longhand.name);notUsed=notUsed&&!styleActiveProperties.has(longhandCanonicalName);} -if(!notUsed) -continue;styleActiveProperties.delete(canonicalName);allUsedProperties.delete(canonicalName);result.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);}}}};SDK.CSSMatchedStyles.PropertyState={Active:'Active',Overloaded:'Overloaded'};;SDK.CSSMediaQuery=class{constructor(payload){this._active=payload.active;this._expressions=[];for(var j=0;j<payload.expressions.length;++j) -this._expressions.push(SDK.CSSMediaQueryExpression.parsePayload(payload.expressions[j]));} -static parsePayload(payload){return new SDK.CSSMediaQuery(payload);} -active(){return this._active;} -expressions(){return this._expressions;}};SDK.CSSMediaQueryExpression=class{constructor(payload){this._value=payload.value;this._unit=payload.unit;this._feature=payload.feature;this._valueRange=payload.valueRange?TextUtils.TextRange.fromObject(payload.valueRange):null;this._computedLength=payload.computedLength||null;} -static parsePayload(payload){return new SDK.CSSMediaQueryExpression(payload);} -value(){return this._value;} -unit(){return this._unit;} -feature(){return this._feature;} -valueRange(){return this._valueRange;} -computedLength(){return this._computedLength;}};SDK.CSSMedia=class{constructor(cssModel,payload){this._cssModel=cssModel;this._reinitialize(payload);} -static parsePayload(cssModel,payload){return new SDK.CSSMedia(cssModel,payload);} -static parseMediaArrayPayload(cssModel,payload){var result=[];for(var i=0;i<payload.length;++i) -result.push(SDK.CSSMedia.parsePayload(cssModel,payload[i]));return result;} -_reinitialize(payload){this.text=payload.text;this.source=payload.source;this.sourceURL=payload.sourceURL||'';this.range=payload.range?TextUtils.TextRange.fromObject(payload.range):null;this.styleSheetId=payload.styleSheetId;this.mediaList=null;if(payload.mediaList){this.mediaList=[];for(var i=0;i<payload.mediaList.length;++i) -this.mediaList.push(SDK.CSSMediaQuery.parsePayload(payload.mediaList[i]));}} -rebase(edit){if(this.styleSheetId!==edit.styleSheetId||!this.range) -return;if(edit.oldRange.equal(this.range)) -this._reinitialize((edit.payload));else -this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);} -equal(other){if(!this.styleSheetId||!this.range||!other.range) -return false;return this.styleSheetId===other.styleSheetId&&this.range.equal(other.range);} -active(){if(!this.mediaList) -return true;for(var i=0;i<this.mediaList.length;++i){if(this.mediaList[i].active()) -return true;} -return false;} -lineNumberInSource(){if(!this.range) -return undefined;var header=this.header();if(!header) -return undefined;return header.lineNumberInSource(this.range.startLine);} -columnNumberInSource(){if(!this.range) -return undefined;var header=this.header();if(!header) -return undefined;return header.columnNumberInSource(this.range.startLine,this.range.startColumn);} -header(){return this.styleSheetId?this._cssModel.styleSheetHeaderForId(this.styleSheetId):null;} -rawLocation(){var header=this.header();if(!header||this.lineNumberInSource()===undefined) -return null;var lineNumber=Number(this.lineNumberInSource());return new SDK.CSSLocation(header,lineNumber,this.columnNumberInSource());}};SDK.CSSMedia.Source={LINKED_SHEET:'linkedSheet',INLINE_SHEET:'inlineSheet',MEDIA_RULE:'mediaRule',IMPORT_RULE:'importRule'};;SDK.CSSMetadata=class{constructor(properties){this._values=([]);this._longhands=new Map();this._shorthands=new Map();this._inherited=new Set();this._svgProperties=new Set();for(var i=0;i<properties.length;++i){var property=properties[i];var propertyName=property.name;if(!CSS.supports(propertyName,'initial')) -continue;this._values.push(propertyName);if(property.inherited) -this._inherited.add(propertyName);if(property.svg) -this._svgProperties.add(propertyName);var longhands=properties[i].longhands;if(longhands){this._longhands.set(propertyName,longhands);for(var j=0;j<longhands.length;++j){var longhandName=longhands[j];var shorthands=this._shorthands.get(longhandName);if(!shorthands){shorthands=[];this._shorthands.set(longhandName,shorthands);} -shorthands.push(propertyName);}}} -this._values.sort();this._valuesSet=new Set(this._values);} -allProperties(){return this._values;} -isSVGProperty(name){name=name.toLowerCase();return this._svgProperties.has(name);} -longhands(shorthand){return this._longhands.get(shorthand)||null;} -shorthands(longhand){return this._shorthands.get(longhand)||null;} -isColorAwareProperty(propertyName){return!!SDK.CSSMetadata._colorAwareProperties.has(propertyName.toLowerCase())||this.isCustomProperty(propertyName.toLowerCase());} -isLengthProperty(propertyName){propertyName=propertyName.toLowerCase();if(propertyName==='line-height') -return false;return SDK.CSSMetadata._distanceProperties.has(propertyName)||propertyName.startsWith('margin')||propertyName.startsWith('padding')||propertyName.indexOf('width')!==-1||propertyName.indexOf('height')!==-1;} -isBezierAwareProperty(propertyName){propertyName=propertyName.toLowerCase();return!!SDK.CSSMetadata._bezierAwareProperties.has(propertyName)||this.isCustomProperty(propertyName);} -isCustomProperty(propertyName){return propertyName.startsWith('--');} -canonicalPropertyName(name){name=name.toLowerCase();if(!name||name.length<9||name.charAt(0)!=='-') -return name;var match=name.match(/(?:-webkit-)(.+)/);if(!match||!this._valuesSet.has(match[1])) -return name;return match[1];} -isCSSPropertyName(propertyName){propertyName=propertyName.toLowerCase();if(propertyName.startsWith('-moz-')||propertyName.startsWith('-o-')||propertyName.startsWith('-webkit-')||propertyName.startsWith('-ms-')) -return true;return this._valuesSet.has(propertyName);} -isPropertyInherited(propertyName){propertyName=propertyName.toLowerCase();return propertyName.startsWith('--')||this._inherited.has(this.canonicalPropertyName(propertyName))||this._inherited.has(propertyName);} -propertyValues(propertyName){var acceptedKeywords=['inherit','initial','unset'];propertyName=propertyName.toLowerCase();var unprefixedName=propertyName.replace(/^-webkit-/,'');var entry=SDK.CSSMetadata._propertyDataMap[propertyName]||SDK.CSSMetadata._propertyDataMap[unprefixedName];if(entry&&entry.values) -acceptedKeywords.pushAll(entry.values);if(this.isColorAwareProperty(propertyName)){acceptedKeywords.push('currentColor');for(var color in Common.Color.Nicknames) -acceptedKeywords.push(color);} -return acceptedKeywords.sort();} -propertyUsageWeight(property){return SDK.CSSMetadata.Weight[property]||SDK.CSSMetadata.Weight[this.canonicalPropertyName(property)]||0;}};SDK.CSSMetadata.VariableRegex=/(var\(--.*?\))/g;SDK.CSSMetadata.URLRegex=/url\(\s*('.+?'|".+?"|[^)]+)\s*\)/g;SDK.cssMetadata=function(){if(!SDK.CSSMetadata._instance) -SDK.CSSMetadata._instance=new SDK.CSSMetadata(SDK.CSSMetadata._generatedProperties||[]);return SDK.CSSMetadata._instance;};SDK.CSSMetadata._distanceProperties=new Set(['background-position','border-spacing','bottom','font-size','height','left','letter-spacing','max-height','max-width','min-height','min-width','right','text-indent','top','width','word-spacing','grid-row-gap','grid-column-gap']);SDK.CSSMetadata._bezierAwareProperties=new Set(['animation','animation-timing-function','transition','transition-timing-function','-webkit-animation','-webkit-animation-timing-function','-webkit-transition','-webkit-transition-timing-function']);SDK.CSSMetadata._colorAwareProperties=new Set(['backdrop-filter','background','background-color','background-image','border','border-color','border-image','border-image-source','border-bottom','border-bottom-color','border-left','border-left-color','border-right','border-right-color','border-top','border-top-color','box-shadow','caret-color','color','column-rule','column-rule-color','fill','list-style','list-style-image','outline','outline-color','stroke','text-decoration-color','text-shadow','-webkit-border-after','-webkit-border-after-color','-webkit-border-before','-webkit-border-before-color','-webkit-border-end','-webkit-border-end-color','-webkit-border-start','-webkit-border-start-color','-webkit-box-reflect','-webkit-box-shadow','-webkit-column-rule-color','-webkit-filter','-webkit-mask','-webkit-mask-box-image','-webkit-mask-box-image-source','-webkit-mask-image','-webkit-tap-highlight-color','-webkit-text-decoration-color','-webkit-text-emphasis','-webkit-text-emphasis-color','-webkit-text-fill-color','-webkit-text-stroke','-webkit-text-stroke-color']);SDK.CSSMetadata._propertyDataMap={'table-layout':{values:['auto','fixed']},'visibility':{values:['hidden','visible','collapse']},'background-repeat':{values:['repeat','repeat-x','repeat-y','no-repeat','space','round']},'content':{values:['none','normal','close-quote','no-close-quote','no-open-quote','open-quote']},'list-style-image':{values:['none']},'clear':{values:['none','left','right','both']},'overflow-x':{values:['hidden','auto','visible','overlay','scroll']},'stroke-linejoin':{values:['round','miter','bevel']},'baseline-shift':{values:['baseline','sub','super']},'border-bottom-width':{values:['medium','thick','thin']},'margin-top-collapse':{values:['collapse','separate','discard']},'max-height':{values:['none','min-content','max-content','-webkit-fill-available','fit-content']},'box-orient':{values:['horizontal','vertical','inline-axis','block-axis'],},'font-stretch':{values:['normal','ultra-condensed','extra-condensed','condensed','semi-condensed','semi-expanded','expanded','extra-expanded','ultra-expanded']},'border-left-width':{values:['medium','thick','thin']},'box-shadow':{values:['inset','none']},'-webkit-writing-mode':{values:['horizontal-tb','vertical-rl','vertical-lr']},'writing-mode':{values:['lr','rl','tb','lr-tb','rl-tb','tb-rl','horizontal-tb','vertical-rl','vertical-lr']},'border-collapse':{values:['collapse','separate']},'page-break-inside':{values:['auto','avoid']},'border-top-width':{values:['medium','thick','thin']},'outline-style':{values:['auto','none','inset','groove','ridge','outset','dotted','dashed','solid','double']},'cursor':{values:['none','copy','auto','crosshair','default','pointer','move','vertical-text','cell','context-menu','alias','progress','no-drop','not-allowed','-webkit-zoom-in','-webkit-zoom-out','e-resize','ne-resize','nw-resize','n-resize','se-resize','sw-resize','s-resize','w-resize','ew-resize','ns-resize','nesw-resize','nwse-resize','col-resize','row-resize','text','wait','help','all-scroll','zoom-in','zoom-out','-webkit-grab','-webkit-grabbing']},'border-width':{values:['medium','thick','thin']},'border-style':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double']},'size':{values:['auto','a3','a4','a5','b4','b5','landscape','ledger','legal','letter','portrait']},'background-size':{values:['auto','contain','cover']},'direction':{values:['ltr','rtl']},'enable-background':{values:['accumulate','new']},'float':{values:['none','left','right']},'overflow-y':{values:['hidden','auto','visible','overlay','scroll','-webkit-paged-x','-webkit-paged-y']},'margin-bottom-collapse':{values:['collapse','separate','discard']},'box-reflect':{values:['left','right','above','below']},'overflow':{values:['hidden','auto','visible','overlay','scroll','-webkit-paged-x','-webkit-paged-y']},'contain':{values:['none','strict','content','size','layout','style','paint']},'text-rendering':{values:['auto','optimizeSpeed','optimizeLegibility','geometricPrecision']},'text-align':{values:['-webkit-auto','start','end','left','right','center','justify','-webkit-left','-webkit-right','-webkit-center','-webkit-match-parent']},'list-style-position':{values:['outside','inside']},'margin-bottom':{values:['auto']},'color-interpolation':{values:['auto','sRGB','linearRGB']},'background-origin':{values:['border-box','content-box','padding-box']},'word-wrap':{values:['normal','break-word']},'font-weight':{values:['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900']},'margin-before-collapse':{values:['collapse','separate','discard']},'text-transform':{values:['none','capitalize','uppercase','lowercase']},'border-right-style':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double']},'border-left-style':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double']},'-webkit-text-emphasis':{values:['circle','filled','open','dot','double-circle','triangle','sesame','none']},'font-style':{values:['italic','oblique','normal']},'speak':{values:['none','normal','spell-out','digits','literal-punctuation','no-punctuation']},'color-rendering':{values:['auto','optimizeSpeed','optimizeQuality']},'list-style-type':{values:['none','disc','circle','square','decimal','decimal-leading-zero','arabic-indic','bengali','cambodian','khmer','devanagari','gujarati','gurmukhi','kannada','lao','malayalam','mongolian','myanmar','oriya','persian','urdu','telugu','tibetan','thai','lower-roman','upper-roman','lower-greek','lower-alpha','lower-latin','upper-alpha','upper-latin','ethiopic-halehame','ethiopic-halehame-am','ethiopic-halehame-ti-er','ethiopic-halehame-ti-et','cjk-earthly-branch','cjk-heavenly-stem','hangul-consonant','hangul','korean-hangul-formal','korean-hanja-formal','korean-hanja-informal','simp-chinese-formal','simp-chinese-informal','trad-chinese-formal','trad-chinese-informal','hebrew','armenian','lower-armenian','upper-armenian','georgian','cjk-ideographic','hiragana','katakana','hiragana-iroha','katakana-iroha']},'text-combine-upright':{values:['none','all']},'-webkit-text-combine':{values:['none','horizontal']},'text-orientation':{values:['mixed','upright','sideways','sideways-right']},'outline':{values:['none','inset','groove','ridge','outset','dotted','dashed','solid','double','medium','auto','thick','thin']},'font':{values:['caption','icon','menu','message-box','small-caption','-webkit-mini-control','-webkit-small-control','-webkit-control','status-bar','italic','oblique','small-caps','normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','xx-small','x-small','small','medium','large','x-large','xx-large','-webkit-xxx-large','smaller','larger','serif','sans-serif','cursive','fantasy','monospace','-webkit-body','-webkit-pictograph']},'dominant-baseline':{values:['middle','auto','central','text-before-edge','text-after-edge','ideographic','alphabetic','hanging','mathematical','use-script','no-change','reset-size']},'display':{values:['none','inline','block','flow-root','list-item','inline-block','table','inline-table','table-row-group','table-header-group','table-footer-group','table-row','table-column-group','table-column','table-cell','table-caption','-webkit-box','-webkit-inline-box','flex','inline-flex','grid','inline-grid','contents']},'-webkit-text-emphasis-position':{values:['over','under']},'image-rendering':{values:['auto','pixelated','-webkit-optimize-contrast']},'alignment-baseline':{values:['baseline','middle','auto','before-edge','after-edge','central','text-before-edge','text-after-edge','ideographic','alphabetic','hanging','mathematical']},'outline-width':{values:['medium','thick','thin']},'box-align':{values:['baseline','center','stretch','start','end']},'border-right-width':{values:['medium','thick','thin']},'border-top-style':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double']},'line-height':{values:['normal']},'text-overflow':{values:['clip','ellipsis']},'overflow-wrap':{values:['normal','break-word']},'box-direction':{values:['normal','reverse']},'margin-after-collapse':{values:['collapse','separate','discard']},'page-break-before':{values:['left','right','auto','always','avoid']},'border-image':{values:['repeat','stretch','none','space','round']},'text-decoration':{values:['none','blink','line-through','overline','underline','wavy','double','solid','dashed','dotted']},'position':{values:['absolute','fixed','relative','static','sticky']},'font-family':{values:['serif','sans-serif','cursive','fantasy','monospace','-webkit-body','-webkit-pictograph']},'text-overflow-mode':{values:['clip','ellipsis']},'border-bottom-style':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double']},'unicode-bidi':{values:['normal','bidi-override','embed','isolate','isolate-override','plaintext']},'clip-rule':{values:['nonzero','evenodd']},'margin-left':{values:['auto']},'margin-top':{values:['auto']},'zoom':{values:['normal']},'max-width':{values:['none','min-content','max-content','-webkit-fill-available','fit-content']},'caption-side':{values:['top','bottom']},'empty-cells':{values:['hide','show']},'pointer-events':{values:['none','all','auto','visible','visiblepainted','visiblefill','visiblestroke','painted','fill','stroke','bounding-box']},'letter-spacing':{values:['normal']},'background-clip':{values:['border-box','content-box','padding-box']},'-webkit-font-smoothing':{values:['none','auto','antialiased','subpixel-antialiased']},'border':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double','medium','thick','thin']},'font-size':{values:['xx-small','x-small','small','medium','large','x-large','xx-large','-webkit-xxx-large','smaller','larger']},'font-variant':{values:['small-caps','normal','none','common-ligatures','no-common-ligatures','discretionary-ligatures','no-discretionary-ligatures','historical-ligatures','no-historical-ligatures','contextual','no-contextual','all-small-caps','petite-caps','all-petite-caps','unicase','titling-caps','lining-nums','oldstyle-nums','proportional-nums','tabular-nums','diagonal-fractions','stacked-fractions','ordinal','slashed-zero','jis78','jis83','jis90','jis04','simplified','traditional','full-width','proportional-width','ruby']},'vertical-align':{values:['baseline','middle','sub','super','text-top','text-bottom','top','bottom','-webkit-baseline-middle']},'white-space':{values:['normal','nowrap','pre','pre-line','pre-wrap']},'box-lines':{values:['single','multiple']},'page-break-after':{values:['left','right','auto','always','avoid']},'clip-path':{values:['none']},'margin':{values:['auto']},'margin-right':{values:['auto']},'word-break':{values:['normal','break-all','break-word','keep-all']},'word-spacing':{values:['normal']},'-webkit-text-emphasis-style':{values:['circle','filled','open','dot','double-circle','triangle','sesame','none']},'transform':{values:['scale','scaleX','scaleY','scale3d','rotate','rotateX','rotateY','rotateZ','rotate3d','skew','skewX','skewY','translate','translateX','translateY','translateZ','translate3d','matrix','matrix3d','perspective','none']},'image-resolution':{values:['from-image','snap']},'box-sizing':{values:['content-box','border-box']},'clip':{values:['auto']},'resize':{values:['none','both','horizontal','vertical','auto']},'align-content':{values:['normal','baseline','space-between','space-around','space-evenly','stretch','unsafe','safe','center','start','end','flex-start','flex-end','left','right']},'justify-content':{values:['normal','space-between','space-around','space-evenly','stretch','unsafe','safe','center','start','end','flex-start','flex-end','left','right','baseline']},'place-content':{values:['normal','space-between','space-around','space-evenly','stretch','unsafe','safe','center','start','end','flex-start','flex-end','left','right','baseline']},'align-items':{values:['normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right']},'justify-items':{values:['normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right','legacy','auto']},'place-items':{values:['auto','normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right']},'align-self':{values:['auto','normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right']},'justify-self':{values:['auto','normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right']},'place-self':{values:['auto','normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right']},'flex-direction':{values:['row','row-reverse','column','column-reverse']},'flex-wrap':{values:['nowrap','wrap','wrap-reverse']},'perspective':{values:['none']},'perspective-origin':{values:['left','center','right','top','bottom']},'transform-origin':{values:['left','center','right','top','bottom']},'transform-style':{values:['flat','preserve-3d']},'transition-timing-function':{values:['ease','linear','ease-in','ease-out','ease-in-out','step-start','step-end','steps','frames','cubic-bezier','step-middle']},'animation-timing-function':{values:['ease','linear','ease-in','ease-out','ease-in-out','step-start','step-end','steps','frames','cubic-bezier','step-middle']},'animation-direction':{values:['normal','reverse','alternate','alternate-reverse']},'animation-play-state':{values:['running','paused']},'animation-fill-mode':{values:['none','forwards','backwards','both']},'-webkit-backface-visibility':{values:['visible','hidden']},'-webkit-box-decoration-break':{values:['slice','clone']},'-webkit-column-break-after':{values:['auto','always','avoid','left','right','page','column','avoid-page','avoid-column']},'-webkit-column-break-before':{values:['auto','always','avoid','left','right','page','column','avoid-page','avoid-column']},'-webkit-column-break-inside':{values:['auto','avoid','avoid-page','avoid-column']},'-webkit-column-span':{values:['none','all']},'-webkit-column-count':{values:['auto']},'-webkit-column-gap':{values:['normal']},'filter':{values:['url','blur','brightness','contrast','drop-shadow','grayscale','hue-rotate','invert','opacity','saturate','sepia','none']},'line-break':{values:['auto','loose','normal','strict','after-white-space']},'user-select':{values:['none','text','all','auto']},'-webkit-user-modify':{values:['read-only','read-write','read-write-plaintext-only']},'text-align-last':{values:['auto','start','end','left','right','center','justify']},'-webkit-text-decoration-line':{values:['none','underline','overline','line-through','blink']},'-webkit-text-decoration-style':{values:['solid','double','dotted','dashed','wavy']},'-webkit-text-decoration-skip':{values:['none','objects','spaces','ink','edges','box-decoration']},'mix-blend-mode':{values:['normal','multiply','screen','overlay','darken','lighten','color-dodge','color-burn','hard-light','soft-light','difference','exclusion','hue','saturation','color','luminosity','unset']},'background-blend-mode':{values:['normal','multiply','screen','overlay','darken','lighten','color-dodge','color-burn','hard-light','soft-light','difference','exclusion','hue','saturation','color','luminosity','unset']},'caret-color':{values:['auto']},'grid-template-columns':{values:['none','auto','min-content','max-content']},'grid-template-rows':{values:['none','auto','min-content','max-content']},'grid-template-areas':{values:['none']},'grid-template':{values:['none']},'grid-auto-columns':{values:['auto','min-content','max-content']},'grid-auto-rows':{values:['auto','min-content','max-content']},'grid-auto-flow':{values:['row','column','dense']},'grid':{values:['none']},'grid-row-start':{values:['auto']},'grid-column-start':{values:['auto']},'grid-row-end':{values:['auto']},'grid-column-end':{values:['auto']},'grid-row':{values:['auto']},'grid-column':{values:['auto']},'grid-area':{values:['auto']},'animation-iteration-count':{values:['infinite']},'font-feature-settings':{values:['normal']},'font-kerning':{values:['none','normal','auto']},'font-size-adjust':{values:['none']},'font-variant-caps':{values:['small-caps','all-small-caps','petite-caps','all-petite-caps','unicase','titling-caps','normal']},'font-variant-east-asian':{values:['jis78','jis83','jis90','jis04','simplified','traditional','full-width','proportional-width','ruby']},'font-variant-ligatures':{values:['none','common-ligatures','no-common-ligatures','discretionary-ligatures','no-discretionary-ligatures','historical-ligatures','no-historical-ligatures','contextual','no-contextual','normal']},'font-variant-numeric':{values:['lining-nums','oldstyle-nums','proportional-nums','tabular-nums','diagonal-fractions','stacked-fractions','ordinal','slashed-zero','normal']},'font-variation-settings':{values:['normal']},'-webkit-locale':{values:['auto']},'backdrop-filter':{values:['none']},'backface-visibility':{values:['hidden','visible']},'background':{values:['none','repeat','repeat-x','repeat-y','no-repeat','top','bottom','left','right','center','fixed','local','scroll','space','round','border-box','content-box','padding-box']},'background-attachment':{values:['fixed','local','scroll']},'background-image':{values:['none']},'background-position':{values:['top','bottom','left','right','center']},'background-position-x':{values:['left','right','center']},'background-position-y':{values:['top','bottom','center']},'background-repeat-x':{values:['repeat','no-repeat']},'background-repeat-y':{values:['repeat','no-repeat']},'border-bottom':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'border-image-repeat':{values:['repeat','stretch','space','round']},'border-image-source':{values:['none']},'border-image-width':{values:['auto']},'border-left':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'border-right':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'border-top':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'bottom':{values:['auto']},'break-after':{values:['left','right','auto','avoid','column','avoid-page','page','recto','verso','avoid-column']},'break-before':{values:['left','right','auto','avoid','column','avoid-page','page','recto','verso','avoid-column']},'break-inside':{values:['auto','avoid','avoid-page','avoid-column']},'buffered-rendering':{values:['auto','static','dynamic']},'color-interpolation-filters':{values:['auto','srgb','linearrgb']},'column-count':{values:['auto']},'column-fill':{values:['auto','balance']},'column-gap':{values:['normal']},'column-rule':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'column-rule-style':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double']},'column-rule-width':{values:['medium','thick','thin']},'column-span':{values:['none','all']},'column-width':{values:['auto']},'columns':{values:['auto']},'d':{values:['none']},'fill':{values:['none']},'fill-rule':{values:['nonzero','evenodd']},'flex':{values:['none','auto']},'flex-basis':{values:['auto']},'flex-flow':{values:['nowrap','row','row-reverse','column','column-reverse','wrap','wrap-reverse']},'height':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'hyphens':{values:['none','manual']},'inline-size':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'isolation':{values:['auto','isolate']},'left':{values:['auto']},'list-style':{values:['none','outside','inside','disc','circle','square','decimal','decimal-leading-zero','arabic-indic','bengali','cambodian','khmer','devanagari','gujarati','gurmukhi','kannada','lao','malayalam','mongolian','myanmar','oriya','persian','urdu','telugu','tibetan','thai','lower-roman','upper-roman','lower-greek','lower-alpha','lower-latin','upper-alpha','upper-latin','cjk-earthly-branch','cjk-heavenly-stem','ethiopic-halehame','ethiopic-halehame-am','ethiopic-halehame-ti-er','ethiopic-halehame-ti-et','hangul','hangul-consonant','korean-hangul-formal','korean-hanja-formal','korean-hanja-informal','hebrew','armenian','lower-armenian','upper-armenian','georgian','cjk-ideographic','simp-chinese-formal','simp-chinese-informal','trad-chinese-formal','trad-chinese-informal','hiragana','katakana','hiragana-iroha','katakana-iroha']},'marker':{values:['none']},'marker-end':{values:['none']},'marker-mid':{values:['none']},'marker-start':{values:['none']},'mask':{values:['none']},'mask-source-type':{values:['auto','alpha','luminance']},'mask-type':{values:['alpha','luminance']},'max-block-size':{values:['none','-webkit-fill-available','min-content','max-content','fit-content']},'max-inline-size':{values:['none','-webkit-fill-available','min-content','max-content','fit-content']},'min-block-size':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'min-height':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'min-inline-size':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'min-width':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'object-fit':{values:['none','contain','cover','fill','scale-down']},'object-position':{values:['top','bottom','left','right','center']},'offset-anchor':{values:['top','bottom','left','right','center','auto']},'offset-path':{values:['none']},'offset-position':{values:['top','bottom','left','right','center','auto']},'offset-rotate':{values:['auto','reverse']},'overflow-anchor':{values:['none','auto','visible']},'paint-order':{values:['normal','fill','stroke','markers']},'quotes':{values:['none']},'right':{values:['auto']},'rotate':{values:['none']},'rx':{values:['auto']},'ry':{values:['auto']},'scale':{values:['none']},'scroll-behavior':{values:['auto','smooth']},'shape-outside':{values:['none','border-box','content-box','padding-box','margin-box']},'shape-rendering':{values:['auto','optimizespeed','geometricprecision','crispedges']},'stroke':{values:['none']},'stroke-dasharray':{values:['none']},'stroke-linecap':{values:['square','round','butt']},'text-anchor':{values:['middle','start','end']},'text-decoration-line':{values:['none','blink','line-through','overline','underline']},'text-decoration-skip':{values:['objects','ink']},'text-decoration-style':{values:['dotted','dashed','solid','double','wavy']},'text-justify':{values:['none','inter-word','distribute','auto']},'text-shadow':{values:['none']},'text-size-adjust':{values:['none','auto']},'text-underline-position':{values:['auto','under']},'top':{values:['auto']},'touch-action':{values:['none','auto','pan-x','pan-y','pan-left','pan-right','pan-up','pan-down','manipulation','pinch-zoom']},'transform-box':{values:['border-box','fill-box','view-box']},'translate':{values:['none']},'vector-effect':{values:['none','non-scaling-stroke']},'-webkit-app-region':{values:['drag','no-drag']},'-webkit-appearance':{values:['none','checkbox','radio','push-button','square-button','button','button-bevel','inner-spin-button','listbox','listitem','media-enter-fullscreen-button','media-exit-fullscreen-button','media-mute-button','media-play-button','media-overlay-play-button','media-toggle-closed-captions-button','media-slider','media-sliderthumb','media-volume-slider-container','media-volume-slider','media-volume-sliderthumb','media-controls-background','media-controls-fullscreen-background','media-current-time-display','media-time-remaining-display','menulist','menulist-button','menulist-text','menulist-textfield','meter','progress-bar','progress-bar-value','slider-horizontal','slider-vertical','sliderthumb-horizontal','sliderthumb-vertical','caret','searchfield','searchfield-cancel-button','textfield','textarea']},'-webkit-border-after':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'-webkit-border-after-style':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double']},'-webkit-border-after-width':{values:['medium','thick','thin']},'-webkit-border-before':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'-webkit-border-before-style':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double']},'-webkit-border-before-width':{values:['medium','thick','thin']},'-webkit-border-end':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'-webkit-border-end-style':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double']},'-webkit-border-end-width':{values:['medium','thick','thin']},'-webkit-border-start':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'-webkit-border-start-style':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double']},'-webkit-border-start-width':{values:['medium','thick','thin']},'-webkit-box-pack':{values:['center','justify','start','end']},'-webkit-highlight':{values:['none']},'-webkit-hyphenate-character':{values:['auto']},'-webkit-logical-height':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-logical-width':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-margin-after':{values:['auto']},'-webkit-margin-before':{values:['auto']},'-webkit-margin-collapse':{values:['collapse','separate','discard']},'-webkit-margin-end':{values:['auto']},'-webkit-margin-start':{values:['auto']},'-webkit-mask-box-image':{values:['none','repeat','stretch','space','round']},'-webkit-mask-box-image-repeat':{values:['repeat','stretch','space','round']},'-webkit-mask-box-image-source':{values:['none']},'-webkit-mask-box-image-width':{values:['auto']},'-webkit-mask-clip':{values:['text','border','border-box','content','content-box','padding','padding-box']},'-webkit-mask-composite':{values:['clear','copy','source-over','source-in','source-out','source-atop','destination-over','destination-in','destination-out','destination-atop','xor','plus-lighter']},'-webkit-mask-image':{values:['none']},'-webkit-mask-origin':{values:['border','border-box','content','content-box','padding','padding-box']},'-webkit-mask-position':{values:['top','bottom','left','right','center']},'-webkit-mask-position-x':{values:['left','right','center']},'-webkit-mask-position-y':{values:['top','bottom','center']},'-webkit-mask-repeat':{values:['repeat','repeat-x','repeat-y','no-repeat','space','round']},'-webkit-mask-size':{values:['auto','contain','cover']},'-webkit-max-logical-height':{values:['none','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-max-logical-width':{values:['none','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-min-logical-height':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-min-logical-width':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-perspective-origin-x':{values:['left','right','center']},'-webkit-perspective-origin-y':{values:['top','bottom','center']},'-webkit-print-color-adjust':{values:['economy','exact']},'-webkit-rtl-ordering':{values:['logical','visual']},'-webkit-ruby-position':{values:['after','before']},'-webkit-text-decorations-in-effect':{values:['none','blink','line-through','overline','underline']},'-webkit-text-security':{values:['none','disc','circle','square']},'-webkit-text-stroke':{values:['medium','thick','thin']},'-webkit-text-stroke-width':{values:['medium','thick','thin']},'-webkit-transform-origin-x':{values:['left','right','center']},'-webkit-transform-origin-y':{values:['top','bottom','center']},'-webkit-user-drag':{values:['none','auto','element']},'width':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'z-index':{values:['auto']}};SDK.CSSMetadata.Weight={'align-content':57,'align-items':129,'align-self':55,'animation':175,'animation-delay':114,'animation-direction':113,'animation-duration':137,'animation-fill-mode':132,'animation-iteration-count':124,'animation-name':139,'animation-play-state':104,'animation-timing-function':141,'backface-visibility':123,'background':260,'background-attachment':119,'background-clip':165,'background-color':259,'background-image':246,'background-origin':107,'background-position':237,'background-position-x':108,'background-position-y':93,'background-repeat':234,'background-size':203,'border':263,'border-bottom':233,'border-bottom-color':190,'border-bottom-left-radius':186,'border-bottom-right-radius':185,'border-bottom-style':150,'border-bottom-width':179,'border-collapse':209,'border-color':226,'border-image':89,'border-image-outset':50,'border-image-repeat':49,'border-image-slice':58,'border-image-source':32,'border-image-width':52,'border-left':221,'border-left-color':174,'border-left-style':142,'border-left-width':172,'border-radius':224,'border-right':223,'border-right-color':182,'border-right-style':130,'border-right-width':178,'border-spacing':198,'border-style':206,'border-top':231,'border-top-color':192,'border-top-left-radius':187,'border-top-right-radius':189,'border-top-style':152,'border-top-width':180,'border-width':214,'bottom':227,'box-shadow':213,'box-sizing':216,'caption-side':96,'clear':229,'clip':173,'clip-rule':5,'color':256,'content':219,'counter-increment':111,'counter-reset':110,'cursor':250,'direction':176,'display':262,'empty-cells':99,'fill':140,'fill-opacity':82,'fill-rule':22,'filter':160,'flex':133,'flex-basis':66,'flex-direction':85,'flex-flow':94,'flex-grow':112,'flex-shrink':61,'flex-wrap':68,'float':252,'font':211,'font-family':254,'font-kerning':18,'font-size':264,'font-stretch':77,'font-style':220,'font-variant':161,'font-weight':257,'height':266,'image-rendering':90,'justify-content':127,'left':248,'letter-spacing':188,'line-height':244,'list-style':215,'list-style-image':145,'list-style-position':149,'list-style-type':199,'margin':267,'margin-bottom':241,'margin-left':243,'margin-right':238,'margin-top':253,'mask':20,'max-height':205,'max-width':225,'min-height':217,'min-width':218,'object-fit':33,'opacity':251,'order':117,'orphans':146,'outline':222,'outline-color':153,'outline-offset':147,'outline-style':151,'outline-width':148,'overflow':255,'overflow-wrap':105,'overflow-x':184,'overflow-y':196,'padding':265,'padding-bottom':230,'padding-left':235,'padding-right':232,'padding-top':240,'page':8,'page-break-after':120,'page-break-before':69,'page-break-inside':121,'perspective':92,'perspective-origin':103,'pointer-events':183,'position':261,'quotes':158,'resize':168,'right':245,'shape-rendering':38,'size':64,'speak':118,'src':170,'stop-color':42,'stop-opacity':31,'stroke':98,'stroke-dasharray':36,'stroke-dashoffset':3,'stroke-linecap':30,'stroke-linejoin':21,'stroke-miterlimit':12,'stroke-opacity':34,'stroke-width':87,'table-layout':171,'tab-size':46,'text-align':260,'text-anchor':35,'text-decoration':247,'text-indent':207,'text-overflow':204,'text-rendering':155,'text-shadow':208,'text-transform':202,'top':258,'touch-action':80,'transform':181,'transform-origin':162,'transform-style':86,'transition':193,'transition-delay':134,'transition-duration':135,'transition-property':131,'transition-timing-function':122,'unicode-bidi':156,'unicode-range':136,'vertical-align':236,'visibility':242,'-webkit-appearance':191,'-webkit-backface-visibility':154,'-webkit-background-clip':164,'-webkit-background-origin':40,'-webkit-background-size':163,'-webkit-border-end':9,'-webkit-border-horizontal-spacing':81,'-webkit-border-image':75,'-webkit-border-radius':212,'-webkit-border-start':10,'-webkit-border-start-color':16,'-webkit-border-start-width':13,'-webkit-border-vertical-spacing':43,'-webkit-box-align':101,'-webkit-box-direction':51,'-webkit-box-flex':128,'-webkit-box-lines':2,'-webkit-box-ordinal-group':91,'-webkit-box-orient':144,'-webkit-box-pack':106,'-webkit-box-reflect':39,'-webkit-box-shadow':210,'-webkit-column-break-inside':60,'-webkit-column-count':84,'-webkit-column-gap':76,'-webkit-column-rule':25,'-webkit-column-rule-color':23,'-webkit-columns':44,'-webkit-column-span':29,'-webkit-column-width':47,'-webkit-filter':159,'-webkit-font-feature-settings':59,'-webkit-font-smoothing':177,'-webkit-highlight':1,'-webkit-line-break':45,'-webkit-line-clamp':126,'-webkit-margin-after':67,'-webkit-margin-before':70,'-webkit-margin-collapse':14,'-webkit-margin-end':65,'-webkit-margin-start':100,'-webkit-margin-top-collapse':78,'-webkit-mask':19,'-webkit-mask-box-image':72,'-webkit-mask-image':88,'-webkit-mask-position':54,'-webkit-mask-repeat':63,'-webkit-mask-size':79,'-webkit-padding-after':15,'-webkit-padding-before':28,'-webkit-padding-end':48,'-webkit-padding-start':73,'-webkit-print-color-adjust':83,'-webkit-rtl-ordering':7,'-webkit-tap-highlight-color':169,'-webkit-text-emphasis-color':11,'-webkit-text-fill-color':71,'-webkit-text-security':17,'-webkit-text-stroke':56,'-webkit-text-stroke-color':37,'-webkit-text-stroke-width':53,'-webkit-user-drag':95,'-webkit-user-modify':62,'-webkit-user-select':194,'-webkit-writing-mode':4,'white-space':228,'widows':115,'width':268,'will-change':74,'word-break':166,'word-spacing':157,'word-wrap':197,'writing-mode':41,'z-index':239,'zoom':200};;SDK.CSSModel=class extends SDK.SDKModel{constructor(target){super(target);this._domModel=(target.model(SDK.DOMModel));this._sourceMapManager=new SDK.SourceMapManager(target);this._agent=target.cssAgent();this._styleLoader=new SDK.CSSModel.ComputedStyleLoader(this);this._resourceTreeModel=target.model(SDK.ResourceTreeModel);if(this._resourceTreeModel){this._resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._resetStyleSheets,this);} -target.registerCSSDispatcher(new SDK.CSSDispatcher(this));this._enable();this._styleSheetIdToHeader=new Map();this._styleSheetIdsForURL=new Map();this._originalStyleSheetText=new Map();this._sourceMapManager.setEnabled(Common.moduleSetting('cssSourceMapsEnabled').get());Common.moduleSetting('cssSourceMapsEnabled').addChangeListener(event=>this._sourceMapManager.setEnabled((event.data)));} -sourceMapManager(){return this._sourceMapManager;} -static trimSourceURL(text){var sourceURLIndex=text.lastIndexOf('/*# sourceURL=');if(sourceURLIndex===-1){sourceURLIndex=text.lastIndexOf('/*@ sourceURL=');if(sourceURLIndex===-1) -return text;} -var sourceURLLineIndex=text.lastIndexOf('\n',sourceURLIndex);if(sourceURLLineIndex===-1) -return text;var sourceURLLine=text.substr(sourceURLLineIndex+1).split('\n',1)[0];var sourceURLRegex=/[\040\t]*\/\*[#@] sourceURL=[\040\t]*([^\s]*)[\040\t]*\*\/[\040\t]*$/;if(sourceURLLine.search(sourceURLRegex)===-1) -return text;return text.substr(0,sourceURLLineIndex)+text.substr(sourceURLLineIndex+sourceURLLine.length+1);} -domModel(){return this._domModel;} -setStyleText(styleSheetId,range,text,majorChange){var original=this._innerSetStyleTexts.bind(this,[styleSheetId],[range],[text],majorChange);var header=this.styleSheetHeaderForId(styleSheetId);if(!header) -return original();var sourceMap=this._sourceMapManager.sourceMapForClient(header);if(!sourceMap) -return original();var originalAndDetach=originalAndDetachIfSuccess.bind(this,header);if(!sourceMap.editable()) -return original();return(sourceMap.editCompiled([range],[text]).then(onEditingDone.bind(this)).catch(onError.bind(this,header)));function onEditingDone(editResult){if(!editResult) -return Promise.resolve(false);var edits=editResult.compiledEdits;if(!edits.length) -return onCSSPatched.call(this,editResult,true);edits.sort(TextUtils.SourceEdit.comparator);edits=edits.reverse();var styleSheetIds=[];var ranges=[];var texts=[];for(var edit of edits){styleSheetIds.push(header.id);ranges.push(edit.oldRange);texts.push(edit.newText);} -return this._innerSetStyleTexts(styleSheetIds,ranges,texts,majorChange).then(onCSSPatched.bind(this,editResult));} -function onCSSPatched(editResult,success){if(!success) -return originalAndDetach();this._sourceMapManager.applySourceMapEdit(editResult);return Promise.resolve(true);} -function onError(header,error){Common.console.error(Common.UIString('LiveSASS failed: %s',sourceMap.compiledURL()));console.error(error);this._sourceMapManager.detachSourceMap(header);return original();} -function originalAndDetachIfSuccess(header){return this._innerSetStyleTexts([styleSheetId],[range],[text],majorChange).then(detachIfSuccess.bind(this));function detachIfSuccess(success){if(success) -this._sourceMapManager.detachSourceMap(header);return success;}}} -async _innerSetStyleTexts(styleSheetIds,ranges,texts,majorChange){console.assert(styleSheetIds.length===ranges.length&&ranges.length===texts.length,'Array lengths must be equal');var edits=[];var ensureContentPromises=[];for(var i=0;i<styleSheetIds.length;++i){edits.push({styleSheetId:styleSheetIds[i],range:ranges[i].serializeToObject(),text:texts[i]});ensureContentPromises.push(this._ensureOriginalStyleSheetText(styleSheetIds[i]));} -try{await Promise.all(ensureContentPromises);var stylePayloads=await this._agent.setStyleTexts(edits);if(!stylePayloads||stylePayloads.length!==ranges.length) -return false;if(majorChange) -this._domModel.markUndoableState();for(var i=0;i<ranges.length;++i){var edit=new SDK.CSSModel.Edit(styleSheetIds[i],ranges[i],texts[i],stylePayloads[i]);this._fireStyleSheetChanged(styleSheetIds[i],edit);} -return true;}catch(e){return false;}} -async setSelectorText(styleSheetId,range,text){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this._ensureOriginalStyleSheetText(styleSheetId);var selectorPayload=await this._agent.setRuleSelector(styleSheetId,range,text);if(!selectorPayload) -return false;this._domModel.markUndoableState();var edit=new SDK.CSSModel.Edit(styleSheetId,range,text,selectorPayload);this._fireStyleSheetChanged(styleSheetId,edit);return true;}catch(e){return false;}} -async setKeyframeKey(styleSheetId,range,text){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this._ensureOriginalStyleSheetText(styleSheetId);var payload=await this._agent.setKeyframeKey(styleSheetId,range,text);if(!payload) -return false;this._domModel.markUndoableState();var edit=new SDK.CSSModel.Edit(styleSheetId,range,text,payload);this._fireStyleSheetChanged(styleSheetId,edit);return true;}catch(e){return false;}} -startCoverage(){this._agent.startRuleUsageTracking();} -takeCoverageDelta(){return this._agent.takeCoverageDelta().then(ruleUsage=>ruleUsage||[]);} -stopCoverage(){return this._agent.stopRuleUsageTracking();} -async mediaQueriesPromise(){var payload=await this._agent.getMediaQueries();return payload?SDK.CSSMedia.parseMediaArrayPayload(this,payload):[];} -isEnabled(){return this._isEnabled;} -async _enable(){await this._agent.enable();this._isEnabled=true;this.dispatchEventToListeners(SDK.CSSModel.Events.ModelWasEnabled);} -async matchedStylesPromise(nodeId){var response=await this._agent.invoke_getMatchedStylesForNode({nodeId});if(response[Protocol.Error]) -return null;var node=this._domModel.nodeForId(nodeId);if(!node) -return null;return new SDK.CSSMatchedStyles(this,(node),response.inlineStyle||null,response.attributesStyle||null,response.matchedCSSRules||[],response.pseudoElements||[],response.inherited||[],response.cssKeyframesRules||[]);} -classNamesPromise(styleSheetId){return this._agent.collectClassNames(styleSheetId).then(classNames=>classNames||[]);} -computedStylePromise(nodeId){return this._styleLoader.computedStylePromise(nodeId);} -async backgroundColorsPromise(nodeId){var response=this._agent.invoke_getBackgroundColors({nodeId});if(response[Protocol.Error]) -return null;return response;} -platformFontsPromise(nodeId){return this._agent.getPlatformFontsForNode(nodeId);} -allStyleSheets(){var values=this._styleSheetIdToHeader.valuesArray();function styleSheetComparator(a,b){if(a.sourceURL<b.sourceURL) -return-1;else if(a.sourceURL>b.sourceURL) -return 1;return a.startLine-b.startLine||a.startColumn-b.startColumn;} -values.sort(styleSheetComparator);return values;} -async inlineStylesPromise(nodeId){var response=await this._agent.invoke_getInlineStylesForNode({nodeId});if(response[Protocol.Error]||!response.inlineStyle) -return null;var inlineStyle=new SDK.CSSStyleDeclaration(this,null,response.inlineStyle,SDK.CSSStyleDeclaration.Type.Inline);var attributesStyle=response.attributesStyle?new SDK.CSSStyleDeclaration(this,null,response.attributesStyle,SDK.CSSStyleDeclaration.Type.Attributes):null;return new SDK.CSSModel.InlineStyleResult(inlineStyle,attributesStyle);} -forcePseudoState(node,pseudoClass,enable){var pseudoClasses=node.marker(SDK.CSSModel.PseudoStateMarker)||[];if(enable){if(pseudoClasses.indexOf(pseudoClass)>=0) -return false;pseudoClasses.push(pseudoClass);node.setMarker(SDK.CSSModel.PseudoStateMarker,pseudoClasses);}else{if(pseudoClasses.indexOf(pseudoClass)<0) -return false;pseudoClasses.remove(pseudoClass);if(pseudoClasses.length) -node.setMarker(SDK.CSSModel.PseudoStateMarker,pseudoClasses);else -node.setMarker(SDK.CSSModel.PseudoStateMarker,null);} -this._agent.forcePseudoState(node.id,pseudoClasses);this.dispatchEventToListeners(SDK.CSSModel.Events.PseudoStateForced,{node:node,pseudoClass:pseudoClass,enable:enable});return true;} -pseudoState(node){return node.marker(SDK.CSSModel.PseudoStateMarker)||[];} -async setMediaText(styleSheetId,range,newMediaText){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this._ensureOriginalStyleSheetText(styleSheetId);var mediaPayload=await this._agent.setMediaText(styleSheetId,range,newMediaText);if(!mediaPayload) -return false;this._domModel.markUndoableState();var edit=new SDK.CSSModel.Edit(styleSheetId,range,newMediaText,mediaPayload);this._fireStyleSheetChanged(styleSheetId,edit);return true;}catch(e){return false;}} -async addRule(styleSheetId,ruleText,ruleLocation){try{await this._ensureOriginalStyleSheetText(styleSheetId);var rulePayload=await this._agent.addRule(styleSheetId,ruleText,ruleLocation);if(!rulePayload) -return null;this._domModel.markUndoableState();var edit=new SDK.CSSModel.Edit(styleSheetId,ruleLocation,ruleText,rulePayload);this._fireStyleSheetChanged(styleSheetId,edit);return new SDK.CSSStyleRule(this,rulePayload);}catch(e){return null;}} -async requestViaInspectorStylesheet(node){var frameId=node.frameId()||(this._resourceTreeModel?this._resourceTreeModel.mainFrame.id:'');var headers=this._styleSheetIdToHeader.valuesArray();var styleSheetHeader=headers.find(header=>header.frameId===frameId&&header.isViaInspector());if(styleSheetHeader) -return styleSheetHeader;try{var styleSheetId=await this._agent.createStyleSheet(frameId);return styleSheetId&&this._styleSheetIdToHeader.get(styleSheetId)||null;}catch(e){return null;}} -mediaQueryResultChanged(){this.dispatchEventToListeners(SDK.CSSModel.Events.MediaQueryResultChanged);} -fontsUpdated(){this.dispatchEventToListeners(SDK.CSSModel.Events.FontsUpdated);} -styleSheetHeaderForId(id){return this._styleSheetIdToHeader.get(id)||null;} -styleSheetHeaders(){return this._styleSheetIdToHeader.valuesArray();} -_fireStyleSheetChanged(styleSheetId,edit){this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetChanged,{styleSheetId:styleSheetId,edit:edit});} -_ensureOriginalStyleSheetText(styleSheetId){var header=this.styleSheetHeaderForId(styleSheetId);if(!header) -return Promise.resolve((null));var promise=this._originalStyleSheetText.get(header);if(!promise){promise=this.getStyleSheetText(header.id);this._originalStyleSheetText.set(header,promise);this._originalContentRequestedForTest(header);} -return promise;} -_originalContentRequestedForTest(header){} -originalStyleSheetText(header){return this._ensureOriginalStyleSheetText(header.id);} -_styleSheetAdded(header){console.assert(!this._styleSheetIdToHeader.get(header.styleSheetId));var styleSheetHeader=new SDK.CSSStyleSheetHeader(this,header);this._styleSheetIdToHeader.set(header.styleSheetId,styleSheetHeader);var url=styleSheetHeader.resourceURL();if(!this._styleSheetIdsForURL.get(url)) -this._styleSheetIdsForURL.set(url,{});var frameIdToStyleSheetIds=this._styleSheetIdsForURL.get(url);var styleSheetIds=frameIdToStyleSheetIds[styleSheetHeader.frameId];if(!styleSheetIds){styleSheetIds=[];frameIdToStyleSheetIds[styleSheetHeader.frameId]=styleSheetIds;} -styleSheetIds.push(styleSheetHeader.id);this._sourceMapManager.attachSourceMap(styleSheetHeader,styleSheetHeader.sourceURL,styleSheetHeader.sourceMapURL);this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetAdded,styleSheetHeader);} -_styleSheetRemoved(id){var header=this._styleSheetIdToHeader.get(id);console.assert(header);if(!header) -return;this._styleSheetIdToHeader.remove(id);var url=header.resourceURL();var frameIdToStyleSheetIds=(this._styleSheetIdsForURL.get(url));console.assert(frameIdToStyleSheetIds,'No frameId to styleSheetId map is available for given style sheet URL.');frameIdToStyleSheetIds[header.frameId].remove(id);if(!frameIdToStyleSheetIds[header.frameId].length){delete frameIdToStyleSheetIds[header.frameId];if(!Object.keys(frameIdToStyleSheetIds).length) -this._styleSheetIdsForURL.remove(url);} -this._originalStyleSheetText.remove(header);this._sourceMapManager.detachSourceMap(header);this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetRemoved,header);} -styleSheetIdsForURL(url){var frameIdToStyleSheetIds=this._styleSheetIdsForURL.get(url);if(!frameIdToStyleSheetIds) -return[];var result=[];for(var frameId in frameIdToStyleSheetIds) -result=result.concat(frameIdToStyleSheetIds[frameId]);return result;} -async setStyleSheetText(styleSheetId,newText,majorChange){var header=(this._styleSheetIdToHeader.get(styleSheetId));console.assert(header);newText=SDK.CSSModel.trimSourceURL(newText);if(header.hasSourceURL) -newText+='\n/*# sourceURL='+header.sourceURL+' */';await this._ensureOriginalStyleSheetText(styleSheetId);var response=await this._agent.invoke_setStyleSheetText({styleSheetId:header.id,text:newText});var sourceMapURL=response.sourceMapURL;this._sourceMapManager.detachSourceMap(header);header.setSourceMapURL(sourceMapURL);this._sourceMapManager.attachSourceMap(header,header.sourceURL,header.sourceMapURL);if(sourceMapURL===null) -return'Error in CSS.setStyleSheetText';if(majorChange) -this._domModel.markUndoableState();this._fireStyleSheetChanged(styleSheetId);return null;} -async getStyleSheetText(styleSheetId){try{var text=await this._agent.getStyleSheetText(styleSheetId);return text&&SDK.CSSModel.trimSourceURL(text);}catch(e){return null;}} -_resetStyleSheets(){var headers=this._styleSheetIdToHeader.valuesArray();this._styleSheetIdsForURL.clear();this._styleSheetIdToHeader.clear();for(var i=0;i<headers.length;++i){this._sourceMapManager.detachSourceMap(headers[i]);this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetRemoved,headers[i]);}} -suspendModel(){this._isEnabled=false;return this._agent.disable().then(this._resetStyleSheets.bind(this));} -async resumeModel(){return this._enable();} -setEffectivePropertyValueForNode(nodeId,name,value){this._agent.setEffectivePropertyValueForNode(nodeId,name,value);} -cachedMatchedCascadeForNode(node){if(this._cachedMatchedCascadeNode!==node) -this.discardCachedMatchedCascade();this._cachedMatchedCascadeNode=node;if(!this._cachedMatchedCascadePromise) -this._cachedMatchedCascadePromise=this.matchedStylesPromise(node.id);return this._cachedMatchedCascadePromise;} -discardCachedMatchedCascade(){delete this._cachedMatchedCascadeNode;delete this._cachedMatchedCascadePromise;} -dispose(){super.dispose();this._sourceMapManager.dispose();}};SDK.SDKModel.register(SDK.CSSModel,SDK.Target.Capability.DOM,true);SDK.CSSModel.RuleUsage;SDK.CSSModel.ContrastInfo;SDK.CSSModel.Events={FontsUpdated:Symbol('FontsUpdated'),MediaQueryResultChanged:Symbol('MediaQueryResultChanged'),ModelWasEnabled:Symbol('ModelWasEnabled'),PseudoStateForced:Symbol('PseudoStateForced'),StyleSheetAdded:Symbol('StyleSheetAdded'),StyleSheetChanged:Symbol('StyleSheetChanged'),StyleSheetRemoved:Symbol('StyleSheetRemoved')};SDK.CSSModel.MediaTypes=['all','braille','embossed','handheld','print','projection','screen','speech','tty','tv'];SDK.CSSModel.PseudoStateMarker='pseudo-state-marker';SDK.CSSModel.Edit=class{constructor(styleSheetId,oldRange,newText,payload){this.styleSheetId=styleSheetId;this.oldRange=oldRange;this.newRange=TextUtils.TextRange.fromEdit(oldRange,newText);this.payload=payload;}};SDK.CSSLocation=class{constructor(header,lineNumber,columnNumber){this._cssModel=header.cssModel();this.styleSheetId=header.id;this.url=header.resourceURL();this.lineNumber=lineNumber;this.columnNumber=columnNumber||0;} -cssModel(){return this._cssModel;} -header(){return this._cssModel.styleSheetHeaderForId(this.styleSheetId);}};SDK.CSSDispatcher=class{constructor(cssModel){this._cssModel=cssModel;} -mediaQueryResultChanged(){this._cssModel.mediaQueryResultChanged();} -fontsUpdated(){this._cssModel.fontsUpdated();} -styleSheetChanged(styleSheetId){this._cssModel._fireStyleSheetChanged(styleSheetId);} -styleSheetAdded(header){this._cssModel._styleSheetAdded(header);} -styleSheetRemoved(id){this._cssModel._styleSheetRemoved(id);}};SDK.CSSModel.ComputedStyleLoader=class{constructor(cssModel){this._cssModel=cssModel;this._nodeIdToPromise=new Map();} -computedStylePromise(nodeId){var promise=this._nodeIdToPromise.get(nodeId);if(promise) -return promise;promise=this._cssModel._agent.getComputedStyleForNode(nodeId).then(parsePayload.bind(this));this._nodeIdToPromise.set(nodeId,promise);return promise;function parsePayload(computedPayload){this._nodeIdToPromise.delete(nodeId);if(!computedPayload||!computedPayload.length) -return null;var result=new Map();for(var property of computedPayload) -result.set(property.name,property.value);return result;}}};SDK.CSSModel.InlineStyleResult=class{constructor(inlineStyle,attributesStyle){this.inlineStyle=inlineStyle;this.attributesStyle=attributesStyle;}};;SDK.CSSProperty=class{constructor(ownerStyle,index,name,value,important,disabled,parsedOk,implicit,text,range){this.ownerStyle=ownerStyle;this.index=index;this.name=name;this.value=value;this.important=important;this.disabled=disabled;this.parsedOk=parsedOk;this.implicit=implicit;this.text=text;this.range=range?TextUtils.TextRange.fromObject(range):null;this._active=true;this._nameRange=null;this._valueRange=null;} -static parsePayload(ownerStyle,index,payload){var result=new SDK.CSSProperty(ownerStyle,index,payload.name,payload.value,payload.important||false,payload.disabled||false,('parsedOk'in payload)?!!payload.parsedOk:true,!!payload.implicit,payload.text,payload.range);return result;} -_ensureRanges(){if(this._nameRange&&this._valueRange) -return;var range=this.range;var text=this.text?new TextUtils.Text(this.text):null;if(!range||!text) -return;var nameIndex=text.value().indexOf(this.name);var valueIndex=text.value().lastIndexOf(this.value);if(nameIndex===-1||valueIndex===-1||nameIndex>valueIndex) -return;var nameSourceRange=new TextUtils.SourceRange(nameIndex,this.name.length);var valueSourceRange=new TextUtils.SourceRange(valueIndex,this.value.length);this._nameRange=rebase(text.toTextRange(nameSourceRange),range.startLine,range.startColumn);this._valueRange=rebase(text.toTextRange(valueSourceRange),range.startLine,range.startColumn);function rebase(oneLineRange,lineOffset,columnOffset){if(oneLineRange.startLine===0){oneLineRange.startColumn+=columnOffset;oneLineRange.endColumn+=columnOffset;} -oneLineRange.startLine+=lineOffset;oneLineRange.endLine+=lineOffset;return oneLineRange;}} -nameRange(){this._ensureRanges();return this._nameRange;} -valueRange(){this._ensureRanges();return this._valueRange;} -rebase(edit){if(this.ownerStyle.styleSheetId!==edit.styleSheetId) -return;if(this.range) -this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);} -setActive(active){this._active=active;} -get propertyText(){if(this.text!==undefined) -return this.text;if(this.name==='') -return'';return this.name+': '+this.value+(this.important?' !important':'')+';';} -activeInStyle(){return this._active;} -setText(propertyText,majorChange,overwrite){if(!this.ownerStyle) -return Promise.reject(new Error('No ownerStyle for property'));if(!this.ownerStyle.styleSheetId) -return Promise.reject(new Error('No owner style id'));if(!this.range||!this.ownerStyle.range) -return Promise.reject(new Error('Style not editable'));if(majorChange) -Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);if(overwrite&&propertyText===this.propertyText){if(majorChange) -this.ownerStyle.cssModel().domModel().markUndoableState();return Promise.resolve(true);} -var range=this.range.relativeTo(this.ownerStyle.range.startLine,this.ownerStyle.range.startColumn);var indentation=this.ownerStyle.cssText?this._detectIndentation(this.ownerStyle.cssText):Common.moduleSetting('textEditorIndent').get();var endIndentation=this.ownerStyle.cssText?indentation.substring(0,this.ownerStyle.range.endColumn):'';var text=new TextUtils.Text(this.ownerStyle.cssText||'');var newStyleText=text.replaceRange(range,String.sprintf(';%s;',propertyText));return self.runtime.extension(TextUtils.TokenizerFactory).instance().then(this._formatStyle.bind(this,newStyleText,indentation,endIndentation)).then(setStyleText.bind(this));function setStyleText(styleText){return this.ownerStyle.setText(styleText,majorChange);}} -_formatStyle(styleText,indentation,endIndentation,tokenizerFactory){if(indentation) -indentation='\n'+indentation;var result='';var propertyText;var insideProperty=false;var tokenize=tokenizerFactory.createTokenizer('text/css');tokenize('*{'+styleText+'}',processToken);if(insideProperty) -result+=propertyText;result=result.substring(2,result.length-1).trimRight();return result+(indentation?'\n'+endIndentation:'');function processToken(token,tokenType,column,newColumn){if(!insideProperty){var disabledProperty=tokenType&&tokenType.includes('css-comment')&&isDisabledProperty(token);var isPropertyStart=tokenType&&(tokenType.includes('css-string')||tokenType.includes('css-meta')||tokenType.includes('css-property')||tokenType.includes('css-variable-2'));if(disabledProperty){result=result.trimRight()+indentation+token;}else if(isPropertyStart){insideProperty=true;propertyText=token;}else if(token!==';'){result+=token;} -return;} -if(token==='}'||token===';'){result=result.trimRight()+indentation+propertyText.trim()+';';insideProperty=false;if(token==='}') -result+='}';}else{propertyText+=token;}} -function isDisabledProperty(text){var colon=text.indexOf(':');if(colon===-1) -return false;var propertyName=text.substring(2,colon).trim();return SDK.cssMetadata().isCSSPropertyName(propertyName);}} -_detectIndentation(text){var lines=text.split('\n');if(lines.length<2) -return'';return TextUtils.TextUtils.lineIndent(lines[1]);} -setValue(newValue,majorChange,overwrite,userCallback){var text=this.name+': '+newValue+(this.important?' !important':'')+';';this.setText(text,majorChange,overwrite).then(userCallback);} -setDisabled(disabled){if(!this.ownerStyle) -return Promise.resolve(false);if(disabled===this.disabled) -return Promise.resolve(true);var propertyText=this.text.trim();var text=disabled?'/* '+propertyText+' */':this.text.substring(2,propertyText.length-2).trim();return this.setText(text,true,true);}};;SDK.CSSValue=class{constructor(payload){this.text=payload.text;if(payload.range) -this.range=TextUtils.TextRange.fromObject(payload.range);} -rebase(edit){if(!this.range) -return;this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);}};SDK.CSSRule=class{constructor(cssModel,payload){this._cssModel=cssModel;this.styleSheetId=payload.styleSheetId;if(this.styleSheetId){var styleSheetHeader=cssModel.styleSheetHeaderForId(this.styleSheetId);this.sourceURL=styleSheetHeader.sourceURL;} -this.origin=payload.origin;this.style=new SDK.CSSStyleDeclaration(this._cssModel,this,payload.style,SDK.CSSStyleDeclaration.Type.Regular);} -rebase(edit){if(this.styleSheetId!==edit.styleSheetId) -return;this.style.rebase(edit);} -resourceURL(){if(!this.styleSheetId) -return'';var styleSheetHeader=this._cssModel.styleSheetHeaderForId(this.styleSheetId);return styleSheetHeader.resourceURL();} -isUserAgent(){return this.origin===Protocol.CSS.StyleSheetOrigin.UserAgent;} -isInjected(){return this.origin===Protocol.CSS.StyleSheetOrigin.Injected;} -isViaInspector(){return this.origin===Protocol.CSS.StyleSheetOrigin.Inspector;} -isRegular(){return this.origin===Protocol.CSS.StyleSheetOrigin.Regular;} -cssModel(){return this._cssModel;}};SDK.CSSStyleRule=class extends SDK.CSSRule{constructor(cssModel,payload,wasUsed){super(cssModel,payload);this._reinitializeSelectors(payload.selectorList);this.media=payload.media?SDK.CSSMedia.parseMediaArrayPayload(cssModel,payload.media):[];this.wasUsed=wasUsed||false;} -static createDummyRule(cssModel,selectorText){var dummyPayload={selectorList:{selectors:[{text:selectorText}],},style:{styleSheetId:'0',range:new TextUtils.TextRange(0,0,0,0),shorthandEntries:[],cssProperties:[]}};return new SDK.CSSStyleRule(cssModel,(dummyPayload));} -_reinitializeSelectors(selectorList){this.selectors=[];for(var i=0;i<selectorList.selectors.length;++i) -this.selectors.push(new SDK.CSSValue(selectorList.selectors[i]));} -setSelectorText(newSelector){var styleSheetId=this.styleSheetId;if(!styleSheetId) -throw'No rule stylesheet id';var range=this.selectorRange();if(!range) -throw'Rule selector is not editable';return this._cssModel.setSelectorText(styleSheetId,range,newSelector);} -selectorText(){return this.selectors.select('text').join(', ');} -selectorRange(){var firstRange=this.selectors[0].range;if(!firstRange) -return null;var lastRange=this.selectors.peekLast().range;return new TextUtils.TextRange(firstRange.startLine,firstRange.startColumn,lastRange.endLine,lastRange.endColumn);} -lineNumberInSource(selectorIndex){var selector=this.selectors[selectorIndex];if(!selector||!selector.range||!this.styleSheetId) -return 0;var styleSheetHeader=this._cssModel.styleSheetHeaderForId(this.styleSheetId);return styleSheetHeader.lineNumberInSource(selector.range.startLine);} -columnNumberInSource(selectorIndex){var selector=this.selectors[selectorIndex];if(!selector||!selector.range||!this.styleSheetId) -return undefined;var styleSheetHeader=this._cssModel.styleSheetHeaderForId(this.styleSheetId);console.assert(styleSheetHeader);return styleSheetHeader.columnNumberInSource(selector.range.startLine,selector.range.startColumn);} -rebase(edit){if(this.styleSheetId!==edit.styleSheetId) -return;if(this.selectorRange().equal(edit.oldRange)){this._reinitializeSelectors((edit.payload));}else{for(var i=0;i<this.selectors.length;++i) -this.selectors[i].rebase(edit);} -for(var media of this.media) -media.rebase(edit);super.rebase(edit);}};SDK.CSSKeyframesRule=class{constructor(cssModel,payload){this._cssModel=cssModel;this._animationName=new SDK.CSSValue(payload.animationName);this._keyframes=payload.keyframes.map(keyframeRule=>new SDK.CSSKeyframeRule(cssModel,keyframeRule));} -name(){return this._animationName;} -keyframes(){return this._keyframes;}};SDK.CSSKeyframeRule=class extends SDK.CSSRule{constructor(cssModel,payload){super(cssModel,payload);this._reinitializeKey(payload.keyText);} -key(){return this._keyText;} -_reinitializeKey(payload){this._keyText=new SDK.CSSValue(payload);} -rebase(edit){if(this.styleSheetId!==edit.styleSheetId||!this._keyText.range) -return;if(edit.oldRange.equal(this._keyText.range)) -this._reinitializeKey((edit.payload));else -this._keyText.rebase(edit);super.rebase(edit);} -setKeyText(newKeyText){var styleSheetId=this.styleSheetId;if(!styleSheetId) -throw'No rule stylesheet id';var range=this._keyText.range;if(!range) -throw'Keyframe key is not editable';return this._cssModel.setKeyframeKey(styleSheetId,range,newKeyText);}};;SDK.CSSStyleDeclaration=class{constructor(cssModel,parentRule,payload,type){this._cssModel=cssModel;this.parentRule=parentRule;this._allProperties;this.styleSheetId;this.range;this.cssText;this._shorthandValues;this._shorthandIsImportant;this._activePropertyMap;this._leadingProperties;this._reinitialize(payload);this.type=type;} -rebase(edit){if(this.styleSheetId!==edit.styleSheetId||!this.range) -return;if(edit.oldRange.equal(this.range)){this._reinitialize((edit.payload));}else{this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);for(var i=0;i<this._allProperties.length;++i) -this._allProperties[i].rebase(edit);}} -_reinitialize(payload){this.styleSheetId=payload.styleSheetId;this.range=payload.range?TextUtils.TextRange.fromObject(payload.range):null;var shorthandEntries=payload.shorthandEntries;this._shorthandValues=new Map();this._shorthandIsImportant=new Set();for(var i=0;i<shorthandEntries.length;++i){this._shorthandValues.set(shorthandEntries[i].name,shorthandEntries[i].value);if(shorthandEntries[i].important) -this._shorthandIsImportant.add(shorthandEntries[i].name);} -this._allProperties=[];for(var i=0;i<payload.cssProperties.length;++i){var property=SDK.CSSProperty.parsePayload(this,i,payload.cssProperties[i]);this._allProperties.push(property);} -this._generateSyntheticPropertiesIfNeeded();this._computeInactiveProperties();this._activePropertyMap=new Map();for(var property of this._allProperties){if(!property.activeInStyle()) -continue;this._activePropertyMap.set(property.name,property);} -this.cssText=payload.cssText;this._leadingProperties=null;} -_generateSyntheticPropertiesIfNeeded(){if(this.range) -return;if(!this._shorthandValues.size) -return;var propertiesSet=new Set();for(var property of this._allProperties) -propertiesSet.add(property.name);var generatedProperties=[];for(var property of this._allProperties){var shorthands=SDK.cssMetadata().shorthands(property.name)||[];for(var shorthand of shorthands){if(propertiesSet.has(shorthand)) -continue;var shorthandValue=this._shorthandValues.get(shorthand);if(!shorthandValue) -continue;var shorthandImportance=!!this._shorthandIsImportant.has(shorthand);var shorthandProperty=new SDK.CSSProperty(this,this.allProperties().length,shorthand,shorthandValue,shorthandImportance,false,true,false);generatedProperties.push(shorthandProperty);propertiesSet.add(shorthand);}} -this._allProperties=this._allProperties.concat(generatedProperties);} -_computeLeadingProperties(){function propertyHasRange(property){return!!property.range;} -if(this.range) -return this._allProperties.filter(propertyHasRange);var leadingProperties=[];for(var property of this._allProperties){var shorthands=SDK.cssMetadata().shorthands(property.name)||[];var belongToAnyShorthand=false;for(var shorthand of shorthands){if(this._shorthandValues.get(shorthand)){belongToAnyShorthand=true;break;}} -if(!belongToAnyShorthand) -leadingProperties.push(property);} -return leadingProperties;} -leadingProperties(){if(!this._leadingProperties) -this._leadingProperties=this._computeLeadingProperties();return this._leadingProperties;} -target(){return this._cssModel.target();} -cssModel(){return this._cssModel;} -_computeInactiveProperties(){var activeProperties={};for(var i=0;i<this._allProperties.length;++i){var property=this._allProperties[i];if(property.disabled||!property.parsedOk){property.setActive(false);continue;} -var canonicalName=SDK.cssMetadata().canonicalPropertyName(property.name);var activeProperty=activeProperties[canonicalName];if(!activeProperty){activeProperties[canonicalName]=property;}else if(!activeProperty.important||property.important){activeProperty.setActive(false);activeProperties[canonicalName]=property;}else{property.setActive(false);}}} -allProperties(){return this._allProperties;} -getPropertyValue(name){var property=this._activePropertyMap.get(name);return property?property.value:'';} -isPropertyImplicit(name){var property=this._activePropertyMap.get(name);return property?property.implicit:false;} -longhandProperties(name){var longhands=SDK.cssMetadata().longhands(name);var result=[];for(var i=0;longhands&&i<longhands.length;++i){var property=this._activePropertyMap.get(longhands[i]);if(property) -result.push(property);} -return result;} -propertyAt(index){return(index<this.allProperties().length)?this.allProperties()[index]:null;} -pastLastSourcePropertyIndex(){for(var i=this.allProperties().length-1;i>=0;--i){if(this.allProperties()[i].range) -return i+1;} -return 0;} -_insertionRange(index){var property=this.propertyAt(index);return property&&property.range?property.range.collapseToStart():this.range.collapseToEnd();} -newBlankProperty(index){index=(typeof index==='undefined')?this.pastLastSourcePropertyIndex():index;var property=new SDK.CSSProperty(this,index,'','',false,false,true,false,'',this._insertionRange(index));return property;} -setText(text,majorChange){if(!this.range||!this.styleSheetId) -return Promise.resolve(false);return this._cssModel.setStyleText(this.styleSheetId,this.range,text,majorChange);} -insertPropertyAt(index,name,value,userCallback){this.newBlankProperty(index).setText(name+': '+value+';',false,true).then(userCallback);} -appendProperty(name,value,userCallback){this.insertPropertyAt(this.allProperties().length,name,value,userCallback);}};SDK.CSSStyleDeclaration.Type={Regular:'Regular',Inline:'Inline',Attributes:'Attributes'};;SDK.CSSStyleSheetHeader=class{constructor(cssModel,payload){this._cssModel=cssModel;this.id=payload.styleSheetId;this.frameId=payload.frameId;this.sourceURL=payload.sourceURL;this.hasSourceURL=!!payload.hasSourceURL;this.origin=payload.origin;this.title=payload.title;this.disabled=payload.disabled;this.isInline=payload.isInline;this.startLine=payload.startLine;this.startColumn=payload.startColumn;this.contentLength=payload.length;if(payload.ownerNode) -this.ownerNode=new SDK.DeferredDOMNode(cssModel.target(),payload.ownerNode);this.setSourceMapURL(payload.sourceMapURL);} -originalContentProvider(){if(!this._originalContentProvider){var lazyContent=this._cssModel.originalStyleSheetText.bind(this._cssModel,this);this._originalContentProvider=new Common.StaticContentProvider(this.contentURL(),this.contentType(),(lazyContent));} -return this._originalContentProvider;} -setSourceMapURL(sourceMapURL){this.sourceMapURL=sourceMapURL;} -cssModel(){return this._cssModel;} -isAnonymousInlineStyleSheet(){return!this.resourceURL()&&!this._cssModel.sourceMapManager().sourceMapForClient(this);} -resourceURL(){return this.isViaInspector()?this._viaInspectorResourceURL():this.sourceURL;} -_viaInspectorResourceURL(){var frame=this._cssModel.target().model(SDK.ResourceTreeModel).frameForId(this.frameId);console.assert(frame);var parsedURL=new Common.ParsedURL(frame.url);var fakeURL='inspector://'+parsedURL.host+parsedURL.folderPathComponents;if(!fakeURL.endsWith('/')) -fakeURL+='/';fakeURL+='inspector-stylesheet';return fakeURL;} -lineNumberInSource(lineNumberInStyleSheet){return this.startLine+lineNumberInStyleSheet;} -columnNumberInSource(lineNumberInStyleSheet,columnNumberInStyleSheet){return(lineNumberInStyleSheet?0:this.startColumn)+columnNumberInStyleSheet;} -contentURL(){return this.resourceURL();} -contentType(){return Common.resourceTypes.Stylesheet;} -contentEncoded(){return Promise.resolve(false);} -requestContent(){return this._cssModel.getStyleSheetText(this.id);} -async searchInContent(query,caseSensitive,isRegex){var content=await this.requestContent();return Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex);} -isViaInspector(){return this.origin==='inspector';}};;SDK.DOMDebuggerModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.domdebuggerAgent();this._runtimeModel=(target.model(SDK.RuntimeModel));this._domModel=(target.model(SDK.DOMModel));this._domModel.addEventListener(SDK.DOMModel.Events.DocumentUpdated,this._documentUpdated,this);this._domModel.addEventListener(SDK.DOMModel.Events.NodeRemoved,this._nodeRemoved,this);this._domBreakpoints=[];this._domBreakpointsSetting=Common.settings.createLocalSetting('domBreakpoints',[]);if(this._domModel.existingDocument()) -this._documentUpdated();} -runtimeModel(){return this._runtimeModel;} -async eventListeners(remoteObject){console.assert(remoteObject.runtimeModel()===this._runtimeModel);if(!remoteObject.objectId) -return[];var payloads=await this._agent.getEventListeners((remoteObject.objectId));var eventListeners=[];for(var payload of payloads||[]){var location=this._runtimeModel.debuggerModel().createRawLocationByScriptId(payload.scriptId,payload.lineNumber,payload.columnNumber);if(!location) -continue;eventListeners.push(new SDK.EventListener(this,remoteObject,payload.type,payload.useCapture,payload.passive,payload.once,payload.handler?this._runtimeModel.createRemoteObject(payload.handler):null,payload.originalHandler?this._runtimeModel.createRemoteObject(payload.originalHandler):null,location,null));} -return eventListeners;} -retrieveDOMBreakpoints(){this._domModel.requestDocumentPromise();} -domBreakpoints(){return this._domBreakpoints.slice();} -hasDOMBreakpoint(node,type){return this._domBreakpoints.some(breakpoint=>(breakpoint.node===node&&breakpoint.type===type));} -setDOMBreakpoint(node,type){for(var breakpoint of this._domBreakpoints){if(breakpoint.node===node&&breakpoint.type===type){this.toggleDOMBreakpoint(breakpoint,true);return breakpoint;}} -var breakpoint=new SDK.DOMDebuggerModel.DOMBreakpoint(this,node,type,true);this._domBreakpoints.push(breakpoint);this._saveDOMBreakpoints();this._enableDOMBreakpoint(breakpoint);this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointAdded,breakpoint);return breakpoint;} -removeDOMBreakpoint(node,type){this._removeDOMBreakpoints(breakpoint=>breakpoint.node===node&&breakpoint.type===type);} -removeAllDOMBreakpoints(){this._removeDOMBreakpoints(breakpoint=>true);} -toggleDOMBreakpoint(breakpoint,enabled){if(enabled===breakpoint.enabled) -return;breakpoint.enabled=enabled;if(enabled) -this._enableDOMBreakpoint(breakpoint);else -this._disableDOMBreakpoint(breakpoint);this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointToggled,breakpoint);} -_enableDOMBreakpoint(breakpoint){this._agent.setDOMBreakpoint(breakpoint.node.id,breakpoint.type);breakpoint.node.setMarker(SDK.DOMDebuggerModel.DOMBreakpoint.Marker,true);} -_disableDOMBreakpoint(breakpoint){this._agent.removeDOMBreakpoint(breakpoint.node.id,breakpoint.type);breakpoint.node.setMarker(SDK.DOMDebuggerModel.DOMBreakpoint.Marker,this._nodeHasBreakpoints(breakpoint.node)?true:null);} -_nodeHasBreakpoints(node){for(var breakpoint of this._domBreakpoints){if(breakpoint.node===node&&breakpoint.enabled) -return true;} -return false;} -resolveDOMBreakpointData(auxData){var type=auxData['type'];var node=this._domModel.nodeForId(auxData['nodeId']);if(!type||!node) -return null;var targetNode=null;var insertion=false;if(type===SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified){insertion=auxData['insertion']||false;targetNode=this._domModel.nodeForId(auxData['targetNodeId']);} -return{type:type,node:node,targetNode:targetNode,insertion:insertion};} -_currentURL(){var domDocument=this._domModel.existingDocument();return domDocument?domDocument.documentURL:'';} -_documentUpdated(){var removed=this._domBreakpoints;this._domBreakpoints=[];this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointsRemoved,removed);var currentURL=this._currentURL();for(var breakpoint of this._domBreakpointsSetting.get()){if(breakpoint.url===currentURL) -this._domModel.pushNodeByPathToFrontend(breakpoint.path).then(appendBreakpoint.bind(this,breakpoint));} -function appendBreakpoint(breakpoint,nodeId){var node=nodeId?this._domModel.nodeForId(nodeId):null;if(!node) -return;var domBreakpoint=new SDK.DOMDebuggerModel.DOMBreakpoint(this,node,breakpoint.type,breakpoint.enabled);this._domBreakpoints.push(domBreakpoint);if(breakpoint.enabled) -this._enableDOMBreakpoint(domBreakpoint);this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointAdded,domBreakpoint);}} -_removeDOMBreakpoints(filter){var removed=[];var left=[];for(var breakpoint of this._domBreakpoints){if(filter(breakpoint)){removed.push(breakpoint);if(breakpoint.enabled){breakpoint.enabled=false;this._disableDOMBreakpoint(breakpoint);}}else{left.push(breakpoint);}} -if(!removed.length) -return;this._domBreakpoints=left;this._saveDOMBreakpoints();this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointsRemoved,removed);} -_nodeRemoved(event){var node=(event.data.node);var children=node.children()||[];this._removeDOMBreakpoints(breakpoint=>breakpoint.node===node||children.indexOf(breakpoint.node)!==-1);} -_saveDOMBreakpoints(){var currentURL=this._currentURL();var breakpoints=this._domBreakpointsSetting.get().filter(breakpoint=>breakpoint.url!==currentURL);for(var breakpoint of this._domBreakpoints){breakpoints.push({url:currentURL,path:breakpoint.node.path(),type:breakpoint.type,enabled:breakpoint.enabled});} -this._domBreakpointsSetting.set(breakpoints);}};SDK.SDKModel.register(SDK.DOMDebuggerModel,SDK.Target.Capability.DOM,false);SDK.DOMDebuggerModel.Events={DOMBreakpointAdded:Symbol('DOMBreakpointAdded'),DOMBreakpointToggled:Symbol('DOMBreakpointToggled'),DOMBreakpointsRemoved:Symbol('DOMBreakpointsRemoved'),};SDK.DOMDebuggerModel.DOMBreakpoint=class{constructor(domDebuggerModel,node,type,enabled){this.domDebuggerModel=domDebuggerModel;this.node=node;this.type=type;this.enabled=enabled;}};SDK.DOMDebuggerModel.DOMBreakpoint.Type=Protocol.DOMDebugger.DOMBreakpointType;SDK.DOMDebuggerModel.DOMBreakpoint.Marker='breakpoint-marker';SDK.EventListener=class{constructor(domDebuggerModel,eventTarget,type,useCapture,passive,once,handler,originalHandler,location,customRemoveFunction,origin){this._domDebuggerModel=domDebuggerModel;this._eventTarget=eventTarget;this._type=type;this._useCapture=useCapture;this._passive=passive;this._once=once;this._handler=handler;this._originalHandler=originalHandler||handler;this._location=location;var script=location.script();this._sourceURL=script?script.contentURL():'';this._customRemoveFunction=customRemoveFunction;this._origin=origin||SDK.EventListener.Origin.Raw;} -domDebuggerModel(){return this._domDebuggerModel;} -type(){return this._type;} -useCapture(){return this._useCapture;} -passive(){return this._passive;} -once(){return this._once;} -handler(){return this._handler;} -location(){return this._location;} -sourceURL(){return this._sourceURL;} -originalHandler(){return this._originalHandler;} -canRemove(){return!!this._customRemoveFunction||this._origin!==SDK.EventListener.Origin.FrameworkUser;} -remove(){if(!this.canRemove()) -return Promise.resolve();if(this._origin!==SDK.EventListener.Origin.FrameworkUser){function removeListener(type,listener,useCapture){this.removeEventListener(type,listener,useCapture);if(this['on'+type]) -this['on'+type]=undefined;} -return(this._eventTarget.callFunctionPromise(removeListener,[SDK.RemoteObject.toCallArgument(this._type),SDK.RemoteObject.toCallArgument(this._originalHandler),SDK.RemoteObject.toCallArgument(this._useCapture)]));} -return this._customRemoveFunction.callFunctionPromise(callCustomRemove,[SDK.RemoteObject.toCallArgument(this._type),SDK.RemoteObject.toCallArgument(this._originalHandler),SDK.RemoteObject.toCallArgument(this._useCapture),SDK.RemoteObject.toCallArgument(this._passive),]).then(()=>undefined);function callCustomRemove(type,listener,useCapture,passive){this.call(null,type,listener,useCapture,passive);}} -canTogglePassive(){return this._origin!==SDK.EventListener.Origin.FrameworkUser;} -togglePassive(){return(this._eventTarget.callFunctionPromise(callTogglePassive,[SDK.RemoteObject.toCallArgument(this._type),SDK.RemoteObject.toCallArgument(this._originalHandler),SDK.RemoteObject.toCallArgument(this._useCapture),SDK.RemoteObject.toCallArgument(this._passive),]));function callTogglePassive(type,listener,useCapture,passive){this.removeEventListener(type,listener,{capture:useCapture});this.addEventListener(type,listener,{capture:useCapture,passive:!passive});}} -origin(){return this._origin;} -markAsFramework(){this._origin=SDK.EventListener.Origin.Framework;} -isScrollBlockingType(){return this._type==='touchstart'||this._type==='touchmove'||this._type==='mousewheel'||this._type==='wheel';}};SDK.EventListener.Origin={Raw:'Raw',Framework:'Framework',FrameworkUser:'FrameworkUser'};SDK.DOMDebuggerModel.EventListenerBreakpoint=class{constructor(instrumentationName,eventName,eventTargetNames,category,title){this._instrumentationName=instrumentationName;this._eventName=eventName;this._eventTargetNames=eventTargetNames;this._category=category;this._title=title;this._enabled=false;} -category(){return this._category;} -enabled(){return this._enabled;} -setEnabled(enabled){if(this._enabled===enabled) -return;this._enabled=enabled;for(var model of SDK.targetManager.models(SDK.DOMDebuggerModel)) -this._updateOnModel(model);} -_updateOnModel(model){if(this._instrumentationName){if(this._enabled) -model._agent.setInstrumentationBreakpoint(this._instrumentationName);else -model._agent.removeInstrumentationBreakpoint(this._instrumentationName);}else{for(var eventTargetName of this._eventTargetNames){if(this._enabled) -model._agent.setEventListenerBreakpoint(this._eventName,eventTargetName);else -model._agent.removeEventListenerBreakpoint(this._eventName,eventTargetName);}}} -title(){return this._title;}};SDK.DOMDebuggerModel.EventListenerBreakpoint._listener='listener:';SDK.DOMDebuggerModel.EventListenerBreakpoint._instrumentation='instrumentation:';SDK.DOMDebuggerManager=class{constructor(){this._xhrBreakpointsSetting=Common.settings.createLocalSetting('xhrBreakpoints',[]);this._xhrBreakpoints=new Map();for(var breakpoint of this._xhrBreakpointsSetting.get()) -this._xhrBreakpoints.set(breakpoint.url,breakpoint.enabled);this._eventListenerBreakpoints=[];this._createInstrumentationBreakpoints(Common.UIString('Animation'),['requestAnimationFrame','cancelAnimationFrame','requestAnimationFrame.callback']);this._createInstrumentationBreakpoints(Common.UIString('Canvas'),['canvasContextCreated','webglErrorFired','webglWarningFired']);this._createInstrumentationBreakpoints(Common.UIString('Geolocation'),['Geolocation.getCurrentPosition','Geolocation.watchPosition']);this._createInstrumentationBreakpoints(Common.UIString('Notification'),['Notification.requestPermission']);this._createInstrumentationBreakpoints(Common.UIString('Parse'),['Element.setInnerHTML','Document.write']);this._createInstrumentationBreakpoints(Common.UIString('Script'),['scriptFirstStatement','scriptBlockedByCSP']);this._createInstrumentationBreakpoints(Common.UIString('Timer'),['setTimeout','clearTimeout','setInterval','clearInterval','setTimeout.callback','setInterval.callback']);this._createInstrumentationBreakpoints(Common.UIString('Window'),['DOMWindow.close']);this._createEventListenerBreakpoints(Common.UIString('Media'),['play','pause','playing','canplay','canplaythrough','seeking','seeked','timeupdate','ended','ratechange','durationchange','volumechange','loadstart','progress','suspend','abort','error','emptied','stalled','loadedmetadata','loadeddata','waiting'],['audio','video']);this._createEventListenerBreakpoints(Common.UIString('Clipboard'),['copy','cut','paste','beforecopy','beforecut','beforepaste'],['*']);this._createEventListenerBreakpoints(Common.UIString('Control'),['resize','scroll','zoom','focus','blur','select','change','submit','reset'],['*']);this._createEventListenerBreakpoints(Common.UIString('Device'),['deviceorientation','devicemotion'],['*']);this._createEventListenerBreakpoints(Common.UIString('DOM Mutation'),['DOMActivate','DOMFocusIn','DOMFocusOut','DOMAttrModified','DOMCharacterDataModified','DOMNodeInserted','DOMNodeInsertedIntoDocument','DOMNodeRemoved','DOMNodeRemovedFromDocument','DOMSubtreeModified','DOMContentLoaded'],['*']);this._createEventListenerBreakpoints(Common.UIString('Drag / drop'),['dragenter','dragover','dragleave','drop'],['*']);this._createEventListenerBreakpoints(Common.UIString('Keyboard'),['keydown','keyup','keypress','input'],['*']);this._createEventListenerBreakpoints(Common.UIString('Load'),['load','beforeunload','unload','abort','error','hashchange','popstate'],['*']);this._createEventListenerBreakpoints(Common.UIString('Mouse'),['auxclick','click','dblclick','mousedown','mouseup','mouseover','mousemove','mouseout','mouseenter','mouseleave','mousewheel','wheel','contextmenu'],['*']);this._createEventListenerBreakpoints(Common.UIString('Pointer'),['pointerover','pointerout','pointerenter','pointerleave','pointerdown','pointerup','pointermove','pointercancel','gotpointercapture','lostpointercapture'],['*']);this._createEventListenerBreakpoints(Common.UIString('Touch'),['touchstart','touchmove','touchend','touchcancel'],['*']);this._createEventListenerBreakpoints(Common.UIString('XHR'),['readystatechange','load','loadstart','loadend','abort','error','progress','timeout'],['xmlhttprequest','xmlhttprequestupload']);this._resolveEventListenerBreakpoint('instrumentation:setTimeout.callback')._title=Common.UIString('setTimeout fired');this._resolveEventListenerBreakpoint('instrumentation:setInterval.callback')._title=Common.UIString('setInterval fired');this._resolveEventListenerBreakpoint('instrumentation:scriptFirstStatement')._title=Common.UIString('Script First Statement');this._resolveEventListenerBreakpoint('instrumentation:scriptBlockedByCSP')._title=Common.UIString('Script Blocked by Content Security Policy');this._resolveEventListenerBreakpoint('instrumentation:requestAnimationFrame')._title=Common.UIString('Request Animation Frame');this._resolveEventListenerBreakpoint('instrumentation:cancelAnimationFrame')._title=Common.UIString('Cancel Animation Frame');this._resolveEventListenerBreakpoint('instrumentation:requestAnimationFrame.callback')._title=Common.UIString('Animation Frame Fired');this._resolveEventListenerBreakpoint('instrumentation:webglErrorFired')._title=Common.UIString('WebGL Error Fired');this._resolveEventListenerBreakpoint('instrumentation:webglWarningFired')._title=Common.UIString('WebGL Warning Fired');this._resolveEventListenerBreakpoint('instrumentation:Element.setInnerHTML')._title=Common.UIString('Set innerHTML');this._resolveEventListenerBreakpoint('instrumentation:canvasContextCreated')._title=Common.UIString('Create canvas context');this._resolveEventListenerBreakpoint('instrumentation:Geolocation.getCurrentPosition')._title='getCurrentPosition';this._resolveEventListenerBreakpoint('instrumentation:Geolocation.watchPosition')._title='watchPosition';this._resolveEventListenerBreakpoint('instrumentation:Notification.requestPermission')._title='requestPermission';this._resolveEventListenerBreakpoint('instrumentation:DOMWindow.close')._title='window.close';this._resolveEventListenerBreakpoint('instrumentation:Document.write')._title='document.write';SDK.targetManager.observeModels(SDK.DOMDebuggerModel,this);} -_createInstrumentationBreakpoints(category,instrumentationNames){for(var instrumentationName of instrumentationNames){this._eventListenerBreakpoints.push(new SDK.DOMDebuggerModel.EventListenerBreakpoint(instrumentationName,'',[],category,instrumentationName));}} -_createEventListenerBreakpoints(category,eventNames,eventTargetNames){for(var eventName of eventNames){this._eventListenerBreakpoints.push(new SDK.DOMDebuggerModel.EventListenerBreakpoint('',eventName,eventTargetNames,category,eventName));}} -_resolveEventListenerBreakpoint(eventName,eventTargetName){var instrumentationPrefix='instrumentation:';var listenerPrefix='listener:';var instrumentationName='';if(eventName.startsWith(instrumentationPrefix)){instrumentationName=eventName.substring(instrumentationPrefix.length);eventName='';}else if(eventName.startsWith(listenerPrefix)){eventName=eventName.substring(listenerPrefix.length);}else{return null;} -eventTargetName=(eventTargetName||'*').toLowerCase();var result=null;for(var breakpoint of this._eventListenerBreakpoints){if(instrumentationName&&breakpoint._instrumentationName===instrumentationName) -result=breakpoint;if(eventName&&breakpoint._eventName===eventName&&breakpoint._eventTargetNames.indexOf(eventTargetName)!==-1) -result=breakpoint;if(!result&&eventName&&breakpoint._eventName===eventName&&breakpoint._eventTargetNames.indexOf('*')!==-1) -result=breakpoint;} -return result;} -eventListenerBreakpoints(){return this._eventListenerBreakpoints.slice();} -resolveEventListenerBreakpointTitle(auxData){var id=auxData['eventName'];if(id==='instrumentation:webglErrorFired'&&auxData['webglErrorName']){var errorName=auxData['webglErrorName'];errorName=errorName.replace(/^.*(0x[0-9a-f]+).*$/i,'$1');return Common.UIString('WebGL Error Fired (%s)',errorName);} -if(id==='instrumentation:scriptBlockedByCSP'&&auxData['directiveText']) -return Common.UIString('Script blocked due to Content Security Policy directive: %s',auxData['directiveText']);var breakpoint=this._resolveEventListenerBreakpoint(id,auxData['targetName']);if(!breakpoint) -return'';if(auxData['targetName']) -return auxData['targetName']+'.'+breakpoint._title;return breakpoint._title;} -resolveEventListenerBreakpoint(auxData){return this._resolveEventListenerBreakpoint(auxData['eventName'],auxData['targetName']);} -xhrBreakpoints(){return this._xhrBreakpoints;} -_saveXHRBreakpoints(){var breakpoints=[];for(var url of this._xhrBreakpoints.keys()) -breakpoints.push({url:url,enabled:this._xhrBreakpoints.get(url)});this._xhrBreakpointsSetting.set(breakpoints);} -addXHRBreakpoint(url,enabled){this._xhrBreakpoints.set(url,enabled);if(enabled){for(var model of SDK.targetManager.models(SDK.DOMDebuggerModel)) -model._agent.setXHRBreakpoint(url);} -this._saveXHRBreakpoints();} -removeXHRBreakpoint(url){var enabled=this._xhrBreakpoints.get(url);this._xhrBreakpoints.delete(url);if(enabled){for(var model of SDK.targetManager.models(SDK.DOMDebuggerModel)) -model._agent.removeXHRBreakpoint(url);} -this._saveXHRBreakpoints();} -toggleXHRBreakpoint(url,enabled){this._xhrBreakpoints.set(url,enabled);for(var model of SDK.targetManager.models(SDK.DOMDebuggerModel)){if(enabled) -model._agent.setXHRBreakpoint(url);else -model._agent.removeXHRBreakpoint(url);} -this._saveXHRBreakpoints();} -modelAdded(domDebuggerModel){for(var url of this._xhrBreakpoints.keys()){if(this._xhrBreakpoints.get(url)) -domDebuggerModel._agent.setXHRBreakpoint(url);} -for(var breakpoint of this._eventListenerBreakpoints){if(breakpoint._enabled) -breakpoint._updateOnModel(domDebuggerModel);}} -modelRemoved(domDebuggerModel){}};SDK.domDebuggerManager;;SDK.DOMNode=class{constructor(domModel){this._domModel=domModel;} -static create(domModel,doc,isInShadowTree,payload){var node=new SDK.DOMNode(domModel);node._init(doc,isInShadowTree,payload);return node;} -_init(doc,isInShadowTree,payload){this._agent=this._domModel._agent;this.ownerDocument=doc;this._isInShadowTree=isInShadowTree;this.id=payload.nodeId;this._backendNodeId=payload.backendNodeId;this._domModel._idToDOMNode[this.id]=this;this._nodeType=payload.nodeType;this._nodeName=payload.nodeName;this._localName=payload.localName;this._nodeValue=payload.nodeValue;this._pseudoType=payload.pseudoType;this._shadowRootType=payload.shadowRootType;this._frameOwnerFrameId=payload.frameId||null;this._xmlVersion=payload.xmlVersion;this._isSVGNode=!!payload.isSVG;this._shadowRoots=[];this._attributes=[];this._attributesMap={};if(payload.attributes) -this._setAttributesPayload(payload.attributes);this._markers=new Map();this._subtreeMarkerCount=0;this._childNodeCount=payload.childNodeCount||0;this._children=null;this.nextSibling=null;this.previousSibling=null;this.firstChild=null;this.lastChild=null;this.parentNode=null;if(payload.shadowRoots){for(var i=0;i<payload.shadowRoots.length;++i){var root=payload.shadowRoots[i];var node=SDK.DOMNode.create(this._domModel,this.ownerDocument,true,root);this._shadowRoots.push(node);node.parentNode=this;}} -if(payload.templateContent){this._templateContent=SDK.DOMNode.create(this._domModel,this.ownerDocument,true,payload.templateContent);this._templateContent.parentNode=this;} -if(payload.importedDocument){this._importedDocument=SDK.DOMNode.create(this._domModel,this.ownerDocument,true,payload.importedDocument);this._importedDocument.parentNode=this;} -if(payload.distributedNodes) -this._setDistributedNodePayloads(payload.distributedNodes);if(payload.children) -this._setChildrenPayload(payload.children);this._setPseudoElements(payload.pseudoElements);if(payload.contentDocument){this._contentDocument=new SDK.DOMDocument(this._domModel,payload.contentDocument);this._children=[this._contentDocument];this._renumber();} -if(this._nodeType===Node.ELEMENT_NODE){if(this.ownerDocument&&!this.ownerDocument.documentElement&&this._nodeName==='HTML') -this.ownerDocument.documentElement=this;if(this.ownerDocument&&!this.ownerDocument.body&&this._nodeName==='BODY') -this.ownerDocument.body=this;}else if(this._nodeType===Node.DOCUMENT_TYPE_NODE){this.publicId=payload.publicId;this.systemId=payload.systemId;this.internalSubset=payload.internalSubset;}else if(this._nodeType===Node.ATTRIBUTE_NODE){this.name=payload.name;this.value=payload.value;}} -isSVGNode(){return this._isSVGNode;} -domModel(){return this._domModel;} -backendNodeId(){return this._backendNodeId;} -children(){return this._children?this._children.slice():null;} -hasAttributes(){return this._attributes.length>0;} -childNodeCount(){return this._childNodeCount;} -hasShadowRoots(){return!!this._shadowRoots.length;} -shadowRoots(){return this._shadowRoots.slice();} -templateContent(){return this._templateContent||null;} -importedDocument(){return this._importedDocument||null;} -nodeType(){return this._nodeType;} -nodeName(){return this._nodeName;} -pseudoType(){return this._pseudoType;} -hasPseudoElements(){return this._pseudoElements.size>0;} -pseudoElements(){return this._pseudoElements;} -beforePseudoElement(){if(!this._pseudoElements) -return null;return this._pseudoElements.get(SDK.DOMNode.PseudoElementNames.Before);} -afterPseudoElement(){if(!this._pseudoElements) -return null;return this._pseudoElements.get(SDK.DOMNode.PseudoElementNames.After);} -isInsertionPoint(){return!this.isXMLNode()&&(this._nodeName==='SHADOW'||this._nodeName==='CONTENT'||this._nodeName==='SLOT');} -distributedNodes(){return this._distributedNodes||[];} -isInShadowTree(){return this._isInShadowTree;} -ancestorShadowHost(){var ancestorShadowRoot=this.ancestorShadowRoot();return ancestorShadowRoot?ancestorShadowRoot.parentNode:null;} -ancestorShadowRoot(){if(!this._isInShadowTree) -return null;var current=this;while(current&&!current.isShadowRoot()) -current=current.parentNode;return current;} -ancestorUserAgentShadowRoot(){var ancestorShadowRoot=this.ancestorShadowRoot();if(!ancestorShadowRoot) -return null;return ancestorShadowRoot.shadowRootType()===SDK.DOMNode.ShadowRootTypes.UserAgent?ancestorShadowRoot:null;} -isShadowRoot(){return!!this._shadowRootType;} -shadowRootType(){return this._shadowRootType||null;} -nodeNameInCorrectCase(){var shadowRootType=this.shadowRootType();if(shadowRootType) -return'#shadow-root ('+shadowRootType+')';if(!this.localName()) -return this.nodeName();if(this.localName().length!==this.nodeName().length) -return this.nodeName();return this.localName();} -setNodeName(name,callback){this._agent.invoke_setNodeName({nodeId:this.id,name}).then(response=>{if(!response[Protocol.Error]) -this._domModel.markUndoableState();if(callback) -callback(response[Protocol.Error]||null,response.nodeId);});} -localName(){return this._localName;} -nodeValue(){return this._nodeValue;} -setNodeValue(value,callback){this._agent.invoke_setNodeValue({nodeId:this.id,value}).then(response=>{if(!response[Protocol.Error]) -this._domModel.markUndoableState();if(callback) -callback(response[Protocol.Error]||null);});} -getAttribute(name){var attr=this._attributesMap[name];return attr?attr.value:undefined;} -setAttribute(name,text,callback){this._agent.invoke_setAttributesAsText({nodeId:this.id,text,name}).then(response=>{if(!response[Protocol.Error]) -this._domModel.markUndoableState();if(callback) -callback(response[Protocol.Error]||null);});} -setAttributeValue(name,value,callback){this._agent.invoke_setAttributeValue({nodeId:this.id,name,value}).then(response=>{if(!response[Protocol.Error]) -this._domModel.markUndoableState();if(callback) -callback(response[Protocol.Error]||null);});} -setAttributeValuePromise(name,value){return new Promise(fulfill=>this.setAttributeValue(name,value,fulfill));} -attributes(){return this._attributes;} -async removeAttribute(name){var response=await this._agent.invoke_removeAttribute({nodeId:this.id,name});if(response[Protocol.Error]) -return;delete this._attributesMap[name];var index=this._attributes.findIndex(attr=>attr.name===name);if(index!==-1) -this._attributes.splice(index,1);this._domModel.markUndoableState();} -getChildNodes(callback){if(this._children){callback(this.children());return;} -this._agent.invoke_requestChildNodes({nodeId:this.id}).then(response=>{callback(response[Protocol.Error]?null:this.children());});} -async getSubtree(depth){var response=await this._agent.invoke_requestChildNodes({id:this.id,depth});return response[Protocol.Error]?null:this._children;} -getOuterHTML(){return this._agent.getOuterHTML(this.id);} -setOuterHTML(html,callback){this._agent.invoke_setOuterHTML({nodeId:this.id,outerHTML:html}).then(response=>{if(!response[Protocol.Error]) -this._domModel.markUndoableState();if(callback) -callback(response[Protocol.Error]||null);});} -removeNode(callback){this._agent.invoke_removeNode({nodeId:this.id}).then(response=>{if(!response[Protocol.Error]) -this._domModel.markUndoableState();if(callback) -callback(response[Protocol.Error]||null);});} -async copyNode(){var text=await this._agent.getOuterHTML(this.id);if(text!==null) -InspectorFrontendHost.copyText(text);return text;} -path(){function canPush(node){return node&&('index'in node||(node.isShadowRoot()&&node.parentNode))&&node._nodeName.length;} -var path=[];var node=this;while(canPush(node)){var index=typeof node.index==='number'?node.index:(node.shadowRootType()===SDK.DOMNode.ShadowRootTypes.UserAgent?'u':'a');path.push([index,node._nodeName]);node=node.parentNode;} -path.reverse();return path.join(',');} -isAncestor(node){if(!node) -return false;var currentNode=node.parentNode;while(currentNode){if(this===currentNode) -return true;currentNode=currentNode.parentNode;} -return false;} -isDescendant(descendant){return descendant!==null&&descendant.isAncestor(this);} -frameId(){var node=this.parentNode||this;while(!node._frameOwnerFrameId&&node.parentNode) -node=node.parentNode;return node._frameOwnerFrameId;} -_setAttributesPayload(attrs){var attributesChanged=!this._attributes||attrs.length!==this._attributes.length*2;var oldAttributesMap=this._attributesMap||{};this._attributes=[];this._attributesMap={};for(var i=0;i<attrs.length;i+=2){var name=attrs[i];var value=attrs[i+1];this._addAttribute(name,value);if(attributesChanged) -continue;if(!oldAttributesMap[name]||oldAttributesMap[name].value!==value) -attributesChanged=true;} -return attributesChanged;} -_insertChild(prev,payload){var node=SDK.DOMNode.create(this._domModel,this.ownerDocument,this._isInShadowTree,payload);this._children.splice(this._children.indexOf(prev)+1,0,node);this._renumber();return node;} -_removeChild(node){if(node.pseudoType()){this._pseudoElements.delete(node.pseudoType());}else{var shadowRootIndex=this._shadowRoots.indexOf(node);if(shadowRootIndex!==-1){this._shadowRoots.splice(shadowRootIndex,1);}else{console.assert(this._children.indexOf(node)!==-1);this._children.splice(this._children.indexOf(node),1);}} -node.parentNode=null;this._subtreeMarkerCount-=node._subtreeMarkerCount;if(node._subtreeMarkerCount) -this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged,this);this._renumber();} -_setChildrenPayload(payloads){if(this._contentDocument) -return;this._children=[];for(var i=0;i<payloads.length;++i){var payload=payloads[i];var node=SDK.DOMNode.create(this._domModel,this.ownerDocument,this._isInShadowTree,payload);this._children.push(node);} -this._renumber();} -_setPseudoElements(payloads){this._pseudoElements=new Map();if(!payloads) -return;for(var i=0;i<payloads.length;++i){var node=SDK.DOMNode.create(this._domModel,this.ownerDocument,this._isInShadowTree,payloads[i]);node.parentNode=this;this._pseudoElements.set(node.pseudoType(),node);}} -_setDistributedNodePayloads(payloads){this._distributedNodes=[];for(var payload of payloads){this._distributedNodes.push(new SDK.DOMNodeShortcut(this._domModel.target(),payload.backendNodeId,payload.nodeType,payload.nodeName));}} -_renumber(){this._childNodeCount=this._children.length;if(this._childNodeCount===0){this.firstChild=null;this.lastChild=null;return;} -this.firstChild=this._children[0];this.lastChild=this._children[this._childNodeCount-1];for(var i=0;i<this._childNodeCount;++i){var child=this._children[i];child.index=i;child.nextSibling=i+1<this._childNodeCount?this._children[i+1]:null;child.previousSibling=i-1>=0?this._children[i-1]:null;child.parentNode=this;}} -_addAttribute(name,value){var attr={name:name,value:value,_node:this};this._attributesMap[name]=attr;this._attributes.push(attr);} -_setAttribute(name,value){var attr=this._attributesMap[name];if(attr) -attr.value=value;else -this._addAttribute(name,value);} -_removeAttribute(name){var attr=this._attributesMap[name];if(attr){this._attributes.remove(attr);delete this._attributesMap[name];}} -copyTo(targetNode,anchorNode,callback){this._agent.invoke_copyTo({nodeId:this.id,targetNodeId:targetNode.id,insertBeforeNodeId:anchorNode?anchorNode.id:undefined}).then(response=>{if(!response[Protocol.Error]) -this._domModel.markUndoableState();if(callback) -callback(response[Protocol.Error]||null,response.nodeId);});} -moveTo(targetNode,anchorNode,callback){this._agent.invoke_moveTo({nodeId:this.id,targetNodeId:targetNode.id,insertBeforeNodeId:anchorNode?anchorNode.id:undefined}).then(response=>{if(!response[Protocol.Error]) -this._domModel.markUndoableState();if(callback) -callback(response[Protocol.Error]||null,response.nodeId);});} -isXMLNode(){return!!this._xmlVersion;} -setMarker(name,value){if(value===null){if(!this._markers.has(name)) -return;this._markers.delete(name);for(var node=this;node;node=node.parentNode) ---node._subtreeMarkerCount;for(var node=this;node;node=node.parentNode) -this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged,node);return;} -if(this.parentNode&&!this._markers.has(name)){for(var node=this;node;node=node.parentNode) -++node._subtreeMarkerCount;} -this._markers.set(name,value);for(var node=this;node;node=node.parentNode) -this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged,node);} -marker(name){return this._markers.get(name)||null;} -traverseMarkers(visitor){function traverse(node){if(!node._subtreeMarkerCount) -return;for(var marker of node._markers.keys()) -visitor(node,marker);if(!node._children) -return;for(var child of node._children) -traverse(child);} -traverse(this);} -resolveURL(url){if(!url) -return url;for(var frameOwnerCandidate=this;frameOwnerCandidate;frameOwnerCandidate=frameOwnerCandidate.parentNode){if(frameOwnerCandidate.baseURL) -return Common.ParsedURL.completeURL(frameOwnerCandidate.baseURL,url);} -return null;} -highlight(mode,objectId){this._domModel.overlayModel().highlightDOMNode(this.id,mode,undefined,objectId);} -highlightForTwoSeconds(){this._domModel.overlayModel().highlightDOMNodeForTwoSeconds(this.id);} -async resolveToObject(objectGroup){var object=await this._agent.resolveNode(this.id,undefined,objectGroup);return object&&this._domModel._runtimeModel.createRemoteObject(object);} -boxModel(){return this._agent.getBoxModel(this.id);} -setAsInspectedNode(){var node=this;while(true){var ancestor=node.ancestorUserAgentShadowRoot();if(!ancestor) -break;ancestor=node.ancestorShadowHost();if(!ancestor) -break;node=ancestor;} -this._agent.setInspectedNode(node.id);} -enclosingElementOrSelf(){var node=this;if(node&&node.nodeType()===Node.TEXT_NODE&&node.parentNode) -node=node.parentNode;if(node&&node.nodeType()!==Node.ELEMENT_NODE) -node=null;return node;} -async scrollIntoView(){var node=this.enclosingElementOrSelf();var object=await node.resolveToObject('');if(object) -object.callFunction(scrollIntoView);object.release();node.highlightForTwoSeconds();function scrollIntoView(){this.scrollIntoViewIfNeeded(true);}}};SDK.DOMNode.PseudoElementNames={Before:'before',After:'after'};SDK.DOMNode.ShadowRootTypes={UserAgent:'user-agent',Open:'open',Closed:'closed'};SDK.DOMNode.Attribute;SDK.DeferredDOMNode=class{constructor(target,backendNodeId){this._domModel=target.model(SDK.DOMModel);this._backendNodeId=backendNodeId;} -resolve(callback){this.resolvePromise().then(callback);} -async resolvePromise(){if(!this._domModel) -return null;var nodeIds=await this._domModel.pushNodesByBackendIdsToFrontend(new Set([this._backendNodeId]));return nodeIds&&nodeIds.get(this._backendNodeId)||null;} -backendNodeId(){return this._backendNodeId;} -highlight(){if(this._domModel) -this._domModel.overlayModel().highlightDOMNode(undefined,undefined,this._backendNodeId);}};SDK.DOMNodeShortcut=class{constructor(target,backendNodeId,nodeType,nodeName){this.nodeType=nodeType;this.nodeName=nodeName;this.deferredNode=new SDK.DeferredDOMNode(target,backendNodeId);}};SDK.DOMDocument=class extends SDK.DOMNode{constructor(domModel,payload){super(domModel);this._init(this,false,payload);this.documentURL=payload.documentURL||'';this.baseURL=payload.baseURL||'';}};SDK.DOMModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.domAgent();this._idToDOMNode={};this._document=null;this._attributeLoadNodeIds=new Set();target.registerDOMDispatcher(new SDK.DOMDispatcher(this));this._runtimeModel=(target.model(SDK.RuntimeModel));this._agent.enable();} -runtimeModel(){return this._runtimeModel;} -cssModel(){return(this.target().model(SDK.CSSModel));} -overlayModel(){return(this.target().model(SDK.OverlayModel));} -static cancelSearch(){for(var domModel of SDK.targetManager.models(SDK.DOMModel)) -domModel._cancelSearch();} -_scheduleMutationEvent(node){if(!this.hasEventListeners(SDK.DOMModel.Events.DOMMutated)) -return;this._lastMutationId=(this._lastMutationId||0)+1;Promise.resolve().then(callObserve.bind(this,node,this._lastMutationId));function callObserve(node,mutationId){if(!this.hasEventListeners(SDK.DOMModel.Events.DOMMutated)||this._lastMutationId!==mutationId) -return;this.dispatchEventToListeners(SDK.DOMModel.Events.DOMMutated,node);}} -requestDocument(callback){if(this._document) -callback(this._document);else -this.requestDocumentPromise().then(callback);} -requestDocumentPromise(){if(this._document) -return Promise.resolve(this._document);if(this._pendingDocumentRequestPromise) -return this._pendingDocumentRequestPromise;this._pendingDocumentRequestPromise=this._agent.getDocument().then(root=>{if(root) -this._setDocument(root);delete this._pendingDocumentRequestPromise;if(!this._document) -console.error('No document');return this._document;});return this._pendingDocumentRequestPromise;} -existingDocument(){return this._document;} -async pushNodeToFrontend(objectId){await this.requestDocumentPromise();var nodeId=await this._agent.requestNode(objectId);return nodeId?this.nodeForId(nodeId):null;} -pushNodeByPathToFrontend(path){return this.requestDocumentPromise().then(()=>this._agent.pushNodeByPathToFrontend(path));} -async pushNodesByBackendIdsToFrontend(backendNodeIds){await this.requestDocumentPromise();var backendNodeIdsArray=backendNodeIds.valuesArray();var nodeIds=await this._agent.pushNodesByBackendIdsToFrontend(backendNodeIdsArray);if(!nodeIds) -return null;var map=new Map();for(var i=0;i<nodeIds.length;++i){if(nodeIds[i]) -map.set(backendNodeIdsArray[i],this.nodeForId(nodeIds[i]));} -return map;} -_wrapClientCallback(callback){function wrapper(error,result){callback(error?null:result||null);} -return wrapper;} -_attributeModified(nodeId,name,value){var node=this._idToDOMNode[nodeId];if(!node) -return;node._setAttribute(name,value);this.dispatchEventToListeners(SDK.DOMModel.Events.AttrModified,{node:node,name:name});this._scheduleMutationEvent(node);} -_attributeRemoved(nodeId,name){var node=this._idToDOMNode[nodeId];if(!node) -return;node._removeAttribute(name);this.dispatchEventToListeners(SDK.DOMModel.Events.AttrRemoved,{node:node,name:name});this._scheduleMutationEvent(node);} -_inlineStyleInvalidated(nodeIds){this._attributeLoadNodeIds.addAll(nodeIds);if(!this._loadNodeAttributesTimeout) -this._loadNodeAttributesTimeout=setTimeout(this._loadNodeAttributes.bind(this),20);} -_loadNodeAttributes(){delete this._loadNodeAttributesTimeout;for(let nodeId of this._attributeLoadNodeIds){this._agent.getAttributes(nodeId).then(attributes=>{if(!attributes){return;} -var node=this._idToDOMNode[nodeId];if(!node) -return;if(node._setAttributesPayload(attributes)){this.dispatchEventToListeners(SDK.DOMModel.Events.AttrModified,{node:node,name:'style'});this._scheduleMutationEvent(node);}});} -this._attributeLoadNodeIds.clear();} -_characterDataModified(nodeId,newValue){var node=this._idToDOMNode[nodeId];node._nodeValue=newValue;this.dispatchEventToListeners(SDK.DOMModel.Events.CharacterDataModified,node);this._scheduleMutationEvent(node);} -nodeForId(nodeId){return this._idToDOMNode[nodeId]||null;} -_documentUpdated(){this._setDocument(null);} -_setDocument(payload){this._idToDOMNode={};if(payload&&'nodeId'in payload) -this._document=new SDK.DOMDocument(this,payload);else -this._document=null;this.dispatchEventToListeners(SDK.DOMModel.Events.DocumentUpdated,this);} -_setDetachedRoot(payload){if(payload.nodeName==='#document') -new SDK.DOMDocument(this,payload);else -SDK.DOMNode.create(this,null,false,payload);} -_setChildNodes(parentId,payloads){if(!parentId&&payloads.length){this._setDetachedRoot(payloads[0]);return;} -var parent=this._idToDOMNode[parentId];parent._setChildrenPayload(payloads);} -_childNodeCountUpdated(nodeId,newValue){var node=this._idToDOMNode[nodeId];node._childNodeCount=newValue;this.dispatchEventToListeners(SDK.DOMModel.Events.ChildNodeCountUpdated,node);this._scheduleMutationEvent(node);} -_childNodeInserted(parentId,prevId,payload){var parent=this._idToDOMNode[parentId];var prev=this._idToDOMNode[prevId];var node=parent._insertChild(prev,payload);this._idToDOMNode[node.id]=node;this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,node);this._scheduleMutationEvent(node);} -_childNodeRemoved(parentId,nodeId){var parent=this._idToDOMNode[parentId];var node=this._idToDOMNode[nodeId];parent._removeChild(node);this._unbind(node);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:node,parent:parent});this._scheduleMutationEvent(node);} -_shadowRootPushed(hostId,root){var host=this._idToDOMNode[hostId];if(!host) -return;var node=SDK.DOMNode.create(this,host.ownerDocument,true,root);node.parentNode=host;this._idToDOMNode[node.id]=node;host._shadowRoots.unshift(node);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,node);this._scheduleMutationEvent(node);} -_shadowRootPopped(hostId,rootId){var host=this._idToDOMNode[hostId];if(!host) -return;var root=this._idToDOMNode[rootId];if(!root) -return;host._removeChild(root);this._unbind(root);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:root,parent:host});this._scheduleMutationEvent(root);} -_pseudoElementAdded(parentId,pseudoElement){var parent=this._idToDOMNode[parentId];if(!parent) -return;var node=SDK.DOMNode.create(this,parent.ownerDocument,false,pseudoElement);node.parentNode=parent;this._idToDOMNode[node.id]=node;console.assert(!parent._pseudoElements.get(node.pseudoType()));parent._pseudoElements.set(node.pseudoType(),node);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,node);this._scheduleMutationEvent(node);} -_pseudoElementRemoved(parentId,pseudoElementId){var parent=this._idToDOMNode[parentId];if(!parent) -return;var pseudoElement=this._idToDOMNode[pseudoElementId];if(!pseudoElement) -return;parent._removeChild(pseudoElement);this._unbind(pseudoElement);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:pseudoElement,parent:parent});this._scheduleMutationEvent(pseudoElement);} -_distributedNodesUpdated(insertionPointId,distributedNodes){var insertionPoint=this._idToDOMNode[insertionPointId];if(!insertionPoint) -return;insertionPoint._setDistributedNodePayloads(distributedNodes);this.dispatchEventToListeners(SDK.DOMModel.Events.DistributedNodesChanged,insertionPoint);this._scheduleMutationEvent(insertionPoint);} -_unbind(node){delete this._idToDOMNode[node.id];for(var i=0;node._children&&i<node._children.length;++i) -this._unbind(node._children[i]);for(var i=0;i<node._shadowRoots.length;++i) -this._unbind(node._shadowRoots[i]);var pseudoElements=node.pseudoElements();for(var value of pseudoElements.values()) -this._unbind(value);if(node._templateContent) -this._unbind(node._templateContent);} -async performSearch(query,includeUserAgentShadowDOM){var response=await this._agent.invoke_performSearch({query,includeUserAgentShadowDOM});if(!response[Protocol.Error]) -this._searchId=response.searchId;return response[Protocol.Error]?0:response.resultCount;} -async searchResult(index){if(!this._searchId) -return null;var nodeIds=await this._agent.getSearchResults(this._searchId,index,index+1);return nodeIds&&nodeIds.length===1?this.nodeForId(nodeIds[0]):null;} -_cancelSearch(){if(!this._searchId) -return;this._agent.discardSearchResults(this._searchId);delete this._searchId;} -classNamesPromise(nodeId){return this._agent.collectClassNamesFromSubtree(nodeId).then(classNames=>classNames||[]);} -querySelector(nodeId,selectors){return this._agent.querySelector(nodeId,selectors);} -querySelectorAll(nodeId,selectors){return this._agent.querySelectorAll(nodeId,selectors);} -markUndoableState(){this._agent.markUndoableState();} -undo(){return this._agent.undo();} -redo(){return this._agent.redo();} -nodeForLocation(x,y,includeUserAgentShadowDOM){return this._agent.getNodeForLocation(x,y,includeUserAgentShadowDOM).then(nodeId=>nodeId?this.nodeForId(nodeId):null);} -pushObjectAsNodeToFrontend(object){return object.isNode()?this.pushNodeToFrontend((object.objectId)):Promise.resolve(null);} -suspendModel(){return this._agent.disable().then(()=>this._setDocument(null));} -resumeModel(){return this._agent.enable();}};SDK.SDKModel.register(SDK.DOMModel,SDK.Target.Capability.DOM,true);SDK.DOMModel.Events={AttrModified:Symbol('AttrModified'),AttrRemoved:Symbol('AttrRemoved'),CharacterDataModified:Symbol('CharacterDataModified'),DOMMutated:Symbol('DOMMutated'),NodeInserted:Symbol('NodeInserted'),NodeRemoved:Symbol('NodeRemoved'),DocumentUpdated:Symbol('DocumentUpdated'),ChildNodeCountUpdated:Symbol('ChildNodeCountUpdated'),DistributedNodesChanged:Symbol('DistributedNodesChanged'),MarkersChanged:Symbol('MarkersChanged')};SDK.DOMDispatcher=class{constructor(domModel){this._domModel=domModel;} -documentUpdated(){this._domModel._documentUpdated();} -attributeModified(nodeId,name,value){this._domModel._attributeModified(nodeId,name,value);} -attributeRemoved(nodeId,name){this._domModel._attributeRemoved(nodeId,name);} -inlineStyleInvalidated(nodeIds){this._domModel._inlineStyleInvalidated(nodeIds);} -characterDataModified(nodeId,characterData){this._domModel._characterDataModified(nodeId,characterData);} -setChildNodes(parentId,payloads){this._domModel._setChildNodes(parentId,payloads);} -childNodeCountUpdated(nodeId,childNodeCount){this._domModel._childNodeCountUpdated(nodeId,childNodeCount);} -childNodeInserted(parentNodeId,previousNodeId,payload){this._domModel._childNodeInserted(parentNodeId,previousNodeId,payload);} -childNodeRemoved(parentNodeId,nodeId){this._domModel._childNodeRemoved(parentNodeId,nodeId);} -shadowRootPushed(hostId,root){this._domModel._shadowRootPushed(hostId,root);} -shadowRootPopped(hostId,rootId){this._domModel._shadowRootPopped(hostId,rootId);} -pseudoElementAdded(parentId,pseudoElement){this._domModel._pseudoElementAdded(parentId,pseudoElement);} -pseudoElementRemoved(parentId,pseudoElementId){this._domModel._pseudoElementRemoved(parentId,pseudoElementId);} -distributedNodesUpdated(insertionPointId,distributedNodes){this._domModel._distributedNodesUpdated(insertionPointId,distributedNodes);}};;SDK.DebuggerModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerDebuggerDispatcher(new SDK.DebuggerDispatcher(this));this._agent=target.debuggerAgent();this._runtimeModel=(target.model(SDK.RuntimeModel));this._sourceMapManager=new SDK.SourceMapManager(target);this._sourceMapIdToScript=new Map();this._debuggerPausedDetails=null;this._scripts=new Map();this._scriptsBySourceURL=new Map();this._discardableScripts=[];this._breakpointResolvedEventTarget=new Common.Object();this._isPausing=false;Common.moduleSetting('pauseOnExceptionEnabled').addChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('pauseOnCaughtException').addChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('disableAsyncStackTraces').addChangeListener(this._asyncStackTracesStateChanged,this);this._enableDebugger();this._stringMap=new Map();this._sourceMapManager.setEnabled(Common.moduleSetting('jsSourceMapsEnabled').get());Common.moduleSetting('jsSourceMapsEnabled').addChangeListener(event=>this._sourceMapManager.setEnabled((event.data)));} -static _sourceMapId(executionContextId,sourceURL,sourceMapURL){if(!sourceMapURL) -return null;return executionContextId+':'+sourceURL+':'+sourceMapURL;} -sourceMapManager(){return this._sourceMapManager;} -runtimeModel(){return this._runtimeModel;} -debuggerEnabled(){return!!this._debuggerEnabled;} -_enableDebugger(){if(this._debuggerEnabled) -return Promise.resolve();this._debuggerEnabled=true;var enablePromise=this._agent.enable();this._pauseOnExceptionStateChanged();this._asyncStackTracesStateChanged();this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerWasEnabled,this);return enablePromise;} -_disableDebugger(){if(!this._debuggerEnabled) -return Promise.resolve();this._debuggerEnabled=false;var disablePromise=this._agent.disable();this._isPausing=false;this._asyncStackTracesStateChanged();this.globalObjectCleared();this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerWasDisabled);return disablePromise;} -_skipAllPauses(skip){if(this._skipAllPausesTimeout){clearTimeout(this._skipAllPausesTimeout);delete this._skipAllPausesTimeout;} -this._agent.setSkipAllPauses(skip);} -skipAllPausesUntilReloadOrTimeout(timeout){if(this._skipAllPausesTimeout) -clearTimeout(this._skipAllPausesTimeout);this._agent.setSkipAllPauses(true);this._skipAllPausesTimeout=setTimeout(this._skipAllPauses.bind(this,false),timeout);} -_pauseOnExceptionStateChanged(){var state;if(!Common.moduleSetting('pauseOnExceptionEnabled').get()) -state=SDK.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions;else if(Common.moduleSetting('pauseOnCaughtException').get()) -state=SDK.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions;else -state=SDK.DebuggerModel.PauseOnExceptionsState.PauseOnUncaughtExceptions;this._agent.setPauseOnExceptions(state);} -_asyncStackTracesStateChanged(){const maxAsyncStackChainDepth=32;var enabled=!Common.moduleSetting('disableAsyncStackTraces').get()&&this._debuggerEnabled;this._agent.setAsyncCallStackDepth(enabled?maxAsyncStackChainDepth:0);} -stepInto(){this._agent.stepInto();} -stepOver(){this._agent.stepOver();} -stepOut(){this._agent.stepOut();} -scheduleStepIntoAsync(){this._agent.scheduleStepIntoAsync();} -resume(){this._agent.resume();this._isPausing=false;} -pause(){this._isPausing=true;this._skipAllPauses(false);this._agent.pause();} -setBreakpointsActive(active){this._agent.setBreakpointsActive(active);} -async setBreakpointByURL(url,lineNumber,columnNumber,condition){if(this.target().isNodeJS()&&SDK.DebuggerModel._fileURLToNodeJSPath.has(url)) -url=SDK.DebuggerModel._fileURLToNodeJSPath.get(url);var minColumnNumber=0;var scripts=this._scriptsBySourceURL.get(url)||[];for(var i=0,l=scripts.length;i<l;++i){var script=scripts[i];if(lineNumber===script.lineOffset) -minColumnNumber=minColumnNumber?Math.min(minColumnNumber,script.columnOffset):script.columnOffset;} -columnNumber=Math.max(columnNumber,minColumnNumber);var response=await this._agent.invoke_setBreakpointByUrl({lineNumber:lineNumber,url:url,columnNumber:columnNumber,condition:condition});if(response[Protocol.Error]) -return{locations:[],breakpointId:null};var locations;if(response.locations) -locations=response.locations.map(payload=>SDK.DebuggerModel.Location.fromPayload(this,payload));return{locations:locations,breakpointId:response.breakpointId};} -async setBreakpointInAnonymousScript(scriptId,scriptHash,lineNumber,columnNumber,condition){var response=await this._agent.invoke_setBreakpointByUrl({lineNumber:lineNumber,scriptHash:scriptHash,columnNumber:columnNumber,condition:condition});var error=response[Protocol.Error];if(error){if(error!=='Either url or urlRegex must be specified.') -return{locations:[],breakpointId:null};return this._setBreakpointBySourceId(scriptId,lineNumber,columnNumber,condition);} -var locations;if(response.locations) -locations=response.locations.map(payload=>SDK.DebuggerModel.Location.fromPayload(this,payload));return{locations:locations,breakpointId:response.breakpointId};} -async _setBreakpointBySourceId(scriptId,lineNumber,columnNumber,condition){var response=await this._agent.invoke_setBreakpoint({location:{scriptId:scriptId,lineNumber:lineNumber,columnNumber:columnNumber},condition:condition});if(response[Protocol.Error]) -return{breakpointId:null,locations:[]};var actualLocation=[];if(response.actualLocation) -actualLocation=[SDK.DebuggerModel.Location.fromPayload(this,response.actualLocation)];return{locations:actualLocation,breakpointId:response.breakpointId};} -async removeBreakpoint(breakpointId){var response=await this._agent.invoke_removeBreakpoint({breakpointId});if(response[Protocol.Error]) -console.error('Failed to remove breakpoint: '+response[Protocol.Error]);} -async getPossibleBreakpoints(startLocation,endLocation,restrictToFunction){var response=await this._agent.invoke_getPossibleBreakpoints({start:startLocation.payload(),end:endLocation.payload(),restrictToFunction:restrictToFunction});if(response[Protocol.Error]||!response.locations) -return[];return response.locations.map(location=>SDK.DebuggerModel.BreakLocation.fromPayload(this,location));} -_breakpointResolved(breakpointId,location){this._breakpointResolvedEventTarget.dispatchEventToListeners(breakpointId,SDK.DebuggerModel.Location.fromPayload(this,location));} -globalObjectCleared(){this._setDebuggerPausedDetails(null);this._reset();this.dispatchEventToListeners(SDK.DebuggerModel.Events.GlobalObjectCleared,this);} -_reset(){for(var scriptWithSourceMap of this._sourceMapIdToScript.values()) -this._sourceMapManager.detachSourceMap(scriptWithSourceMap);this._sourceMapIdToScript.clear();this._scripts.clear();this._scriptsBySourceURL.clear();this._stringMap.clear();this._discardableScripts=[];} -scripts(){return Array.from(this._scripts.values());} -scriptForId(scriptId){return this._scripts.get(scriptId)||null;} -scriptsForSourceURL(sourceURL){if(!sourceURL) -return[];return this._scriptsBySourceURL.get(sourceURL)||[];} -scriptsForExecutionContext(executionContext){var result=[];for(var script of this._scripts.values()){if(script.executionContextId===executionContext.id) -result.push(script);} -return result;} -setScriptSource(scriptId,newSource,callback){this._scripts.get(scriptId).editSource(newSource,this._didEditScriptSource.bind(this,scriptId,newSource,callback));} -_didEditScriptSource(scriptId,newSource,callback,error,exceptionDetails,callFrames,asyncStackTrace,needsStepIn){callback(error,exceptionDetails);if(needsStepIn){this.stepInto();return;} -if(!error&&callFrames&&callFrames.length){this._pausedScript(callFrames,this._debuggerPausedDetails.reason,this._debuggerPausedDetails.auxData,this._debuggerPausedDetails.breakpointIds,asyncStackTrace);}} -get callFrames(){return this._debuggerPausedDetails?this._debuggerPausedDetails.callFrames:null;} -debuggerPausedDetails(){return this._debuggerPausedDetails;} -_setDebuggerPausedDetails(debuggerPausedDetails){this._isPausing=false;this._debuggerPausedDetails=debuggerPausedDetails;if(this._debuggerPausedDetails){if(Runtime.experiments.isEnabled('emptySourceMapAutoStepping')&&this._beforePausedCallback){if(!this._beforePausedCallback.call(null,this._debuggerPausedDetails)) -return false;} -this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerPaused,this);} -if(debuggerPausedDetails) -this.setSelectedCallFrame(debuggerPausedDetails.callFrames[0]);else -this.setSelectedCallFrame(null);return true;} -setBeforePausedCallback(callback){this._beforePausedCallback=callback;} -_pausedScript(callFrames,reason,auxData,breakpointIds,asyncStackTrace){var pausedDetails=new SDK.DebuggerPausedDetails(this,callFrames,reason,auxData,breakpointIds,asyncStackTrace);if(pausedDetails&&this._continueToLocationCallback){var callback=this._continueToLocationCallback;delete this._continueToLocationCallback;if(callback(pausedDetails)) -return;} -if(!this._setDebuggerPausedDetails(pausedDetails)) -this._agent.stepInto();} -_resumedScript(){this._setDebuggerPausedDetails(null);this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerResumed,this);} -_parsedScriptSource(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,isLiveEdit,sourceMapURL,hasSourceURL,hasSyntaxError,length){var isContentScript=false;if(executionContextAuxData&&('isDefault'in executionContextAuxData)) -isContentScript=!executionContextAuxData['isDefault'];if(this.target().isNodeJS()&&sourceURL&&sourceURL.startsWith('/')){var nodeJSPath=sourceURL;sourceURL=Common.ParsedURL.platformPathToURL(nodeJSPath);sourceURL=this._internString(sourceURL);SDK.DebuggerModel._fileURLToNodeJSPath.set(sourceURL,nodeJSPath);}else{sourceURL=this._internString(sourceURL);} -var script=new SDK.Script(this,scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,this._internString(hash),isContentScript,isLiveEdit,sourceMapURL,hasSourceURL,length);this._registerScript(script);if(!hasSyntaxError) -this.dispatchEventToListeners(SDK.DebuggerModel.Events.ParsedScriptSource,script);else -this.dispatchEventToListeners(SDK.DebuggerModel.Events.FailedToParseScriptSource,script);var sourceMapId=SDK.DebuggerModel._sourceMapId(script.executionContextId,script.sourceURL,script.sourceMapURL);if(sourceMapId&&!hasSyntaxError){var previousScript=this._sourceMapIdToScript.get(sourceMapId);if(previousScript) -this._sourceMapManager.detachSourceMap(previousScript);this._sourceMapIdToScript.set(sourceMapId,script);this._sourceMapManager.attachSourceMap(script,script.sourceURL,script.sourceMapURL);} -var isDiscardable=hasSyntaxError&&script.isAnonymousScript();if(isDiscardable){this._discardableScripts.push(script);this._collectDiscardedScripts();} -return script;} -setSourceMapURL(script,newSourceMapURL){var sourceMapId=SDK.DebuggerModel._sourceMapId(script.executionContextId,script.sourceURL,script.sourceMapURL);if(sourceMapId&&this._sourceMapIdToScript.get(sourceMapId)===script) -this._sourceMapIdToScript.delete(sourceMapId);this._sourceMapManager.detachSourceMap(script);script.sourceMapURL=newSourceMapURL;sourceMapId=SDK.DebuggerModel._sourceMapId(script.executionContextId,script.sourceURL,script.sourceMapURL);if(!sourceMapId) -return;this._sourceMapIdToScript.set(sourceMapId,script);this._sourceMapManager.attachSourceMap(script,script.sourceURL,script.sourceMapURL);} -executionContextDestroyed(executionContext){var sourceMapIds=Array.from(this._sourceMapIdToScript.keys());for(var sourceMapId of sourceMapIds){var script=this._sourceMapIdToScript.get(sourceMapId);if(script.executionContextId===executionContext.id){this._sourceMapIdToScript.delete(sourceMapId);this._sourceMapManager.detachSourceMap(script);}}} -_registerScript(script){this._scripts.set(script.scriptId,script);if(script.isAnonymousScript()) -return;var scripts=this._scriptsBySourceURL.get(script.sourceURL);if(!scripts){scripts=[];this._scriptsBySourceURL.set(script.sourceURL,scripts);} -scripts.push(script);} -_unregisterScript(script){console.assert(script.isAnonymousScript());this._scripts.delete(script.scriptId);} -_collectDiscardedScripts(){if(this._discardableScripts.length<1000) -return;var scriptsToDiscard=this._discardableScripts.splice(0,100);for(var script of scriptsToDiscard){this._unregisterScript(script);this.dispatchEventToListeners(SDK.DebuggerModel.Events.DiscardedAnonymousScriptSource,script);}} -createRawLocation(script,lineNumber,columnNumber){return new SDK.DebuggerModel.Location(this,script.scriptId,lineNumber,columnNumber);} -createRawLocationByURL(sourceURL,lineNumber,columnNumber){var closestScript=null;var scripts=this._scriptsBySourceURL.get(sourceURL)||[];for(var i=0,l=scripts.length;i<l;++i){var script=scripts[i];if(!closestScript) -closestScript=script;if(script.lineOffset>lineNumber||(script.lineOffset===lineNumber&&script.columnOffset>columnNumber)) -continue;if(script.endLine<lineNumber||(script.endLine===lineNumber&&script.endColumn<=columnNumber)) -continue;closestScript=script;break;} -return closestScript?new SDK.DebuggerModel.Location(this,closestScript.scriptId,lineNumber,columnNumber):null;} -createRawLocationByScriptId(scriptId,lineNumber,columnNumber){var script=this.scriptForId(scriptId);return script?this.createRawLocation(script,lineNumber,columnNumber):null;} -createRawLocationsByStackTrace(stackTrace){var frames=[];while(stackTrace){for(var frame of stackTrace.callFrames) -frames.push(frame);stackTrace=stackTrace.parent;} -var rawLocations=[];for(var frame of frames){var rawLocation=this.createRawLocationByScriptId(frame.scriptId,frame.lineNumber,frame.columnNumber);if(rawLocation) -rawLocations.push(rawLocation);} -return rawLocations;} -isPaused(){return!!this.debuggerPausedDetails();} -isPausing(){return this._isPausing;} -setSelectedCallFrame(callFrame){if(this._selectedCallFrame===callFrame) -return;this._selectedCallFrame=callFrame;this.dispatchEventToListeners(SDK.DebuggerModel.Events.CallFrameSelected,this);} -selectedCallFrame(){return this._selectedCallFrame;} -evaluateOnSelectedCallFrame(options){return this.selectedCallFrame().evaluate(options);} -functionDetailsPromise(remoteObject){return remoteObject.getAllPropertiesPromise(false,false).then(buildDetails.bind(this));function buildDetails(response){if(!response) -return null;var location=null;if(response.internalProperties){for(var prop of response.internalProperties){if(prop.name==='[[FunctionLocation]]') -location=prop.value;}} -var functionName=null;if(response.properties){for(var prop of response.properties){if(prop.name==='name'&&prop.value&&prop.value.type==='string') -functionName=prop.value;if(prop.name==='displayName'&&prop.value&&prop.value.type==='string'){functionName=prop.value;break;}}} -var debuggerLocation=null;if(location){debuggerLocation=this.createRawLocationByScriptId(location.value.scriptId,location.value.lineNumber,location.value.columnNumber);} -return{location:debuggerLocation,functionName:functionName?functionName.value:''};}} -async setVariableValue(scopeNumber,variableName,newValue,callFrameId){var response=await this._agent.invoke_setVariableValue({scopeNumber,variableName,newValue,callFrameId});var error=response[Protocol.Error];if(error) -console.error(error);return error;} -addBreakpointListener(breakpointId,listener,thisObject){this._breakpointResolvedEventTarget.addEventListener(breakpointId,listener,thisObject);} -removeBreakpointListener(breakpointId,listener,thisObject){this._breakpointResolvedEventTarget.removeEventListener(breakpointId,listener,thisObject);} -async setBlackboxPatterns(patterns){var response=await this._agent.invoke_setBlackboxPatterns({patterns});var error=response[Protocol.Error];if(error) -console.error(error);return!error;} -dispose(){this._sourceMapManager.dispose();Common.moduleSetting('pauseOnExceptionEnabled').removeChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('pauseOnCaughtException').removeChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('disableAsyncStackTraces').removeChangeListener(this._asyncStackTracesStateChanged,this);} -async suspendModel(){await this._disableDebugger();} -async resumeModel(){await this._enableDebugger();} -_internString(string){if(!this._stringMap.has(string)) -this._stringMap.set(string,string);return this._stringMap.get(string);}};SDK.DebuggerModel._fileURLToNodeJSPath=new Map();SDK.SDKModel.register(SDK.DebuggerModel,SDK.Target.Capability.JS,true);SDK.DebuggerModel.FunctionDetails;SDK.DebuggerModel.PauseOnExceptionsState={DontPauseOnExceptions:'none',PauseOnAllExceptions:'all',PauseOnUncaughtExceptions:'uncaught'};SDK.DebuggerModel.Events={DebuggerWasEnabled:Symbol('DebuggerWasEnabled'),DebuggerWasDisabled:Symbol('DebuggerWasDisabled'),DebuggerPaused:Symbol('DebuggerPaused'),DebuggerResumed:Symbol('DebuggerResumed'),ParsedScriptSource:Symbol('ParsedScriptSource'),FailedToParseScriptSource:Symbol('FailedToParseScriptSource'),DiscardedAnonymousScriptSource:Symbol('DiscardedAnonymousScriptSource'),GlobalObjectCleared:Symbol('GlobalObjectCleared'),CallFrameSelected:Symbol('CallFrameSelected'),ConsoleCommandEvaluatedInSelectedCallFrame:Symbol('ConsoleCommandEvaluatedInSelectedCallFrame')};SDK.DebuggerModel.BreakReason={DOM:'DOM',EventListener:'EventListener',XHR:'XHR',Exception:'exception',PromiseRejection:'promiseRejection',Assert:'assert',DebugCommand:'debugCommand',OOM:'OOM',Other:'other'};SDK.DebuggerModel.BreakLocationType={Return:'return',Call:'call',DebuggerStatement:'debuggerStatement'};SDK.DebuggerEventTypes={JavaScriptPause:0,JavaScriptBreakpoint:1,NativeBreakpoint:2};SDK.DebuggerModel.ContinueToLocationTargetCallFrames={Any:'any',Current:'current'};SDK.DebuggerModel.SetBreakpointResult;SDK.DebuggerDispatcher=class{constructor(debuggerModel){this._debuggerModel=debuggerModel;} -paused(callFrames,reason,auxData,breakpointIds,asyncStackTrace){this._debuggerModel._pausedScript(callFrames,reason,auxData,breakpointIds||[],asyncStackTrace);} -resumed(){this._debuggerModel._resumedScript();} -scriptParsed(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,isLiveEdit,sourceMapURL,hasSourceURL,isModule,length){this._debuggerModel._parsedScriptSource(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,!!isLiveEdit,sourceMapURL,!!hasSourceURL,false,length||0);} -scriptFailedToParse(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,sourceMapURL,hasSourceURL,isModule,length){this._debuggerModel._parsedScriptSource(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,false,sourceMapURL,!!hasSourceURL,true,length||0);} -breakpointResolved(breakpointId,location){this._debuggerModel._breakpointResolved(breakpointId,location);}};SDK.DebuggerModel.Location=class{constructor(debuggerModel,scriptId,lineNumber,columnNumber){this.debuggerModel=debuggerModel;this.scriptId=scriptId;this.lineNumber=lineNumber;this.columnNumber=columnNumber||0;} -static fromPayload(debuggerModel,payload){return new SDK.DebuggerModel.Location(debuggerModel,payload.scriptId,payload.lineNumber,payload.columnNumber);} -payload(){return{scriptId:this.scriptId,lineNumber:this.lineNumber,columnNumber:this.columnNumber};} -script(){return this.debuggerModel.scriptForId(this.scriptId);} -continueToLocation(pausedCallback){if(pausedCallback) -this.debuggerModel._continueToLocationCallback=this._paused.bind(this,pausedCallback);this.debuggerModel._agent.continueToLocation(this.payload(),SDK.DebuggerModel.ContinueToLocationTargetCallFrames.Current);} -_paused(pausedCallback,debuggerPausedDetails){var location=debuggerPausedDetails.callFrames[0].location();if(location.scriptId===this.scriptId&&location.lineNumber===this.lineNumber&&location.columnNumber===this.columnNumber){pausedCallback();return true;} -return false;} -id(){return this.debuggerModel.target().id()+':'+this.scriptId+':'+this.lineNumber+':'+this.columnNumber;}};SDK.DebuggerModel.BreakLocation=class extends SDK.DebuggerModel.Location{constructor(debuggerModel,scriptId,lineNumber,columnNumber,type){super(debuggerModel,scriptId,lineNumber,columnNumber);if(type) -this.type=type;} -static fromPayload(debuggerModel,payload){return new SDK.DebuggerModel.BreakLocation(debuggerModel,payload.scriptId,payload.lineNumber,payload.columnNumber,payload.type);}};SDK.DebuggerModel.CallFrame=class{constructor(debuggerModel,script,payload){this.debuggerModel=debuggerModel;this._script=script;this._payload=payload;this._location=SDK.DebuggerModel.Location.fromPayload(debuggerModel,payload.location);this._scopeChain=[];this._localScope=null;for(var i=0;i<payload.scopeChain.length;++i){var scope=new SDK.DebuggerModel.Scope(this,i);this._scopeChain.push(scope);if(scope.type()===Protocol.Debugger.ScopeType.Local) -this._localScope=scope;} -if(payload.functionLocation) -this._functionLocation=SDK.DebuggerModel.Location.fromPayload(debuggerModel,payload.functionLocation);} -static fromPayloadArray(debuggerModel,callFrames){var result=[];for(var i=0;i<callFrames.length;++i){var callFrame=callFrames[i];var script=debuggerModel.scriptForId(callFrame.location.scriptId);if(script) -result.push(new SDK.DebuggerModel.CallFrame(debuggerModel,script,callFrame));} -return result;} -get script(){return this._script;} -get id(){return this._payload.callFrameId;} -scopeChain(){return this._scopeChain;} -localScope(){return this._localScope;} -thisObject(){return this._payload.this?this.debuggerModel._runtimeModel.createRemoteObject(this._payload.this):null;} -returnValue(){return this._payload.returnValue?this.debuggerModel._runtimeModel.createRemoteObject(this._payload.returnValue):null;} -get functionName(){return this._payload.functionName;} -location(){return this._location;} -functionLocation(){return this._functionLocation||null;} -async evaluate(options){var response=await this.debuggerModel._agent.invoke_evaluateOnCallFrame({callFrameId:this.id,expression:options.expression,objectGroup:options.objectGroup,includeCommandLineAPI:options.includeCommandLineAPI,silent:options.silent,returnByValue:options.returnByValue,generatePreview:options.generatePreview,throwOnSideEffect:false});var error=response[Protocol.Error];if(error){console.error(error);return{error:error};} -return{object:this.debuggerModel.runtimeModel().createRemoteObject(response.result),exceptionDetails:response.exceptionDetails};} -async restart(){var response=await this.debuggerModel._agent.invoke_restartFrame({callFrameId:this._payload.callFrameId});if(!response[Protocol.Error]) -this.debuggerModel.stepInto();}};SDK.DebuggerModel.Scope=class{constructor(callFrame,ordinal){this._callFrame=callFrame;this._payload=callFrame._payload.scopeChain[ordinal];this._type=this._payload.type;this._name=this._payload.name;this._ordinal=ordinal;this._startLocation=this._payload.startLocation?SDK.DebuggerModel.Location.fromPayload(callFrame.debuggerModel,this._payload.startLocation):null;this._endLocation=this._payload.endLocation?SDK.DebuggerModel.Location.fromPayload(callFrame.debuggerModel,this._payload.endLocation):null;} -callFrame(){return this._callFrame;} -type(){return this._type;} -typeName(){switch(this._type){case Protocol.Debugger.ScopeType.Local:return Common.UIString('Local');case Protocol.Debugger.ScopeType.Closure:return Common.UIString('Closure');case Protocol.Debugger.ScopeType.Catch:return Common.UIString('Catch');case Protocol.Debugger.ScopeType.Block:return Common.UIString('Block');case Protocol.Debugger.ScopeType.Script:return Common.UIString('Script');case Protocol.Debugger.ScopeType.With:return Common.UIString('With Block');case Protocol.Debugger.ScopeType.Global:return Common.UIString('Global');case Protocol.Debugger.ScopeType.Module:return Common.UIString('Module');} -return'';} -name(){return this._name;} -startLocation(){return this._startLocation;} -endLocation(){return this._endLocation;} -object(){if(this._object) -return this._object;var runtimeModel=this._callFrame.debuggerModel._runtimeModel;var declarativeScope=this._type!==Protocol.Debugger.ScopeType.With&&this._type!==Protocol.Debugger.ScopeType.Global;if(declarativeScope){this._object=runtimeModel.createScopeRemoteObject(this._payload.object,new SDK.ScopeRef(this._ordinal,this._callFrame.id));}else{this._object=runtimeModel.createRemoteObject(this._payload.object);} -return this._object;} -description(){var declarativeScope=this._type!==Protocol.Debugger.ScopeType.With&&this._type!==Protocol.Debugger.ScopeType.Global;return declarativeScope?'':(this._payload.object.description||'');}};SDK.DebuggerPausedDetails=class{constructor(debuggerModel,callFrames,reason,auxData,breakpointIds,asyncStackTrace){this.debuggerModel=debuggerModel;this.callFrames=SDK.DebuggerModel.CallFrame.fromPayloadArray(debuggerModel,callFrames);this.reason=reason;this.auxData=auxData;this.breakpointIds=breakpointIds;if(asyncStackTrace) -this.asyncStackTrace=this._cleanRedundantFrames(asyncStackTrace);} -exception(){if(this.reason!==SDK.DebuggerModel.BreakReason.Exception&&this.reason!==SDK.DebuggerModel.BreakReason.PromiseRejection) -return null;return this.debuggerModel._runtimeModel.createRemoteObject((this.auxData));} -_cleanRedundantFrames(asyncStackTrace){var stack=asyncStackTrace;var previous=null;while(stack){if(stack.description==='async function'&&stack.callFrames.length) -stack.callFrames.shift();if(previous&&(!stack.callFrames.length&&!stack.promiseCreationFrame)) -previous.parent=stack.parent;else -previous=stack;stack=stack.parent;} -return asyncStackTrace;}};;SDK.EmulationModel=class extends SDK.SDKModel{constructor(target){super(target);this._emulationAgent=target.emulationAgent();this._pageAgent=target.pageAgent();this._deviceOrientationAgent=target.deviceOrientationAgent();this._cssModel=target.model(SDK.CSSModel);this._overlayModel=target.model(SDK.OverlayModel);if(this._overlayModel) -this._overlayModel.addEventListener(SDK.OverlayModel.Events.InspectModeWillBeToggled,this._updateTouch,this);var disableJavascriptSetting=Common.settings.moduleSetting('javaScriptDisabled');disableJavascriptSetting.addChangeListener(()=>this._emulationAgent.setScriptExecutionDisabled(disableJavascriptSetting.get()));if(disableJavascriptSetting.get()) -this._emulationAgent.setScriptExecutionDisabled(true);var mediaSetting=Common.moduleSetting('emulatedCSSMedia');mediaSetting.addChangeListener(()=>this._emulateCSSMedia(mediaSetting.get()));if(mediaSetting.get()) -this._emulateCSSMedia(mediaSetting.get());this._touchEnabled=false;this._touchMobile=false;this._customTouchEnabled=false;this._touchConfiguration={enabled:false,configuration:'mobile',scriptId:''};} -supportsDeviceEmulation(){return this.target().hasAllCapabilities(SDK.Target.Capability.DeviceEmulation);} -resetPageScaleFactor(){return this._emulationAgent.resetPageScaleFactor();} -emulateDevice(metrics){if(metrics) -return this._emulationAgent.invoke_setDeviceMetricsOverride(metrics);else -return this._emulationAgent.clearDeviceMetricsOverride();} -overlayModel(){return this._overlayModel;} -emulateGeolocation(geolocation){if(!geolocation){this._emulationAgent.clearGeolocationOverride();return;} -if(geolocation.error){this._emulationAgent.setGeolocationOverride();}else{this._emulationAgent.setGeolocationOverride(geolocation.latitude,geolocation.longitude,SDK.EmulationModel.Geolocation.DefaultMockAccuracy);}} -emulateDeviceOrientation(deviceOrientation){if(deviceOrientation){this._deviceOrientationAgent.setDeviceOrientationOverride(deviceOrientation.alpha,deviceOrientation.beta,deviceOrientation.gamma);}else{this._deviceOrientationAgent.clearDeviceOrientationOverride();}} -_emulateCSSMedia(media){this._emulationAgent.setEmulatedMedia(media);if(this._cssModel) -this._cssModel.mediaQueryResultChanged();} -setCPUThrottlingRate(rate){this._emulationAgent.setCPUThrottlingRate(rate);} -emulateTouch(enabled,mobile){this._touchEnabled=enabled;this._touchMobile=mobile;this._updateTouch();} -overrideEmulateTouch(enabled){this._customTouchEnabled=enabled;this._updateTouch();} -_updateTouch(){var configuration={enabled:this._touchEnabled,configuration:this._touchMobile?'mobile':'desktop',};if(this._customTouchEnabled) -configuration={enabled:true,configuration:'mobile'};if(this._overlayModel&&this._overlayModel.inspectModeEnabled()) -configuration={enabled:false,configuration:'mobile'};if(!this._touchConfiguration.enabled&&!configuration.enabled) -return;if(this._touchConfiguration.enabled&&configuration.enabled&&this._touchConfiguration.configuration===configuration.configuration) -return;this._touchConfiguration=configuration;this._emulationAgent.setTouchEmulationEnabled(configuration.enabled,1);this._emulationAgent.setEmitTouchEventsForMouse(configuration.enabled,configuration.configuration);}};SDK.SDKModel.register(SDK.EmulationModel,SDK.Target.Capability.Emulation,true);SDK.EmulationModel.Geolocation=class{constructor(latitude,longitude,error){this.latitude=latitude;this.longitude=longitude;this.error=error;} -static parseSetting(value){if(value){var splitError=value.split(':');if(splitError.length===2){var splitPosition=splitError[0].split('@');if(splitPosition.length===2){return new SDK.EmulationModel.Geolocation(parseFloat(splitPosition[0]),parseFloat(splitPosition[1]),splitError[1]);}}} -return new SDK.EmulationModel.Geolocation(0,0,false);} -static parseUserInput(latitudeString,longitudeString,errorStatus){if(!latitudeString&&!longitudeString) -return null;var isLatitudeValid=SDK.EmulationModel.Geolocation.latitudeValidator(latitudeString);var isLongitudeValid=SDK.EmulationModel.Geolocation.longitudeValidator(longitudeString);if(!isLatitudeValid&&!isLongitudeValid) -return null;var latitude=isLatitudeValid?parseFloat(latitudeString):-1;var longitude=isLongitudeValid?parseFloat(longitudeString):-1;return new SDK.EmulationModel.Geolocation(latitude,longitude,!!errorStatus);} -static latitudeValidator(value){var numValue=parseFloat(value);return/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(value)&&numValue>=-90&&numValue<=90;} -static longitudeValidator(value){var numValue=parseFloat(value);return/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(value)&&numValue>=-180&&numValue<=180;} -toSetting(){return(typeof this.latitude==='number'&&typeof this.longitude==='number'&&typeof this.error==='string')?this.latitude+'@'+this.longitude+':'+this.error:'';}};SDK.EmulationModel.Geolocation.DefaultMockAccuracy=150;SDK.EmulationModel.DeviceOrientation=class{constructor(alpha,beta,gamma){this.alpha=alpha;this.beta=beta;this.gamma=gamma;} -static parseSetting(value){if(value){var jsonObject=JSON.parse(value);return new SDK.EmulationModel.DeviceOrientation(jsonObject.alpha,jsonObject.beta,jsonObject.gamma);} -return new SDK.EmulationModel.DeviceOrientation(0,0,0);} -static parseUserInput(alphaString,betaString,gammaString){if(!alphaString&&!betaString&&!gammaString) -return null;var isAlphaValid=SDK.EmulationModel.DeviceOrientation.validator(alphaString);var isBetaValid=SDK.EmulationModel.DeviceOrientation.validator(betaString);var isGammaValid=SDK.EmulationModel.DeviceOrientation.validator(gammaString);if(!isAlphaValid&&!isBetaValid&&!isGammaValid) -return null;var alpha=isAlphaValid?parseFloat(alphaString):-1;var beta=isBetaValid?parseFloat(betaString):-1;var gamma=isGammaValid?parseFloat(gammaString):-1;return new SDK.EmulationModel.DeviceOrientation(alpha,beta,gamma);} -static validator(value){return/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(value);} -toSetting(){return JSON.stringify(this);}};;SDK.SnapshotWithRect;SDK.Layer=function(){};SDK.Layer.prototype={id(){},parentId(){},parent(){},isRoot(){},children(){},addChild(child){},node(){},nodeForSelfOrAncestor(){},offsetX(){},offsetY(){},width(){},height(){},transform(){},quad(){},anchorPoint(){},invisible(){},paintCount(){},lastPaintRect(){},scrollRects(){},stickyPositionConstraint(){},gpuMemoryUsage(){},requestCompositingReasons(){},drawsContent(){},snapshots(){}};SDK.Layer.ScrollRectType={NonFastScrollable:'NonFastScrollable',TouchEventHandler:'TouchEventHandler',WheelEventHandler:'WheelEventHandler',RepaintsOnScroll:'RepaintsOnScroll'};SDK.Layer.StickyPositionConstraint=class{constructor(layerTree,constraint){this._stickyBoxRect=constraint.stickyBoxRect;this._containingBlockRect=constraint.containingBlockRect;this._nearestLayerShiftingStickyBox=null;if(layerTree&&constraint.nearestLayerShiftingStickyBox) -this._nearestLayerShiftingStickyBox=layerTree.layerById(constraint.nearestLayerShiftingStickyBox);this._nearestLayerShiftingContainingBlock=null;if(layerTree&&constraint.nearestLayerShiftingContainingBlock) -this._nearestLayerShiftingContainingBlock=layerTree.layerById(constraint.nearestLayerShiftingContainingBlock);} -stickyBoxRect(){return this._stickyBoxRect;} -containingBlockRect(){return this._containingBlockRect;} -nearestLayerShiftingStickyBox(){return this._nearestLayerShiftingStickyBox;} -nearestLayerShiftingContainingBlock(){return this._nearestLayerShiftingContainingBlock;}};SDK.LayerTreeBase=class{constructor(target){this._target=target;this._domModel=target?target.model(SDK.DOMModel):null;this._layersById={};this._root=null;this._contentRoot=null;this._backendNodeIdToNode=new Map();} -target(){return this._target;} -root(){return this._root;} -setRoot(root){this._root=root;} -contentRoot(){return this._contentRoot;} -setContentRoot(contentRoot){this._contentRoot=contentRoot;} -forEachLayer(callback,root){if(!root){root=this.root();if(!root) -return false;} -return callback(root)||root.children().some(this.forEachLayer.bind(this,callback));} -layerById(id){return this._layersById[id]||null;} -async resolveBackendNodeIds(requestedNodeIds){if(!requestedNodeIds.size||!this._domModel) -return;var nodesMap=await this._domModel.pushNodesByBackendIdsToFrontend(requestedNodeIds);if(!nodesMap) -return;for(var nodeId of nodesMap.keysArray()) -this._backendNodeIdToNode.set(nodeId,nodesMap.get(nodeId)||null);} -backendNodeIdToNode(){return this._backendNodeIdToNode;} -setViewportSize(viewportSize){this._viewportSize=viewportSize;} -viewportSize(){return this._viewportSize;} -_nodeForId(id){return this._domModel?this._domModel.nodeForId(id):null;}};;SDK.LogModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerLogDispatcher(this);this._logAgent=target.logAgent();this._logAgent.enable();if(!Host.isUnderTest()){this._logAgent.startViolationsReport([{name:'longTask',threshold:200},{name:'longLayout',threshold:30},{name:'blockedEvent',threshold:100},{name:'blockedParser',threshold:-1},{name:'handler',threshold:150},{name:'recurringHandler',threshold:50},{name:'discouragedAPIUse',threshold:-1}]);}} -entryAdded(payload){this.dispatchEventToListeners(SDK.LogModel.Events.EntryAdded,{logModel:this,entry:payload});} -requestClear(){this._logAgent.clear();}};SDK.SDKModel.register(SDK.LogModel,SDK.Target.Capability.Log,true);SDK.LogModel.Events={EntryAdded:Symbol('EntryAdded')};;SDK.ServiceWorkerManager=class extends SDK.SDKModel{constructor(target){super(target);target.registerServiceWorkerDispatcher(new SDK.ServiceWorkerDispatcher(this));this._lastAnonymousTargetId=0;this._agent=target.serviceWorkerAgent();this._registrations=new Map();this.enable();this._forceUpdateSetting=Common.settings.createSetting('serviceWorkerUpdateOnReload',false);if(this._forceUpdateSetting.get()) -this._forceUpdateSettingChanged();this._forceUpdateSetting.addChangeListener(this._forceUpdateSettingChanged,this);new SDK.ServiceWorkerContextNamer(target,this);} -enable(){if(this._enabled) -return;this._enabled=true;this._agent.enable();} -disable(){if(!this._enabled) -return;this._enabled=false;this._registrations.clear();this._agent.disable();} -registrations(){return this._registrations;} -findVersion(versionId){for(var registration of this.registrations().values()){var version=registration.versions.get(versionId);if(version) -return version;} -return null;} -deleteRegistration(registrationId){var registration=this._registrations.get(registrationId);if(!registration) -return;if(registration._isRedundant()){this._registrations.delete(registrationId);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationDeleted,registration);return;} -registration._deleting=true;for(var version of registration.versions.values()) -this.stopWorker(version.id);this._unregister(registration.scopeURL);} -updateRegistration(registrationId){var registration=this._registrations.get(registrationId);if(!registration) -return;this._agent.updateRegistration(registration.scopeURL);} -deliverPushMessage(registrationId,data){var registration=this._registrations.get(registrationId);if(!registration) -return;var origin=Common.ParsedURL.extractOrigin(registration.scopeURL);this._agent.deliverPushMessage(origin,registrationId,data);} -dispatchSyncEvent(registrationId,tag,lastChance){var registration=this._registrations.get(registrationId);if(!registration) -return;var origin=Common.ParsedURL.extractOrigin(registration.scopeURL);this._agent.dispatchSyncEvent(origin,registrationId,tag,lastChance);} -_unregister(scope){this._agent.unregister(scope);} -startWorker(scope){this._agent.startWorker(scope);} -skipWaiting(scope){this._agent.skipWaiting(scope);} -stopWorker(versionId){this._agent.stopWorker(versionId);} -inspectWorker(versionId){this._agent.inspectWorker(versionId);} -_workerRegistrationUpdated(registrations){for(var payload of registrations){var registration=this._registrations.get(payload.registrationId);if(!registration){registration=new SDK.ServiceWorkerRegistration(payload);this._registrations.set(payload.registrationId,registration);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationUpdated,registration);continue;} -registration._update(payload);if(registration._shouldBeRemoved()){this._registrations.delete(registration.id);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationDeleted,registration);}else{this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationUpdated,registration);}}} -_workerVersionUpdated(versions){var registrations=new Set();for(var payload of versions){var registration=this._registrations.get(payload.registrationId);if(!registration) -continue;registration._updateVersion(payload);registrations.add(registration);} -for(var registration of registrations){if(registration._shouldBeRemoved()){this._registrations.delete(registration.id);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationDeleted,registration);}else{this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationUpdated,registration);}}} -_workerErrorReported(payload){var registration=this._registrations.get(payload.registrationId);if(!registration) -return;registration.errors.push(payload);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationErrorAdded,{registration:registration,error:payload});} -forceUpdateOnReloadSetting(){return this._forceUpdateSetting;} -_forceUpdateSettingChanged(){this._agent.setForceUpdateOnPageLoad(this._forceUpdateSetting.get());}};SDK.SDKModel.register(SDK.ServiceWorkerManager,SDK.Target.Capability.Target|SDK.Target.Capability.Browser,true);SDK.ServiceWorkerManager.Events={RegistrationUpdated:Symbol('RegistrationUpdated'),RegistrationErrorAdded:Symbol('RegistrationErrorAdded'),RegistrationDeleted:Symbol('RegistrationDeleted')};SDK.ServiceWorkerDispatcher=class{constructor(manager){this._manager=manager;} -workerRegistrationUpdated(registrations){this._manager._workerRegistrationUpdated(registrations);} -workerVersionUpdated(versions){this._manager._workerVersionUpdated(versions);} -workerErrorReported(errorMessage){this._manager._workerErrorReported(errorMessage);}};SDK.ServiceWorkerVersion=class{constructor(registration,payload){this.registration=registration;this._update(payload);} -_update(payload){this.id=payload.versionId;this.scriptURL=payload.scriptURL;var parsedURL=new Common.ParsedURL(payload.scriptURL);this.securityOrigin=parsedURL.securityOrigin();this.runningStatus=payload.runningStatus;this.status=payload.status;this.scriptLastModified=payload.scriptLastModified;this.scriptResponseTime=payload.scriptResponseTime;this.controlledClients=[];for(var i=0;i<payload.controlledClients.length;++i) -this.controlledClients.push(payload.controlledClients[i]);this.targetId=payload.targetId||null;} -isStartable(){return!this.registration.isDeleted&&this.isActivated()&&this.isStopped();} -isStoppedAndRedundant(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Stopped&&this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Redundant;} -isStopped(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Stopped;} -isStarting(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Starting;} -isRunning(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Running;} -isStopping(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Stopping;} -isNew(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.New;} -isInstalling(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Installing;} -isInstalled(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Installed;} -isActivating(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Activating;} -isActivated(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Activated;} -isRedundant(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Redundant;} -mode(){if(this.isNew()||this.isInstalling()) -return SDK.ServiceWorkerVersion.Modes.Installing;else if(this.isInstalled()) -return SDK.ServiceWorkerVersion.Modes.Waiting;else if(this.isActivating()||this.isActivated()) -return SDK.ServiceWorkerVersion.Modes.Active;return SDK.ServiceWorkerVersion.Modes.Redundant;}};SDK.ServiceWorkerVersion.Modes={Installing:'installing',Waiting:'waiting',Active:'active',Redundant:'redundant'};SDK.ServiceWorkerRegistration=class{constructor(payload){this._update(payload);this.versions=new Map();this._deleting=false;this.errors=[];} -_update(payload){this._fingerprint=Symbol('fingerprint');this.id=payload.registrationId;this.scopeURL=payload.scopeURL;var parsedURL=new Common.ParsedURL(payload.scopeURL);this.securityOrigin=parsedURL.securityOrigin();this.isDeleted=payload.isDeleted;this.forceUpdateOnPageLoad=payload.forceUpdateOnPageLoad;} -fingerprint(){return this._fingerprint;} -versionsByMode(){var result=new Map();for(var version of this.versions.values()) -result.set(version.mode(),version);return result;} -_updateVersion(payload){this._fingerprint=Symbol('fingerprint');var version=this.versions.get(payload.versionId);if(!version){version=new SDK.ServiceWorkerVersion(this,payload);this.versions.set(payload.versionId,version);return version;} -version._update(payload);return version;} -_isRedundant(){for(var version of this.versions.values()){if(!version.isStoppedAndRedundant()) -return false;} -return true;} -_shouldBeRemoved(){return this._isRedundant()&&(!this.errors.length||this._deleting);} -canBeRemoved(){return this.isDeleted||this._deleting;} -clearErrors(){this._fingerprint=Symbol('fingerprint');this.errors=[];}};SDK.ServiceWorkerContextNamer=class{constructor(target,serviceWorkerManager){this._target=target;this._serviceWorkerManager=serviceWorkerManager;this._versionByTargetId=new Map();serviceWorkerManager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationUpdated,this._registrationsUpdated,this);serviceWorkerManager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationDeleted,this._registrationsUpdated,this);SDK.targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextCreated,this._executionContextCreated,this);} -_registrationsUpdated(event){this._versionByTargetId.clear();var registrations=this._serviceWorkerManager.registrations().valuesArray();for(var registration of registrations){var versions=registration.versions.valuesArray();for(var version of versions){if(version.targetId) -this._versionByTargetId.set(version.targetId,version);}} -this._updateAllContextLabels();} -_executionContextCreated(event){var executionContext=(event.data);var serviceWorkerTargetId=this._serviceWorkerTargetIdForWorker(executionContext.target());if(!serviceWorkerTargetId) -return;this._updateContextLabel(executionContext,this._versionByTargetId.get(serviceWorkerTargetId)||null);} -_serviceWorkerTargetIdForWorker(target){var parent=target.parentTarget();if(!parent||parent.parentTarget()!==this._target) -return null;return parent.id();} -_updateAllContextLabels(){for(var target of SDK.targetManager.targets()){var serviceWorkerTargetId=this._serviceWorkerTargetIdForWorker(target);if(!serviceWorkerTargetId) -continue;var version=this._versionByTargetId.get(serviceWorkerTargetId)||null;var runtimeModel=target.model(SDK.RuntimeModel);var executionContexts=runtimeModel?runtimeModel.executionContexts():[];for(var context of executionContexts) -this._updateContextLabel(context,version);}} -_updateContextLabel(context,version){if(!version){context.setLabel('');return;} -var parsedUrl=context.origin.asParsedURL();var label=parsedUrl?parsedUrl.lastPathComponentWithFragment():context.name;context.setLabel(label+' #'+version.id+' ('+version.status+')');}};;SDK.TracingManagerClient=function(){};SDK.TracingManagerClient.prototype={traceEventsCollected(events){},tracingComplete(){},tracingBufferUsage(usage){},eventsRetrievalProgress(progress){}};SDK.TracingManager=class extends SDK.SDKModel{constructor(target){super(target);this._tracingAgent=target.tracingAgent();target.registerTracingDispatcher(new SDK.TracingDispatcher(this));this._activeClient=null;this._eventBufferSize=0;this._eventsRetrieved=0;} -_bufferUsage(usage,eventCount,percentFull){this._eventBufferSize=eventCount;this._activeClient.tracingBufferUsage(usage||percentFull||0);} -_eventsCollected(events){this._activeClient.traceEventsCollected(events);this._eventsRetrieved+=events.length;if(!this._eventBufferSize) -return;if(this._eventsRetrieved>this._eventBufferSize) -this._eventsRetrieved=this._eventBufferSize;this._activeClient.eventsRetrievalProgress(this._eventsRetrieved/this._eventBufferSize);} -_tracingComplete(){this._eventBufferSize=0;this._eventsRetrieved=0;this._activeClient.tracingComplete();this._activeClient=null;this._finishing=false;} -start(client,categoryFilter,options){if(this._activeClient) -throw new Error('Tracing is already started');var bufferUsageReportingIntervalMs=500;this._activeClient=client;return this._tracingAgent.start(categoryFilter,options,bufferUsageReportingIntervalMs,SDK.TracingManager.TransferMode.ReportEvents);} -stop(){if(!this._activeClient) -throw new Error('Tracing is not started');if(this._finishing) -throw new Error('Tracing is already being stopped');this._finishing=true;this._tracingAgent.end();}};SDK.SDKModel.register(SDK.TracingManager,SDK.Target.Capability.Tracing,false);SDK.TracingManager.EventPayload;SDK.TracingManager.TransferMode={ReportEvents:'ReportEvents',ReturnAsStream:'ReturnAsStream'};SDK.TracingDispatcher=class{constructor(tracingManager){this._tracingManager=tracingManager;} -bufferUsage(usage,eventCount,percentFull){this._tracingManager._bufferUsage(usage,eventCount,percentFull);} -dataCollected(data){this._tracingManager._eventsCollected(data);} -tracingComplete(){this._tracingManager._tracingComplete();}};;SDK.TracingModel=class{constructor(backingStorage){this._backingStorage=backingStorage;this._firstWritePending=true;this._processById=new Map();this._processByName=new Map();this._minimumRecordTime=0;this._maximumRecordTime=0;this._devToolsMetadataEvents=[];this._asyncEvents=[];this._openAsyncEvents=new Map();this._openNestableAsyncEvents=new Map();this._profileGroups=new Map();this._parsedCategories=new Map();} -static isNestableAsyncPhase(phase){return phase==='b'||phase==='e'||phase==='n';} -static isAsyncBeginPhase(phase){return phase==='S'||phase==='b';} -static isAsyncPhase(phase){return SDK.TracingModel.isNestableAsyncPhase(phase)||phase==='S'||phase==='T'||phase==='F'||phase==='p';} -static isFlowPhase(phase){return phase==='s'||phase==='t'||phase==='f';} -static isTopLevelEvent(event){return event.hasCategory(SDK.TracingModel.TopLevelEventCategory)||event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory)&&event.name==='Program';} -static _extractId(payload){var scope=payload.scope||'';if(typeof payload.id2==='undefined') -return scope&&payload.id?`${scope}@${payload.id}`:payload.id;var id2=payload.id2;if(typeof id2==='object'&&('global'in id2)!==('local'in id2)){return typeof id2['global']!=='undefined'?`:${scope}:${id2['global']}`:`:${scope}:${payload.pid}:${id2['local']}`;} -console.error(`Unexpected id2 field at ${payload.ts / 1000}, one and only one of 'local' and 'global' should be present.`);} -static browserMainThread(tracingModel){var processes=tracingModel.sortedProcesses();if(!processes.length) -return null;var browserProcesses=[];var crRendererMainThreads=[];for(var process of processes){if(process.name().toLowerCase().endsWith('browser')) -browserProcesses.push(process);crRendererMainThreads.push(...process.sortedThreads().filter(t=>t.name()==='CrBrowserMain'));} -if(crRendererMainThreads.length===1) -return crRendererMainThreads[0];if(browserProcesses.length===1) -return browserProcesses[0].threadByName('CrBrowserMain');var tracingStartedInBrowser=tracingModel.devToolsMetadataEvents().filter(e=>e.name==='TracingStartedInBrowser');if(tracingStartedInBrowser.length===1) -return tracingStartedInBrowser[0].thread;Common.console.error('Failed to find browser main thread in trace, some timeline features may be unavailable');return null;} -devToolsMetadataEvents(){return this._devToolsMetadataEvents;} -addEvents(events){for(var i=0;i<events.length;++i) -this._addEvent(events[i]);} -tracingComplete(){this._processPendingAsyncEvents();this._backingStorage.appendString(this._firstWritePending?'[]':']');this._backingStorage.finishWriting();this._firstWritePending=false;for(var process of this._processById.values()){for(var thread of process._threads.values()) -thread.tracingComplete();}} -dispose(){if(!this._firstWritePending) -this._backingStorage.reset();} -adjustTime(offset){this._minimumRecordTime+=offset;this._maximumRecordTime+=offset;for(const process of this._processById.values()){for(const thread of process._threads.values()){for(const event of thread.events()){event.startTime+=offset;if(typeof event.endTime==='number') -event.endTime+=offset;} -for(const event of thread.asyncEvents()){event.startTime+=offset;if(typeof event.endTime==='number') -event.endTime+=offset;}}}} -_addEvent(payload){var process=this._processById.get(payload.pid);if(!process){process=new SDK.TracingModel.Process(this,payload.pid);this._processById.set(payload.pid,process);} -const phase=SDK.TracingModel.Phase;const eventsDelimiter=',\n';this._backingStorage.appendString(this._firstWritePending?'[':eventsDelimiter);this._firstWritePending=false;var stringPayload=JSON.stringify(payload);var isAccessible=payload.ph===phase.SnapshotObject;var backingStorage=null;var keepStringsLessThan=10000;if(isAccessible&&stringPayload.length>keepStringsLessThan) -backingStorage=this._backingStorage.appendAccessibleString(stringPayload);else -this._backingStorage.appendString(stringPayload);const timestamp=payload.ts/1000;if(timestamp&&(!this._minimumRecordTime||timestamp<this._minimumRecordTime)&&(payload.ph===phase.Begin||payload.ph===phase.Complete||payload.ph===phase.Instant)) -this._minimumRecordTime=timestamp;const endTimeStamp=(payload.ts+(payload.dur||0))/1000;this._maximumRecordTime=Math.max(this._maximumRecordTime,endTimeStamp);const event=process._addEvent(payload);if(!event) -return;if(payload.ph===phase.Sample){this._addSampleEvent(event);return;} -if(SDK.TracingModel.isAsyncPhase(payload.ph)) -this._asyncEvents.push(event);event._setBackingStorage(backingStorage);if(event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory)) -this._devToolsMetadataEvents.push(event);if(payload.ph!==phase.Metadata) -return;switch(payload.name){case SDK.TracingModel.MetadataEvent.ProcessSortIndex:process._setSortIndex(payload.args['sort_index']);break;case SDK.TracingModel.MetadataEvent.ProcessName:var processName=payload.args['name'];process._setName(processName);this._processByName.set(processName,process);break;case SDK.TracingModel.MetadataEvent.ThreadSortIndex:process.threadById(payload.tid)._setSortIndex(payload.args['sort_index']);break;case SDK.TracingModel.MetadataEvent.ThreadName:process.threadById(payload.tid)._setName(payload.args['name']);break;}} -_addSampleEvent(event){var group=this._profileGroups.get(event.id);if(group) -group._addChild(event);else -this._profileGroups.set(event.id,new SDK.TracingModel.ProfileEventsGroup(event));} -profileGroup(id){return this._profileGroups.get(id)||null;} -minimumRecordTime(){return this._minimumRecordTime;} -maximumRecordTime(){return this._maximumRecordTime;} -sortedProcesses(){return SDK.TracingModel.NamedObject._sort(this._processById.valuesArray());} -processByName(name){return this._processByName.get(name);} -threadByName(processName,threadName){var process=this.processByName(processName);return process&&process.threadByName(threadName);} -_processPendingAsyncEvents(){this._asyncEvents.stableSort(SDK.TracingModel.Event.compareStartTime);for(var i=0;i<this._asyncEvents.length;++i){var event=this._asyncEvents[i];if(SDK.TracingModel.isNestableAsyncPhase(event.phase)) -this._addNestableAsyncEvent(event);else -this._addAsyncEvent(event);} -this._asyncEvents=[];this._closeOpenAsyncEvents();} -_closeOpenAsyncEvents(){for(var event of this._openAsyncEvents.values()){event.setEndTime(this._maximumRecordTime);event.steps[0].setEndTime(this._maximumRecordTime);} -this._openAsyncEvents.clear();for(var eventStack of this._openNestableAsyncEvents.values()){while(eventStack.length) -eventStack.pop().setEndTime(this._maximumRecordTime);} -this._openNestableAsyncEvents.clear();} -_addNestableAsyncEvent(event){var phase=SDK.TracingModel.Phase;var key=event.categoriesString+'.'+event.id;var openEventsStack=this._openNestableAsyncEvents.get(key);switch(event.phase){case phase.NestableAsyncBegin:if(!openEventsStack){openEventsStack=[];this._openNestableAsyncEvents.set(key,openEventsStack);} -var asyncEvent=new SDK.TracingModel.AsyncEvent(event);openEventsStack.push(asyncEvent);event.thread._addAsyncEvent(asyncEvent);break;case phase.NestableAsyncInstant:if(openEventsStack&&openEventsStack.length) -openEventsStack.peekLast()._addStep(event);break;case phase.NestableAsyncEnd:if(!openEventsStack||!openEventsStack.length) -break;var top=openEventsStack.pop();if(top.name!==event.name){console.error(`Begin/end event mismatch for nestable async event, ${top.name} vs. ${event.name}, key: ${key}`);break;} -top._addStep(event);}} -_addAsyncEvent(event){var phase=SDK.TracingModel.Phase;var key=event.categoriesString+'.'+event.name+'.'+event.id;var asyncEvent=this._openAsyncEvents.get(key);if(event.phase===phase.AsyncBegin){if(asyncEvent){console.error(`Event ${event.name} has already been started`);return;} -asyncEvent=new SDK.TracingModel.AsyncEvent(event);this._openAsyncEvents.set(key,asyncEvent);event.thread._addAsyncEvent(asyncEvent);return;} -if(!asyncEvent){return;} -if(event.phase===phase.AsyncEnd){asyncEvent._addStep(event);this._openAsyncEvents.delete(key);return;} -if(event.phase===phase.AsyncStepInto||event.phase===phase.AsyncStepPast){var lastStep=asyncEvent.steps.peekLast();if(lastStep.phase!==phase.AsyncBegin&&lastStep.phase!==event.phase){console.assert(false,'Async event step phase mismatch: '+lastStep.phase+' at '+lastStep.startTime+' vs. '+ -event.phase+' at '+event.startTime);return;} -asyncEvent._addStep(event);return;} -console.assert(false,'Invalid async event phase');} -backingStorage(){return this._backingStorage;} -_parsedCategoriesForString(str){var parsedCategories=this._parsedCategories.get(str);if(!parsedCategories){parsedCategories=new Set(str.split(','));this._parsedCategories.set(str,parsedCategories);} -return parsedCategories;}};SDK.TracingModel.Phase={Begin:'B',End:'E',Complete:'X',Instant:'I',AsyncBegin:'S',AsyncStepInto:'T',AsyncStepPast:'p',AsyncEnd:'F',NestableAsyncBegin:'b',NestableAsyncEnd:'e',NestableAsyncInstant:'n',FlowBegin:'s',FlowStep:'t',FlowEnd:'f',Metadata:'M',Counter:'C',Sample:'P',CreateObject:'N',SnapshotObject:'O',DeleteObject:'D'};SDK.TracingModel.MetadataEvent={ProcessSortIndex:'process_sort_index',ProcessName:'process_name',ThreadSortIndex:'thread_sort_index',ThreadName:'thread_name'};SDK.TracingModel.TopLevelEventCategory='toplevel';SDK.TracingModel.DevToolsMetadataEventCategory='disabled-by-default-devtools.timeline';SDK.TracingModel.DevToolsTimelineEventCategory='disabled-by-default-devtools.timeline';SDK.TracingModel.FrameLifecycleEventCategory='cc,devtools';SDK.BackingStorage=function(){};SDK.BackingStorage.prototype={appendString(string){},appendAccessibleString(string){},finishWriting(){},reset(){}};SDK.TracingModel.Event=class{constructor(categories,name,phase,startTime,thread){this.categoriesString=categories;this._parsedCategories=thread._model._parsedCategoriesForString(categories);this.name=name;this.phase=phase;this.startTime=startTime;this.thread=thread;this.args={};this.selfTime=0;} -static fromPayload(payload,thread){var event=new SDK.TracingModel.Event(payload.cat,payload.name,(payload.ph),payload.ts/1000,thread);if(payload.args) -event.addArgs(payload.args);else -console.error('Missing mandatory event argument \'args\' at '+payload.ts/1000);if(typeof payload.dur==='number') -event.setEndTime((payload.ts+payload.dur)/1000);var id=SDK.TracingModel._extractId(payload);if(typeof id!=='undefined') -event.id=id;if(payload.bind_id) -event.bind_id=payload.bind_id;return event;} -static compareStartTime(a,b){return a.startTime-b.startTime;} -static compareStartAndEndTime(a,b){return a.startTime-b.startTime||(b.endTime!==undefined&&a.endTime!==undefined&&b.endTime-a.endTime)||0;} -static orderedCompareStartTime(a,b){return a.startTime-b.startTime||a.ordinal-b.ordinal||-1;} -hasCategory(categoryName){return this._parsedCategories.has(categoryName);} -setEndTime(endTime){if(endTime<this.startTime){console.assert(false,'Event out of order: '+this.name);return;} -this.endTime=endTime;this.duration=endTime-this.startTime;} -addArgs(args){for(var name in args){if(name in this.args) -console.error('Same argument name ('+name+') is used for begin and end phases of '+this.name);this.args[name]=args[name];}} -_complete(endEvent){if(endEvent.args) -this.addArgs(endEvent.args);else -console.error('Missing mandatory event argument \'args\' at '+endEvent.startTime);this.setEndTime(endEvent.startTime);} -_setBackingStorage(backingStorage){}};SDK.TracingModel.ObjectSnapshot=class extends SDK.TracingModel.Event{constructor(category,name,startTime,thread){super(category,name,SDK.TracingModel.Phase.SnapshotObject,startTime,thread);this._backingStorage=null;this.id;this._objectPromise=null;} -static fromPayload(payload,thread){var snapshot=new SDK.TracingModel.ObjectSnapshot(payload.cat,payload.name,payload.ts/1000,thread);var id=SDK.TracingModel._extractId(payload);if(typeof id!=='undefined') -snapshot.id=id;if(!payload.args||!payload.args['snapshot']){console.error('Missing mandatory \'snapshot\' argument at '+payload.ts/1000);return snapshot;} -if(payload.args) -snapshot.addArgs(payload.args);return snapshot;} -requestObject(callback){var snapshot=this.args['snapshot'];if(snapshot){callback(snapshot);return;} -this._backingStorage().then(onRead,callback.bind(null,null));function onRead(result){if(!result){callback(null);return;} -try{var payload=JSON.parse(result);callback(payload['args']['snapshot']);}catch(e){Common.console.error('Malformed event data in backing storage');callback(null);}}} -objectPromise(){if(!this._objectPromise) -this._objectPromise=new Promise(this.requestObject.bind(this));return this._objectPromise;} -_setBackingStorage(backingStorage){if(!backingStorage) -return;this._backingStorage=backingStorage;this.args={};}};SDK.TracingModel.AsyncEvent=class extends SDK.TracingModel.Event{constructor(startEvent){super(startEvent.categoriesString,startEvent.name,startEvent.phase,startEvent.startTime,startEvent.thread);this.addArgs(startEvent.args);this.steps=[startEvent];} -_addStep(event){this.steps.push(event);if(event.phase===SDK.TracingModel.Phase.AsyncEnd||event.phase===SDK.TracingModel.Phase.NestableAsyncEnd){this.setEndTime(event.startTime);this.steps[0].setEndTime(event.startTime);}}};SDK.TracingModel.ProfileEventsGroup=class{constructor(event){this.children=[event];} -_addChild(event){this.children.push(event);}};SDK.TracingModel.NamedObject=class{constructor(model,id){this._model=model;this._id=id;this._name='';this._sortIndex=0;} -static _sort(array){function comparator(a,b){return a._sortIndex!==b._sortIndex?a._sortIndex-b._sortIndex:a.name().localeCompare(b.name());} -return array.sort(comparator);} -_setName(name){this._name=name;} -name(){return this._name;} -_setSortIndex(sortIndex){this._sortIndex=sortIndex;}};SDK.TracingModel.Process=class extends SDK.TracingModel.NamedObject{constructor(model,id){super(model,id);this._threads=new Map();this._threadByName=new Map();} -id(){return this._id;} -threadById(id){var thread=this._threads.get(id);if(!thread){thread=new SDK.TracingModel.Thread(this,id);this._threads.set(id,thread);} -return thread;} -threadByName(name){return this._threadByName.get(name)||null;} -_setThreadByName(name,thread){this._threadByName.set(name,thread);} -_addEvent(payload){return this.threadById(payload.tid)._addEvent(payload);} -sortedThreads(){return SDK.TracingModel.NamedObject._sort(this._threads.valuesArray());}};SDK.TracingModel.Thread=class extends SDK.TracingModel.NamedObject{constructor(process,id){super(process._model,id);this._process=process;this._events=[];this._asyncEvents=[];this._lastTopLevelEvent=null;} -tracingComplete(){this._asyncEvents.stableSort(SDK.TracingModel.Event.compareStartAndEndTime);this._events.stableSort(SDK.TracingModel.Event.compareStartTime);var phases=SDK.TracingModel.Phase;var stack=[];for(var i=0;i<this._events.length;++i){var e=this._events[i];e.ordinal=i;switch(e.phase){case phases.End:this._events[i]=null;if(!stack.length) -continue;var top=stack.pop();if(top.name!==e.name||top.categoriesString!==e.categoriesString){console.error('B/E events mismatch at '+top.startTime+' ('+top.name+') vs. '+e.startTime+' ('+e.name+')');}else{top._complete(e);} -break;case phases.Begin:stack.push(e);break;}} -while(stack.length) -stack.pop().setEndTime(this._model.maximumRecordTime());this._events.remove(null,false);} -_addEvent(payload){var event=payload.ph===SDK.TracingModel.Phase.SnapshotObject?SDK.TracingModel.ObjectSnapshot.fromPayload(payload,this):SDK.TracingModel.Event.fromPayload(payload,this);if(SDK.TracingModel.isTopLevelEvent(event)){if(this._lastTopLevelEvent&&this._lastTopLevelEvent.endTime>event.startTime) -return null;this._lastTopLevelEvent=event;} -this._events.push(event);return event;} -_addAsyncEvent(asyncEvent){this._asyncEvents.push(asyncEvent);} -_setName(name){super._setName(name);this._process._setThreadByName(name,this);} -id(){return this._id;} -process(){return this._process;} -events(){return this._events;} -asyncEvents(){return this._asyncEvents;}};;SDK.OverlayModel=class extends SDK.SDKModel{constructor(target){super(target);this._domModel=(target.model(SDK.DOMModel));target.registerOverlayDispatcher(this);this._overlayAgent=target.overlayAgent();this._overlayAgent.enable();this._overlayAgent.setShowViewportSizeOnResize(true);this._debuggerModel=target.model(SDK.DebuggerModel);if(this._debuggerModel){Common.moduleSetting('disablePausedStateOverlay').addChangeListener(this._updatePausedInDebuggerMessage,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerPaused,this._updatePausedInDebuggerMessage,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerResumed,this._updatePausedInDebuggerMessage,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._updatePausedInDebuggerMessage,this);} -this._inspectModeEnabled=false;this._hideHighlightTimeout=null;this._defaultHighlighter=new SDK.OverlayModel.DefaultHighlighter(this);this._highlighter=this._defaultHighlighter;this._showPaintRectsSetting=Common.moduleSetting('showPaintRects');this._showPaintRectsSetting.addChangeListener(()=>this._overlayAgent.setShowPaintRects(this._showPaintRectsSetting.get()));if(this._showPaintRectsSetting.get()) -this._overlayAgent.setShowPaintRects(true);this._showDebugBordersSetting=Common.moduleSetting('showDebugBorders');this._showDebugBordersSetting.addChangeListener(()=>this._overlayAgent.setShowDebugBorders(this._showDebugBordersSetting.get()));if(this._showDebugBordersSetting.get()) -this._overlayAgent.setShowDebugBorders(true);this._showFPSCounterSetting=Common.moduleSetting('showFPSCounter');this._showFPSCounterSetting.addChangeListener(()=>this._overlayAgent.setShowFPSCounter(this._showFPSCounterSetting.get()));if(this._showFPSCounterSetting.get()) -this._overlayAgent.setShowFPSCounter(true);this._showScrollBottleneckRectsSetting=Common.moduleSetting('showScrollBottleneckRects');this._showScrollBottleneckRectsSetting.addChangeListener(()=>this._overlayAgent.setShowScrollBottleneckRects(this._showScrollBottleneckRectsSetting.get()));if(this._showScrollBottleneckRectsSetting.get()) -this._overlayAgent.setShowScrollBottleneckRects(true);} -static highlightObjectAsDOMNode(object){var domModel=object.runtimeModel().target().model(SDK.DOMModel);if(domModel) -domModel.overlayModel().highlightDOMNode(undefined,undefined,undefined,object.objectId);} -static hideDOMNodeHighlight(){for(var overlayModel of SDK.targetManager.models(SDK.OverlayModel)) -overlayModel.highlightDOMNode(0);} -static muteHighlight(){SDK.OverlayModel.hideDOMNodeHighlight();SDK.OverlayModel._highlightDisabled=true;} -static unmuteHighlight(){SDK.OverlayModel._highlightDisabled=false;} -suspendModel(){return this._overlayAgent.setSuspended(true);} -resumeModel(){return this._overlayAgent.setSuspended(false);} -setShowViewportSizeOnResize(show){this._overlayAgent.setShowViewportSizeOnResize(show);} -_updatePausedInDebuggerMessage(){var message=this._debuggerModel.isPaused()&&!Common.moduleSetting('disablePausedStateOverlay').get()?Common.UIString('Paused in debugger'):undefined;this._overlayAgent.setPausedInDebuggerMessage(message);} -setHighlighter(highlighter){this._highlighter=highlighter||this._defaultHighlighter;} -async setInspectMode(mode){await this._domModel.requestDocumentPromise();this._inspectModeEnabled=mode!==Protocol.Overlay.InspectMode.None;this.dispatchEventToListeners(SDK.OverlayModel.Events.InspectModeWillBeToggled,this);this._highlighter.setInspectMode(mode,this._buildHighlightConfig());} -inspectModeEnabled(){return this._inspectModeEnabled;} -highlightDOMNode(nodeId,mode,backendNodeId,objectId){this.highlightDOMNodeWithConfig(nodeId,{mode:mode},backendNodeId,objectId);} -highlightDOMNodeWithConfig(nodeId,config,backendNodeId,objectId){if(SDK.OverlayModel._highlightDisabled) -return;config=config||{mode:'all',showInfo:undefined,selectors:undefined};if(this._hideHighlightTimeout){clearTimeout(this._hideHighlightTimeout);this._hideHighlightTimeout=null;} -var highlightConfig=this._buildHighlightConfig(config.mode);if(typeof config.showInfo!=='undefined') -highlightConfig.showInfo=config.showInfo;if(typeof config.selectors!=='undefined') -highlightConfig.selectorList=config.selectors;this._highlighter.highlightDOMNode(this._domModel.nodeForId(nodeId||0),highlightConfig,backendNodeId,objectId);} -highlightDOMNodeForTwoSeconds(nodeId){this.highlightDOMNode(nodeId);this._hideHighlightTimeout=setTimeout(()=>this.highlightDOMNode(0),2000);} -highlightFrame(frameId){if(SDK.OverlayModel._highlightDisabled) -return;this._highlighter.highlightFrame(frameId);} -_buildHighlightConfig(mode){mode=mode||'all';var showRulers=Common.moduleSetting('showMetricsRulers').get();var highlightConfig={showInfo:mode==='all',showRulers:showRulers,showExtensionLines:showRulers};if(mode==='all'||mode==='content') -highlightConfig.contentColor=Common.Color.PageHighlight.Content.toProtocolRGBA();if(mode==='all'||mode==='padding') -highlightConfig.paddingColor=Common.Color.PageHighlight.Padding.toProtocolRGBA();if(mode==='all'||mode==='border') -highlightConfig.borderColor=Common.Color.PageHighlight.Border.toProtocolRGBA();if(mode==='all'||mode==='margin') -highlightConfig.marginColor=Common.Color.PageHighlight.Margin.toProtocolRGBA();if(mode==='all'){highlightConfig.eventTargetColor=Common.Color.PageHighlight.EventTarget.toProtocolRGBA();highlightConfig.shapeColor=Common.Color.PageHighlight.Shape.toProtocolRGBA();highlightConfig.shapeMarginColor=Common.Color.PageHighlight.ShapeMargin.toProtocolRGBA();highlightConfig.displayAsMaterial=true;} -if(mode==='all') -highlightConfig.cssGridColor=Common.Color.PageHighlight.CssGrid.toProtocolRGBA();return highlightConfig;} -nodeHighlightRequested(nodeId){var node=this._domModel.nodeForId(nodeId);if(node) -this.dispatchEventToListeners(SDK.OverlayModel.Events.HighlightNodeRequested,node);} -inspectNodeRequested(backendNodeId){var deferredNode=new SDK.DeferredDOMNode(this.target(),backendNodeId);this.dispatchEventToListeners(SDK.OverlayModel.Events.InspectNodeRequested,deferredNode);} -screenshotRequested(viewport){this.dispatchEventToListeners(SDK.OverlayModel.Events.ScreenshotRequested,viewport);}};SDK.SDKModel.register(SDK.OverlayModel,SDK.Target.Capability.DOM,true);SDK.OverlayModel.Events={InspectModeWillBeToggled:Symbol('InspectModeWillBeToggled'),HighlightNodeRequested:Symbol('HighlightNodeRequested'),InspectNodeRequested:Symbol('InspectNodeRequested'),ScreenshotRequested:Symbol('ScreenshotRequested'),};SDK.OverlayModel.Highlighter=function(){};SDK.OverlayModel.Highlighter.prototype={highlightDOMNode(node,config,backendNodeId,objectId){},setInspectMode(mode,config){},highlightFrame(frameId){}};SDK.OverlayModel.DefaultHighlighter=class{constructor(model){this._model=model;} -highlightDOMNode(node,config,backendNodeId,objectId){if(objectId||node||backendNodeId){this._model._overlayAgent.highlightNode(config,(objectId||backendNodeId)?undefined:node.id,backendNodeId,objectId);}else{this._model._overlayAgent.hideHighlight();}} -setInspectMode(mode,config){return this._model._overlayAgent.setInspectMode(mode,config);} -highlightFrame(frameId){this._model._overlayAgent.highlightFrame(frameId,Common.Color.PageHighlight.Content.toProtocolRGBA(),Common.Color.PageHighlight.ContentOutline.toProtocolRGBA());}};;SDK.RuntimeModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.runtimeAgent();this.target().registerRuntimeDispatcher(new SDK.RuntimeDispatcher(this));this._agent.enable();this._executionContextById=new Map();this._executionContextComparator=SDK.ExecutionContext.comparator;if(Common.moduleSetting('customFormatters').get()) -this._agent.setCustomObjectFormatterEnabled(true);Common.moduleSetting('customFormatters').addChangeListener(this._customFormattersStateChanged.bind(this));} -static wrapObjectLiteralExpressionIfNeeded(code){if(!(/^\s*\{/.test(code)&&/\}\s*$/.test(code))) -return code;var parse=(async()=>0).constructor;try{parse('return '+code+';');var wrappedCode='('+code+')';parse(wrappedCode);return wrappedCode;}catch(e){return code;}} -debuggerModel(){return(this.target().model(SDK.DebuggerModel));} -heapProfilerModel(){return(this.target().model(SDK.HeapProfilerModel));} -executionContexts(){return this._executionContextById.valuesArray().sort(this.executionContextComparator());} -setExecutionContextComparator(comparator){this._executionContextComparator=comparator;} -executionContextComparator(){return this._executionContextComparator;} -defaultExecutionContext(){for(var context of this.executionContexts()){if(context.isDefault) -return context;} -return null;} -executionContext(id){return this._executionContextById.get(id)||null;} -_executionContextCreated(context){var data=context.auxData||{isDefault:true};var executionContext=new SDK.ExecutionContext(this,context.id,context.name,context.origin,data['isDefault'],data['frameId']);this._executionContextById.set(executionContext.id,executionContext);this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextCreated,executionContext);} -_executionContextDestroyed(executionContextId){var executionContext=this._executionContextById.get(executionContextId);if(!executionContext) -return;this.debuggerModel().executionContextDestroyed(executionContext);this._executionContextById.delete(executionContextId);this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextDestroyed,executionContext);} -fireExecutionContextOrderChanged(){this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextOrderChanged,this);} -_executionContextsCleared(){this.debuggerModel().globalObjectCleared();var contexts=this.executionContexts();this._executionContextById.clear();for(var i=0;i<contexts.length;++i) -this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextDestroyed,contexts[i]);} -createRemoteObject(payload){console.assert(typeof payload==='object','Remote object payload should only be an object');return new SDK.RemoteObjectImpl(this,payload.objectId,payload.type,payload.subtype,payload.value,payload.unserializableValue,payload.description,payload.preview,payload.customPreview);} -createScopeRemoteObject(payload,scopeRef){return new SDK.ScopeRemoteObject(this,payload.objectId,scopeRef,payload.type,payload.subtype,payload.value,payload.unserializableValue,payload.description,payload.preview);} -createRemoteObjectFromPrimitiveValue(value){var type=typeof value;var unserializableValue=undefined;if(typeof value==='number'){var description=String(value);if(value===0&&1/value<0) -unserializableValue=Protocol.Runtime.UnserializableValue.Negative0;if(description==='NaN') -unserializableValue=Protocol.Runtime.UnserializableValue.NaN;if(description==='Infinity') -unserializableValue=Protocol.Runtime.UnserializableValue.Infinity;if(description==='-Infinity') -unserializableValue=Protocol.Runtime.UnserializableValue.NegativeInfinity;if(typeof unserializableValue!=='undefined') -value=undefined;} -return new SDK.RemoteObjectImpl(this,undefined,type,undefined,value,unserializableValue);} -createRemotePropertyFromPrimitiveValue(name,value){return new SDK.RemoteObjectProperty(name,this.createRemoteObjectFromPrimitiveValue(value));} -discardConsoleEntries(){this._agent.discardConsoleEntries();} -releaseObjectGroup(objectGroupName){this._agent.releaseObjectGroup(objectGroupName);} -runIfWaitingForDebugger(){this._agent.runIfWaitingForDebugger();} -_customFormattersStateChanged(event){var enabled=(event.data);this._agent.setCustomObjectFormatterEnabled(enabled);} -async compileScript(expression,sourceURL,persistScript,executionContextId){var response=await this._agent.invoke_compileScript({expression:expression,sourceURL:sourceURL,persistScript:persistScript,executionContextId:executionContextId});if(response[Protocol.Error]){console.error(response[Protocol.Error]);return null;} -return{scriptId:response.scriptId,exceptionDetails:response.exceptionDetails};} -async runScript(scriptId,executionContextId,objectGroup,silent,includeCommandLineAPI,returnByValue,generatePreview,awaitPromise){var response=await this._agent.invoke_runScript({scriptId,executionContextId,objectGroup,silent,includeCommandLineAPI,returnByValue,generatePreview,awaitPromise});var error=response[Protocol.Error];if(error){console.error(error);return{error:error};} -return{object:this.createRemoteObject(response.result),exceptionDetails:response.exceptionDetails};} -async queryObjects(prototype){if(!prototype.objectId) -return{error:'Prototype should be an Object.'};var response=await this._agent.invoke_queryObjects({prototypeObjectId:(prototype.objectId)});var error=response[Protocol.Error];if(error){console.error(error);return{error:error};} -return{objects:this.createRemoteObject(response.objects)};} -_inspectRequested(payload,hints){var object=this.createRemoteObject(payload);if(hints.copyToClipboard){this._copyRequested(object);return;} -if(hints.queryObjects){this._queryObjectsRequested(object);return;} -if(object.isNode()){Common.Revealer.revealPromise(object).then(object.release.bind(object));return;} -if(object.type==='function'){SDK.RemoteFunction.objectAsFunction(object).targetFunctionDetails().then(didGetDetails);return;} -function didGetDetails(response){object.release();if(!response||!response.location) -return;Common.Revealer.reveal(response.location);} -object.release();} -_copyRequested(object){if(!object.objectId){InspectorFrontendHost.copyText(object.value);return;} -object.callFunctionJSON(toStringForClipboard,[{value:object.subtype}],InspectorFrontendHost.copyText.bind(InspectorFrontendHost));function toStringForClipboard(subtype){if(subtype==='node') -return this.outerHTML;if(subtype&&typeof this==='undefined') -return subtype+'';try{return JSON.stringify(this,null,' ');}catch(e){return''+this;}}} -async _queryObjectsRequested(object){var result=await this.queryObjects(object);object.release();if(result.error){Common.console.error(result.error);return;} -this.dispatchEventToListeners(SDK.RuntimeModel.Events.QueryObjectRequested,{objects:result.objects});} -static simpleTextFromException(exceptionDetails){var text=exceptionDetails.text;if(exceptionDetails.exception&&exceptionDetails.exception.description){var description=exceptionDetails.exception.description;if(description.indexOf('\n')!==-1) -description=description.substring(0,description.indexOf('\n'));text+=' '+description;} -return text;} -exceptionThrown(timestamp,exceptionDetails){var exceptionWithTimestamp={timestamp:timestamp,details:exceptionDetails};this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExceptionThrown,exceptionWithTimestamp);} -_exceptionRevoked(exceptionId){this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExceptionRevoked,exceptionId);} -_consoleAPICalled(type,args,executionContextId,timestamp,stackTrace,context){var consoleAPICall={type:type,args:args,executionContextId:executionContextId,timestamp:timestamp,stackTrace:stackTrace,context:context};this.dispatchEventToListeners(SDK.RuntimeModel.Events.ConsoleAPICalled,consoleAPICall);} -executionContextIdForScriptId(scriptId){var script=this.debuggerModel().scriptForId(scriptId);return script?script.executionContextId:0;} -executionContextForStackTrace(stackTrace){while(stackTrace&&!stackTrace.callFrames.length) -stackTrace=stackTrace.parent;if(!stackTrace||!stackTrace.callFrames.length) -return 0;return this.executionContextIdForScriptId(stackTrace.callFrames[0].scriptId);}};SDK.SDKModel.register(SDK.RuntimeModel,SDK.Target.Capability.JS,true);SDK.RuntimeModel.Events={ExecutionContextCreated:Symbol('ExecutionContextCreated'),ExecutionContextDestroyed:Symbol('ExecutionContextDestroyed'),ExecutionContextChanged:Symbol('ExecutionContextChanged'),ExecutionContextOrderChanged:Symbol('ExecutionContextOrderChanged'),ExceptionThrown:Symbol('ExceptionThrown'),ExceptionRevoked:Symbol('ExceptionRevoked'),ConsoleAPICalled:Symbol('ConsoleAPICalled'),QueryObjectRequested:Symbol('QueryObjectRequested'),};SDK.RuntimeModel.ExceptionWithTimestamp;SDK.RuntimeModel.CompileScriptResult;SDK.RuntimeModel.EvaluationOptions;SDK.RuntimeModel.EvaluationResult;SDK.RuntimeModel.QueryObjectResult;SDK.RuntimeModel.ConsoleAPICall;SDK.RuntimeDispatcher=class{constructor(runtimeModel){this._runtimeModel=runtimeModel;} -executionContextCreated(context){this._runtimeModel._executionContextCreated(context);} -executionContextDestroyed(executionContextId){this._runtimeModel._executionContextDestroyed(executionContextId);} -executionContextsCleared(){this._runtimeModel._executionContextsCleared();} -exceptionThrown(timestamp,exceptionDetails){this._runtimeModel.exceptionThrown(timestamp,exceptionDetails);} -exceptionRevoked(reason,exceptionId){this._runtimeModel._exceptionRevoked(exceptionId);} -consoleAPICalled(type,args,executionContextId,timestamp,stackTrace,context){this._runtimeModel._consoleAPICalled(type,args,executionContextId,timestamp,stackTrace,context);} -inspectRequested(payload,hints){this._runtimeModel._inspectRequested(payload,hints);}};SDK.ExecutionContext=class{constructor(runtimeModel,id,name,origin,isDefault,frameId){this.id=id;this.name=name;this.origin=origin;this.isDefault=isDefault;this.runtimeModel=runtimeModel;this.debuggerModel=runtimeModel.debuggerModel();this.frameId=frameId;this._setLabel('');} -target(){return this.runtimeModel.target();} -static comparator(a,b){function targetWeight(target){if(!target.parentTarget()) -return 4;if(target.hasBrowserCapability()) -return 3;if(target.hasJSCapability()) -return 2;return 1;} -var weightDiff=targetWeight(a.target())-targetWeight(b.target());if(weightDiff) -return-weightDiff;if(a.isDefault) -return-1;if(b.isDefault) -return+1;return a.name.localeCompare(b.name);} -evaluate(options,userGesture,awaitPromise){if(this.debuggerModel.selectedCallFrame()) -return this.debuggerModel.evaluateOnSelectedCallFrame(options);return this._evaluateGlobal(options,userGesture,awaitPromise);} -globalObject(objectGroup,generatePreview){return this._evaluateGlobal({expression:'this',objectGroup:objectGroup,includeCommandLineAPI:false,silent:true,returnByValue:false,generatePreview:generatePreview},false,false);} -async _evaluateGlobal(options,userGesture,awaitPromise){if(!options.expression){options.expression='this';} -var response=await this.runtimeModel._agent.invoke_evaluate({expression:options.expression,objectGroup:options.objectGroup,includeCommandLineAPI:options.includeCommandLineAPI,silent:options.silent,contextId:this.id,returnByValue:options.returnByValue,generatePreview:options.generatePreview,userGesture:userGesture,awaitPromise:awaitPromise});var error=response[Protocol.Error];if(error){console.error(error);return{error:error};} -return{object:this.runtimeModel.createRemoteObject(response.result),exceptionDetails:response.exceptionDetails};} -async globalLexicalScopeNames(){var response=await this.runtimeModel._agent.invoke_globalLexicalScopeNames({executionContextId:this.id});return response[Protocol.Error]?[]:response.names;} -label(){return this._label;} -setLabel(label){this._setLabel(label);this.runtimeModel.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextChanged,this);} -_setLabel(label){if(label){this._label=label;return;} -if(this.name){this._label=this.name;return;} -var parsedUrl=this.origin.asParsedURL();this._label=parsedUrl?parsedUrl.lastPathComponentWithFragment():'';}};;SDK.ScreenCaptureModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.pageAgent();this._onScreencastFrame=null;this._onScreencastVisibilityChanged=null;target.registerPageDispatcher(this);} -startScreencast(format,quality,width,height,everyNthFrame,onFrame,onVisibilityChanged){this._onScreencastFrame=onFrame;this._onScreencastVisibilityChanged=onVisibilityChanged;this._agent.startScreencast(format,quality,width,height,everyNthFrame);} -stopScreencast(){this._onScreencastFrame=null;this._onScreencastVisibilityChanged=null;this._agent.stopScreencast();} -captureScreenshot(format,quality,clip){return this._agent.captureScreenshot(format,quality,clip,true);} -async fetchLayoutMetrics(){var response=await this._agent.invoke_getLayoutMetrics({});if(response[Protocol.Error]) -return null;return{viewportX:response.visualViewport.pageX,viewportY:response.visualViewport.pageY,viewportScale:response.visualViewport.scale,contentWidth:response.contentSize.width,contentHeight:response.contentSize.height};} -screencastFrame(data,metadata,sessionId){this._agent.screencastFrameAck(sessionId);if(this._onScreencastFrame) -this._onScreencastFrame.call(null,data,metadata);} -screencastVisibilityChanged(visible){if(this._onScreencastVisibilityChanged) -this._onScreencastVisibilityChanged.call(null,visible);} -domContentEventFired(time){} -loadEventFired(time){} -lifecycleEvent(frameId,name,time){} -frameAttached(frameId,parentFrameId){} -frameNavigated(frame){} -frameDetached(frameId){} -frameStartedLoading(frameId){} -frameStoppedLoading(frameId){} -frameScheduledNavigation(frameId,delay){} -frameClearedScheduledNavigation(frameId){} -frameResized(){} -javascriptDialogOpening(url,message,dialogType,prompt){} -javascriptDialogClosed(result,userInput){} -interstitialShown(){} -interstitialHidden(){} -windowOpen(url,windowName,windowFeatures,userGesture){}};SDK.SDKModel.register(SDK.ScreenCaptureModel,SDK.Target.Capability.ScreenCapture,false);;SDK.Script=class{constructor(debuggerModel,scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,isContentScript,isLiveEdit,sourceMapURL,hasSourceURL,length){this.debuggerModel=debuggerModel;this.scriptId=scriptId;this.sourceURL=sourceURL;this.lineOffset=startLine;this.columnOffset=startColumn;this.endLine=endLine;this.endColumn=endColumn;this.executionContextId=executionContextId;this.hash=hash;this._isContentScript=isContentScript;this._isLiveEdit=isLiveEdit;this.sourceMapURL=sourceMapURL;this.hasSourceURL=hasSourceURL;this.contentLength=length;this._originalContentProvider=null;this._originalSource=null;} -static _trimSourceURLComment(source){var sourceURLIndex=source.lastIndexOf('//# sourceURL=');if(sourceURLIndex===-1){sourceURLIndex=source.lastIndexOf('//@ sourceURL=');if(sourceURLIndex===-1) -return source;} -var sourceURLLineIndex=source.lastIndexOf('\n',sourceURLIndex);if(sourceURLLineIndex===-1) -return source;var sourceURLLine=source.substr(sourceURLLineIndex+1).split('\n',1)[0];if(sourceURLLine.search(SDK.Script.sourceURLRegex)===-1) -return source;return source.substr(0,sourceURLLineIndex)+source.substr(sourceURLLineIndex+sourceURLLine.length+1);} -isContentScript(){return this._isContentScript;} -executionContext(){return this.debuggerModel.runtimeModel().executionContext(this.executionContextId);} -isLiveEdit(){return this._isLiveEdit;} -contentURL(){return this.sourceURL;} -contentType(){return Common.resourceTypes.Script;} -contentEncoded(){return Promise.resolve(false);} -async requestContent(){if(this._source) -return this._source;if(!this.scriptId) -return'';var source=await this.debuggerModel.target().debuggerAgent().getScriptSource(this.scriptId);this._source=source?SDK.Script._trimSourceURLComment(source):'';if(this._originalSource===null) -this._originalSource=this._source;return this._source;} -originalContentProvider(){if(!this._originalContentProvider){var lazyContent=()=>this.requestContent().then(()=>this._originalSource);this._originalContentProvider=new Common.StaticContentProvider(this.contentURL(),this.contentType(),lazyContent);} -return this._originalContentProvider;} -async searchInContent(query,caseSensitive,isRegex){if(!this.scriptId) -return[];var matches=await this.debuggerModel.target().debuggerAgent().searchInContent(this.scriptId,query,caseSensitive,isRegex);return(matches||[]).map(match=>new Common.ContentProvider.SearchMatch(match.lineNumber,match.lineContent));} -_appendSourceURLCommentIfNeeded(source){if(!this.hasSourceURL) -return source;return source+'\n //# sourceURL='+this.sourceURL;} -async editSource(newSource,callback){newSource=SDK.Script._trimSourceURLComment(newSource);newSource=this._appendSourceURLCommentIfNeeded(newSource);if(!this.scriptId){callback('Script failed to parse');return;} -await this.requestContent();var response=await this.debuggerModel.target().debuggerAgent().invoke_setScriptSource({scriptId:this.scriptId,scriptSource:newSource});if(!response[Protocol.Error]&&!response.exceptionDetails) -this._source=newSource;var needsStepIn=!!response.stackChanged;callback(response[Protocol.Error],response.exceptionDetails,response.callFrames,response.asyncStackTrace,needsStepIn);} -rawLocation(lineNumber,columnNumber){return new SDK.DebuggerModel.Location(this.debuggerModel,this.scriptId,lineNumber,columnNumber||0);} -isInlineScript(){var startsAtZero=!this.lineOffset&&!this.columnOffset;return!!this.sourceURL&&!startsAtZero;} -isAnonymousScript(){return!this.sourceURL;} -isInlineScriptWithSourceURL(){return!!this.hasSourceURL&&this.isInlineScript();} -async setBlackboxedRanges(positions){var response=await this.debuggerModel.target().debuggerAgent().invoke_setBlackboxedRanges({scriptId:this.scriptId,positions});var error=response[Protocol.Error];if(error) -console.error(error);return!error;}};SDK.Script.sourceURLRegex=/^[\040\t]*\/\/[@#] sourceURL=\s*(\S*?)\s*$/m;;SDK.ServiceWorkerCacheModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerStorageDispatcher(this);this._caches=new Map();this._cacheAgent=target.cacheStorageAgent();this._storageAgent=target.storageAgent();this._securityOriginManager=target.model(SDK.SecurityOriginManager);this._originsUpdated=new Set();this._throttler=new Common.Throttler(2000);this._enabled=false;} -enable(){if(this._enabled) -return;this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginAdded,this._securityOriginAdded,this);this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,this._securityOriginRemoved,this);for(var securityOrigin of this._securityOriginManager.securityOrigins()) -this._addOrigin(securityOrigin);this._enabled=true;} -clearForOrigin(origin){this._removeOrigin(origin);this._addOrigin(origin);} -refreshCacheNames(){for(var cache of this._caches.values()) -this._cacheRemoved(cache);this._caches.clear();var securityOrigins=this._securityOriginManager.securityOrigins();for(var securityOrigin of securityOrigins) -this._loadCacheNames(securityOrigin);} -async deleteCache(cache){var response=await this._cacheAgent.invoke_deleteCache({cacheId:cache.cacheId});if(response[Protocol.Error]){console.error(`ServiceWorkerCacheAgent error deleting cache ${cache.toString()}: ${response[Protocol.Error]}`);return;} -this._caches.delete(cache.cacheId);this._cacheRemoved(cache);} -async deleteCacheEntry(cache,request){var response=await this._cacheAgent.invoke_deleteEntry({cacheId:cache.cacheId,request});if(!response[Protocol.Error]) -return;Common.console.error(Common.UIString('ServiceWorkerCacheAgent error deleting cache entry %s in cache: %s',cache.toString(),response[Protocol.Error]));} -loadCacheData(cache,skipCount,pageSize,callback){this._requestEntries(cache,skipCount,pageSize,callback);} -caches(){var caches=new Array();for(var cache of this._caches.values()) -caches.push(cache);return caches;} -dispose(){for(var cache of this._caches.values()) -this._cacheRemoved(cache);this._caches.clear();if(this._enabled){this._securityOriginManager.removeEventListener(SDK.SecurityOriginManager.Events.SecurityOriginAdded,this._securityOriginAdded,this);this._securityOriginManager.removeEventListener(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,this._securityOriginRemoved,this);}} -_addOrigin(securityOrigin){this._loadCacheNames(securityOrigin);if(this._isValidSecurityOrigin(securityOrigin)) -this._storageAgent.trackCacheStorageForOrigin(securityOrigin);} -_removeOrigin(securityOrigin){for(var opaqueId of this._caches.keys()){var cache=this._caches.get(opaqueId);if(cache.securityOrigin===securityOrigin){this._caches.delete(opaqueId);this._cacheRemoved(cache);}} -if(this._isValidSecurityOrigin(securityOrigin)) -this._storageAgent.untrackCacheStorageForOrigin(securityOrigin);} -_isValidSecurityOrigin(securityOrigin){var parsedURL=securityOrigin.asParsedURL();return!!parsedURL&&parsedURL.scheme.startsWith('http');} -async _loadCacheNames(securityOrigin){var caches=await this._cacheAgent.requestCacheNames(securityOrigin);if(!caches) -return;this._updateCacheNames(securityOrigin,caches);} -_updateCacheNames(securityOrigin,cachesJson){function deleteAndSaveOldCaches(cache){if(cache.securityOrigin===securityOrigin&&!updatingCachesIds.has(cache.cacheId)){oldCaches.set(cache.cacheId,cache);this._caches.delete(cache.cacheId);}} -var updatingCachesIds=new Set();var newCaches=new Map();var oldCaches=new Map();for(var cacheJson of cachesJson){var cache=new SDK.ServiceWorkerCacheModel.Cache(this,cacheJson.securityOrigin,cacheJson.cacheName,cacheJson.cacheId);updatingCachesIds.add(cache.cacheId);if(this._caches.has(cache.cacheId)) -continue;newCaches.set(cache.cacheId,cache);this._caches.set(cache.cacheId,cache);} -this._caches.forEach(deleteAndSaveOldCaches,this);newCaches.forEach(this._cacheAdded,this);oldCaches.forEach(this._cacheRemoved,this);} -_securityOriginAdded(event){var securityOrigin=(event.data);this._addOrigin(securityOrigin);} -_securityOriginRemoved(event){var securityOrigin=(event.data);this._removeOrigin(securityOrigin);} -_cacheAdded(cache){this.dispatchEventToListeners(SDK.ServiceWorkerCacheModel.Events.CacheAdded,{model:this,cache:cache});} -_cacheRemoved(cache){this.dispatchEventToListeners(SDK.ServiceWorkerCacheModel.Events.CacheRemoved,{model:this,cache:cache});} -async _requestEntries(cache,skipCount,pageSize,callback){var response=await this._cacheAgent.invoke_requestEntries({cacheId:cache.cacheId,skipCount,pageSize});if(response[Protocol.Error]){console.error('ServiceWorkerCacheAgent error while requesting entries: ',response[Protocol.Error]);return;} -callback(response.cacheDataEntries,response.hasMore);} -cacheStorageListUpdated(origin){this._originsUpdated.add(origin);this._throttler.schedule(()=>{var promises=Array.from(this._originsUpdated,origin=>this._loadCacheNames(origin));this._originsUpdated.clear();return Promise.all(promises);});} -cacheStorageContentUpdated(origin,cacheName){this.dispatchEventToListeners(SDK.ServiceWorkerCacheModel.Events.CacheStorageContentUpdated,{origin:origin,cacheName:cacheName});} -indexedDBListUpdated(origin){} -indexedDBContentUpdated(origin,databaseName,objectStoreName){}};SDK.SDKModel.register(SDK.ServiceWorkerCacheModel,SDK.Target.Capability.Browser,false);SDK.ServiceWorkerCacheModel.Events={CacheAdded:Symbol('CacheAdded'),CacheRemoved:Symbol('CacheRemoved'),CacheStorageContentUpdated:Symbol('CacheStorageContentUpdated')};SDK.ServiceWorkerCacheModel.Cache=class{constructor(model,securityOrigin,cacheName,cacheId){this._model=model;this.securityOrigin=securityOrigin;this.cacheName=cacheName;this.cacheId=cacheId;} -equals(cache){return this.cacheId===cache.cacheId;} -toString(){return this.securityOrigin+this.cacheName;} -requestCachedResponse(url){return this._model._cacheAgent.requestCachedResponse(this.cacheId,url);}};;SDK.CallFunctionResult;SDK.RemoteObject=class{static fromLocalObject(value){return new SDK.LocalJSONObject(value);} -static type(remoteObject){if(remoteObject===null) -return'null';var type=typeof remoteObject;if(type!=='object'&&type!=='function') -return type;return remoteObject.type;} -static arrayNameFromDescription(description){return description.replace(SDK.RemoteObject._descriptionLengthParenRegex,'').replace(SDK.RemoteObject._descriptionLengthSquareRegex,'');} -static arrayLength(object){if(object.subtype!=='array'&&object.subtype!=='typedarray') -return 0;var parenMatches=object.description.match(SDK.RemoteObject._descriptionLengthParenRegex);var squareMatches=object.description.match(SDK.RemoteObject._descriptionLengthSquareRegex);return parenMatches?parseInt(parenMatches[1],10):(squareMatches?parseInt(squareMatches[1],10):0);} -static toCallArgument(object){var type=typeof object;if(type==='undefined') -return{};if(type==='number'){var description=String(object);if(object===0&&1/object<0) -return{unserializableValue:Protocol.Runtime.UnserializableValue.Negative0};if(description==='NaN') -return{unserializableValue:Protocol.Runtime.UnserializableValue.NaN};if(description==='Infinity') -return{unserializableValue:Protocol.Runtime.UnserializableValue.Infinity};if(description==='-Infinity') -return{unserializableValue:Protocol.Runtime.UnserializableValue.NegativeInfinity};return{value:object};} -if(type==='string'||type==='boolean') -return{value:object};if(!object) -return{value:null};if(typeof object.unserializableValue!=='undefined') -return{unserializableValue:object.unserializableValue};if(object instanceof SDK.RemoteObjectImpl&&typeof object._unserializableValue!=='undefined') -return{unserializableValue:object._unserializableValue};if(typeof object.objectId!=='undefined') -return{objectId:object.objectId};return{value:object.value};} -static loadFromObjectPerProto(object,generatePreview,callback){var savedOwnProperties;var savedAccessorProperties;var savedInternalProperties;var resultCounter=2;function processCallback(){if(--resultCounter) -return;if(savedOwnProperties&&savedAccessorProperties){var propertiesMap=new Map();var propertySymbols=[];for(var i=0;i<savedAccessorProperties.length;i++){var property=savedAccessorProperties[i];if(property.symbol) -propertySymbols.push(property);else -propertiesMap.set(property.name,property);} -for(var i=0;i<savedOwnProperties.length;i++){var property=savedOwnProperties[i];if(property.isAccessorProperty()) -continue;if(property.symbol) -propertySymbols.push(property);else -propertiesMap.set(property.name,property);} -return callback(propertiesMap.valuesArray().concat(propertySymbols),savedInternalProperties?savedInternalProperties:null);}else{callback(null,null);}} -function allAccessorPropertiesCallback(properties,internalProperties){savedAccessorProperties=properties;processCallback();} -function ownPropertiesCallback(properties,internalProperties){savedOwnProperties=properties;savedInternalProperties=internalProperties;processCallback();} -object.getAllProperties(true,generatePreview,allAccessorPropertiesCallback);object.getOwnProperties(generatePreview,ownPropertiesCallback);} -customPreview(){return null;} -get objectId(){return'Not implemented';} -get type(){throw'Not implemented';} -get subtype(){throw'Not implemented';} -get value(){throw'Not implemented';} -get description(){throw'Not implemented';} -get hasChildren(){throw'Not implemented';} -get preview(){return undefined;} -arrayLength(){throw'Not implemented';} -getOwnProperties(generatePreview,callback){throw'Not implemented';} -getOwnPropertiesPromise(generatePreview){return new Promise(promiseConstructor.bind(this));function promiseConstructor(success){this.getOwnProperties(!!generatePreview,getOwnPropertiesCallback.bind(null,success));} -function getOwnPropertiesCallback(callback,properties,internalProperties){callback({properties:properties,internalProperties:internalProperties});}} -getAllProperties(accessorPropertiesOnly,generatePreview,callback){throw'Not implemented';} -getAllPropertiesPromise(accessorPropertiesOnly,generatePreview){return new Promise(promiseConstructor.bind(this));function promiseConstructor(success){this.getAllProperties(accessorPropertiesOnly,generatePreview,getAllPropertiesCallback.bind(null,success));} -function getAllPropertiesCallback(callback,properties,internalProperties){callback({properties:properties,internalProperties:internalProperties});}} -getProperty(propertyPath,callback){throw'Not implemented';} -async deleteProperty(name){throw'Not implemented';} -async setPropertyValue(name,value){throw'Not implemented';} -callFunction(functionDeclaration,args,callback){throw'Not implemented';} -callFunctionPromise(functionDeclaration,args){return new Promise(promiseConstructor.bind(this));function promiseConstructor(success){this.callFunction(functionDeclaration,args,callFunctionCallback.bind(null,success));} -function callFunctionCallback(callback,object,wasThrown){callback({object:object,wasThrown:wasThrown});}} -callFunctionJSON(functionDeclaration,args,callback){throw'Not implemented';} -callFunctionJSONPromise(functionDeclaration,args){return new Promise(success=>this.callFunctionJSON(functionDeclaration,args,success));} -release(){} -debuggerModel(){throw new Error('DebuggerModel-less object');} -runtimeModel(){throw new Error('RuntimeModel-less object');} -isNode(){return false;}};SDK.RemoteObjectImpl=class extends SDK.RemoteObject{constructor(runtimeModel,objectId,type,subtype,value,unserializableValue,description,preview,customPreview){super();this._runtimeModel=runtimeModel;this._runtimeAgent=runtimeModel.target().runtimeAgent();this._type=type;this._subtype=subtype;if(objectId){this._objectId=objectId;this._description=description;this._hasChildren=(type!=='symbol');this._preview=preview;}else{this._description=description;if(!this.description&&unserializableValue) -this._description=unserializableValue;if(!this._description&&(typeof value!=='object'||value===null)) -this._description=value+'';this._hasChildren=false;if(typeof unserializableValue!=='undefined'){this._unserializableValue=unserializableValue;if(unserializableValue===Protocol.Runtime.UnserializableValue.Infinity||unserializableValue===Protocol.Runtime.UnserializableValue.NegativeInfinity||unserializableValue===Protocol.Runtime.UnserializableValue.Negative0||unserializableValue===Protocol.Runtime.UnserializableValue.NaN) -this._value=Number(unserializableValue);else -this._value=unserializableValue;}else{this._value=value;}} -this._customPreview=customPreview||null;} -customPreview(){return this._customPreview;} -get objectId(){return this._objectId;} -get type(){return this._type;} -get subtype(){return this._subtype;} -get value(){return this._value;} -get description(){return this._description;} -get hasChildren(){return this._hasChildren;} -get preview(){return this._preview;} -getOwnProperties(generatePreview,callback){this.doGetProperties(true,false,generatePreview,callback);} -getAllProperties(accessorPropertiesOnly,generatePreview,callback){this.doGetProperties(false,accessorPropertiesOnly,generatePreview,callback);} -getProperty(propertyPath,callback){function remoteFunction(arrayStr){var result=this;var properties=JSON.parse(arrayStr);for(var i=0,n=properties.length;i<n;++i) -result=result[properties[i]];return result;} -var args=[{value:JSON.stringify(propertyPath)}];this.callFunction(remoteFunction,args,callback);} -doGetProperties(ownProperties,accessorPropertiesOnly,generatePreview,callback){if(!this._objectId){callback(null,null);return;} -this._runtimeAgent.invoke_getProperties({objectId:this._objectId,ownProperties,accessorPropertiesOnly,generatePreview}).then(remoteObjectBinder.bind(this));function remoteObjectBinder(response){if(response[Protocol.Error]){callback(null,null);return;} -if(response.exceptionDetails){this._runtimeModel.exceptionThrown(Date.now(),response.exceptionDetails);callback(null,null);return;} -var properties=response.result;var internalProperties=response.internalProperties;var result=[];for(var i=0;properties&&i<properties.length;++i){var property=properties[i];var propertyValue=property.value?this._runtimeModel.createRemoteObject(property.value):null;var propertySymbol=property.symbol?this._runtimeModel.createRemoteObject(property.symbol):null;var remoteProperty=new SDK.RemoteObjectProperty(property.name,propertyValue,!!property.enumerable,!!property.writable,!!property.isOwn,!!property.wasThrown,propertySymbol);if(typeof property.value==='undefined'){if(property.get&&property.get.type!=='undefined') -remoteProperty.getter=this._runtimeModel.createRemoteObject(property.get);if(property.set&&property.set.type!=='undefined') -remoteProperty.setter=this._runtimeModel.createRemoteObject(property.set);} -result.push(remoteProperty);} -var internalPropertiesResult=null;if(internalProperties){internalPropertiesResult=[];for(var i=0;i<internalProperties.length;i++){var property=internalProperties[i];if(!property.value) -continue;var propertyValue=this._runtimeModel.createRemoteObject(property.value);internalPropertiesResult.push(new SDK.RemoteObjectProperty(property.name,propertyValue,true,false));}} -callback(result,internalPropertiesResult);}} -async setPropertyValue(name,value){if(!this._objectId) -return`Can't set a property of non-object.`;var response=await this._runtimeAgent.invoke_evaluate({expression:value,silent:true});if(response[Protocol.Error]||response.exceptionDetails){return response[Protocol.Error]||(response.result.type!=='string'?response.result.description:(response.result.value));} -if(typeof name==='string') -name=SDK.RemoteObject.toCallArgument(name);var resultPromise=this.doSetObjectPropertyValue(response.result,name);if(response.result.objectId) -this._runtimeAgent.releaseObject(response.result.objectId);return resultPromise;} -async doSetObjectPropertyValue(result,name){var setPropertyValueFunction='function(a, b) { this[a] = b; }';var argv=[name,SDK.RemoteObject.toCallArgument(result)];var response=await this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:setPropertyValueFunction,arguments:argv,silent:true});var error=response[Protocol.Error];return error||response.exceptionDetails?error||response.result.description:undefined;} -async deleteProperty(name){if(!this._objectId) -return`Can't delete a property of non-object.`;var deletePropertyFunction='function(a) { delete this[a]; return !(a in this); }';var response=await this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:deletePropertyFunction,arguments:[name],silent:true});if(response[Protocol.Error]||response.exceptionDetails) -return response[Protocol.Error]||response.result.description;if(!response.result.value) -return'Failed to delete property.';} -callFunction(functionDeclaration,args,callback){this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:functionDeclaration.toString(),arguments:args,silent:true}).then(response=>{if(!callback) -return;if(response[Protocol.Error]) -callback(null,false);else -callback(this._runtimeModel.createRemoteObject(response.result),!!response.exceptionDetails);});} -callFunctionJSON(functionDeclaration,args,callback){this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:functionDeclaration.toString(),arguments:args,silent:true,returnByValue:true}).then(response=>callback(response[Protocol.Error]||response.exceptionDetails?null:response.result.value));} -release(){if(!this._objectId) -return;this._runtimeAgent.releaseObject(this._objectId);} -arrayLength(){return SDK.RemoteObject.arrayLength(this);} -debuggerModel(){return this._runtimeModel.debuggerModel();} -runtimeModel(){return this._runtimeModel;} -isNode(){return!!this._objectId&&this.type==='object'&&this.subtype==='node';}};SDK.ScopeRemoteObject=class extends SDK.RemoteObjectImpl{constructor(runtimeModel,objectId,scopeRef,type,subtype,value,unserializableValue,description,preview){super(runtimeModel,objectId,type,subtype,value,unserializableValue,description,preview);this._scopeRef=scopeRef;this._savedScopeProperties=undefined;} -doGetProperties(ownProperties,accessorPropertiesOnly,generatePreview,callback){if(accessorPropertiesOnly){callback([],[]);return;} -if(this._savedScopeProperties){callback(this._savedScopeProperties.slice(),[]);return;} -function wrappedCallback(properties,internalProperties){if(this._scopeRef&&Array.isArray(properties)){this._savedScopeProperties=properties.slice();if(!this._scopeRef.callFrameId){for(var property of this._savedScopeProperties) -property.writable=false;}} -callback(properties,internalProperties);} -generatePreview=true;super.doGetProperties(ownProperties,accessorPropertiesOnly,generatePreview,wrappedCallback.bind(this));} -async doSetObjectPropertyValue(result,argumentName){var name=(argumentName.value);var error=await this.debuggerModel().setVariableValue(this._scopeRef.number,name,SDK.RemoteObject.toCallArgument(result),this._scopeRef.callFrameId);if(error) -return error;if(this._savedScopeProperties){for(var property of this._savedScopeProperties){if(property.name===name) -property.value=this._runtimeModel.createRemoteObject(result);}}}};SDK.ScopeRef=class{constructor(number,callFrameId){this.number=number;this.callFrameId=callFrameId;}};SDK.RemoteObjectProperty=class{constructor(name,value,enumerable,writable,isOwn,wasThrown,symbol,synthetic){this.name=name;if(value!==null) -this.value=value;this.enumerable=typeof enumerable!=='undefined'?enumerable:true;this.writable=typeof writable!=='undefined'?writable:true;this.isOwn=!!isOwn;this.wasThrown=!!wasThrown;if(symbol) -this.symbol=symbol;this.synthetic=!!synthetic;} -isAccessorProperty(){return!!(this.getter||this.setter);}};SDK.LocalJSONObject=class extends SDK.RemoteObject{constructor(value){super();this._value=value;this._cachedDescription;this._cachedChildren;} -get objectId(){return undefined;} -get value(){return this._value;} -get description(){if(this._cachedDescription) -return this._cachedDescription;function formatArrayItem(property){return this._formatValue(property.value);} -function formatObjectItem(property){var name=property.name;if(/^\s|\s$|^$|\n/.test(name)) -name='"'+name.replace(/\n/g,'\u21B5')+'"';return name+': '+this._formatValue(property.value);} -if(this.type==='object'){switch(this.subtype){case'array':this._cachedDescription=this._concatenate('[',']',formatArrayItem.bind(this));break;case'date':this._cachedDescription=''+this._value;break;case'null':this._cachedDescription='null';break;default:this._cachedDescription=this._concatenate('{','}',formatObjectItem.bind(this));}}else{this._cachedDescription=String(this._value);} -return this._cachedDescription;} -_formatValue(value){if(!value) -return'undefined';var description=value.description||'';if(value.type==='string') -return'"'+description.replace(/\n/g,'\u21B5')+'"';return description;} -_concatenate(prefix,suffix,formatProperty){var previewChars=100;var buffer=prefix;var children=this._children();for(var i=0;i<children.length;++i){var itemDescription=formatProperty(children[i]);if(buffer.length+itemDescription.length>previewChars){buffer+=',\u2026';break;} -if(i) -buffer+=', ';buffer+=itemDescription;} -buffer+=suffix;return buffer;} -get type(){return typeof this._value;} -get subtype(){if(this._value===null) -return'null';if(Array.isArray(this._value)) -return'array';if(this._value instanceof Date) -return'date';return undefined;} -get hasChildren(){if((typeof this._value!=='object')||(this._value===null)) -return false;return!!Object.keys((this._value)).length;} -getOwnProperties(generatePreview,callback){callback(this._children(),null);} -getAllProperties(accessorPropertiesOnly,generatePreview,callback){if(accessorPropertiesOnly) -callback([],null);else -callback(this._children(),null);} -_children(){if(!this.hasChildren) -return[];var value=(this._value);function buildProperty(propName){var propValue=value[propName];if(!(propValue instanceof SDK.RemoteObject)) -propValue=SDK.RemoteObject.fromLocalObject(propValue);return new SDK.RemoteObjectProperty(propName,propValue);} -if(!this._cachedChildren) -this._cachedChildren=Object.keys(value).map(buildProperty);return this._cachedChildren;} -isError(){return false;} -arrayLength(){return Array.isArray(this._value)?this._value.length:0;} -callFunction(functionDeclaration,args,callback){var target=(this._value);var rawArgs=args?args.map(arg=>arg.value):[];var result;var wasThrown=false;try{result=functionDeclaration.apply(target,rawArgs);}catch(e){wasThrown=true;} -if(!callback) -return;callback(SDK.RemoteObject.fromLocalObject(result),wasThrown);} -callFunctionJSON(functionDeclaration,args,callback){var target=(this._value);var rawArgs=args?args.map(arg=>arg.value):[];var result;try{result=functionDeclaration.apply(target,rawArgs);}catch(e){result=null;} -callback(result);}};SDK.RemoteArray=class{constructor(object){this._object=object;} -static objectAsArray(object){if(!object||object.type!=='object'||(object.subtype!=='array'&&object.subtype!=='typedarray')) -throw new Error('Object is empty or not an array');return new SDK.RemoteArray(object);} -static createFromRemoteObjects(objects){if(!objects.length) -throw new Error('Input array is empty');var objectArguments=[];for(var i=0;i<objects.length;++i) -objectArguments.push(SDK.RemoteObject.toCallArgument(objects[i]));return objects[0].callFunctionPromise(createArray,objectArguments).then(returnRemoteArray);function createArray(){if(arguments.length>1) -return new Array(arguments);return[arguments[0]];} -function returnRemoteArray(result){if(result.wasThrown||!result.object) -throw new Error('Call function throws exceptions or returns empty value');return SDK.RemoteArray.objectAsArray(result.object);}} -at(index){if(index<0||index>this._object.arrayLength()) -throw new Error('Out of range');return this._object.callFunctionPromise(at,[SDK.RemoteObject.toCallArgument(index)]).then(assertCallFunctionResult);function at(index){return this[index];} -function assertCallFunctionResult(result){if(result.wasThrown||!result.object) -throw new Error('Exception in callFunction or result value is empty');return result.object;}} -length(){return this._object.arrayLength();} -map(func){var promises=[];for(var i=0;i<this.length();++i) -promises.push(this.at(i).then(func));return Promise.all(promises);} -object(){return this._object;}};SDK.RemoteFunction=class{constructor(object){this._object=object;} -static objectAsFunction(object){if(!object||object.type!=='function') -throw new Error('Object is empty or not a function');return new SDK.RemoteFunction(object);} -targetFunction(){return this._object.getOwnPropertiesPromise(false).then(targetFunction.bind(this));function targetFunction(ownProperties){if(!ownProperties.internalProperties) -return this._object;var internalProperties=ownProperties.internalProperties;for(var property of internalProperties){if(property.name==='[[TargetFunction]]') -return property.value;} -return this._object;}} -targetFunctionDetails(){return this.targetFunction().then(functionDetails.bind(this));function functionDetails(targetFunction){var boundReleaseFunctionDetails=releaseTargetFunction.bind(null,this._object!==targetFunction?targetFunction:null);return targetFunction.debuggerModel().functionDetailsPromise(targetFunction).then(boundReleaseFunctionDetails);} -function releaseTargetFunction(targetFunction,functionDetails){if(targetFunction) -targetFunction.release();return functionDetails;}} -object(){return this._object;}};SDK.RemoteObject._descriptionLengthParenRegex=/\(([0-9]+)\)/;SDK.RemoteObject._descriptionLengthSquareRegex=/\[([0-9]+)\]/;;SDK.Resource=class{constructor(resourceTreeModel,request,url,documentURL,frameId,loaderId,type,mimeType,lastModified,contentSize){this._resourceTreeModel=resourceTreeModel;this._request=request;this.url=url;this._documentURL=documentURL;this._frameId=frameId;this._loaderId=loaderId;this._type=type||Common.resourceTypes.Other;this._mimeType=mimeType;this._lastModified=lastModified&&lastModified.isValid()?lastModified:null;this._contentSize=contentSize;this._content;this._contentEncoded;this._pendingContentCallbacks=[];if(this._request&&!this._request.finished) -this._request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._requestFinished,this);} -lastModified(){if(this._lastModified||!this._request) -return this._lastModified;var lastModifiedHeader=this._request.responseLastModified();var date=lastModifiedHeader?new Date(lastModifiedHeader):null;this._lastModified=date&&date.isValid()?date:null;return this._lastModified;} -contentSize(){if(typeof this._contentSize==='number'||!this._request) -return this._contentSize;return this._request.resourceSize;} -get request(){return this._request;} -get url(){return this._url;} -set url(x){this._url=x;this._parsedURL=new Common.ParsedURL(x);} -get parsedURL(){return this._parsedURL;} -get documentURL(){return this._documentURL;} -get frameId(){return this._frameId;} -get loaderId(){return this._loaderId;} -get displayName(){return this._parsedURL.displayName;} -resourceType(){return this._request?this._request.resourceType():this._type;} -get mimeType(){return this._request?this._request.mimeType:this._mimeType;} -get content(){return this._content;} -contentURL(){return this._url;} -contentType(){if(this.resourceType()===Common.resourceTypes.Document&&this.mimeType.indexOf('javascript')!==-1) -return Common.resourceTypes.Script;return this.resourceType();} -async contentEncoded(){await this.requestContent();return this._contentEncoded;} -requestContent(){if(typeof this._content!=='undefined') -return Promise.resolve(this._content);var callback;var promise=new Promise(fulfill=>callback=fulfill);this._pendingContentCallbacks.push(callback);if(!this._request||this._request.finished) -this._innerRequestContent();return promise;} -canonicalMimeType(){return this.contentType().canonicalMimeType()||this.mimeType;} -async searchInContent(query,caseSensitive,isRegex){if(!this.frameId) -return[];var result=await this._resourceTreeModel.target().pageAgent().searchInResource(this.frameId,this.url,query,caseSensitive,isRegex);return result||[];} -populateImageSource(image){function onResourceContent(content){var imageSrc=Common.ContentProvider.contentAsDataURL(content,this._mimeType,true);if(imageSrc===null) -imageSrc=this._url;image.src=imageSrc;} -this.requestContent().then(onResourceContent.bind(this));} -_requestFinished(){this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._requestFinished,this);if(this._pendingContentCallbacks.length) -this._innerRequestContent();} -async _innerRequestContent(){if(this._contentRequested) -return;this._contentRequested=true;if(this.request){var contentData=await this.request.contentData();this._content=contentData.content;this._contentEncoded=contentData.encoded;}else{var response=await this._resourceTreeModel.target().pageAgent().invoke_getResourceContent({frameId:this.frameId,url:this.url});this._content=response[Protocol.Error]?null:response.content;this._contentEncoded=response.base64Encoded;} -if(this._content===null) -this._contentEncoded=false;for(var callback of this._pendingContentCallbacks.splice(0)) -callback(this._content);delete this._contentRequested;} -hasTextContent(){if(this._type.isTextType()) -return true;if(this._type===Common.resourceTypes.Other) -return!!this._content&&!this._contentEncoded;return false;}};;SDK.ResourceTreeModel=class extends SDK.SDKModel{constructor(target){super(target);var networkManager=target.model(SDK.NetworkManager);if(networkManager){networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished,this._onRequestFinished,this);networkManager.addEventListener(SDK.NetworkManager.Events.RequestUpdateDropped,this._onRequestUpdateDropped,this);} -this._agent=target.pageAgent();this._agent.enable();this._securityOriginManager=target.model(SDK.SecurityOriginManager);target.registerPageDispatcher(new SDK.PageDispatcher(this));this._frames=new Map();this._cachedResourcesProcessed=false;this._pendingReloadOptions=null;this._reloadSuspensionCount=0;this._isInterstitialShowing=false;this.mainFrame=null;this._agent.getResourceTree().then(this._processCachedResources.bind(this));} -static frameForRequest(request){var networkManager=SDK.NetworkManager.forRequest(request);var resourceTreeModel=networkManager?networkManager.target().model(SDK.ResourceTreeModel):null;if(!resourceTreeModel) -return null;return resourceTreeModel.frameForId(request.frameId);} -static frames(){var result=[];for(var resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) -result=result.concat(resourceTreeModel._frames.valuesArray());return result;} -static resourceForURL(url){for(var resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)){var mainFrame=resourceTreeModel.mainFrame;var result=mainFrame?mainFrame.resourceForURL(url):null;if(result) -return result;} -return null;} -static reloadAllPages(bypassCache,scriptToEvaluateOnLoad){for(var resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)){if(!resourceTreeModel.target().parentTarget()) -resourceTreeModel.reloadPage(bypassCache,scriptToEvaluateOnLoad);}} -domModel(){return(this.target().model(SDK.DOMModel));} -_processCachedResources(mainFramePayload){if(mainFramePayload){this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.WillLoadCachedResources);this._addFramesRecursively(null,mainFramePayload);this.target().setInspectedURL(mainFramePayload.frame.url);} -this._cachedResourcesProcessed=true;var runtimeModel=this.target().model(SDK.RuntimeModel);if(runtimeModel){runtimeModel.setExecutionContextComparator(this._executionContextComparator.bind(this));runtimeModel.fireExecutionContextOrderChanged();} -this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.CachedResourcesLoaded,this);} -cachedResourcesLoaded(){return this._cachedResourcesProcessed;} -isInterstitialShowing(){return this._isInterstitialShowing;} -_addFrame(frame,aboutToNavigate){this._frames.set(frame.id,frame);if(frame.isMainFrame()) -this.mainFrame=frame;this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameAdded,frame);this._updateSecurityOrigins();} -_frameAttached(frameId,parentFrameId,stackTrace){if(!this._cachedResourcesProcessed&&parentFrameId) -return null;if(this._frames.has(frameId)) -return null;var parentFrame=parentFrameId?(this._frames.get(parentFrameId)||null):null;var frame=new SDK.ResourceTreeFrame(this,parentFrame,frameId,null,stackTrace||null);if(frame.isMainFrame()&&this.mainFrame){this._frameDetached(this.mainFrame.id);} -this._addFrame(frame,true);return frame;} -_frameNavigated(framePayload){if(!this._cachedResourcesProcessed&&framePayload.parentId) -return;var frame=this._frames.get(framePayload.id);if(!frame){console.assert(!framePayload.parentId,'Main frame shouldn\'t have parent frame id.');frame=this._frameAttached(framePayload.id,framePayload.parentId||'');console.assert(frame);} -this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameWillNavigate,frame);frame._navigate(framePayload);this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameNavigated,frame);if(frame.isMainFrame()) -this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.MainFrameNavigated,frame);var resources=frame.resources();for(var i=0;i<resources.length;++i) -this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.ResourceAdded,resources[i]);if(frame.isMainFrame()) -this.target().setInspectedURL(frame.url);this._updateSecurityOrigins();} -_frameDetached(frameId){if(!this._cachedResourcesProcessed) -return;var frame=this._frames.get(frameId);if(!frame) -return;if(frame.parentFrame) -frame.parentFrame._removeChildFrame(frame);else -frame._remove();this._updateSecurityOrigins();} -_onRequestFinished(event){if(!this._cachedResourcesProcessed) -return;var request=(event.data);if(request.failed||request.resourceType()===Common.resourceTypes.XHR) -return;var frame=this._frames.get(request.frameId);if(frame) -frame._addRequest(request);} -_onRequestUpdateDropped(event){if(!this._cachedResourcesProcessed) -return;var frameId=event.data.frameId;var frame=this._frames.get(frameId);if(!frame) -return;var url=event.data.url;if(frame._resourcesMap[url]) -return;var resource=new SDK.Resource(this,null,url,frame.url,frameId,event.data.loaderId,Common.resourceTypes[event.data.resourceType],event.data.mimeType,event.data.lastModified,null);frame.addResource(resource);} -frameForId(frameId){return this._frames.get(frameId);} -forAllResources(callback){if(this.mainFrame) -return this.mainFrame._callForFrameResources(callback);return false;} -frames(){return this._frames.valuesArray();} -resourceForURL(url){return this.mainFrame?this.mainFrame.resourceForURL(url):null;} -_addFramesRecursively(parentFrame,frameTreePayload){var framePayload=frameTreePayload.frame;var frame=new SDK.ResourceTreeFrame(this,parentFrame,framePayload.id,framePayload,null);this._addFrame(frame);for(var i=0;frameTreePayload.childFrames&&i<frameTreePayload.childFrames.length;++i) -this._addFramesRecursively(frame,frameTreePayload.childFrames[i]);for(var i=0;i<frameTreePayload.resources.length;++i){var subresource=frameTreePayload.resources[i];var resource=this._createResourceFromFramePayload(framePayload,subresource.url,Common.resourceTypes[subresource.type],subresource.mimeType,subresource.lastModified||null,subresource.contentSize||null);frame.addResource(resource);} -if(!frame._resourcesMap[framePayload.url]){var frameResource=this._createResourceFromFramePayload(framePayload,framePayload.url,Common.resourceTypes.Document,framePayload.mimeType,null,null);frame.addResource(frameResource);}} -_createResourceFromFramePayload(frame,url,type,mimeType,lastModifiedTime,contentSize){var lastModified=typeof lastModifiedTime==='number'?new Date(lastModifiedTime*1000):null;return new SDK.Resource(this,null,url,frame.url,frame.id,frame.loaderId,type,mimeType,lastModified,contentSize);} -suspendReload(){this._reloadSuspensionCount++;} -resumeReload(){this._reloadSuspensionCount--;console.assert(this._reloadSuspensionCount>=0,'Unbalanced call to ResourceTreeModel.resumeReload()');if(!this._reloadSuspensionCount&&this._pendingReloadOptions) -this.reloadPage.apply(this,this._pendingReloadOptions);} -reloadPage(bypassCache,scriptToEvaluateOnLoad){if(!this._pendingReloadOptions) -this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.PageReloadRequested,this);if(this._reloadSuspensionCount){this._pendingReloadOptions=[bypassCache,scriptToEvaluateOnLoad];return;} -this._pendingReloadOptions=null;this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.WillReloadPage);this._agent.reload(bypassCache,scriptToEvaluateOnLoad);} -navigate(url){return this._agent.navigate(url);} -async navigationHistory(){var response=await this._agent.invoke_getNavigationHistory({});if(response[Protocol.Error]) -return null;return{currentIndex:response.currentIndex,entries:response.entries};} -navigateToHistoryEntry(entry){this._agent.navigateToHistoryEntry(entry.id);} -async fetchAppManifest(callback){var response=await this._agent.invoke_getAppManifest({});if(response[Protocol.Error]) -callback(response.url,null,[]);else -callback(response.url,response.data||null,response.errors);} -_executionContextComparator(a,b){function framePath(frame){var currentFrame=frame;var parents=[];while(currentFrame){parents.push(currentFrame);currentFrame=currentFrame.parentFrame;} -return parents.reverse();} -if(a.target()!==b.target()) -return SDK.ExecutionContext.comparator(a,b);var framesA=a.frameId?framePath(this.frameForId(a.frameId)):[];var framesB=b.frameId?framePath(this.frameForId(b.frameId)):[];var frameA;var frameB;for(var i=0;;i++){if(!framesA[i]||!framesB[i]||(framesA[i]!==framesB[i])){frameA=framesA[i];frameB=framesB[i];break;}} -if(!frameA&&frameB) -return-1;if(!frameB&&frameA) -return 1;if(frameA&&frameB) -return frameA.id.localeCompare(frameB.id);return SDK.ExecutionContext.comparator(a,b);} -_updateSecurityOrigins(){var securityOrigins=new Set();var mainSecurityOrigin=null;for(var frame of this._frames.values()){var origin=frame.securityOrigin;if(!origin) -continue;securityOrigins.add(origin);if(frame.isMainFrame()) -mainSecurityOrigin=origin;} -this._securityOriginManager.updateSecurityOrigins(securityOrigins);this._securityOriginManager.setMainSecurityOrigin(mainSecurityOrigin||'');}};SDK.SDKModel.register(SDK.ResourceTreeModel,SDK.Target.Capability.DOM,true);SDK.ResourceTreeModel.Events={FrameAdded:Symbol('FrameAdded'),FrameNavigated:Symbol('FrameNavigated'),FrameDetached:Symbol('FrameDetached'),FrameResized:Symbol('FrameResized'),FrameWillNavigate:Symbol('FrameWillNavigate'),MainFrameNavigated:Symbol('MainFrameNavigated'),ResourceAdded:Symbol('ResourceAdded'),WillLoadCachedResources:Symbol('WillLoadCachedResources'),CachedResourcesLoaded:Symbol('CachedResourcesLoaded'),DOMContentLoaded:Symbol('DOMContentLoaded'),Load:Symbol('Load'),PageReloadRequested:Symbol('PageReloadRequested'),WillReloadPage:Symbol('WillReloadPage'),InterstitialShown:Symbol('InterstitialShown'),InterstitialHidden:Symbol('InterstitialHidden')};SDK.ResourceTreeFrame=class{constructor(model,parentFrame,frameId,payload,creationStackTrace){this._model=model;this._parentFrame=parentFrame;this._id=frameId;this._url='';if(payload){this._loaderId=payload.loaderId;this._name=payload.name;this._url=payload.url;this._securityOrigin=payload.securityOrigin;this._mimeType=payload.mimeType;} -this._creationStackTrace=creationStackTrace;this._childFrames=[];this._resourcesMap={};if(this._parentFrame) -this._parentFrame._childFrames.push(this);} -resourceTreeModel(){return this._model;} -get id(){return this._id;} -get name(){return this._name||'';} -get url(){return this._url;} -get securityOrigin(){return this._securityOrigin;} -get loaderId(){return this._loaderId;} -get parentFrame(){return this._parentFrame;} -get childFrames(){return this._childFrames;} -findCreationCallFrame(searchFn){var stackTrace=this._creationStackTrace;while(stackTrace){var foundEntry=stackTrace.callFrames.find(searchFn);if(foundEntry) -return foundEntry;stackTrace=this.parent;} -return null;} -isMainFrame(){return!this._parentFrame;} -_navigate(framePayload){this._loaderId=framePayload.loaderId;this._name=framePayload.name;this._url=framePayload.url;this._securityOrigin=framePayload.securityOrigin;this._mimeType=framePayload.mimeType;var mainResource=this._resourcesMap[this._url];this._resourcesMap={};this._removeChildFrames();if(mainResource&&mainResource.loaderId===this._loaderId) -this.addResource(mainResource);} -get mainResource(){return this._resourcesMap[this._url];} -_removeChildFrame(frame){this._childFrames.remove(frame);frame._remove();} -_removeChildFrames(){var frames=this._childFrames;this._childFrames=[];for(var i=0;i<frames.length;++i) -frames[i]._remove();} -_remove(){this._removeChildFrames();this._model._frames.delete(this.id);this._model.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameDetached,this);} -addResource(resource){if(this._resourcesMap[resource.url]===resource){return;} -this._resourcesMap[resource.url]=resource;this._model.dispatchEventToListeners(SDK.ResourceTreeModel.Events.ResourceAdded,resource);} -_addRequest(request){var resource=this._resourcesMap[request.url()];if(resource&&resource.request===request){return;} -resource=new SDK.Resource(this._model,request,request.url(),request.documentURL,request.frameId,request.loaderId,request.resourceType(),request.mimeType,null,null);this._resourcesMap[resource.url]=resource;this._model.dispatchEventToListeners(SDK.ResourceTreeModel.Events.ResourceAdded,resource);} -resources(){var result=[];for(var url in this._resourcesMap) -result.push(this._resourcesMap[url]);return result;} -resourceForURL(url){var resource=this._resourcesMap[url]||null;if(resource) -return resource;for(var i=0;!resource&&i<this._childFrames.length;++i) -resource=this._childFrames[i].resourceForURL(url);return resource;} -_callForFrameResources(callback){for(var url in this._resourcesMap){if(callback(this._resourcesMap[url])) -return true;} -for(var i=0;i<this._childFrames.length;++i){if(this._childFrames[i]._callForFrameResources(callback)) -return true;} -return false;} -displayName(){if(!this._parentFrame&&!this._model.target().parentTarget()) -return Common.UIString('top');var subtitle=new Common.ParsedURL(this._url).displayName;if(subtitle){if(!this._name) -return subtitle;return this._name+' ('+subtitle+')';} -return Common.UIString('<iframe>');}};SDK.PageDispatcher=class{constructor(resourceTreeModel){this._resourceTreeModel=resourceTreeModel;} -domContentEventFired(time){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.DOMContentLoaded,time);} -loadEventFired(time){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.Load,{resourceTreeModel:this._resourceTreeModel,loadTime:time});} -lifecycleEvent(frameId,name,time){} -frameAttached(frameId,parentFrameId,stackTrace){this._resourceTreeModel._frameAttached(frameId,parentFrameId,stackTrace);} -frameNavigated(frame){this._resourceTreeModel._frameNavigated(frame);} -frameDetached(frameId){this._resourceTreeModel._frameDetached(frameId);} -frameStartedLoading(frameId){} -frameStoppedLoading(frameId){} -frameScheduledNavigation(frameId,delay){} -frameClearedScheduledNavigation(frameId){} -frameResized(){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameResized,null);} -javascriptDialogOpening(url,message,dialogType,prompt){} -javascriptDialogClosed(result,userInput){} -screencastFrame(data,metadata,sessionId){} -screencastVisibilityChanged(visible){} -interstitialShown(){this._resourceTreeModel._isInterstitialShowing=true;this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.InterstitialShown);} -interstitialHidden(){this._resourceTreeModel._isInterstitialShowing=false;this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.InterstitialHidden);} -windowOpen(url,windowName,windowFeatures,userGesture){}};;SDK.SecurityOriginManager=class extends SDK.SDKModel{constructor(target){super(target);this._securityOrigins=new Set();this._mainSecurityOrigin='';} -updateSecurityOrigins(securityOrigins){var oldOrigins=this._securityOrigins;this._securityOrigins=securityOrigins;for(var origin of oldOrigins){if(!this._securityOrigins.has(origin)) -this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,origin);} -for(var origin of this._securityOrigins){if(!oldOrigins.has(origin)) -this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.SecurityOriginAdded,origin);}} -securityOrigins(){return this._securityOrigins.valuesArray();} -mainSecurityOrigin(){return this._mainSecurityOrigin;} -setMainSecurityOrigin(securityOrigin){this._mainSecurityOrigin=securityOrigin;this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.MainSecurityOriginChanged,securityOrigin);}};SDK.SDKModel.register(SDK.SecurityOriginManager,SDK.Target.Capability.None,false);SDK.SecurityOriginManager.Events={SecurityOriginAdded:Symbol('SecurityOriginAdded'),SecurityOriginRemoved:Symbol('SecurityOriginRemoved'),MainSecurityOriginChanged:Symbol('MainSecurityOriginChanged')};;SDK.SourceMapV3=class{constructor(){this.version;this.file;this.sources;this.sections;this.mappings;this.sourceRoot;this.names;}};SDK.SourceMapV3.Section=class{constructor(){this.map;this.offset;}};SDK.SourceMapV3.Offset=class{constructor(){this.line;this.column;}};SDK.SourceMapEntry=class{constructor(lineNumber,columnNumber,sourceURL,sourceLineNumber,sourceColumnNumber,name){this.lineNumber=lineNumber;this.columnNumber=columnNumber;this.sourceURL=sourceURL;this.sourceLineNumber=sourceLineNumber;this.sourceColumnNumber=sourceColumnNumber;this.name=name;} -static compare(entry1,entry2){if(entry1.lineNumber!==entry2.lineNumber) -return entry1.lineNumber-entry2.lineNumber;return entry1.columnNumber-entry2.columnNumber;}};SDK.SourceMap=function(){};SDK.SourceMap.prototype={compiledURL(){},url(){},sourceURLs(){},sourceContentProvider(sourceURL,contentType){},embeddedContentByURL(sourceURL){},findEntry(lineNumber,columnNumber){},editable(){},editCompiled(ranges,texts){},};SDK.SourceMap.EditResult=class{constructor(map,compiledEdits,newSources){this.map=map;this.compiledEdits=compiledEdits;this.newSources=newSources;}};SDK.SourceMapFactory=function(){};SDK.SourceMapFactory.prototype={editableSourceMap(target,sourceMap){},};SDK.TextSourceMap=class{constructor(compiledURL,sourceMappingURL,payload){if(!SDK.TextSourceMap._base64Map){const base64Digits='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';SDK.TextSourceMap._base64Map={};for(var i=0;i<base64Digits.length;++i) -SDK.TextSourceMap._base64Map[base64Digits.charAt(i)]=i;} -this._json=payload;this._compiledURL=compiledURL;this._sourceMappingURL=sourceMappingURL;this._baseURL=sourceMappingURL.startsWith('data:')?compiledURL:sourceMappingURL;this._mappings=null;this._sourceInfos=new Map();this._eachSection(this._parseSources.bind(this));} -static load(sourceMapURL,compiledURL){var callback;var promise=new Promise(fulfill=>callback=fulfill);SDK.multitargetNetworkManager.loadResource(sourceMapURL,contentLoaded);return promise;function contentLoaded(statusCode,headers,content){if(!content||statusCode>=400){callback(null);return;} -if(content.slice(0,3)===')]}') -content=content.substring(content.indexOf('\n'));try{var payload=(JSON.parse(content));callback(new SDK.TextSourceMap(compiledURL,sourceMapURL,payload));}catch(e){console.error(e);Common.console.warn('DevTools failed to parse SourceMap: '+sourceMapURL);callback(null);}}} -compiledURL(){return this._compiledURL;} -url(){return this._sourceMappingURL;} -sourceURLs(){return this._sourceInfos.keysArray();} -sourceContentProvider(sourceURL,contentType){var info=this._sourceInfos.get(sourceURL);if(info.content) -return Common.StaticContentProvider.fromString(sourceURL,contentType,info.content);return new SDK.CompilerSourceMappingContentProvider(sourceURL,contentType);} -embeddedContentByURL(sourceURL){if(!this._sourceInfos.has(sourceURL)) -return null;return this._sourceInfos.get(sourceURL).content;} -editable(){return false;} -editCompiled(ranges,texts){return Promise.resolve((null));} -findEntry(lineNumber,columnNumber){var mappings=this.mappings();var index=mappings.upperBound(undefined,(unused,entry)=>lineNumber-entry.lineNumber||columnNumber-entry.columnNumber);return index?mappings[index-1]:null;} -sourceLineMapping(sourceURL,lineNumber,columnNumber){var mappings=this._reversedMappings(sourceURL);var first=mappings.lowerBound(lineNumber,lineComparator);var last=mappings.upperBound(lineNumber,lineComparator);if(first>=mappings.length||mappings[first].sourceLineNumber!==lineNumber) -return null;var columnMappings=mappings.slice(first,last);var index=columnMappings.lowerBound(columnNumber,(columnNumber,mapping)=>columnNumber-mapping.sourceColumnNumber);if(index>=columnMappings.length) -return null;return columnMappings[index];function lineComparator(lineNumber,mapping){return lineNumber-mapping.sourceLineNumber;}} -findReverseEntries(sourceURL,lineNumber,columnNumber){var mappings=this._reversedMappings(sourceURL);var endIndex=mappings.upperBound(undefined,(unused,entry)=>lineNumber-entry.sourceLineNumber||columnNumber-entry.sourceColumnNumber);var startIndex=endIndex;while(startIndex>0&&mappings[startIndex-1].sourceLineNumber===mappings[endIndex-1].sourceLineNumber&&mappings[startIndex-1].sourceColumnNumber===mappings[endIndex-1].sourceColumnNumber) ---startIndex;return mappings.slice(startIndex,endIndex);} -mappings(){if(this._mappings===null){this._mappings=[];this._eachSection(this._parseMap.bind(this));this._json=null;} -return(this._mappings);} -_reversedMappings(sourceURL){if(!this._sourceInfos.has(sourceURL)) -return[];var mappings=this.mappings();var info=this._sourceInfos.get(sourceURL);if(info.reverseMappings===null) -info.reverseMappings=mappings.filter(mapping=>mapping.sourceURL===sourceURL).sort(sourceMappingComparator);return info.reverseMappings;function sourceMappingComparator(a,b){if(a.sourceLineNumber!==b.sourceLineNumber) -return a.sourceLineNumber-b.sourceLineNumber;if(a.sourceColumnNumber!==b.sourceColumnNumber) -return a.sourceColumnNumber-b.sourceColumnNumber;if(a.lineNumber!==b.lineNumber) -return a.lineNumber-b.lineNumber;return a.columnNumber-b.columnNumber;}} -_eachSection(callback){if(!this._json.sections){callback(this._json,0,0);return;} -for(var section of this._json.sections) -callback(section.map,section.offset.line,section.offset.column);} -_parseSources(sourceMap){var sourcesList=[];var sourceRoot=sourceMap.sourceRoot||'';if(sourceRoot&&!sourceRoot.endsWith('/')) -sourceRoot+='/';for(var i=0;i<sourceMap.sources.length;++i){var href=sourceRoot+sourceMap.sources[i];var url=Common.ParsedURL.completeURL(this._baseURL,href)||href;var source=sourceMap.sourcesContent&&sourceMap.sourcesContent[i];if(url===this._compiledURL&&source) -url+=Common.UIString('? [sm]');this._sourceInfos.set(url,new SDK.TextSourceMap.SourceInfo(source,null));sourcesList.push(url);} -sourceMap[SDK.TextSourceMap._sourcesListSymbol]=sourcesList;} -_parseMap(map,lineNumber,columnNumber){var sourceIndex=0;var sourceLineNumber=0;var sourceColumnNumber=0;var nameIndex=0;var sources=map[SDK.TextSourceMap._sourcesListSymbol];var names=map.names||[];var stringCharIterator=new SDK.TextSourceMap.StringCharIterator(map.mappings);var sourceURL=sources[sourceIndex];while(true){if(stringCharIterator.peek()===','){stringCharIterator.next();}else{while(stringCharIterator.peek()===';'){lineNumber+=1;columnNumber=0;stringCharIterator.next();} -if(!stringCharIterator.hasNext()) -break;} -columnNumber+=this._decodeVLQ(stringCharIterator);if(!stringCharIterator.hasNext()||this._isSeparator(stringCharIterator.peek())){this._mappings.push(new SDK.SourceMapEntry(lineNumber,columnNumber));continue;} -var sourceIndexDelta=this._decodeVLQ(stringCharIterator);if(sourceIndexDelta){sourceIndex+=sourceIndexDelta;sourceURL=sources[sourceIndex];} -sourceLineNumber+=this._decodeVLQ(stringCharIterator);sourceColumnNumber+=this._decodeVLQ(stringCharIterator);if(!stringCharIterator.hasNext()||this._isSeparator(stringCharIterator.peek())){this._mappings.push(new SDK.SourceMapEntry(lineNumber,columnNumber,sourceURL,sourceLineNumber,sourceColumnNumber));continue;} -nameIndex+=this._decodeVLQ(stringCharIterator);this._mappings.push(new SDK.SourceMapEntry(lineNumber,columnNumber,sourceURL,sourceLineNumber,sourceColumnNumber,names[nameIndex]));} -this._mappings.stableSort(SDK.SourceMapEntry.compare);} -_isSeparator(char){return char===','||char===';';} -_decodeVLQ(stringCharIterator){var result=0;var shift=0;do{var digit=SDK.TextSourceMap._base64Map[stringCharIterator.next()];result+=(digit&SDK.TextSourceMap._VLQ_BASE_MASK)<<shift;shift+=SDK.TextSourceMap._VLQ_BASE_SHIFT;}while(digit&SDK.TextSourceMap._VLQ_CONTINUATION_MASK);var negative=result&1;result>>=1;return negative?-result:result;} -reverseMapTextRange(url,textRange){function comparator(position,mapping){if(position.lineNumber!==mapping.sourceLineNumber) -return position.lineNumber-mapping.sourceLineNumber;return position.columnNumber-mapping.sourceColumnNumber;} -var mappings=this._reversedMappings(url);var startIndex=mappings.lowerBound({lineNumber:textRange.startLine,columnNumber:textRange.startColumn},comparator);var endIndex=mappings.upperBound({lineNumber:textRange.endLine,columnNumber:textRange.endColumn},comparator);var startMapping=mappings[startIndex];var endMapping=mappings[endIndex];return new TextUtils.TextRange(startMapping.lineNumber,startMapping.columnNumber,endMapping.lineNumber,endMapping.columnNumber);}};SDK.TextSourceMap._VLQ_BASE_SHIFT=5;SDK.TextSourceMap._VLQ_BASE_MASK=(1<<5)-1;SDK.TextSourceMap._VLQ_CONTINUATION_MASK=1<<5;SDK.TextSourceMap.StringCharIterator=class{constructor(string){this._string=string;this._position=0;} -next(){return this._string.charAt(this._position++);} -peek(){return this._string.charAt(this._position);} -hasNext(){return this._position<this._string.length;}};SDK.TextSourceMap.SourceInfo=class{constructor(content,reverseMappings){this.content=content;this.reverseMappings=reverseMappings;}};SDK.TextSourceMap._sourcesListSymbol=Symbol('sourcesList');;SDK.SourceMapManager=class extends Common.Object{constructor(target){super();this._target=target;this._isEnabled=true;this._relativeSourceURL=new Map();this._relativeSourceMapURL=new Map();this._resolvedSourceMapURL=new Map();this._sourceMapByURL=new Map();this._sourceMapURLToLoadingClients=new Multimap();this._sourceMapURLToClients=new Multimap();SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._inspectedURLChanged,this);} -setEnabled(isEnabled){if(isEnabled===this._isEnabled) -return;this._isEnabled=isEnabled;var clients=Array.from(this._resolvedSourceMapURL.keys());for(var client of clients){var relativeSourceURL=this._relativeSourceURL.get(client);var relativeSourceMapURL=this._relativeSourceMapURL.get(client);this.detachSourceMap(client);this.attachSourceMap(client,relativeSourceURL,relativeSourceMapURL);}} -_inspectedURLChanged(event){if(event.data!==this._target) -return;var clients=Array.from(this._resolvedSourceMapURL.keys());for(var client of clients){var relativeSourceURL=this._relativeSourceURL.get(client);var relativeSourceMapURL=this._relativeSourceMapURL.get(client);var resolvedSourceMapURL=this._resolvedSourceMapURL.get(client);var sourceMapURL=this._resolveRelativeURLs(relativeSourceURL,relativeSourceMapURL).sourceMapURL;if(sourceMapURL!==resolvedSourceMapURL){this.detachSourceMap(client);this.attachSourceMap(client,relativeSourceURL,relativeSourceMapURL);}}} -sourceMapForClient(client){var sourceMapURL=this._resolvedSourceMapURL.get(client);return sourceMapURL?this._sourceMapByURL.get(sourceMapURL)||null:null;} -clientsForSourceMap(sourceMap){if(this._sourceMapURLToClients.has(sourceMap.url())) -return this._sourceMapURLToClients.get(sourceMap.url()).valuesArray();return this._sourceMapURLToLoadingClients.get(sourceMap.url()).valuesArray();} -applySourceMapEdit(editResult){console.assert(this._sourceMapByURL.has(editResult.map.url()),'Cannot apply edit result for non-existing source map');this._sourceMapByURL.set(editResult.map.url(),editResult.map);this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapChanged,{sourceMap:editResult.map,newSources:editResult.newSources});} -_resolveRelativeURLs(sourceURL,sourceMapURL){var resolvedSourceURL=Common.ParsedURL.completeURL(this._target.inspectedURL(),sourceURL);var resolvedSourceMapURL=resolvedSourceURL?Common.ParsedURL.completeURL(resolvedSourceURL,sourceMapURL):null;return{sourceURL:resolvedSourceURL,sourceMapURL:resolvedSourceMapURL};} -attachSourceMap(client,sourceURL,sourceMapURL){if(!sourceMapURL) -return;console.assert(!this._resolvedSourceMapURL.has(client),'SourceMap is already attached to client');var resolvedURLs=this._resolveRelativeURLs(sourceURL,sourceMapURL);if(!resolvedURLs.sourceURL||!resolvedURLs.sourceMapURL) -return;this._relativeSourceURL.set(client,sourceURL);this._relativeSourceMapURL.set(client,sourceMapURL);this._resolvedSourceMapURL.set(client,resolvedURLs.sourceMapURL);sourceURL=resolvedURLs.sourceURL;sourceMapURL=resolvedURLs.sourceMapURL;if(!this._isEnabled) -return;this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapWillAttach,client);if(this._sourceMapByURL.has(sourceMapURL)){attach.call(this,sourceMapURL,client);return;} -if(!this._sourceMapURLToLoadingClients.has(sourceMapURL)){SDK.TextSourceMap.load(sourceMapURL,sourceURL).then(onTextSourceMapLoaded.bind(this,sourceMapURL)).then(onSourceMap.bind(this,sourceMapURL));} -this._sourceMapURLToLoadingClients.set(sourceMapURL,client);function onTextSourceMapLoaded(sourceMapURL,sourceMap){if(!sourceMap) -return Promise.resolve((null));var factoryExtension=this._factoryForSourceMap(sourceMap);if(!factoryExtension) -return Promise.resolve((sourceMap));return factoryExtension.instance().then(factory=>factory.editableSourceMap(this._target,sourceMap)).then(map=>map||sourceMap).catchException((null));} -function onSourceMap(sourceMapURL,sourceMap){this._sourceMapLoadedForTest();var clients=this._sourceMapURLToLoadingClients.get(sourceMapURL);this._sourceMapURLToLoadingClients.deleteAll(sourceMapURL);if(!clients.size) -return;if(!sourceMap){for(var client of clients) -this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapFailedToAttach,client);return;} -this._sourceMapByURL.set(sourceMapURL,sourceMap);for(var client of clients) -attach.call(this,sourceMapURL,client);} -function attach(sourceMapURL,client){this._sourceMapURLToClients.set(sourceMapURL,client);var sourceMap=this._sourceMapByURL.get(sourceMapURL);this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapAttached,{client:client,sourceMap:sourceMap});}} -_factoryForSourceMap(sourceMap){var sourceExtensions=new Set();for(var url of sourceMap.sourceURLs()) -sourceExtensions.add(Common.ParsedURL.extractExtension(url));for(var runtimeExtension of self.runtime.extensions(SDK.SourceMapFactory)){var supportedExtensions=new Set(runtimeExtension.descriptor()['extensions']);if(supportedExtensions.containsAll(sourceExtensions)) -return runtimeExtension;} -return null;} -detachSourceMap(client){var sourceMapURL=this._resolvedSourceMapURL.get(client);this._relativeSourceURL.delete(client);this._relativeSourceMapURL.delete(client);this._resolvedSourceMapURL.delete(client);if(!sourceMapURL) -return;if(!this._sourceMapURLToClients.hasValue(sourceMapURL,client)){if(this._sourceMapURLToLoadingClients.delete(sourceMapURL,client)) -this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapFailedToAttach,client);return;} -this._sourceMapURLToClients.delete(sourceMapURL,client);var sourceMap=this._sourceMapByURL.get(sourceMapURL);if(!this._sourceMapURLToClients.has(sourceMapURL)) -this._sourceMapByURL.delete(sourceMapURL);this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapDetached,{client:client,sourceMap:sourceMap});} -_sourceMapLoadedForTest(){} -dispose(){SDK.targetManager.removeEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._inspectedURLChanged,this);}};SDK.SourceMapManager.Events={SourceMapWillAttach:Symbol('SourceMapWillAttach'),SourceMapFailedToAttach:Symbol('SourceMapFailedToAttach'),SourceMapAttached:Symbol('SourceMapAttached'),SourceMapDetached:Symbol('SourceMapDetached'),SourceMapChanged:Symbol('SourceMapChanged')};;SDK.NetworkManager=class extends SDK.SDKModel{constructor(target){super(target);this._dispatcher=new SDK.NetworkDispatcher(this);this._networkAgent=target.networkAgent();target.registerNetworkDispatcher(this._dispatcher);if(Common.moduleSetting('cacheDisabled').get()) -this._networkAgent.setCacheDisabled(true);if(Runtime.queryParam('remoteFrontend')||Runtime.queryParam('ws')) -this._networkAgent.enable(10000000,5000000);else -this._networkAgent.enable();this._bypassServiceWorkerSetting=Common.settings.createSetting('bypassServiceWorker',false);if(this._bypassServiceWorkerSetting.get()) -this._bypassServiceWorkerChanged();this._bypassServiceWorkerSetting.addChangeListener(this._bypassServiceWorkerChanged,this);Common.moduleSetting('cacheDisabled').addChangeListener(this._cacheDisabledSettingChanged,this);} -static forRequest(request){return request[SDK.NetworkManager._networkManagerForRequestSymbol];} -static canReplayRequest(request){return!!request[SDK.NetworkManager._networkManagerForRequestSymbol]&&request.resourceType()===Common.resourceTypes.XHR;} -static replayRequest(request){var manager=request[SDK.NetworkManager._networkManagerForRequestSymbol];if(!manager) -return;manager._networkAgent.replayXHR(request.requestId());} -static async requestContentData(request){if(request.resourceType()===Common.resourceTypes.WebSocket) -return{error:'Content for WebSockets is currently not supported',content:null,encoded:false};if(!request.finished) -await request.once(SDK.NetworkRequest.Events.FinishedLoading);var manager=SDK.NetworkManager.forRequest(request);if(!manager) -return{error:'No network manager for request',content:null,encoded:false};var response=await manager._networkAgent.invoke_getResponseBody({requestId:request.requestId()});var error=response[Protocol.Error]||null;return{error:error,content:error?null:response.body,encoded:response.base64Encoded};} -static _connectionType(conditions){if(!conditions.download&&!conditions.upload) -return Protocol.Network.ConnectionType.None;var types=SDK.NetworkManager._connectionTypes;if(!types){SDK.NetworkManager._connectionTypes=[];types=SDK.NetworkManager._connectionTypes;types.push(['2g',Protocol.Network.ConnectionType.Cellular2g]);types.push(['3g',Protocol.Network.ConnectionType.Cellular3g]);types.push(['4g',Protocol.Network.ConnectionType.Cellular4g]);types.push(['bluetooth',Protocol.Network.ConnectionType.Bluetooth]);types.push(['wifi',Protocol.Network.ConnectionType.Wifi]);types.push(['wimax',Protocol.Network.ConnectionType.Wimax]);} -for(var type of types){if(conditions.title.toLowerCase().indexOf(type[0])!==-1) -return type[1];} -return Protocol.Network.ConnectionType.Other;} -inflightRequestForURL(url){return this._dispatcher._inflightRequestsByURL[url];} -_cacheDisabledSettingChanged(event){var enabled=(event.data);this._networkAgent.setCacheDisabled(enabled);} -dispose(){Common.moduleSetting('cacheDisabled').removeChangeListener(this._cacheDisabledSettingChanged,this);} -_bypassServiceWorkerChanged(){this._networkAgent.setBypassServiceWorker(this._bypassServiceWorkerSetting.get());}};SDK.SDKModel.register(SDK.NetworkManager,SDK.Target.Capability.Network,true);SDK.NetworkManager.Events={RequestStarted:Symbol('RequestStarted'),RequestUpdated:Symbol('RequestUpdated'),RequestFinished:Symbol('RequestFinished'),RequestUpdateDropped:Symbol('RequestUpdateDropped'),ResponseReceived:Symbol('ResponseReceived'),MessageGenerated:Symbol('MessageGenerated'),RequestRedirected:Symbol('RequestRedirected'),};SDK.NetworkManager.Message;SDK.NetworkManager._MIMETypes={'text/html':{'document':true},'text/xml':{'document':true},'text/plain':{'document':true},'application/xhtml+xml':{'document':true},'image/svg+xml':{'document':true},'text/css':{'stylesheet':true},'text/xsl':{'stylesheet':true},'text/vtt':{'texttrack':true},};SDK.NetworkManager.Conditions;SDK.NetworkManager.NoThrottlingConditions={title:Common.UIString('Online'),download:-1,upload:-1,latency:0};SDK.NetworkManager.OfflineConditions={title:Common.UIString('Offline'),download:0,upload:0,latency:0,};SDK.NetworkManager.Slow3GConditions={title:Common.UIString('Slow 3G'),download:500*1024/8*.8,upload:500*1024/8*.8,latency:400*5,};SDK.NetworkManager.Fast3GConditions={title:Common.UIString('Fast 3G'),download:1.6*1024*1024/8*.9,upload:750*1024/8*.9,latency:150*3.75,};SDK.NetworkManager.BlockedPattern;SDK.NetworkManager._networkManagerForRequestSymbol=Symbol('NetworkManager');SDK.NetworkDispatcher=class{constructor(manager){this._manager=manager;this._inflightRequestsById={};this._inflightRequestsByURL={};} -_headersMapToHeadersArray(headersMap){var result=[];for(var name in headersMap){var values=headersMap[name].split('\n');for(var i=0;i<values.length;++i) -result.push({name:name,value:values[i]});} -return result;} -_updateNetworkRequestWithRequest(networkRequest,request){networkRequest.requestMethod=request.method;networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers));networkRequest.requestFormData=request.postData;networkRequest.setInitialPriority(request.initialPriority);networkRequest.mixedContentType=request.mixedContentType||Protocol.Security.MixedContentType.None;networkRequest.setReferrerPolicy(request.referrerPolicy);} -_updateNetworkRequestWithResponse(networkRequest,response){if(response.url&&networkRequest.url()!==response.url) -networkRequest.setUrl(response.url);networkRequest.mimeType=response.mimeType;networkRequest.statusCode=response.status;networkRequest.statusText=response.statusText;networkRequest.responseHeaders=this._headersMapToHeadersArray(response.headers);if(response.encodedDataLength>=0) -networkRequest.setTransferSize(response.encodedDataLength);if(response.headersText) -networkRequest.responseHeadersText=response.headersText;if(response.requestHeaders){networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders));networkRequest.setRequestHeadersText(response.requestHeadersText||'');} -networkRequest.connectionReused=response.connectionReused;networkRequest.connectionId=String(response.connectionId);if(response.remoteIPAddress) -networkRequest.setRemoteAddress(response.remoteIPAddress,response.remotePort||-1);if(response.fromServiceWorker) -networkRequest.fetchedViaServiceWorker=true;if(response.fromDiskCache) -networkRequest.setFromDiskCache();networkRequest.timing=response.timing;networkRequest.protocol=response.protocol;networkRequest.setSecurityState(response.securityState);if(!this._mimeTypeIsConsistentWithType(networkRequest)){var message=Common.UIString('Resource interpreted as %s but transferred with MIME type %s: "%s".',networkRequest.resourceType().title(),networkRequest.mimeType,networkRequest.url());this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:networkRequest.requestId(),warning:true});} -if(response.securityDetails) -networkRequest.setSecurityDetails(response.securityDetails);} -_mimeTypeIsConsistentWithType(networkRequest){if(networkRequest.hasErrorStatusCode()||networkRequest.statusCode===304||networkRequest.statusCode===204) -return true;var resourceType=networkRequest.resourceType();if(resourceType!==Common.resourceTypes.Stylesheet&&resourceType!==Common.resourceTypes.Document&&resourceType!==Common.resourceTypes.TextTrack) -return true;if(!networkRequest.mimeType) -return true;if(networkRequest.mimeType in SDK.NetworkManager._MIMETypes) -return resourceType.name()in SDK.NetworkManager._MIMETypes[networkRequest.mimeType];return false;} -resourceChangedPriority(requestId,newPriority,timestamp){var networkRequest=this._inflightRequestsById[requestId];if(networkRequest) -networkRequest.setPriority(newPriority);} -requestWillBeSent(requestId,loaderId,documentURL,request,time,wallTime,initiator,redirectResponse,resourceType,frameId){var networkRequest=this._inflightRequestsById[requestId];if(networkRequest){if(!redirectResponse) -return;this.responseReceived(requestId,loaderId,time,Protocol.Page.ResourceType.Other,redirectResponse,frameId);networkRequest=this._appendRedirect(requestId,time,request.url);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestRedirected,networkRequest);}else{networkRequest=this._createNetworkRequest(requestId,frameId||'',loaderId,request.url,documentURL,initiator);} -networkRequest.hasNetworkData=true;this._updateNetworkRequestWithRequest(networkRequest,request);networkRequest.setIssueTime(time,wallTime);networkRequest.setResourceType(resourceType?Common.resourceTypes[resourceType]:Protocol.Page.ResourceType.Other);this._startNetworkRequest(networkRequest);} -requestServedFromCache(requestId){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;networkRequest.setFromMemoryCache();} -responseReceived(requestId,loaderId,time,resourceType,response,frameId){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest){var eventData={};eventData.url=response.url;eventData.frameId=frameId||'';eventData.loaderId=loaderId;eventData.resourceType=resourceType;eventData.mimeType=response.mimeType;var lastModifiedHeader=response.headers['last-modified'];eventData.lastModified=lastModifiedHeader?new Date(lastModifiedHeader):null;this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestUpdateDropped,eventData);return;} -networkRequest.responseReceivedTime=time;networkRequest.setResourceType(Common.resourceTypes[resourceType]);if('Set-Cookie'in response.headers&&response.headers['Set-Cookie'].length>4096){var message=Common.UIString('Set-Cookie header is ignored in response from url: %s. Cookie length should be less than or equal to 4096 characters.',response.url);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:requestId,warning:true});} -this._updateNetworkRequestWithResponse(networkRequest,response);this._updateNetworkRequest(networkRequest);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.ResponseReceived,networkRequest);} -dataReceived(requestId,time,dataLength,encodedDataLength){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;networkRequest.resourceSize+=dataLength;if(encodedDataLength!==-1) -networkRequest.increaseTransferSize(encodedDataLength);networkRequest.endTime=time;this._updateNetworkRequest(networkRequest);} -loadingFinished(requestId,finishTime,encodedDataLength){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;this._finishNetworkRequest(networkRequest,finishTime,encodedDataLength);} -loadingFailed(requestId,time,resourceType,localizedDescription,canceled,blockedReason){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;networkRequest.failed=true;networkRequest.setResourceType(Common.resourceTypes[resourceType]);networkRequest.canceled=!!canceled;if(blockedReason){networkRequest.setBlockedReason(blockedReason);if(blockedReason===Protocol.Network.BlockedReason.Inspector){var message=Common.UIString('Request was blocked by DevTools: "%s".',networkRequest.url());this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:requestId,warning:true});}} -networkRequest.localizedFailDescription=localizedDescription;this._finishNetworkRequest(networkRequest,time,-1);} -webSocketCreated(requestId,requestURL,initiator){var networkRequest=new SDK.NetworkRequest(requestId,requestURL,'','','',initiator||null);networkRequest[SDK.NetworkManager._networkManagerForRequestSymbol]=this._manager;networkRequest.setResourceType(Common.resourceTypes.WebSocket);this._startNetworkRequest(networkRequest);} -webSocketWillSendHandshakeRequest(requestId,time,wallTime,request){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;networkRequest.requestMethod='GET';networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers));networkRequest.setIssueTime(time,wallTime);this._updateNetworkRequest(networkRequest);} -webSocketHandshakeResponseReceived(requestId,time,response){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;networkRequest.statusCode=response.status;networkRequest.statusText=response.statusText;networkRequest.responseHeaders=this._headersMapToHeadersArray(response.headers);networkRequest.responseHeadersText=response.headersText||'';if(response.requestHeaders) -networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders));if(response.requestHeadersText) -networkRequest.setRequestHeadersText(response.requestHeadersText);networkRequest.responseReceivedTime=time;networkRequest.protocol='websocket';this._updateNetworkRequest(networkRequest);} -webSocketFrameReceived(requestId,time,response){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;networkRequest.addFrame(response,time,false);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);} -webSocketFrameSent(requestId,time,response){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;networkRequest.addFrame(response,time,true);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);} -webSocketFrameError(requestId,time,errorMessage){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;networkRequest.addFrameError(errorMessage,time);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);} -webSocketClosed(requestId,time){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;this._finishNetworkRequest(networkRequest,time,-1);} -eventSourceMessageReceived(requestId,time,eventName,eventId,data){var networkRequest=this._inflightRequestsById[requestId];if(!networkRequest) -return;networkRequest.addEventSourceMessage(time,eventName,eventId,data);} -requestIntercepted(interceptionId,request,frameId,resourceType,isNavigationRequest,redirectHeaders,redirectStatusCode,redirectUrl,authChallenge){SDK.multitargetNetworkManager._requestIntercepted(new SDK.MultitargetNetworkManager.InterceptedRequest(this._manager.target().networkAgent(),interceptionId,request,frameId,resourceType,isNavigationRequest,redirectHeaders,redirectStatusCode,redirectUrl,authChallenge));} -_appendRedirect(requestId,time,redirectURL){var originalNetworkRequest=this._inflightRequestsById[requestId];var redirectCount=0;for(var redirect=originalNetworkRequest.redirectSource();redirect;redirect=redirect.redirectSource()) -redirectCount++;originalNetworkRequest.setRequestId(requestId+':redirected.'+redirectCount);this._finishNetworkRequest(originalNetworkRequest,time,-1);var newNetworkRequest=this._createNetworkRequest(requestId,originalNetworkRequest.frameId,originalNetworkRequest.loaderId,redirectURL,originalNetworkRequest.documentURL,originalNetworkRequest.initiator());newNetworkRequest.setRedirectSource(originalNetworkRequest);return newNetworkRequest;} -_startNetworkRequest(networkRequest){this._inflightRequestsById[networkRequest.requestId()]=networkRequest;this._inflightRequestsByURL[networkRequest.url()]=networkRequest;this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestStarted,networkRequest);} -_updateNetworkRequest(networkRequest){this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestUpdated,networkRequest);} -_finishNetworkRequest(networkRequest,finishTime,encodedDataLength){networkRequest.endTime=finishTime;networkRequest.finished=true;if(encodedDataLength>=0) -networkRequest.setTransferSize(encodedDataLength);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestFinished,networkRequest);delete this._inflightRequestsById[networkRequest.requestId()];delete this._inflightRequestsByURL[networkRequest.url()];if(Common.moduleSetting('monitoringXHREnabled').get()&&networkRequest.resourceType().category()===Common.resourceCategories.XHR){var message=Common.UIString((networkRequest.failed||networkRequest.hasErrorStatusCode())?'%s failed loading: %s "%s".':'%s finished loading: %s "%s".',networkRequest.resourceType().title(),networkRequest.requestMethod,networkRequest.url());this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:networkRequest.requestId(),warning:false});}} -_createNetworkRequest(requestId,frameId,loaderId,url,documentURL,initiator){var request=new SDK.NetworkRequest(requestId,url,documentURL,frameId,loaderId,initiator);request[SDK.NetworkManager._networkManagerForRequestSymbol]=this._manager;return request;}};SDK.MultitargetNetworkManager=class extends Common.Object{constructor(){super();this._userAgentOverride='';this._agents=new Set();this._networkConditions=SDK.NetworkManager.NoThrottlingConditions;this._updatingInterceptionPatternsPromise=null;this._blockingEnabledSetting=Common.moduleSetting('requestBlockingEnabled');this._blockedPatternsSetting=Common.settings.createSetting('networkBlockedPatterns',[]);this._effectiveBlockedURLs=[];this._updateBlockedPatterns();this._requestInterceptorMap=new Multimap();this._urlsForRequestInterceptor=new Multimap();SDK.targetManager.observeTargets(this,SDK.Target.Capability.Network);} -static patchUserAgentWithChromeVersion(uaString){var chromeRegex=new RegExp('(?:^|\\W)Chrome/(\\S+)');var chromeMatch=navigator.userAgent.match(chromeRegex);if(chromeMatch&&chromeMatch.length>1) -return String.sprintf(uaString,chromeMatch[1]);return uaString;} -targetAdded(target){var networkAgent=target.networkAgent();if(this._extraHeaders) -networkAgent.setExtraHTTPHeaders(this._extraHeaders);if(this._currentUserAgent()) -networkAgent.setUserAgentOverride(this._currentUserAgent());if(this._effectiveBlockedURLs.length) -networkAgent.setBlockedURLs(this._effectiveBlockedURLs);if(this.isIntercepting()){networkAgent.setRequestInterception(this._requestInterceptorMap.keysArray().map(pattern=>({urlPattern:pattern.replace(/([\\?*])/g,'\\$1')})));} -this._agents.add(networkAgent);if(this.isThrottling()) -this._updateNetworkConditions(networkAgent);} -targetRemoved(target){this._agents.delete(target.networkAgent());} -isThrottling(){return this._networkConditions.download>=0||this._networkConditions.upload>=0||this._networkConditions.latency>0;} -isOffline(){return!this._networkConditions.download&&!this._networkConditions.upload;} -setNetworkConditions(conditions){this._networkConditions=conditions;for(var agent of this._agents) -this._updateNetworkConditions(agent);this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.ConditionsChanged);} -networkConditions(){return this._networkConditions;} -_updateNetworkConditions(networkAgent){var conditions=this._networkConditions;if(!this.isThrottling()){networkAgent.emulateNetworkConditions(false,0,0,0);}else{networkAgent.emulateNetworkConditions(this.isOffline(),conditions.latency,conditions.download<0?0:conditions.download,conditions.upload<0?0:conditions.upload,SDK.NetworkManager._connectionType(conditions));}} -setExtraHTTPHeaders(headers){this._extraHeaders=headers;for(var agent of this._agents) -agent.setExtraHTTPHeaders(this._extraHeaders);} -_currentUserAgent(){return this._customUserAgent?this._customUserAgent:this._userAgentOverride;} -_updateUserAgentOverride(){var userAgent=this._currentUserAgent();for(var agent of this._agents) -agent.setUserAgentOverride(userAgent);} -setUserAgentOverride(userAgent){if(this._userAgentOverride===userAgent) -return;this._userAgentOverride=userAgent;if(!this._customUserAgent) -this._updateUserAgentOverride();this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.UserAgentChanged);} -userAgentOverride(){return this._userAgentOverride;} -setCustomUserAgentOverride(userAgent){this._customUserAgent=userAgent;this._updateUserAgentOverride();} -blockedPatterns(){return this._blockedPatternsSetting.get().slice();} -blockingEnabled(){return this._blockingEnabledSetting.get();} -isBlocking(){return!!this._effectiveBlockedURLs.length;} -setBlockedPatterns(patterns){this._blockedPatternsSetting.set(patterns);this._updateBlockedPatterns();this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged);} -setBlockingEnabled(enabled){if(this._blockingEnabledSetting.get()===enabled) -return;this._blockingEnabledSetting.set(enabled);this._updateBlockedPatterns();this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged);} -_updateBlockedPatterns(){var urls=[];if(this._blockingEnabledSetting.get()){for(var pattern of this._blockedPatternsSetting.get()){if(pattern.enabled) -urls.push(pattern.url);}} -if(!urls.length&&!this._effectiveBlockedURLs.length) -return;this._effectiveBlockedURLs=urls;for(var agent of this._agents) -agent.setBlockedURLs(this._effectiveBlockedURLs);} -isIntercepting(){return!!this._requestInterceptorMap.size;} -setInterceptionHandlerForPatterns(patterns,requestInterceptor){var oldPatterns=this._urlsForRequestInterceptor.get(requestInterceptor);if(oldPatterns){for(var oldPattern of oldPatterns) -this._requestInterceptorMap.delete(oldPattern,requestInterceptor);} -this._urlsForRequestInterceptor.deleteAll(requestInterceptor);for(var newPattern of patterns){this._urlsForRequestInterceptor.set(requestInterceptor,newPattern);this._requestInterceptorMap.set(newPattern,requestInterceptor);} -return this._updateInterceptionPatternsOnNextTick();} -_updateInterceptionPatternsOnNextTick(){if(!this._updatingInterceptionPatternsPromise) -this._updatingInterceptionPatternsPromise=Promise.resolve().then(this._updateInterceptionPatterns.bind(this));return this._updatingInterceptionPatternsPromise;} -_updateInterceptionPatterns(){this._updatingInterceptionPatternsPromise=null;var promises=([]);for(var agent of this._agents){var patterns=this._requestInterceptorMap.keysArray().map(pattern=>({urlPattern:pattern.replace(/([\\?*])/g,'\\$1')}));promises.push(agent.setRequestInterception(this.isIntercepting()?patterns:[]));} -this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.InterceptorsChanged);return Promise.all(promises);} -async _requestIntercepted(interceptedRequest){var url=interceptedRequest.request.url;var requestInterceptors=this._requestInterceptorMap.get(url);if(!requestInterceptors) -return;for(var requestInterceptor of requestInterceptors){if(!this._requestInterceptorMap.hasValue(url,requestInterceptor)) -continue;await requestInterceptor(interceptedRequest);if(interceptedRequest.hasResponded()) -return;} -if(!interceptedRequest.hasResponded()) -interceptedRequest.continueRequestWithoutChange();} -clearBrowserCache(){for(var agent of this._agents) -agent.clearBrowserCache();} -clearBrowserCookies(){for(var agent of this._agents) -agent.clearBrowserCookies();} -getCertificate(origin){var target=SDK.targetManager.mainTarget();return target.networkAgent().getCertificate(origin).then(certificate=>certificate||[]);} -loadResource(url,callback){var headers={};var currentUserAgent=this._currentUserAgent();if(currentUserAgent) -headers['User-Agent']=currentUserAgent;if(Common.moduleSetting('cacheDisabled').get()) -headers['Cache-Control']='no-cache';Host.ResourceLoader.load(url,headers,callback);}};SDK.MultitargetNetworkManager.Events={BlockedPatternsChanged:Symbol('BlockedPatternsChanged'),ConditionsChanged:Symbol('ConditionsChanged'),UserAgentChanged:Symbol('UserAgentChanged'),InterceptorsChanged:Symbol('InterceptorsChanged')};SDK.MultitargetNetworkManager.InterceptedRequest=class{constructor(networkAgent,interceptionId,request,frameId,resourceType,isNavigationRequest,redirectHeaders,redirectStatusCode,redirectUrl,authChallenge){this._networkAgent=networkAgent;this._interceptionId=interceptionId;this._hasResponded=false;this.request=request;this.frameId=frameId;this.resourceType=resourceType;this.isNavigationRequest=isNavigationRequest;this.redirectHeaders=redirectHeaders;this.redirectStatusCode=redirectStatusCode;this.redirectUrl=redirectUrl;this.authChallenge=authChallenge;} -hasResponded(){return this._hasResponded;} -async continueRequestWithContent(contentBlob){this._hasResponded=true;var headers=['HTTP/1.1 200 OK','Date: '+(new Date()).toUTCString(),'Server: Chrome Devtools Request Interceptor','Connection: closed','Content-Length: '+contentBlob.size,'Content-Type: '+contentBlob.type||'text/x-unknown',];var encodedResponse=await blobToBase64(new Blob([headers.join('\r\n'),'\r\n\r\n',contentBlob]));this._networkAgent.continueInterceptedRequest(this._interceptionId,undefined,encodedResponse);async function blobToBase64(blob){var reader=new FileReader();var fileContentsLoadedPromise=new Promise(resolve=>reader.onloadend=resolve);reader.readAsDataURL(blob);await fileContentsLoadedPromise;if(reader.error){console.error('Could not convert blob to base64.',reader.error);return'';} -var result=reader.result;if(result===undefined){console.error('Could not convert blob to base64.');return'';} -return result.substring(result.indexOf(',')+1);}} -continueRequestWithoutChange(){console.assert(!this._hasResponded);this._hasResponded=true;this._networkAgent.continueInterceptedRequest(this._interceptionId);} -continueRequestWithError(errorReason){console.assert(!this._hasResponded);this._hasResponded=true;this._networkAgent.continueInterceptedRequest(this._interceptionId,errorReason);}};SDK.MultitargetNetworkManager.RequestInterceptor;SDK.multitargetNetworkManager;;SDK.NetworkRequest=class extends Common.Object{constructor(requestId,url,documentURL,frameId,loaderId,initiator){super();this._requestId=requestId;this.setUrl(url);this._documentURL=documentURL;this._frameId=frameId;this._loaderId=loaderId;this._initiator=initiator;this._redirectSource=null;this._issueTime=-1;this._startTime=-1;this._endTime=-1;this._blockedReason=undefined;this.statusCode=0;this.statusText='';this.requestMethod='';this.requestTime=0;this.protocol='';this.mixedContentType=Protocol.Security.MixedContentType.None;this._initialPriority=null;this._currentPriority=null;this._resourceType=Common.resourceTypes.Other;this._contentData=null;this._frames=[];this._eventSourceMessages=[];this._responseHeaderValues={};this._responseHeadersText='';this._requestHeaders=[];this._requestHeaderValues={};this._remoteAddress='';this._referrerPolicy=null;this._securityState=Protocol.Security.SecurityState.Unknown;this._securityDetails=null;this.connectionId='0';} -indentityCompare(other){if(this._requestId>other._requestId) -return 1;if(this._requestId<other._requestId) -return-1;return 0;} -requestId(){return this._requestId;} -setRequestId(requestId){this._requestId=requestId;} -url(){return this._url;} -setUrl(x){if(this._url===x) -return;this._url=x;this._parsedURL=new Common.ParsedURL(x);delete this._queryString;delete this._parsedQueryParameters;delete this._name;delete this._path;} -get documentURL(){return this._documentURL;} -get parsedURL(){return this._parsedURL;} -get frameId(){return this._frameId;} -get loaderId(){return this._loaderId;} -setRemoteAddress(ip,port){this._remoteAddress=ip+':'+port;this.dispatchEventToListeners(SDK.NetworkRequest.Events.RemoteAddressChanged,this);} -remoteAddress(){return this._remoteAddress;} -setReferrerPolicy(referrerPolicy){this._referrerPolicy=referrerPolicy;} -referrerPolicy(){return this._referrerPolicy;} -securityState(){return this._securityState;} -setSecurityState(securityState){this._securityState=securityState;} -securityDetails(){return this._securityDetails;} -setSecurityDetails(securityDetails){this._securityDetails=securityDetails;} -get startTime(){return this._startTime||-1;} -setIssueTime(monotonicTime,wallTime){this._issueTime=monotonicTime;this._wallIssueTime=wallTime;this._startTime=monotonicTime;} -issueTime(){return this._issueTime;} -pseudoWallTime(monotonicTime){return this._wallIssueTime?this._wallIssueTime-this._issueTime+monotonicTime:monotonicTime;} -get responseReceivedTime(){return this._responseReceivedTime||-1;} -set responseReceivedTime(x){this._responseReceivedTime=x;} -get endTime(){return this._endTime||-1;} -set endTime(x){if(this.timing&&this.timing.requestTime){this._endTime=Math.max(x,this.responseReceivedTime);}else{this._endTime=x;if(this._responseReceivedTime>x) -this._responseReceivedTime=x;} -this.dispatchEventToListeners(SDK.NetworkRequest.Events.TimingChanged,this);} -get duration(){if(this._endTime===-1||this._startTime===-1) -return-1;return this._endTime-this._startTime;} -get latency(){if(this._responseReceivedTime===-1||this._startTime===-1) -return-1;return this._responseReceivedTime-this._startTime;} -get resourceSize(){return this._resourceSize||0;} -set resourceSize(x){this._resourceSize=x;} -get transferSize(){return this._transferSize||0;} -increaseTransferSize(x){this._transferSize=(this._transferSize||0)+x;} -setTransferSize(x){this._transferSize=x;} -get finished(){return this._finished;} -set finished(x){if(this._finished===x) -return;this._finished=x;if(x) -this.dispatchEventToListeners(SDK.NetworkRequest.Events.FinishedLoading,this);} -get failed(){return this._failed;} -set failed(x){this._failed=x;} -get canceled(){return this._canceled;} -set canceled(x){this._canceled=x;} -blockedReason(){return this._blockedReason;} -setBlockedReason(reason){this._blockedReason=reason;} -wasBlocked(){return!!this._blockedReason;} -cached(){return(!!this._fromMemoryCache||!!this._fromDiskCache)&&!this._transferSize;} -cachedInMemory(){return!!this._fromMemoryCache&&!this._transferSize;} -setFromMemoryCache(){this._fromMemoryCache=true;delete this._timing;} -setFromDiskCache(){this._fromDiskCache=true;} -get fetchedViaServiceWorker(){return this._fetchedViaServiceWorker;} -set fetchedViaServiceWorker(x){this._fetchedViaServiceWorker=x;} -get timing(){return this._timing;} -set timing(timingInfo){if(!timingInfo||this._fromMemoryCache) -return;this._startTime=timingInfo.requestTime;var headersReceivedTime=timingInfo.requestTime+timingInfo.receiveHeadersEnd/1000.0;if((this._responseReceivedTime||-1)<0||this._responseReceivedTime>headersReceivedTime) -this._responseReceivedTime=headersReceivedTime;if(this._startTime>this._responseReceivedTime) -this._responseReceivedTime=this._startTime;this._timing=timingInfo;this.dispatchEventToListeners(SDK.NetworkRequest.Events.TimingChanged,this);} -get mimeType(){return this._mimeType;} -set mimeType(x){this._mimeType=x;} -get displayName(){return this._parsedURL.displayName;} -name(){if(this._name) -return this._name;this._parseNameAndPathFromURL();return this._name;} -path(){if(this._path) -return this._path;this._parseNameAndPathFromURL();return this._path;} -_parseNameAndPathFromURL(){if(this._parsedURL.isDataURL()){this._name=this._parsedURL.dataURLDisplayName();this._path='';}else if(this._parsedURL.isAboutBlank()){this._name=this._parsedURL.url;this._path='';}else{this._path=this._parsedURL.host+this._parsedURL.folderPathComponents;var networkManager=SDK.NetworkManager.forRequest(this);var inspectedURL=networkManager?networkManager.target().inspectedURL().asParsedURL():null;this._path=this._path.trimURL(inspectedURL?inspectedURL.host:'');if(this._parsedURL.lastPathComponent||this._parsedURL.queryParams){this._name=this._parsedURL.lastPathComponent+(this._parsedURL.queryParams?'?'+this._parsedURL.queryParams:'');}else if(this._parsedURL.folderPathComponents){this._name=this._parsedURL.folderPathComponents.substring(this._parsedURL.folderPathComponents.lastIndexOf('/')+1)+'/';this._path=this._path.substring(0,this._path.lastIndexOf('/'));}else{this._name=this._parsedURL.host;this._path='';}}} -get folder(){var path=this._parsedURL.path;var indexOfQuery=path.indexOf('?');if(indexOfQuery!==-1) -path=path.substring(0,indexOfQuery);var lastSlashIndex=path.lastIndexOf('/');return lastSlashIndex!==-1?path.substring(0,lastSlashIndex):'';} -resourceType(){return this._resourceType;} -setResourceType(resourceType){this._resourceType=resourceType;} -get domain(){return this._parsedURL.host;} -get scheme(){return this._parsedURL.scheme;} -redirectSource(){return this._redirectSource;} -setRedirectSource(originatingRequest){this._redirectSource=originatingRequest;} -requestHeaders(){return this._requestHeaders;} -setRequestHeaders(headers){this._requestHeaders=headers;delete this._requestCookies;this.dispatchEventToListeners(SDK.NetworkRequest.Events.RequestHeadersChanged);} -requestHeadersText(){return this._requestHeadersText;} -setRequestHeadersText(text){this._requestHeadersText=text;this.dispatchEventToListeners(SDK.NetworkRequest.Events.RequestHeadersChanged);} -requestHeaderValue(headerName){if(headerName in this._requestHeaderValues) -return this._requestHeaderValues[headerName];this._requestHeaderValues[headerName]=this._computeHeaderValue(this.requestHeaders(),headerName);return this._requestHeaderValues[headerName];} -get requestCookies(){if(!this._requestCookies) -this._requestCookies=SDK.CookieParser.parseCookie(this.requestHeaderValue('Cookie'));return this._requestCookies;} -get requestFormData(){return this._requestFormData;} -set requestFormData(x){this._requestFormData=x;delete this._parsedFormParameters;} -_filteredProtocolName(){var protocol=this.protocol.toLowerCase();if(protocol==='h2') -return'http/2.0';return protocol.replace(/^http\/2(\.0)?\+/,'http/2.0+');} -requestHttpVersion(){var headersText=this.requestHeadersText();if(!headersText){var version=this.requestHeaderValue('version')||this.requestHeaderValue(':version');if(version) -return version;return this._filteredProtocolName();} -var firstLine=headersText.split(/\r\n/)[0];var match=firstLine.match(/(HTTP\/\d+\.\d+)$/);return match?match[1]:'HTTP/0.9';} -get responseHeaders(){return this._responseHeaders||[];} -set responseHeaders(x){this._responseHeaders=x;delete this._sortedResponseHeaders;delete this._serverTimings;delete this._responseCookies;this._responseHeaderValues={};this.dispatchEventToListeners(SDK.NetworkRequest.Events.ResponseHeadersChanged);} -get responseHeadersText(){return this._responseHeadersText;} -set responseHeadersText(x){this._responseHeadersText=x;this.dispatchEventToListeners(SDK.NetworkRequest.Events.ResponseHeadersChanged);} -get sortedResponseHeaders(){if(this._sortedResponseHeaders!==undefined) -return this._sortedResponseHeaders;this._sortedResponseHeaders=this.responseHeaders.slice();this._sortedResponseHeaders.sort(function(a,b){return a.name.toLowerCase().compareTo(b.name.toLowerCase());});return this._sortedResponseHeaders;} -responseHeaderValue(headerName){if(headerName in this._responseHeaderValues) -return this._responseHeaderValues[headerName];this._responseHeaderValues[headerName]=this._computeHeaderValue(this.responseHeaders,headerName);return this._responseHeaderValues[headerName];} -get responseCookies(){if(!this._responseCookies) -this._responseCookies=SDK.CookieParser.parseSetCookie(this.responseHeaderValue('Set-Cookie'));return this._responseCookies;} -responseLastModified(){return this.responseHeaderValue('last-modified');} -get serverTimings(){if(typeof this._serverTimings==='undefined') -this._serverTimings=SDK.ServerTiming.parseHeaders(this.responseHeaders);return this._serverTimings;} -queryString(){if(this._queryString!==undefined) -return this._queryString;var queryString=null;var url=this.url();var questionMarkPosition=url.indexOf('?');if(questionMarkPosition!==-1){queryString=url.substring(questionMarkPosition+1);var hashSignPosition=queryString.indexOf('#');if(hashSignPosition!==-1) -queryString=queryString.substring(0,hashSignPosition);} -this._queryString=queryString;return this._queryString;} -get queryParameters(){if(this._parsedQueryParameters) -return this._parsedQueryParameters;var queryString=this.queryString();if(!queryString) -return null;this._parsedQueryParameters=this._parseParameters(queryString);return this._parsedQueryParameters;} -get formParameters(){if(this._parsedFormParameters) -return this._parsedFormParameters;if(!this.requestFormData) -return null;var requestContentType=this.requestContentType();if(!requestContentType||!requestContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)) -return null;this._parsedFormParameters=this._parseParameters(this.requestFormData);return this._parsedFormParameters;} -responseHttpVersion(){var headersText=this._responseHeadersText;if(!headersText){var version=this.responseHeaderValue('version')||this.responseHeaderValue(':version');if(version) -return version;return this._filteredProtocolName();} -var firstLine=headersText.split(/\r\n/)[0];var match=firstLine.match(/^(HTTP\/\d+\.\d+)/);return match?match[1]:'HTTP/0.9';} -_parseParameters(queryString){function parseNameValue(pair){var position=pair.indexOf('=');if(position===-1) -return{name:pair,value:''};else -return{name:pair.substring(0,position),value:pair.substring(position+1)};} -return queryString.split('&').map(parseNameValue);} -_computeHeaderValue(headers,headerName){headerName=headerName.toLowerCase();var values=[];for(var i=0;i<headers.length;++i){if(headers[i].name.toLowerCase()===headerName) -values.push(headers[i].value);} -if(!values.length) -return undefined;if(headerName==='set-cookie') -return values.join('\n');return values.join(', ');} -contentData(){if(this._contentData) -return this._contentData;if(this._contentDataProvider) -this._contentData=this._contentDataProvider();else -this._contentData=SDK.NetworkManager.requestContentData(this);return this._contentData;} -setContentDataProvider(dataProvider){console.assert(!this._contentData,'contentData can only be set once.');this._contentDataProvider=dataProvider;} -contentURL(){return this._url;} -contentType(){return this._resourceType;} -async contentEncoded(){return(await this.contentData()).encoded;} -async requestContent(){return(await this.contentData()).content;} -searchInContent(query,caseSensitive,isRegex){return Promise.resolve([]);} -isHttpFamily(){return!!this.url().match(/^https?:/i);} -requestContentType(){return this.requestHeaderValue('Content-Type');} -hasErrorStatusCode(){return this.statusCode>=400;} -setInitialPriority(priority){this._initialPriority=priority;} -initialPriority(){return this._initialPriority;} -setPriority(priority){this._currentPriority=priority;} -priority(){return this._currentPriority||this._initialPriority||null;} -populateImageSource(image){function onResourceContent(content){var imageSrc=Common.ContentProvider.contentAsDataURL(content,this._mimeType,true);if(imageSrc===null) -imageSrc=this._url;image.src=imageSrc;} -this.requestContent().then(onResourceContent.bind(this));} -initiator(){return this._initiator;} -frames(){return this._frames;} -addFrameError(errorMessage,time){this._addFrame({type:SDK.NetworkRequest.WebSocketFrameType.Error,text:errorMessage,time:this.pseudoWallTime(time),opCode:-1,mask:false});} -addFrame(response,time,sent){var type=sent?SDK.NetworkRequest.WebSocketFrameType.Send:SDK.NetworkRequest.WebSocketFrameType.Receive;this._addFrame({type:type,text:response.payloadData,time:this.pseudoWallTime(time),opCode:response.opcode,mask:response.mask});} -_addFrame(frame){this._frames.push(frame);this.dispatchEventToListeners(SDK.NetworkRequest.Events.WebsocketFrameAdded,frame);} -eventSourceMessages(){return this._eventSourceMessages;} -addEventSourceMessage(time,eventName,eventId,data){var message={time:this.pseudoWallTime(time),eventName:eventName,eventId:eventId,data:data};this._eventSourceMessages.push(message);this.dispatchEventToListeners(SDK.NetworkRequest.Events.EventSourceMessageAdded,message);}};SDK.NetworkRequest.Events={FinishedLoading:Symbol('FinishedLoading'),TimingChanged:Symbol('TimingChanged'),RemoteAddressChanged:Symbol('RemoteAddressChanged'),RequestHeadersChanged:Symbol('RequestHeadersChanged'),ResponseHeadersChanged:Symbol('ResponseHeadersChanged'),WebsocketFrameAdded:Symbol('WebsocketFrameAdded'),EventSourceMessageAdded:Symbol('EventSourceMessageAdded')};SDK.NetworkRequest.InitiatorType={Other:'other',Parser:'parser',Redirect:'redirect',Script:'script',Preload:'preload'};SDK.NetworkRequest.NameValue;SDK.NetworkRequest.WebSocketFrameType={Send:'send',Receive:'receive',Error:'error'};SDK.NetworkRequest.WebSocketFrame;SDK.NetworkRequest.EventSourceMessage;SDK.NetworkRequest.ContentData;;SDK.PaintProfilerModel=class extends SDK.SDKModel{constructor(target){super(target);this._layerTreeAgent=target.layerTreeAgent();} -async loadSnapshotFromFragments(fragments){var snapshotId=await this._layerTreeAgent.loadSnapshot(fragments);return snapshotId&&new SDK.PaintProfilerSnapshot(this,snapshotId);} -loadSnapshot(encodedPicture){var fragment={x:0,y:0,picture:encodedPicture};return this.loadSnapshotFromFragments([fragment]);} -async makeSnapshot(layerId){var snapshotId=await this._layerTreeAgent.makeSnapshot(layerId);return snapshotId&&new SDK.PaintProfilerSnapshot(this,snapshotId);}};SDK.SDKModel.register(SDK.PaintProfilerModel,SDK.Target.Capability.DOM,false);SDK.PictureFragment;SDK.PaintProfilerSnapshot=class{constructor(paintProfilerModel,snapshotId){this._paintProfilerModel=paintProfilerModel;this._id=snapshotId;this._refCount=1;} -release(){console.assert(this._refCount>0,'release is already called on the object');if(!--this._refCount) -this._paintProfilerModel._layerTreeAgent.releaseSnapshot(this._id);} -addReference(){++this._refCount;console.assert(this._refCount>0,'Referencing a dead object');} -replay(scale,firstStep,lastStep){return this._paintProfilerModel._layerTreeAgent.replaySnapshot(this._id,firstStep,lastStep,scale||1.0);} -profile(clipRect){return this._paintProfilerModel._layerTreeAgent.profileSnapshot(this._id,5,1,clipRect||undefined);} -async commandLog(){var log=await this._paintProfilerModel._layerTreeAgent.snapshotCommandLog(this._id);return log&&log.map((entry,index)=>new SDK.PaintProfilerLogItem(entry,index));}};SDK.RawPaintProfilerLogItem;SDK.PaintProfilerLogItem=class{constructor(rawEntry,commandIndex){this.method=rawEntry.method;this.params=rawEntry.params;this.commandIndex=commandIndex;}};;SDK.HeapProfilerModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerHeapProfilerDispatcher(new SDK.HeapProfilerDispatcher(this));this._enabled=false;this._heapProfilerAgent=target.heapProfilerAgent();this._runtimeModel=(target.model(SDK.RuntimeModel));} -debuggerModel(){return this._runtimeModel.debuggerModel();} -runtimeModel(){return this._runtimeModel;} -enable(){if(this._enabled) -return;this._enabled=true;this._heapProfilerAgent.enable();} -startSampling(){var defaultSamplingIntervalInBytes=16384;this._heapProfilerAgent.startSampling(defaultSamplingIntervalInBytes);} -stopSampling(){this._isRecording=false;return this._heapProfilerAgent.stopSampling();} -collectGarbage(){return this._heapProfilerAgent.collectGarbage();} -snapshotObjectIdForObjectId(objectId){return this._heapProfilerAgent.getHeapObjectId(objectId);} -objectForSnapshotObjectId(snapshotObjectId,objectGroupName){return this._heapProfilerAgent.getObjectByHeapObjectId(snapshotObjectId,objectGroupName).then(result=>result&&result.type?this._runtimeModel.createRemoteObject(result):null);} -addInspectedHeapObject(snapshotObjectId){return this._heapProfilerAgent.addInspectedHeapObject(snapshotObjectId);} -takeHeapSnapshot(reportProgress){return this._heapProfilerAgent.takeHeapSnapshot(reportProgress);} -startTrackingHeapObjects(recordAllocationStacks){return this._heapProfilerAgent.startTrackingHeapObjects(recordAllocationStacks);} -stopTrackingHeapObjects(reportProgress){return this._heapProfilerAgent.stopTrackingHeapObjects(reportProgress);} -heapStatsUpdate(samples){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.HeapStatsUpdate,samples);} -lastSeenObjectId(lastSeenObjectId,timestamp){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.LastSeenObjectId,{lastSeenObjectId:lastSeenObjectId,timestamp:timestamp});} -addHeapSnapshotChunk(chunk){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.AddHeapSnapshotChunk,chunk);} -reportHeapSnapshotProgress(done,total,finished){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.ReportHeapSnapshotProgress,{done:done,total:total,finished:finished});} -resetProfiles(){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.ResetProfiles,this);}};SDK.SDKModel.register(SDK.HeapProfilerModel,SDK.Target.Capability.JS,false);SDK.HeapProfilerModel.Events={HeapStatsUpdate:Symbol('HeapStatsUpdate'),LastSeenObjectId:Symbol('LastSeenObjectId'),AddHeapSnapshotChunk:Symbol('AddHeapSnapshotChunk'),ReportHeapSnapshotProgress:Symbol('ReportHeapSnapshotProgress'),ResetProfiles:Symbol('ResetProfiles')};SDK.HeapProfilerDispatcher=class{constructor(model){this._heapProfilerModel=model;} -heapStatsUpdate(samples){this._heapProfilerModel.heapStatsUpdate(samples);} -lastSeenObjectId(lastSeenObjectId,timestamp){this._heapProfilerModel.lastSeenObjectId(lastSeenObjectId,timestamp);} -addHeapSnapshotChunk(chunk){this._heapProfilerModel.addHeapSnapshotChunk(chunk);} -reportHeapSnapshotProgress(done,total,finished){this._heapProfilerModel.reportHeapSnapshotProgress(done,total,finished);} -resetProfiles(){this._heapProfilerModel.resetProfiles();}};;SDK.PerformanceMetricsModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.performanceAgent();} -enable(){return this._agent.enable();} -disable(){return this._agent.disable();} -async requestMetrics(){return await this._agent.getMetrics()||[];}};SDK.SDKModel.register(SDK.PerformanceMetricsModel,SDK.Target.Capability.Browser,false);;SDK.CSSMetadata._generatedProperties=[{"name":"-webkit-app-region"},{"name":"-webkit-appearance"},{"name":"-webkit-background-clip"},{"name":"-webkit-background-origin"},{"longhands":["-webkit-border-after-width","-webkit-border-after-style","-webkit-border-after-color"],"name":"-webkit-border-after"},{"name":"-webkit-border-after-color"},{"name":"-webkit-border-after-style"},{"name":"-webkit-border-after-width"},{"longhands":["-webkit-border-before-width","-webkit-border-before-style","-webkit-border-before-color"],"name":"-webkit-border-before"},{"name":"-webkit-border-before-color"},{"name":"-webkit-border-before-style"},{"name":"-webkit-border-before-width"},{"longhands":["-webkit-border-end-width","-webkit-border-end-style","-webkit-border-end-color"],"name":"-webkit-border-end"},{"name":"-webkit-border-end-color"},{"name":"-webkit-border-end-style"},{"name":"-webkit-border-end-width"},{"name":"-webkit-border-horizontal-spacing","inherited":true},{"name":"-webkit-border-image"},{"longhands":["-webkit-border-start-width","-webkit-border-start-style","-webkit-border-start-color"],"name":"-webkit-border-start"},{"name":"-webkit-border-start-color"},{"name":"-webkit-border-start-style"},{"name":"-webkit-border-start-width"},{"name":"-webkit-border-vertical-spacing","inherited":true},{"name":"-webkit-box-align"},{"name":"-webkit-box-decoration-break"},{"name":"-webkit-box-direction","inherited":true},{"name":"-webkit-box-flex"},{"name":"-webkit-box-flex-group"},{"name":"-webkit-box-lines"},{"name":"-webkit-box-ordinal-group"},{"name":"-webkit-box-orient"},{"name":"-webkit-box-pack"},{"name":"-webkit-box-reflect"},{"longhands":["break-after"],"name":"-webkit-column-break-after"},{"longhands":["break-before"],"name":"-webkit-column-break-before"},{"longhands":["break-inside"],"name":"-webkit-column-break-inside"},{"name":"-webkit-font-size-delta"},{"name":"-webkit-font-smoothing","inherited":true},{"name":"-webkit-highlight","inherited":true},{"name":"-webkit-hyphenate-character","inherited":true},{"name":"-webkit-line-break","inherited":true},{"name":"-webkit-line-clamp"},{"name":"-webkit-locale","inherited":true},{"name":"-webkit-logical-height"},{"name":"-webkit-logical-width"},{"name":"-webkit-margin-after"},{"name":"-webkit-margin-after-collapse"},{"name":"-webkit-margin-before"},{"name":"-webkit-margin-before-collapse"},{"name":"-webkit-margin-bottom-collapse"},{"longhands":["-webkit-margin-before-collapse","-webkit-margin-after-collapse"],"name":"-webkit-margin-collapse"},{"name":"-webkit-margin-end"},{"name":"-webkit-margin-start"},{"name":"-webkit-margin-top-collapse"},{"longhands":["-webkit-mask-image","-webkit-mask-position-x","-webkit-mask-position-y","-webkit-mask-size","-webkit-mask-repeat-x","-webkit-mask-repeat-y","-webkit-mask-origin","-webkit-mask-clip"],"name":"-webkit-mask"},{"longhands":["-webkit-mask-box-image-source","-webkit-mask-box-image-slice","-webkit-mask-box-image-width","-webkit-mask-box-image-outset","-webkit-mask-box-image-repeat"],"name":"-webkit-mask-box-image"},{"name":"-webkit-mask-box-image-outset"},{"name":"-webkit-mask-box-image-repeat"},{"name":"-webkit-mask-box-image-slice"},{"name":"-webkit-mask-box-image-source"},{"name":"-webkit-mask-box-image-width"},{"name":"-webkit-mask-clip"},{"name":"-webkit-mask-composite"},{"name":"-webkit-mask-image"},{"name":"-webkit-mask-origin"},{"longhands":["-webkit-mask-position-x","-webkit-mask-position-y"],"name":"-webkit-mask-position"},{"name":"-webkit-mask-position-x"},{"name":"-webkit-mask-position-y"},{"longhands":["-webkit-mask-repeat-x","-webkit-mask-repeat-y"],"name":"-webkit-mask-repeat"},{"name":"-webkit-mask-repeat-x"},{"name":"-webkit-mask-repeat-y"},{"name":"-webkit-mask-size"},{"name":"-webkit-max-logical-height"},{"name":"-webkit-max-logical-width"},{"name":"-webkit-min-logical-height"},{"name":"-webkit-min-logical-width"},{"name":"-webkit-padding-after"},{"name":"-webkit-padding-before"},{"name":"-webkit-padding-end"},{"name":"-webkit-padding-start"},{"name":"-webkit-perspective-origin-x"},{"name":"-webkit-perspective-origin-y"},{"name":"-webkit-print-color-adjust","inherited":true},{"name":"-webkit-rtl-ordering","inherited":true},{"name":"-webkit-ruby-position","inherited":true},{"name":"-webkit-tap-highlight-color","inherited":true},{"name":"-webkit-text-combine","inherited":true},{"name":"-webkit-text-decorations-in-effect","inherited":true},{"longhands":["-webkit-text-emphasis-style","-webkit-text-emphasis-color"],"name":"-webkit-text-emphasis"},{"name":"-webkit-text-emphasis-color","inherited":true},{"name":"-webkit-text-emphasis-position","inherited":true},{"name":"-webkit-text-emphasis-style","inherited":true},{"name":"-webkit-text-fill-color","inherited":true},{"name":"-webkit-text-orientation","inherited":true},{"name":"-webkit-text-security","inherited":true},{"longhands":["-webkit-text-stroke-width","-webkit-text-stroke-color"],"name":"-webkit-text-stroke"},{"name":"-webkit-text-stroke-color","inherited":true},{"name":"-webkit-text-stroke-width","inherited":true},{"name":"-webkit-transform-origin-x"},{"name":"-webkit-transform-origin-y"},{"name":"-webkit-transform-origin-z"},{"name":"-webkit-user-drag"},{"name":"-webkit-user-modify","inherited":true},{"name":"-webkit-writing-mode","inherited":true},{"name":"align-content"},{"name":"align-items"},{"name":"align-self"},{"svg":true,"name":"alignment-baseline"},{"name":"all"},{"longhands":["animation-name","animation-duration","animation-timing-function","animation-delay","animation-iteration-count","animation-direction","animation-fill-mode","animation-play-state"],"name":"animation"},{"name":"animation-delay"},{"name":"animation-direction"},{"name":"animation-duration"},{"name":"animation-fill-mode"},{"name":"animation-iteration-count"},{"name":"animation-name"},{"name":"animation-play-state"},{"name":"animation-timing-function"},{"name":"backdrop-filter"},{"name":"backface-visibility"},{"longhands":["background-image","background-position-x","background-position-y","background-size","background-repeat-x","background-repeat-y","background-attachment","background-origin","background-clip","background-color"],"name":"background"},{"name":"background-attachment"},{"name":"background-blend-mode"},{"name":"background-clip"},{"name":"background-color"},{"name":"background-image"},{"name":"background-origin"},{"longhands":["background-position-x","background-position-y"],"name":"background-position"},{"name":"background-position-x"},{"name":"background-position-y"},{"longhands":["background-repeat-x","background-repeat-y"],"name":"background-repeat"},{"name":"background-repeat-x"},{"name":"background-repeat-y"},{"name":"background-size"},{"name":"baseline-shift","svg":true},{"name":"block-size"},{"longhands":["border-top-color","border-top-style","border-top-width","border-right-color","border-right-style","border-right-width","border-bottom-color","border-bottom-style","border-bottom-width","border-left-color","border-left-style","border-left-width","border-image-source","border-image-slice","border-image-width","border-image-outset","border-image-repeat"],"name":"border"},{"longhands":["border-bottom-width","border-bottom-style","border-bottom-color"],"name":"border-bottom"},{"name":"border-bottom-color"},{"name":"border-bottom-left-radius"},{"name":"border-bottom-right-radius"},{"name":"border-bottom-style"},{"name":"border-bottom-width"},{"name":"border-collapse","inherited":true},{"longhands":["border-top-color","border-right-color","border-bottom-color","border-left-color"],"name":"border-color"},{"longhands":["border-image-source","border-image-slice","border-image-width","border-image-outset","border-image-repeat"],"name":"border-image"},{"name":"border-image-outset"},{"name":"border-image-repeat"},{"name":"border-image-slice"},{"name":"border-image-source"},{"name":"border-image-width"},{"longhands":["border-left-width","border-left-style","border-left-color"],"name":"border-left"},{"name":"border-left-color"},{"name":"border-left-style"},{"name":"border-left-width"},{"longhands":["border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius"],"name":"border-radius"},{"longhands":["border-right-width","border-right-style","border-right-color"],"name":"border-right"},{"name":"border-right-color"},{"name":"border-right-style"},{"name":"border-right-width"},{"longhands":["-webkit-border-horizontal-spacing","-webkit-border-vertical-spacing"],"name":"border-spacing"},{"name":"border-style","longhands":["border-top-style","border-right-style","border-bottom-style","border-left-style"]},{"longhands":["border-top-width","border-top-style","border-top-color"],"name":"border-top"},{"name":"border-top-color"},{"name":"border-top-left-radius"},{"name":"border-top-right-radius"},{"name":"border-top-style"},{"name":"border-top-width"},{"longhands":["border-top-width","border-right-width","border-bottom-width","border-left-width"],"name":"border-width"},{"name":"bottom"},{"name":"box-shadow"},{"name":"box-sizing"},{"name":"break-after"},{"name":"break-before"},{"name":"break-inside"},{"svg":true,"name":"buffered-rendering"},{"name":"caption-side","inherited":true},{"name":"caret-color","inherited":true},{"name":"clear"},{"name":"clip"},{"name":"clip-path"},{"svg":true,"name":"clip-rule","inherited":true},{"name":"color","inherited":true},{"svg":true,"name":"color-interpolation","inherited":true},{"svg":true,"name":"color-interpolation-filters","inherited":true},{"svg":true,"name":"color-rendering","inherited":true},{"name":"column-count"},{"name":"column-fill"},{"name":"column-gap"},{"longhands":["column-rule-width","column-rule-style","column-rule-color"],"name":"column-rule"},{"name":"column-rule-color"},{"name":"column-rule-style"},{"name":"column-rule-width"},{"name":"column-span"},{"name":"column-width"},{"longhands":["column-width","column-count"],"name":"columns"},{"name":"contain"},{"name":"content"},{"name":"counter-increment"},{"name":"counter-reset"},{"name":"cursor","inherited":true},{"name":"cx","svg":true},{"name":"cy","svg":true},{"name":"d","svg":true},{"name":"direction","inherited":true},{"name":"display"},{"svg":true,"name":"dominant-baseline","inherited":true},{"name":"empty-cells","inherited":true},{"name":"fill","svg":true,"inherited":true},{"name":"fill-opacity","svg":true,"inherited":true},{"svg":true,"name":"fill-rule","inherited":true},{"name":"filter"},{"longhands":["flex-grow","flex-shrink","flex-basis"],"name":"flex"},{"name":"flex-basis"},{"name":"flex-direction"},{"longhands":["flex-direction","flex-wrap"],"name":"flex-flow"},{"name":"flex-grow"},{"name":"flex-shrink"},{"name":"flex-wrap"},{"name":"float"},{"name":"flood-color","svg":true},{"name":"flood-opacity","svg":true},{"longhands":["font-style","font-variant-ligatures","font-variant-caps","font-variant-numeric","font-variant-east-asian","font-weight","font-stretch","font-size","line-height","font-family"],"name":"font"},{"name":"font-display"},{"name":"font-family","inherited":true},{"name":"font-feature-settings","inherited":true},{"name":"font-kerning","inherited":true},{"name":"font-size","inherited":true},{"name":"font-size-adjust","inherited":true},{"name":"font-stretch","inherited":true},{"name":"font-style","inherited":true},{"longhands":["font-variant-ligatures","font-variant-caps","font-variant-numeric","font-variant-east-asian"],"name":"font-variant"},{"name":"font-variant-caps","inherited":true},{"name":"font-variant-east-asian","inherited":true},{"name":"font-variant-ligatures","inherited":true},{"name":"font-variant-numeric","inherited":true},{"name":"font-variation-settings","inherited":true},{"name":"font-weight","inherited":true},{"longhands":["grid-template-rows","grid-template-columns","grid-template-areas","grid-auto-flow","grid-auto-rows","grid-auto-columns"],"name":"grid"},{"longhands":["grid-row-start","grid-column-start","grid-row-end","grid-column-end"],"name":"grid-area"},{"name":"grid-auto-columns"},{"name":"grid-auto-flow"},{"name":"grid-auto-rows"},{"longhands":["grid-column-start","grid-column-end"],"name":"grid-column"},{"name":"grid-column-end"},{"name":"grid-column-gap"},{"name":"grid-column-start"},{"longhands":["grid-row-gap","grid-column-gap"],"name":"grid-gap"},{"longhands":["grid-row-start","grid-row-end"],"name":"grid-row"},{"name":"grid-row-end"},{"name":"grid-row-gap"},{"name":"grid-row-start"},{"longhands":["grid-template-rows","grid-template-columns","grid-template-areas"],"name":"grid-template"},{"name":"grid-template-areas"},{"name":"grid-template-columns"},{"name":"grid-template-rows"},{"name":"height"},{"name":"hyphens","inherited":true},{"name":"image-orientation","inherited":true},{"name":"image-rendering","inherited":true},{"name":"inline-size"},{"name":"isolation"},{"name":"justify-content"},{"name":"justify-items"},{"name":"justify-self"},{"name":"left"},{"name":"letter-spacing","inherited":true},{"name":"lighting-color","svg":true},{"name":"line-break","inherited":true},{"name":"line-height","inherited":true},{"name":"line-height-step","inherited":true},{"longhands":["list-style-type","list-style-position","list-style-image"],"name":"list-style"},{"name":"list-style-image","inherited":true},{"name":"list-style-position","inherited":true},{"name":"list-style-type","inherited":true},{"longhands":["margin-top","margin-right","margin-bottom","margin-left"],"name":"margin"},{"name":"margin-bottom"},{"name":"margin-left"},{"name":"margin-right"},{"name":"margin-top"},{"longhands":["marker-start","marker-mid","marker-end"],"name":"marker"},{"name":"marker-end","svg":true,"inherited":true},{"name":"marker-mid","svg":true,"inherited":true},{"name":"marker-start","svg":true,"inherited":true},{"name":"mask","svg":true},{"name":"mask-source-type"},{"svg":true,"name":"mask-type"},{"name":"max-block-size"},{"name":"max-height"},{"name":"max-inline-size"},{"name":"max-width"},{"name":"max-zoom"},{"name":"min-block-size"},{"name":"min-height"},{"name":"min-inline-size"},{"name":"min-width"},{"name":"min-zoom"},{"name":"mix-blend-mode"},{"name":"object-fit"},{"name":"object-position"},{"longhands":["offset-position","offset-path","offset-distance","offset-rotate","offset-anchor"],"name":"offset"},{"name":"offset-anchor"},{"name":"offset-distance"},{"name":"offset-path"},{"name":"offset-position"},{"name":"offset-rotate"},{"name":"opacity"},{"name":"order"},{"name":"orientation"},{"name":"orphans","inherited":true},{"longhands":["outline-color","outline-style","outline-width"],"name":"outline"},{"name":"outline-color"},{"name":"outline-offset"},{"name":"outline-style"},{"name":"outline-width"},{"longhands":["overflow-x","overflow-y"],"name":"overflow"},{"name":"overflow-anchor","inherited":false},{"name":"overflow-wrap","inherited":true},{"name":"overflow-x"},{"name":"overflow-y"},{"longhands":["overscroll-behavior-x","overscroll-behavior-y"],"name":"overscroll-behavior"},{"name":"overscroll-behavior-x"},{"name":"overscroll-behavior-y"},{"longhands":["padding-top","padding-right","padding-bottom","padding-left"],"name":"padding"},{"name":"padding-bottom"},{"name":"padding-left"},{"name":"padding-right"},{"name":"padding-top"},{"name":"page"},{"longhands":["break-after"],"name":"page-break-after"},{"longhands":["break-before"],"name":"page-break-before"},{"longhands":["break-inside"],"name":"page-break-inside"},{"svg":true,"inherited":true,"name":"paint-order"},{"name":"perspective"},{"name":"perspective-origin"},{"longhands":["align-content","justify-content"],"name":"place-content"},{"longhands":["align-items","justify-items"],"name":"place-items"},{"longhands":["align-self","justify-self"],"name":"place-self"},{"name":"pointer-events","inherited":true},{"name":"position"},{"name":"quotes","inherited":true},{"name":"r","svg":true},{"name":"resize"},{"name":"right"},{"name":"rotate"},{"name":"rx","svg":true},{"name":"ry","svg":true},{"name":"scale"},{"name":"scroll-behavior"},{"longhands":["scroll-padding-top","scroll-padding-right","scroll-padding-bottom","scroll-padding-left"],"name":"scroll-padding"},{"longhands":["scroll-padding-block-start","scroll-padding-block-end"],"name":"scroll-padding-block"},{"name":"scroll-padding-block-end"},{"name":"scroll-padding-block-start"},{"name":"scroll-padding-bottom"},{"longhands":["scroll-padding-inline-start","scroll-padding-inline-end"],"name":"scroll-padding-inline"},{"name":"scroll-padding-inline-end"},{"name":"scroll-padding-inline-start"},{"name":"scroll-padding-left"},{"name":"scroll-padding-right"},{"name":"scroll-padding-top"},{"name":"scroll-snap-align"},{"longhands":["scroll-snap-margin-top","scroll-snap-margin-right","scroll-snap-margin-bottom","scroll-snap-margin-left"],"name":"scroll-snap-margin"},{"longhands":["scroll-snap-margin-block-start","scroll-snap-margin-block-end"],"name":"scroll-snap-margin-block"},{"name":"scroll-snap-margin-block-end"},{"name":"scroll-snap-margin-block-start"},{"name":"scroll-snap-margin-bottom"},{"longhands":["scroll-snap-margin-inline-start","scroll-snap-margin-inline-end"],"name":"scroll-snap-margin-inline"},{"name":"scroll-snap-margin-inline-end"},{"name":"scroll-snap-margin-inline-start"},{"name":"scroll-snap-margin-left"},{"name":"scroll-snap-margin-right"},{"name":"scroll-snap-margin-top"},{"name":"scroll-snap-stop"},{"name":"scroll-snap-type"},{"name":"shape-image-threshold"},{"name":"shape-margin"},{"name":"shape-outside"},{"svg":true,"name":"shape-rendering","inherited":true},{"name":"size"},{"name":"speak","inherited":true},{"name":"src"},{"name":"stop-color","svg":true},{"name":"stop-opacity","svg":true},{"name":"stroke","svg":true,"inherited":true},{"name":"stroke-dasharray","svg":true,"inherited":true},{"name":"stroke-dashoffset","svg":true,"inherited":true},{"name":"stroke-linecap","svg":true,"inherited":true},{"name":"stroke-linejoin","svg":true,"inherited":true},{"name":"stroke-miterlimit","svg":true,"inherited":true},{"name":"stroke-opacity","svg":true,"inherited":true},{"name":"stroke-width","svg":true,"inherited":true},{"name":"tab-size","inherited":true},{"name":"table-layout"},{"name":"text-align","inherited":true},{"name":"text-align-last","inherited":true},{"svg":true,"name":"text-anchor","inherited":true},{"name":"text-combine-upright","inherited":true},{"longhands":["text-decoration-line","text-decoration-style","text-decoration-color"],"name":"text-decoration"},{"name":"text-decoration-color"},{"name":"text-decoration-line"},{"name":"text-decoration-skip","inherited":true},{"name":"text-decoration-style"},{"name":"text-indent","inherited":true},{"name":"text-justify","inherited":true},{"name":"text-orientation","inherited":true},{"name":"text-overflow"},{"name":"text-rendering","inherited":true},{"name":"text-shadow","inherited":true},{"name":"text-size-adjust","inherited":true},{"name":"text-transform","inherited":true},{"name":"text-underline-position","inherited":true},{"name":"top"},{"name":"touch-action"},{"name":"transform"},{"name":"transform-box"},{"name":"transform-origin"},{"name":"transform-style"},{"longhands":["transition-property","transition-duration","transition-timing-function","transition-delay"],"name":"transition"},{"name":"transition-delay"},{"name":"transition-duration"},{"name":"transition-property"},{"name":"transition-timing-function"},{"name":"translate"},{"name":"unicode-bidi"},{"name":"unicode-range"},{"name":"user-select","inherited":true},{"name":"user-zoom"},{"svg":true,"name":"vector-effect"},{"name":"vertical-align"},{"name":"visibility","inherited":true},{"name":"white-space","inherited":true},{"name":"widows","inherited":true},{"name":"width"},{"name":"will-change"},{"name":"word-break","inherited":true},{"name":"word-spacing","inherited":true},{"name":"word-wrap","inherited":true},{"name":"writing-mode","inherited":true},{"name":"x","svg":true},{"name":"y","svg":true},{"name":"z-index"},{"name":"zoom"}];;SDK.FilmStripModel=class{constructor(tracingModel,zeroTime){this.reset(tracingModel,zeroTime);} -reset(tracingModel,zeroTime){this._zeroTime=zeroTime||tracingModel.minimumRecordTime();this._spanTime=tracingModel.maximumRecordTime()-this._zeroTime;this._frames=[];var browserMain=SDK.TracingModel.browserMainThread(tracingModel);if(!browserMain) -return;var events=browserMain.events();for(var i=0;i<events.length;++i){var event=events[i];if(event.startTime<this._zeroTime) -continue;if(!event.hasCategory(SDK.FilmStripModel._category)) -continue;if(event.name===SDK.FilmStripModel.TraceEvents.CaptureFrame){var data=event.args['data'];if(data) -this._frames.push(SDK.FilmStripModel.Frame._fromEvent(this,event,this._frames.length));}else if(event.name===SDK.FilmStripModel.TraceEvents.Screenshot){this._frames.push(SDK.FilmStripModel.Frame._fromSnapshot(this,(event),this._frames.length));}}} -frames(){return this._frames;} -zeroTime(){return this._zeroTime;} -spanTime(){return this._spanTime;} -frameByTimestamp(timestamp){var index=this._frames.upperBound(timestamp,(timestamp,frame)=>timestamp-frame.timestamp)-1;return index>=0?this._frames[index]:null;}};SDK.FilmStripModel._category='disabled-by-default-devtools.screenshot';SDK.FilmStripModel.TraceEvents={CaptureFrame:'CaptureFrame',Screenshot:'Screenshot'};SDK.FilmStripModel.Frame=class{constructor(model,timestamp,index){this._model=model;this.timestamp=timestamp;this.index=index;this._imageData=null;this._snapshot=null;} -static _fromEvent(model,event,index){var frame=new SDK.FilmStripModel.Frame(model,event.startTime,index);frame._imageData=event.args['data'];return frame;} -static _fromSnapshot(model,snapshot,index){var frame=new SDK.FilmStripModel.Frame(model,snapshot.startTime,index);frame._snapshot=snapshot;return frame;} -model(){return this._model;} -imageDataPromise(){if(this._imageData||!this._snapshot) -return Promise.resolve(this._imageData);return(this._snapshot.objectPromise());}};;self['Services']=self['Services']||{};Services.ServiceManager=class{createRemoteService(serviceName){if(!this._remoteConnection){var url=Runtime.queryParam('service-backend');if(!url){console.error('No endpoint address specified');return(Promise.resolve(null));} -this._remoteConnection=new Services.ServiceManager.Connection(new Services.ServiceManager.RemoteServicePort(url));} -return this._remoteConnection._createService(serviceName);} -createAppService(appName,serviceName){var url=appName+'.js';var remoteBase=Runtime.queryParam('remoteBase');var debugFrontend=Runtime.queryParam('debugFrontend');var isUnderTest=Host.isUnderTest();var queryParams=[];if(remoteBase) -queryParams.push('remoteBase='+remoteBase);if(debugFrontend) -queryParams.push('debugFrontend='+debugFrontend);if(isUnderTest) -queryParams.push('isUnderTest=true');if(queryParams.length) -url+=`?${queryParams.join('&')}`;var worker=new Worker(url);var connection=new Services.ServiceManager.Connection(new Services.ServiceManager.WorkerServicePort(worker));return connection._createService(serviceName);}};Services.ServiceManager.Connection=class{constructor(port){this._port=port;this._port.setHandlers(this._onMessage.bind(this),this._connectionClosed.bind(this));this._lastId=1;this._callbacks=new Map();this._services=new Map();} -_createService(serviceName){return this._sendCommand(serviceName+'.create').then(result=>{if(!result){console.error('Could not initialize service: '+serviceName);return null;} -var service=new Services.ServiceManager.Service(this,serviceName,result.id);this._services.set(serviceName+':'+result.id,service);return service;});} -_serviceDisposed(service){this._services.delete(service._serviceName+':'+service._objectId);if(!this._services.size){this._port.close();}} -_sendCommand(method,params){var id=this._lastId++;var message=JSON.stringify({id:id,method:method,params:params||{}});return this._port.send(message).then(success=>{if(!success) -return Promise.resolve(null);return new Promise(fulfill=>this._callbacks.set(id,fulfill));});} -_onMessage(data){var object;try{object=JSON.parse(data);}catch(e){console.error(e);return;} -if(object.id){if(object.error) -console.error('Service error: '+object.error);this._callbacks.get(object.id)(object.error?null:object.result);this._callbacks.delete(object.id);return;} -var tokens=object.method.split('.');var serviceName=tokens[0];var methodName=tokens[1];var service=this._services.get(serviceName+':'+object.params.id);if(!service){console.error('Unable to lookup stub for '+serviceName+':'+object.params.id);return;} -service._dispatchNotification(methodName,object.params);} -_connectionClosed(){for(var callback of this._callbacks.values()) -callback(null);this._callbacks.clear();for(var service of this._services.values()) -service._dispatchNotification('disposed');this._services.clear();}};Services.ServiceManager.Service=class{constructor(connection,serviceName,objectId){this._connection=connection;this._serviceName=serviceName;this._objectId=objectId;this._notificationHandlers=new Map();} -dispose(){var params={id:this._objectId};return this._connection._sendCommand(this._serviceName+'.dispose',params).then(()=>{this._connection._serviceDisposed(this);});} -on(methodName,handler){this._notificationHandlers.set(methodName,handler);} -send(methodName,params){params=params||{};params.id=this._objectId;return this._connection._sendCommand(this._serviceName+'.'+methodName,params);} -_dispatchNotification(methodName,params){var handler=this._notificationHandlers.get(methodName);if(!handler){console.error('Could not report notification \''+methodName+'\' on \''+this._objectId+'\'');return;} -handler(params);}};Services.ServiceManager.RemoteServicePort=class{constructor(url){this._url=url;} -setHandlers(messageHandler,closeHandler){this._messageHandler=messageHandler;this._closeHandler=closeHandler;} -_open(){if(!this._connectionPromise) -this._connectionPromise=new Promise(promiseBody.bind(this));return this._connectionPromise;function promiseBody(fulfill){var socket;try{socket=new WebSocket((this._url));socket.onmessage=onMessage.bind(this);socket.onclose=onClose.bind(this);socket.onopen=onConnect.bind(this);}catch(e){fulfill(false);} -function onConnect(){this._socket=socket;fulfill(true);} -function onMessage(event){this._messageHandler(event.data);} -function onClose(){if(!this._socket) -fulfill(false);this._socketClosed(!!this._socket);}}} -send(message){return this._open().then(()=>{if(this._socket){this._socket.send(message);return true;} -return false;});} -close(){return this._open().then(()=>{if(this._socket){this._socket.close();this._socketClosed(true);} -return true;});} -_socketClosed(notifyClient){this._socket=null;delete this._connectionPromise;if(notifyClient) -this._closeHandler();}};Services.ServiceManager.WorkerServicePort=class{constructor(worker){this._worker=worker;var fulfill;this._workerPromise=new Promise(resolve=>fulfill=resolve);this._worker.onmessage=onMessage.bind(this);this._worker.onclose=this._closeHandler;function onMessage(event){if(event.data==='workerReady'){fulfill(true);return;} -this._messageHandler(event.data);}} -setHandlers(messageHandler,closeHandler){this._messageHandler=messageHandler;this._closeHandler=closeHandler;} -send(message){return this._workerPromise.then(()=>{try{this._worker.postMessage(message);return true;}catch(e){return false;}});} -close(){return this._workerPromise.then(()=>{if(this._worker) -this._worker.terminate();return false;});}};Services.serviceManager=new Services.ServiceManager();;self['Workspace']=self['Workspace']||{};Workspace.FileManager=class extends Common.Object{constructor(){super();this._saveCallbacks=new Map();InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SavedURL,this._savedURL,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.CanceledSaveURL,this._canceledSavedURL,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.AppendedToURL,this._appendedToURL,this);} -save(url,content,forceSaveAs){InspectorFrontendHost.save(url,content,forceSaveAs);return new Promise(resolve=>this._saveCallbacks.set(url,resolve));} -_savedURL(event){var url=(event.data.url);var callback=this._saveCallbacks.get(url);this._saveCallbacks.delete(url);if(callback) -callback({fileSystemPath:(event.data.fileSystemPath)});} -_canceledSavedURL(event){var url=(event.data);var callback=this._saveCallbacks.get(url);this._saveCallbacks.delete(url);if(callback) -callback(null);} -append(url,content){InspectorFrontendHost.append(url,content);} -close(url){} -_appendedToURL(event){var url=(event.data);this.dispatchEventToListeners(Workspace.FileManager.Events.AppendedToURL,url);}};Workspace.FileManager.Events={AppendedToURL:Symbol('AppendedToURL')};Workspace.fileManager;;Workspace.SearchConfig=class{constructor(query,ignoreCase,isRegex){this._query=query;this._ignoreCase=ignoreCase;this._isRegex=isRegex;this._parse();} -static fromPlainObject(object){return new Workspace.SearchConfig(object.query,object.ignoreCase,object.isRegex);} -query(){return this._query;} -ignoreCase(){return this._ignoreCase;} -isRegex(){return this._isRegex;} -toPlainObject(){return{query:this.query(),ignoreCase:this.ignoreCase(),isRegex:this.isRegex()};} -_parse(){var quotedPattern=/"([^\\"]|\\.)+"/;var unquotedWordPattern=/(\s*(?!-?f(ile)?:)[^\\ ]|\\.)+/;var unquotedPattern=unquotedWordPattern.source+'(\\s+'+unquotedWordPattern.source+')*';var pattern=['(\\s*'+Workspace.SearchConfig.FilePatternRegex.source+'\\s*)','('+quotedPattern.source+')','('+unquotedPattern+')',].join('|');var regexp=new RegExp(pattern,'g');var queryParts=this._query.match(regexp)||[];this._fileQueries=[];this._queries=[];for(var i=0;i<queryParts.length;++i){var queryPart=queryParts[i];if(!queryPart) -continue;var fileQuery=this._parseFileQuery(queryPart);if(fileQuery){this._fileQueries.push(fileQuery);this._fileRegexQueries=this._fileRegexQueries||[];this._fileRegexQueries.push({regex:new RegExp(fileQuery.text,this.ignoreCase?'i':''),isNegative:fileQuery.isNegative});continue;} -if(this._isRegex){this._queries.push(queryPart);continue;} -if(queryPart.startsWith('"')){if(!queryPart.endsWith('"')) -continue;this._queries.push(this._parseQuotedQuery(queryPart));continue;} -this._queries.push(this._parseUnquotedQuery(queryPart));}} -filePathMatchesFileQuery(filePath){if(!this._fileRegexQueries) -return true;for(var i=0;i<this._fileRegexQueries.length;++i){if(!!filePath.match(this._fileRegexQueries[i].regex)===this._fileRegexQueries[i].isNegative) -return false;} -return true;} -queries(){return this._queries;} -_parseUnquotedQuery(query){return query.replace(/\\(.)/g,'$1');} -_parseQuotedQuery(query){return query.substring(1,query.length-1).replace(/\\(.)/g,'$1');} -_parseFileQuery(query){var match=query.match(Workspace.SearchConfig.FilePatternRegex);if(!match) -return null;var isNegative=!!match[1];query=match[3];var result='';for(var i=0;i<query.length;++i){var char=query[i];if(char==='*'){result+='.*';}else if(char==='\\'){++i;var nextChar=query[i];if(nextChar===' ') -result+=' ';}else{if(String.regexSpecialCharacters().indexOf(query.charAt(i))!==-1) -result+='\\';result+=query.charAt(i);}} -return new Workspace.SearchConfig.QueryTerm(result,isNegative);}};Workspace.SearchConfig.FilePatternRegex=/(-)?f(ile)?:((?:[^\\ ]|\\.)+)/;Workspace.SearchConfig.RegexQuery;Workspace.SearchConfig.QueryTerm=class{constructor(text,isNegative){this.text=text;this.isNegative=isNegative;}};;Workspace.UISourceCode=class extends Common.Object{constructor(project,url,contentType){super();this._project=project;this._url=url;var parsedURL=url.asParsedURL();if(parsedURL){this._origin=parsedURL.securityOrigin();this._parentURL=this._origin+parsedURL.folderPathComponents;this._name=parsedURL.lastPathComponent;if(parsedURL.queryParams) -this._name+='?'+parsedURL.queryParams;}else{this._origin='';this._parentURL='';this._name=url;} -this._contentType=contentType;this._requestContentPromise=null;this._decorations=null;this._history=null;this._messages=null;this._contentLoaded=false;this._content=null;this._contentEncoded;this._forceLoadOnCheckContent=false;this._checkingContent=false;this._lastAcceptedContent=null;this._workingCopy=null;this._workingCopyGetter=null;} -requestMetadata(){return this._project.requestMetadata(this);} -name(){return this._name;} -mimeType(){return this._project.mimeType(this);} -url(){return this._url;} -parentURL(){return this._parentURL;} -origin(){return this._origin;} -fullDisplayName(){return this._project.fullDisplayName(this);} -displayName(skipTrim){if(!this._name) -return Common.UIString('(index)');var name=this._name;try{if(this.project().type()===Workspace.projectTypes.FileSystem) -name=unescape(name);else -name=decodeURI(name);}catch(e){} -return skipTrim?name:name.trimEnd(100);} -canRename(){return this._project.canRename();} -rename(newName){var fulfill;var promise=new Promise(x=>fulfill=x);this._project.rename(this,newName,innerCallback.bind(this));return promise;function innerCallback(success,newName,newURL,newContentType){if(success){this._updateName((newName),(newURL),(newContentType));} -fulfill(success);}} -remove(){this._project.deleteFile(this);} -_updateName(name,url,contentType){var oldURL=this._url;this._url=this._url.substring(0,this._url.length-this._name.length)+name;this._name=name;if(url) -this._url=url;if(contentType) -this._contentType=contentType;this.dispatchEventToListeners(Workspace.UISourceCode.Events.TitleChanged,this);this.project().workspace().dispatchEventToListeners(Workspace.Workspace.Events.UISourceCodeRenamed,{oldURL:oldURL,uiSourceCode:this});} -contentURL(){return this.url();} -contentType(){return this._contentType;} -async contentEncoded(){await this.requestContent();return this._contentEncoded||false;} -project(){return this._project;} -requestContent(){if(this._requestContentPromise) -return this._requestContentPromise;if(this._contentLoaded){this._requestContentPromise=Promise.resolve(this._content);}else{var fulfill;this._requestContentPromise=new Promise(x=>fulfill=x);this._project.requestFileContent(this,(content,encoded)=>{this._contentLoaded=true;this._content=content;this._contentEncoded=encoded;fulfill(content);});} -return this._requestContentPromise;} -checkContentUpdated(){if(!this._contentLoaded&&!this._forceLoadOnCheckContent) -return;if(!this._project.canSetFileContent()||this._checkingContent) -return;this._checkingContent=true;this._project.requestFileContent(this,contentLoaded.bind(this));function contentLoaded(updatedContent,encoded){this._checkingContent=false;if(updatedContent===null){var workingCopy=this.workingCopy();this._contentCommitted('',false);this.setWorkingCopy(workingCopy);return;} -if(this._lastAcceptedContent===updatedContent) -return;if(this._content===updatedContent){this._lastAcceptedContent=null;return;} -if(!this.isDirty()||this._workingCopy===updatedContent){this._contentCommitted(updatedContent,false);return;} -var shouldUpdate=window.confirm(Common.UIString('This file was changed externally. Would you like to reload it?'));if(shouldUpdate) -this._contentCommitted(updatedContent,false);else -this._lastAcceptedContent=updatedContent;}} -forceLoadOnCheckContent(){this._forceLoadOnCheckContent=true;} -requestOriginalContent(){return new Promise(fulfill=>{this._project.requestFileContent(this,(content,encoded)=>fulfill(content));});} -_commitContent(content){if(this._project.canSetFileContent()) -this._project.setFileContent(this,content,false,function(){});this._contentCommitted(content,true);} -_contentCommitted(content,committedByUser){this._lastAcceptedContent=null;this._content=content;this._contentLoaded=true;this._requestContentPromise=null;if(!this._history) -this._history=[];var lastRevision=this._history.length?this._history[this._history.length-1]:null;if(!lastRevision||lastRevision._content!==this._content){var revision=new Workspace.Revision(this,this._content,new Date());this._history.push(revision);} -this._innerResetWorkingCopy();this.dispatchEventToListeners(Workspace.UISourceCode.Events.WorkingCopyCommitted,{uiSourceCode:this,content:content});this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyCommitted,{uiSourceCode:this,content:content});if(committedByUser){this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyCommittedByUser,{uiSourceCode:this,content:content});}} -addRevision(content){this._commitContent(content);} -revertToOriginal(){function callback(content){if(typeof content!=='string') -return;this.addRevision(content);} -Host.userMetrics.actionTaken(Host.UserMetrics.Action.RevisionApplied);return this.requestOriginalContent().then(callback.bind(this));} -revertAndClearHistory(callback){function revert(content){if(typeof content!=='string') -return;this.addRevision(content);this._history=null;callback(this);} -Host.userMetrics.actionTaken(Host.UserMetrics.Action.RevisionApplied);this.requestOriginalContent().then(revert.bind(this));} -history(){if(!this._history) -this._history=[];return this._history;} -workingCopy(){if(this._workingCopyGetter){this._workingCopy=this._workingCopyGetter();this._workingCopyGetter=null;} -if(this.isDirty()) -return(this._workingCopy);return this._content||'';} -resetWorkingCopy(){this._innerResetWorkingCopy();this._workingCopyChanged();} -_innerResetWorkingCopy(){this._workingCopy=null;this._workingCopyGetter=null;} -setWorkingCopy(newWorkingCopy){this._workingCopy=newWorkingCopy;this._workingCopyGetter=null;this._workingCopyChanged();} -setContent(content,isBase64){if(this._project.canSetFileContent()) -this._project.setFileContent(this,content,isBase64,function(){});this._contentCommitted(content,true);} -setWorkingCopyGetter(workingCopyGetter){this._workingCopyGetter=workingCopyGetter;this._workingCopyChanged();} -_workingCopyChanged(){this._removeAllMessages();this.dispatchEventToListeners(Workspace.UISourceCode.Events.WorkingCopyChanged,this);this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyChanged,{uiSourceCode:this});} -removeWorkingCopyGetter(){if(!this._workingCopyGetter) -return;this._workingCopy=this._workingCopyGetter();this._workingCopyGetter=null;} -commitWorkingCopy(){if(this.isDirty()) -this._commitContent(this.workingCopy());} -isDirty(){return this._workingCopy!==null||this._workingCopyGetter!==null;} -extension(){return Common.ParsedURL.extractExtension(this._name);} -content(){return this._content;} -searchInContent(query,caseSensitive,isRegex){var content=this.content();if(!content) -return this._project.searchInFileContent(this,query,caseSensitive,isRegex);return Promise.resolve(Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex));} -contentLoaded(){return this._contentLoaded;} -uiLocation(lineNumber,columnNumber){if(typeof columnNumber==='undefined') -columnNumber=0;return new Workspace.UILocation(this,lineNumber,columnNumber);} -messages(){return this._messages?new Set(this._messages):new Set();} -addLineMessage(level,text,lineNumber,columnNumber){return this.addMessage(level,text,new TextUtils.TextRange(lineNumber,columnNumber||0,lineNumber,columnNumber||0));} -addMessage(level,text,range){var message=new Workspace.UISourceCode.Message(this,level,text,range);if(!this._messages) -this._messages=new Set();this._messages.add(message);this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageAdded,message);return message;} -removeMessage(message){if(this._messages&&this._messages.delete(message)) -this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageRemoved,message);} -_removeAllMessages(){if(!this._messages) -return;for(var message of this._messages) -this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageRemoved,message);this._messages=null;} -addLineDecoration(lineNumber,type,data){this.addDecoration(TextUtils.TextRange.createFromLocation(lineNumber,0),type,data);} -addDecoration(range,type,data){var marker=new Workspace.UISourceCode.LineMarker(range,type,data);if(!this._decorations) -this._decorations=new Multimap();this._decorations.set(type,marker);this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationAdded,marker);} -removeDecorationsForType(type){if(!this._decorations) -return;var markers=this._decorations.get(type);this._decorations.deleteAll(type);markers.forEach(marker=>{this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationRemoved,marker);});} -allDecorations(){return this._decorations?this._decorations.valuesArray():[];} -removeAllDecorations(){if(!this._decorations) -return;var decorationList=this._decorations.valuesArray();this._decorations.clear();decorationList.forEach(marker=>this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationRemoved,marker));} -decorationsForType(type){return this._decorations?this._decorations.get(type):null;}};Workspace.UISourceCode.Events={WorkingCopyChanged:Symbol('WorkingCopyChanged'),WorkingCopyCommitted:Symbol('WorkingCopyCommitted'),TitleChanged:Symbol('TitleChanged'),MessageAdded:Symbol('MessageAdded'),MessageRemoved:Symbol('MessageRemoved'),LineDecorationAdded:Symbol('LineDecorationAdded'),LineDecorationRemoved:Symbol('LineDecorationRemoved')};Workspace.UILocation=class{constructor(uiSourceCode,lineNumber,columnNumber){this.uiSourceCode=uiSourceCode;this.lineNumber=lineNumber;this.columnNumber=columnNumber;} -linkText(skipTrim){var linkText=this.uiSourceCode.displayName(skipTrim);if(typeof this.lineNumber==='number') -linkText+=':'+(this.lineNumber+1);return linkText;} -id(){return this.uiSourceCode.project().id()+':'+this.uiSourceCode.url()+':'+this.lineNumber+':'+ -this.columnNumber;} -toUIString(){return this.uiSourceCode.url()+':'+(this.lineNumber+1);} -static comparator(location1,location2){return location1.compareTo(location2);} -compareTo(other){if(this.uiSourceCode.url()!==other.uiSourceCode.url()) -return this.uiSourceCode.url()>other.uiSourceCode.url()?1:-1;if(this.lineNumber!==other.lineNumber) -return this.lineNumber-other.lineNumber;return this.columnNumber-other.columnNumber;}};Workspace.Revision=class{constructor(uiSourceCode,content,timestamp){this._uiSourceCode=uiSourceCode;this._content=content;this._timestamp=timestamp;} -get uiSourceCode(){return this._uiSourceCode;} -get timestamp(){return this._timestamp;} -get content(){return this._content||null;} -revertToThis(){function revert(content){if(content&&this._uiSourceCode._content!==content) -this._uiSourceCode.addRevision(content);} -Host.userMetrics.actionTaken(Host.UserMetrics.Action.RevisionApplied);return this.requestContent().then(revert.bind(this));} -contentURL(){return this._uiSourceCode.url();} -contentType(){return this._uiSourceCode.contentType();} -contentEncoded(){return Promise.resolve(false);} -requestContent(){return Promise.resolve((this._content||''));} -searchInContent(query,caseSensitive,isRegex){return Promise.resolve([]);}};Workspace.UISourceCode.Message=class{constructor(uiSourceCode,level,text,range){this._uiSourceCode=uiSourceCode;this._level=level;this._text=text;this._range=range;} -uiSourceCode(){return this._uiSourceCode;} -level(){return this._level;} -text(){return this._text;} -range(){return this._range;} -lineNumber(){return this._range.startLine;} -columnNumber(){return this._range.startColumn;} -isEqual(another){return this._uiSourceCode===another._uiSourceCode&&this.text()===another.text()&&this.level()===another.level()&&this.range().equal(another.range());} -remove(){this._uiSourceCode.removeMessage(this);}};Workspace.UISourceCode.Message.Level={Error:'Error',Warning:'Warning'};Workspace.UISourceCode.LineMarker=class{constructor(range,type,data){this._range=range;this._type=type;this._data=data;} -range(){return this._range;} -type(){return this._type;} -data(){return this._data;}};Workspace.UISourceCodeMetadata=class{constructor(modificationTime,contentSize){this.modificationTime=modificationTime;this.contentSize=contentSize;}};;Workspace.ProjectSearchConfig=function(){};Workspace.ProjectSearchConfig.prototype={query(){},ignoreCase(){},isRegex(){},queries(){},filePathMatchesFileQuery(filePath){}};Workspace.Project=function(){};Workspace.Project.prototype={workspace(){},id(){},type(){},isServiceProject(){},displayName(){},requestMetadata(uiSourceCode){},requestFileContent(uiSourceCode,callback){},canSetFileContent(){},setFileContent(uiSourceCode,newContent,isBase64,callback){},fullDisplayName(uiSourceCode){},mimeType(uiSourceCode){},canRename(){},rename(uiSourceCode,newName,callback){},excludeFolder(path){},createFile(path,name,content,isBase64){},deleteFile(uiSourceCode){},remove(){},searchInFileContent(uiSourceCode,query,caseSensitive,isRegex){},findFilesMatchingSearchRequest(searchConfig,filesMathingFileQuery,progress){},indexContent(progress){},uiSourceCodeForURL(url){},uiSourceCodes(){}};Workspace.projectTypes={Debugger:'debugger',Formatter:'formatter',Network:'network',Snippets:'snippets',FileSystem:'filesystem',ContentScripts:'contentscripts',Service:'service'};Workspace.ProjectStore=class{constructor(workspace,id,type,displayName){this._workspace=workspace;this._id=id;this._type=type;this._displayName=displayName;this._uiSourceCodesMap=new Map();this._uiSourceCodesList=[];this._project=(this);} -id(){return this._id;} -type(){return this._type;} -displayName(){return this._displayName;} -workspace(){return this._workspace;} -createUISourceCode(url,contentType){return new Workspace.UISourceCode(this._project,url,contentType);} -addUISourceCode(uiSourceCode,replace){var url=uiSourceCode.url();if(this.uiSourceCodeForURL(url)){if(replace) -this.removeUISourceCode(url);else -return false;} -this._uiSourceCodesMap.set(url,{uiSourceCode:uiSourceCode,index:this._uiSourceCodesList.length});this._uiSourceCodesList.push(uiSourceCode);this._workspace.dispatchEventToListeners(Workspace.Workspace.Events.UISourceCodeAdded,uiSourceCode);return true;} -removeUISourceCode(url){var uiSourceCode=this.uiSourceCodeForURL(url);if(!uiSourceCode) -return;var entry=this._uiSourceCodesMap.get(url);var movedUISourceCode=this._uiSourceCodesList[this._uiSourceCodesList.length-1];this._uiSourceCodesList[entry.index]=movedUISourceCode;var movedEntry=this._uiSourceCodesMap.get(movedUISourceCode.url());movedEntry.index=entry.index;this._uiSourceCodesList.splice(this._uiSourceCodesList.length-1,1);this._uiSourceCodesMap.delete(url);this._workspace.dispatchEventToListeners(Workspace.Workspace.Events.UISourceCodeRemoved,entry.uiSourceCode);} -removeProject(){this._workspace._removeProject(this._project);this._uiSourceCodesMap=new Map();this._uiSourceCodesList=[];} -uiSourceCodeForURL(url){var entry=this._uiSourceCodesMap.get(url);return entry?entry.uiSourceCode:null;} -uiSourceCodes(){return this._uiSourceCodesList;} -renameUISourceCode(uiSourceCode,newName){var oldPath=uiSourceCode.url();var newPath=uiSourceCode.parentURL()?uiSourceCode.parentURL()+'/'+newName:newName;var value=(this._uiSourceCodesMap.get(oldPath));this._uiSourceCodesMap.set(newPath,value);this._uiSourceCodesMap.delete(oldPath);}};Workspace.Workspace=class extends Common.Object{constructor(){super();this._projects=new Map();this._hasResourceContentTrackingExtensions=false;} -uiSourceCode(projectId,url){var project=this._projects.get(projectId);return project?project.uiSourceCodeForURL(url):null;} -uiSourceCodeForURL(url){for(var project of this._projects.values()){var uiSourceCode=project.uiSourceCodeForURL(url);if(uiSourceCode) -return uiSourceCode;} -return null;} -uiSourceCodesForProjectType(type){var result=[];for(var project of this._projects.values()){if(project.type()===type) -result=result.concat(project.uiSourceCodes());} -return result;} -addProject(project){console.assert(!this._projects.has(project.id()),`A project with id ${project.id()} already exists!`);this._projects.set(project.id(),project);this.dispatchEventToListeners(Workspace.Workspace.Events.ProjectAdded,project);} -_removeProject(project){this._projects.delete(project.id());this.dispatchEventToListeners(Workspace.Workspace.Events.ProjectRemoved,project);} -project(projectId){return this._projects.get(projectId)||null;} -projects(){return this._projects.valuesArray();} -projectsForType(type){function filterByType(project){return project.type()===type;} -return this.projects().filter(filterByType);} -uiSourceCodes(){var result=[];for(var project of this._projects.values()) -result=result.concat(project.uiSourceCodes());return result;} -setHasResourceContentTrackingExtensions(hasExtensions){this._hasResourceContentTrackingExtensions=hasExtensions;} -hasResourceContentTrackingExtensions(){return this._hasResourceContentTrackingExtensions;}};Workspace.Workspace.Events={UISourceCodeAdded:Symbol('UISourceCodeAdded'),UISourceCodeRemoved:Symbol('UISourceCodeRemoved'),UISourceCodeRenamed:Symbol('UISourceCodeRenamed'),WorkingCopyChanged:Symbol('WorkingCopyChanged'),WorkingCopyCommitted:Symbol('WorkingCopyCommitted'),WorkingCopyCommittedByUser:Symbol('WorkingCopyCommittedByUser'),ProjectAdded:Symbol('ProjectAdded'),ProjectRemoved:Symbol('ProjectRemoved')};Workspace.workspace;;self['NetworkLog']=self['NetworkLog']||{};NetworkLog.NetworkLog=class extends Common.Object{constructor(){super();this._requests=[];this._requestsSet=new Set();this._pageLoadForManager=new Map();this._isRecording=true;SDK.targetManager.observeModels(SDK.NetworkManager,this);} -modelAdded(networkManager){var eventListeners=[];eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestStarted,this._onRequestStarted,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestUpdated,this._onRequestUpdated,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestRedirected,this._onRequestRedirect,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished,this._onRequestUpdated,this));var resourceTreeModel=networkManager.target().model(SDK.ResourceTreeModel);if(resourceTreeModel){eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.WillReloadPage,this._willReloadPage,this));eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this));eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load,this._onLoad,this));eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded,this._onDOMContentLoaded.bind(this,resourceTreeModel)));} -networkManager[NetworkLog.NetworkLog._events]=eventListeners;} -modelRemoved(networkManager){this._removeNetworkManagerListeners(networkManager);} -_removeNetworkManagerListeners(networkManager){Common.EventTarget.removeEventListeners(networkManager[NetworkLog.NetworkLog._events]);} -setIsRecording(enabled){if(this._isRecording===enabled) -return;this._isRecording=enabled;if(enabled){SDK.targetManager.observeModels(SDK.NetworkManager,this);}else{SDK.targetManager.unobserveModels(SDK.NetworkManager,this);SDK.targetManager.models(SDK.NetworkManager).forEach(this._removeNetworkManagerListeners.bind(this));}} -requestForURL(url){return this._requests.find(request=>request.url()===url)||null;} -requests(){return this._requests;} -requestByManagerAndId(networkManager,requestId){for(var i=this._requests.length-1;i>=0;i--){var request=this._requests[i];if(requestId===request.requestId()&&networkManager===SDK.NetworkManager.forRequest(request)) -return request;} -return null;} -_requestByManagerAndURL(networkManager,url){for(var request of this._requests){if(url===request.url()&&networkManager===SDK.NetworkManager.forRequest(request)) -return request;} -return null;} -_initializeInitiatorSymbolIfNeeded(request){if(!request[NetworkLog.NetworkLog._initiatorDataSymbol]){request[NetworkLog.NetworkLog._initiatorDataSymbol]={info:null,chain:null,request:undefined,};}} -initiatorInfoForRequest(request){this._initializeInitiatorSymbolIfNeeded(request);if(request[NetworkLog.NetworkLog._initiatorDataSymbol].info) -return request[NetworkLog.NetworkLog._initiatorDataSymbol].info;var type=SDK.NetworkRequest.InitiatorType.Other;var url='';var lineNumber=-Infinity;var columnNumber=-Infinity;var scriptId=null;var initiator=request.initiator();var redirectSource=request.redirectSource();if(redirectSource){type=SDK.NetworkRequest.InitiatorType.Redirect;url=redirectSource.url();}else if(initiator){if(initiator.type===Protocol.Network.InitiatorType.Parser){type=SDK.NetworkRequest.InitiatorType.Parser;url=initiator.url?initiator.url:url;lineNumber=initiator.lineNumber?initiator.lineNumber:lineNumber;}else if(initiator.type===Protocol.Network.InitiatorType.Script){for(var stack=initiator.stack;stack;stack=stack.parent){var topFrame=stack.callFrames.length?stack.callFrames[0]:null;if(!topFrame) -continue;type=SDK.NetworkRequest.InitiatorType.Script;url=topFrame.url||Common.UIString('<anonymous>');lineNumber=topFrame.lineNumber;columnNumber=topFrame.columnNumber;scriptId=topFrame.scriptId;break;} -if(!initiator.stack&&initiator.url){type=SDK.NetworkRequest.InitiatorType.Script;url=initiator.url;lineNumber=initiator.lineNumber||0;}}else if(initiator.type===Protocol.Network.InitiatorType.Preload){type=SDK.NetworkRequest.InitiatorType.Preload;}} -request[NetworkLog.NetworkLog._initiatorDataSymbol].info={type:type,url:url,lineNumber:lineNumber,columnNumber:columnNumber,scriptId:scriptId};return request[NetworkLog.NetworkLog._initiatorDataSymbol].info;} -initiatorGraphForRequest(request){var initiated=new Set();var networkManager=SDK.NetworkManager.forRequest(request);for(var otherRequest of this._requests){var otherRequestManager=SDK.NetworkManager.forRequest(request);if(networkManager===otherRequestManager&&this._initiatorChain(otherRequest).has(request)) -initiated.add(otherRequest);} -return{initiators:this._initiatorChain(request),initiated:initiated};} -_initiatorChain(request){this._initializeInitiatorSymbolIfNeeded(request);var initiatorChainCache=(request[NetworkLog.NetworkLog._initiatorDataSymbol].chain);if(initiatorChainCache) -return initiatorChainCache;initiatorChainCache=new Set();var checkRequest=request;do{initiatorChainCache.add(checkRequest);checkRequest=this._initiatorRequest(checkRequest);}while(checkRequest);request[NetworkLog.NetworkLog._initiatorDataSymbol].chain=initiatorChainCache;return initiatorChainCache;} -_initiatorRequest(request){this._initializeInitiatorSymbolIfNeeded(request);if(request[NetworkLog.NetworkLog._initiatorDataSymbol].request!==undefined) -return request[NetworkLog.NetworkLog._initiatorDataSymbol].request;var url=this.initiatorInfoForRequest(request).url;var networkManager=SDK.NetworkManager.forRequest(request);request[NetworkLog.NetworkLog._initiatorDataSymbol].request=networkManager?this._requestByManagerAndURL(networkManager,url):null;return request[NetworkLog.NetworkLog._initiatorDataSymbol].request;} -_willReloadPage(){if(!Common.moduleSetting('network_log.preserve-log').get()) -this.reset();} -_onMainFrameNavigated(event){var mainFrame=(event.data);var manager=mainFrame.resourceTreeModel().target().model(SDK.NetworkManager);if(!manager) -return;var oldManagerRequests=this._requests.filter(request=>SDK.NetworkManager.forRequest(request)===manager);var oldRequestsSet=this._requestsSet;this._requests=[];this._requestsSet=new Set();this.dispatchEventToListeners(NetworkLog.NetworkLog.Events.Reset);var currentPageLoad=null;var requestsToAdd=[];for(var request of oldManagerRequests){if(request.loaderId!==mainFrame.loaderId) -continue;if(!currentPageLoad){currentPageLoad=new NetworkLog.PageLoad(request);var redirectSource=request.redirectSource();while(redirectSource){requestsToAdd.push(redirectSource);redirectSource=redirectSource.redirectSource();}} -requestsToAdd.push(request);} -for(var request of requestsToAdd){oldRequestsSet.delete(request);this._requests.push(request);this._requestsSet.add(request);currentPageLoad.bindRequest(request);this.dispatchEventToListeners(NetworkLog.NetworkLog.Events.RequestAdded,request);} -if(Common.moduleSetting('network_log.preserve-log').get()){for(var request of oldRequestsSet){this._requests.push(request);this._requestsSet.add(request);this.dispatchEventToListeners(NetworkLog.NetworkLog.Events.RequestAdded,request);}} -if(currentPageLoad) -this._pageLoadForManager.set(manager,currentPageLoad);} -importRequests(requests){this.reset();this._requests=[];this._requestsSet.clear();for(var request of requests){this._requests.push(request);this._requestsSet.add(request);this.dispatchEventToListeners(NetworkLog.NetworkLog.Events.RequestAdded,request);}} -_onRequestStarted(event){var request=(event.data);this._requests.push(request);this._requestsSet.add(request);var manager=SDK.NetworkManager.forRequest(request);var pageLoad=manager?this._pageLoadForManager.get(manager):null;if(pageLoad) -pageLoad.bindRequest(request);this.dispatchEventToListeners(NetworkLog.NetworkLog.Events.RequestAdded,request);} -_onRequestUpdated(event){var request=(event.data);if(!this._requestsSet.has(request)) -return;this.dispatchEventToListeners(NetworkLog.NetworkLog.Events.RequestUpdated,request);} -_onRequestRedirect(event){var request=(event.data);delete request[NetworkLog.NetworkLog._initiatorDataSymbol];} -_onDOMContentLoaded(resourceTreeModel,event){var networkManager=resourceTreeModel.target().model(SDK.NetworkManager);var pageLoad=networkManager?this._pageLoadForManager.get(networkManager):null;if(pageLoad) -pageLoad.contentLoadTime=(event.data);} -_onLoad(event){var networkManager=event.data.resourceTreeModel.target().model(SDK.NetworkManager);var pageLoad=networkManager?this._pageLoadForManager.get(networkManager):null;if(pageLoad) -pageLoad.loadTime=(event.data.loadTime);} -reset(){this._requests=[];this._requestsSet.clear();var managers=new Set(SDK.targetManager.models(SDK.NetworkManager));for(var manager of this._pageLoadForManager.keys()){if(!managers.has(manager)) -this._pageLoadForManager.delete(manager);} -this.dispatchEventToListeners(NetworkLog.NetworkLog.Events.Reset);}};NetworkLog.PageLoad=class{constructor(mainRequest){this.id=++NetworkLog.PageLoad._lastIdentifier;this.url=mainRequest.url();this.startTime=mainRequest.startTime;this.loadTime;this.contentLoadTime;this.mainRequest=mainRequest;this._showDataSaverWarningIfNeeded();} -async _showDataSaverWarningIfNeeded(){var manager=SDK.NetworkManager.forRequest(this.mainRequest);if(!manager) -return;if(!this.mainRequest.finished) -await this.mainRequest.once(SDK.NetworkRequest.Events.FinishedLoading);var saveDataHeader=this.mainRequest.requestHeaderValue('Save-Data');if(!NetworkLog.PageLoad._dataSaverMessageWasShown&&saveDataHeader&&saveDataHeader==='on'){var message=Common.UIString('Consider disabling %s while debugging. For more info see: %s',Common.UIString('Chrome Data Saver'),'https://support.google.com/chrome/?p=datasaver');manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:this.mainRequest.requestId(),warning:true});NetworkLog.PageLoad._dataSaverMessageWasShown=true;}} -static forRequest(request){return request[NetworkLog.PageLoad._pageLoadForRequestSymbol]||null;} -bindRequest(request){request[NetworkLog.PageLoad._pageLoadForRequestSymbol]=this;}};NetworkLog.PageLoad._lastIdentifier=0;NetworkLog.PageLoad._pageLoadForRequestSymbol=Symbol('PageLoadForRequest');NetworkLog.PageLoad._dataSaverMessageWasShown=false;NetworkLog.NetworkLog.InitiatorGraph;NetworkLog.NetworkLog.Events={Reset:Symbol('Reset'),RequestAdded:Symbol('RequestAdded'),RequestUpdated:Symbol('RequestUpdated')};NetworkLog.NetworkLog._InitiatorInfo;NetworkLog.NetworkLog._initiatorDataSymbol=Symbol('InitiatorData');NetworkLog.NetworkLog._events=Symbol('NetworkLog.NetworkLog.events');NetworkLog.networkLog;;NetworkLog.HAREntry=class{constructor(request){this._request=request;} -static _toMilliseconds(time){return time===-1?-1:time*1000;} -build(){var ipAddress=this._request.remoteAddress();var portPositionInString=ipAddress.lastIndexOf(':');if(portPositionInString!==-1) -ipAddress=ipAddress.substr(0,portPositionInString);var timings=this._buildTimings();var time=timings.blocked+timings.dns+timings.connect+timings.send+timings.wait+timings.receive;var entry={startedDateTime:NetworkLog.HARLog.pseudoWallTime(this._request,this._request.issueTime()),time:time,request:this._buildRequest(),response:this._buildResponse(),cache:{},timings:timings,serverIPAddress:ipAddress.replace(/\[\]/g,'')};if(this._request.cached()) -entry._fromCache=this._request.cachedInMemory()?'memory':'disk';if(this._request.connectionId!=='0') -entry.connection=this._request.connectionId;var page=NetworkLog.PageLoad.forRequest(this._request);if(page) -entry.pageref='page_'+page.id;return entry;} -_buildRequest(){var headersText=this._request.requestHeadersText();var res={method:this._request.requestMethod,url:this._buildRequestURL(this._request.url()),httpVersion:this._request.requestHttpVersion(),headers:this._request.requestHeaders(),queryString:this._buildParameters(this._request.queryParameters||[]),cookies:this._buildCookies(this._request.requestCookies||[]),headersSize:headersText?headersText.length:-1,bodySize:this.requestBodySize};if(this._request.requestFormData) -res.postData=this._buildPostData();return res;} -_buildResponse(){var headersText=this._request.responseHeadersText;return{status:this._request.statusCode,statusText:this._request.statusText,httpVersion:this._request.responseHttpVersion(),headers:this._request.responseHeaders,cookies:this._buildCookies(this._request.responseCookies||[]),content:this._buildContent(),redirectURL:this._request.responseHeaderValue('Location')||'',headersSize:headersText?headersText.length:-1,bodySize:this.responseBodySize,_transferSize:this._request.transferSize,_error:this._request.localizedFailDescription};} -_buildContent(){var content={size:this._request.resourceSize,mimeType:this._request.mimeType||'x-unknown',};var compression=this.responseCompression;if(typeof compression==='number') -content.compression=compression;return content;} -_buildTimings(){var timing=this._request.timing;var issueTime=this._request.issueTime();var startTime=this._request.startTime;var result={blocked:-1,dns:-1,ssl:-1,connect:-1,send:0,wait:0,receive:-1,_blocked_queueing:-1};var queuedTime=(issueTime<startTime)?startTime-issueTime:-1;result.blocked=queuedTime;result._blocked_queueing=NetworkLog.HAREntry._toMilliseconds(queuedTime);var highestTime=0;if(timing){var blockedStart=leastNonNegative([timing.dnsStart,timing.connectStart,timing.sendStart]);if(blockedStart!==Infinity) -result.blocked+=blockedStart;if(timing.proxyEnd!==-1) -result._blocked_proxy=timing.proxyEnd-timing.proxyStart;if(result._blocked_proxy&&result._blocked_proxy>result.blocked) -result.blocked=result._blocked_proxy;var dnsStart=timing.dnsEnd>=0?blockedStart:0;var dnsEnd=timing.dnsEnd>=0?timing.dnsEnd:-1;result.dns=dnsEnd-dnsStart;var sslStart=timing.sslEnd>0?timing.sslStart:0;var sslEnd=timing.sslEnd>0?timing.sslEnd:-1;result.ssl=sslEnd-sslStart;var connectStart=timing.connectEnd>=0?leastNonNegative([dnsEnd,blockedStart]):0;var connectEnd=timing.connectEnd>=0?timing.connectEnd:-1;result.connect=connectEnd-connectStart;var sendStart=timing.sendEnd>=0?Math.max(connectEnd,dnsEnd,blockedStart):0;var sendEnd=timing.sendEnd>=0?timing.sendEnd:0;result.send=sendEnd-sendStart;if(result.send<0) -result.send=0;highestTime=Math.max(sendEnd,connectEnd,sslEnd,dnsEnd,blockedStart,0);}else if(this._request.responseReceivedTime===-1){result.blocked=this._request.endTime-issueTime;return result;} -var requestTime=timing?timing.requestTime:startTime;var waitStart=highestTime;var waitEnd=NetworkLog.HAREntry._toMilliseconds(this._request.responseReceivedTime-requestTime);result.wait=waitEnd-waitStart;var receiveStart=waitEnd;var receiveEnd=NetworkLog.HAREntry._toMilliseconds(this._request.endTime-issueTime);result.receive=Math.max(receiveEnd-receiveStart,0);return result;function leastNonNegative(values){return values.reduce((best,value)=>(value>=0&&value<best)?value:best,Infinity);}} -_buildPostData(){var res={mimeType:this._request.requestContentType(),text:this._request.requestFormData};if(this._request.formParameters) -res.params=this._buildParameters(this._request.formParameters);return res;} -_buildParameters(parameters){return parameters.slice();} -_buildRequestURL(url){return url.split('#',2)[0];} -_buildCookies(cookies){return cookies.map(this._buildCookie.bind(this));} -_buildCookie(cookie){var c={name:cookie.name(),value:cookie.value(),path:cookie.path(),domain:cookie.domain(),expires:cookie.expiresDate(NetworkLog.HARLog.pseudoWallTime(this._request,this._request.startTime)),httpOnly:cookie.httpOnly(),secure:cookie.secure()};if(cookie.sameSite()) -c.sameSite=cookie.sameSite();return c;} -get requestBodySize(){return!this._request.requestFormData?0:this._request.requestFormData.length;} -get responseBodySize(){if(this._request.cached()||this._request.statusCode===304) -return 0;if(!this._request.responseHeadersText) -return-1;return this._request.transferSize-this._request.responseHeadersText.length;} -get responseCompression(){if(this._request.cached()||this._request.statusCode===304||this._request.statusCode===206) -return;if(!this._request.responseHeadersText) -return;return this._request.resourceSize-this.responseBodySize;}};NetworkLog.HAREntry.Timing;NetworkLog.HARLog=class{constructor(requests){this._requests=requests;} -static pseudoWallTime(request,monotonicTime){return new Date(request.pseudoWallTime(monotonicTime)*1000);} -build(){return{version:'1.2',creator:this._creator(),pages:this._buildPages(),entries:this._requests.map(this._convertResource.bind(this))};} -_creator(){var webKitVersion=/AppleWebKit\/([^ ]+)/.exec(window.navigator.userAgent);return{name:'WebInspector',version:webKitVersion?webKitVersion[1]:'n/a'};} -_buildPages(){var seenIdentifiers={};var pages=[];for(var i=0;i<this._requests.length;++i){var request=this._requests[i];var page=NetworkLog.PageLoad.forRequest(request);if(!page||seenIdentifiers[page.id]) -continue;seenIdentifiers[page.id]=true;pages.push(this._convertPage(page,request));} -return pages;} -_convertPage(page,request){return{startedDateTime:NetworkLog.HARLog.pseudoWallTime(request,page.startTime),id:'page_'+page.id,title:page.url,pageTimings:{onContentLoad:this._pageEventTime(page,page.contentLoadTime),onLoad:this._pageEventTime(page,page.loadTime)}};} -_convertResource(request){return(new NetworkLog.HAREntry(request)).build();} -_pageEventTime(page,time){var startTime=page.startTime;if(time===-1||startTime===-1) -return-1;return NetworkLog.HAREntry._toMilliseconds(time-startTime);}};;self['ConsoleModel']=self['ConsoleModel']||{};ConsoleModel.ConsoleModel=class extends Common.Object{constructor(){super();this._messages=[];this._messageByExceptionId=new Map();this._warnings=0;this._errors=0;this._pageLoadSequenceNumber=0;SDK.targetManager.observeTargets(this);} -targetAdded(target){var resourceTreeModel=target.model(SDK.ResourceTreeModel);if(!resourceTreeModel||resourceTreeModel.cachedResourcesLoaded()){this._initTarget(target);return;} -var eventListener=resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded,()=>{Common.EventTarget.removeEventListeners([eventListener]);this._initTarget(target);});} -_initTarget(target){var eventListeners=[];var logModel=target.model(SDK.LogModel);if(logModel) -eventListeners.push(logModel.addEventListener(SDK.LogModel.Events.EntryAdded,this._logEntryAdded,this));var cpuProfilerModel=target.model(SDK.CPUProfilerModel);if(cpuProfilerModel){eventListeners.push(cpuProfilerModel.addEventListener(SDK.CPUProfilerModel.Events.ConsoleProfileStarted,this._consoleProfileStarted.bind(this,cpuProfilerModel)));eventListeners.push(cpuProfilerModel.addEventListener(SDK.CPUProfilerModel.Events.ConsoleProfileFinished,this._consoleProfileFinished.bind(this,cpuProfilerModel)));} -var resourceTreeModel=target.model(SDK.ResourceTreeModel);if(resourceTreeModel){eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._mainFrameNavigated,this));} -var runtimeModel=target.model(SDK.RuntimeModel);if(runtimeModel){eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.ExceptionThrown,this._exceptionThrown.bind(this,runtimeModel)));eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.ExceptionRevoked,this._exceptionRevoked.bind(this,runtimeModel)));eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.ConsoleAPICalled,this._consoleAPICalled.bind(this,runtimeModel)));eventListeners.push(runtimeModel.debuggerModel().addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._clearIfNecessary,this));eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.QueryObjectRequested,this._queryObjectRequested.bind(this,runtimeModel)));} -var networkManager=target.model(SDK.NetworkManager);if(networkManager){eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.MessageGenerated,this._networkMessageGenerated.bind(this,networkManager)));} -target[ConsoleModel.ConsoleModel._events]=eventListeners;} -targetRemoved(target){var runtimeModel=target.model(SDK.RuntimeModel);if(runtimeModel) -this._messageByExceptionId.delete(runtimeModel);Common.EventTarget.removeEventListeners(target[ConsoleModel.ConsoleModel._events]||[]);} -async evaluateCommandInConsole(executionContext,originatingMessage,expression,useCommandLineAPI,awaitPromise){var result=await executionContext.evaluate({expression:expression,objectGroup:'console',includeCommandLineAPI:useCommandLineAPI,silent:false,returnByValue:false,generatePreview:true},true,awaitPromise);Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConsoleEvaluated);if(result.error) -return;await Common.console.showPromise();this.dispatchEventToListeners(ConsoleModel.ConsoleModel.Events.CommandEvaluated,{result:result.object,commandMessage:originatingMessage,exceptionDetails:result.exceptionDetails});} -addCommandMessage(executionContext,text){var commandMessage=new ConsoleModel.ConsoleMessage(executionContext.runtimeModel,ConsoleModel.ConsoleMessage.MessageSource.JS,null,text,ConsoleModel.ConsoleMessage.MessageType.Command);commandMessage.setExecutionContextId(executionContext.id);this.addMessage(commandMessage);return commandMessage;} -addMessage(msg){if(msg.source===ConsoleModel.ConsoleMessage.MessageSource.Worker&&SDK.targetManager.targetById(msg.workerId)) -return;msg._pageLoadSequenceNumber=this._pageLoadSequenceNumber;if(msg.source===ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI&&msg.type===ConsoleModel.ConsoleMessage.MessageType.Clear) -this._clearIfNecessary();this._messages.push(msg);var runtimeModel=msg.runtimeModel();if(msg._exceptionId&&runtimeModel){var modelMap=this._messageByExceptionId.get(runtimeModel);if(!modelMap){modelMap=new Map();this._messageByExceptionId.set(runtimeModel,modelMap);} -modelMap.set(msg._exceptionId,msg);} -this._incrementErrorWarningCount(msg);this.dispatchEventToListeners(ConsoleModel.ConsoleModel.Events.MessageAdded,msg);} -_logEntryAdded(event){var data=(event.data);var consoleMessage=new ConsoleModel.ConsoleMessage(data.logModel.target().model(SDK.RuntimeModel),data.entry.source,data.entry.level,data.entry.text,undefined,data.entry.url,data.entry.lineNumber,undefined,data.entry.networkRequestId,[data.entry.text,...(data.entry.args||[])],data.entry.stackTrace,data.entry.timestamp,undefined,undefined,data.entry.workerId);this.addMessage(consoleMessage);} -_exceptionThrown(runtimeModel,event){var exceptionWithTimestamp=(event.data);var consoleMessage=ConsoleModel.ConsoleMessage.fromException(runtimeModel,exceptionWithTimestamp.details,undefined,exceptionWithTimestamp.timestamp,undefined);consoleMessage.setExceptionId(exceptionWithTimestamp.details.exceptionId);this.addMessage(consoleMessage);} -_exceptionRevoked(runtimeModel,event){var exceptionId=(event.data);var modelMap=this._messageByExceptionId.get(runtimeModel);var exceptionMessage=modelMap?modelMap.get(exceptionId):null;if(!exceptionMessage) -return;this._errors--;exceptionMessage.level=ConsoleModel.ConsoleMessage.MessageLevel.Info;this.dispatchEventToListeners(ConsoleModel.ConsoleModel.Events.MessageUpdated,exceptionMessage);} -_consoleAPICalled(runtimeModel,event){var call=(event.data);var level=ConsoleModel.ConsoleMessage.MessageLevel.Info;if(call.type===ConsoleModel.ConsoleMessage.MessageType.Debug) -level=ConsoleModel.ConsoleMessage.MessageLevel.Verbose;else if(call.type===ConsoleModel.ConsoleMessage.MessageType.Error||call.type===ConsoleModel.ConsoleMessage.MessageType.Assert) -level=ConsoleModel.ConsoleMessage.MessageLevel.Error;else if(call.type===ConsoleModel.ConsoleMessage.MessageType.Warning) -level=ConsoleModel.ConsoleMessage.MessageLevel.Warning;else if(call.type===ConsoleModel.ConsoleMessage.MessageType.Info||call.type===ConsoleModel.ConsoleMessage.MessageType.Log) -level=ConsoleModel.ConsoleMessage.MessageLevel.Info;var message='';if(call.args.length&&call.args[0].unserializableValue) -message=call.args[0].unserializableValue;else if(call.args.length&&(typeof call.args[0].value!=='object'||call.args[0].value===null)) -message=call.args[0].value+'';else if(call.args.length&&call.args[0].description) -message=call.args[0].description;var callFrame=call.stackTrace&&call.stackTrace.callFrames.length?call.stackTrace.callFrames[0]:null;var consoleMessage=new ConsoleModel.ConsoleMessage(runtimeModel,ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI,level,(message),call.type,callFrame?callFrame.url:undefined,callFrame?callFrame.lineNumber:undefined,callFrame?callFrame.columnNumber:undefined,undefined,call.args,call.stackTrace,call.timestamp,call.executionContextId,undefined,undefined,call.context);this.addMessage(consoleMessage);} -_queryObjectRequested(runtimeModel,event){var consoleMessage=new ConsoleModel.ConsoleMessage(runtimeModel,ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI,ConsoleModel.ConsoleMessage.MessageLevel.Info,'',undefined,undefined,undefined,undefined,undefined,[event.data.objects],undefined,undefined,undefined,undefined,undefined,undefined);this.addMessage(consoleMessage);} -_clearIfNecessary(){if(!Common.moduleSetting('preserveConsoleLog').get()) -this._clear();++this._pageLoadSequenceNumber;} -_mainFrameNavigated(event){if(Common.moduleSetting('preserveConsoleLog').get()) -Common.console.log(Common.UIString('Navigated to %s',event.data.url));} -_consoleProfileStarted(cpuProfilerModel,event){var data=(event.data);this._addConsoleProfileMessage(cpuProfilerModel,ConsoleModel.ConsoleMessage.MessageType.Profile,data.scriptLocation,Common.UIString('Profile \'%s\' started.',data.title));} -_consoleProfileFinished(cpuProfilerModel,event){var data=(event.data);this._addConsoleProfileMessage(cpuProfilerModel,ConsoleModel.ConsoleMessage.MessageType.ProfileEnd,data.scriptLocation,Common.UIString('Profile \'%s\' finished.',data.title));} -_addConsoleProfileMessage(cpuProfilerModel,type,scriptLocation,messageText){var stackTrace=[{functionName:'',scriptId:scriptLocation.scriptId,url:scriptLocation.script()?scriptLocation.script().contentURL():'',lineNumber:scriptLocation.lineNumber,columnNumber:scriptLocation.columnNumber||0}];this.addMessage(new ConsoleModel.ConsoleMessage(cpuProfilerModel.runtimeModel(),ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI,ConsoleModel.ConsoleMessage.MessageLevel.Info,messageText,type,undefined,undefined,undefined,undefined,stackTrace));} -_networkMessageGenerated(networkManager,event){var message=(event.data);this.addMessage(new ConsoleModel.ConsoleMessage(networkManager.target().model(SDK.RuntimeModel),ConsoleModel.ConsoleMessage.MessageSource.Network,message.warning?ConsoleModel.ConsoleMessage.MessageLevel.Warning:ConsoleModel.ConsoleMessage.MessageLevel.Info,message.message,undefined,undefined,undefined,undefined,message.requestId));} -_incrementErrorWarningCount(msg){if(msg.source===ConsoleModel.ConsoleMessage.MessageSource.Violation) -return;switch(msg.level){case ConsoleModel.ConsoleMessage.MessageLevel.Warning:this._warnings++;break;case ConsoleModel.ConsoleMessage.MessageLevel.Error:this._errors++;break;}} -messages(){return this._messages;} -requestClearMessages(){for(var logModel of SDK.targetManager.models(SDK.LogModel)) -logModel.requestClear();for(var runtimeModel of SDK.targetManager.models(SDK.RuntimeModel)) -runtimeModel.discardConsoleEntries();this._clear();} -_clear(){this._messages=[];this._messageByExceptionId.clear();this._errors=0;this._warnings=0;this.dispatchEventToListeners(ConsoleModel.ConsoleModel.Events.ConsoleCleared);} -errors(){return this._errors;} -warnings(){return this._warnings;}};ConsoleModel.ConsoleModel.Events={ConsoleCleared:Symbol('ConsoleCleared'),MessageAdded:Symbol('MessageAdded'),MessageUpdated:Symbol('MessageUpdated'),CommandEvaluated:Symbol('CommandEvaluated')};ConsoleModel.ConsoleMessage=class{constructor(runtimeModel,source,level,messageText,type,url,line,column,requestId,parameters,stackTrace,timestamp,executionContextId,scriptId,workerId,context){this._runtimeModel=runtimeModel;this.source=source;this.level=(level);this.messageText=messageText;this.type=type||ConsoleModel.ConsoleMessage.MessageType.Log;this.url=url||undefined;this.line=line||0;this.column=column||0;this.parameters=parameters;this.stackTrace=stackTrace;this.timestamp=timestamp||Date.now();this.executionContextId=executionContextId||0;this.scriptId=scriptId||null;this.workerId=workerId||null;var manager=runtimeModel?runtimeModel.target().model(SDK.NetworkManager):null;this.request=(manager&&requestId)?NetworkLog.networkLog.requestByManagerAndId(manager,requestId):null;if(this.request){var initiator=this.request.initiator();if(initiator){this.stackTrace=initiator.stack||undefined;if(initiator.url){this.url=initiator.url;this.line=initiator.lineNumber||0;}}} -if(!this.executionContextId&&this._runtimeModel){if(this.scriptId) -this.executionContextId=this._runtimeModel.executionContextIdForScriptId(this.scriptId);else if(this.stackTrace) -this.executionContextId=this._runtimeModel.executionContextForStackTrace(this.stackTrace);} -if(context) -this.context=context.match(/[^#]*/)[0];} -static fromException(runtimeModel,exceptionDetails,messageType,timestamp,forceUrl){return new ConsoleModel.ConsoleMessage(runtimeModel,ConsoleModel.ConsoleMessage.MessageSource.JS,ConsoleModel.ConsoleMessage.MessageLevel.Error,SDK.RuntimeModel.simpleTextFromException(exceptionDetails),messageType,forceUrl||exceptionDetails.url,exceptionDetails.lineNumber,exceptionDetails.columnNumber,undefined,exceptionDetails.exception?[SDK.RemoteObject.fromLocalObject(exceptionDetails.text),exceptionDetails.exception]:undefined,exceptionDetails.stackTrace,timestamp,exceptionDetails.executionContextId,exceptionDetails.scriptId);} -runtimeModel(){return this._runtimeModel;} -setOriginatingMessage(originatingMessage){this._originatingConsoleMessage=originatingMessage;this.executionContextId=originatingMessage.executionContextId;} -setExecutionContextId(executionContextId){this.executionContextId=executionContextId;} -setExceptionId(exceptionId){this._exceptionId=exceptionId;} -originatingMessage(){return this._originatingConsoleMessage;} -isGroupMessage(){return this.type===ConsoleModel.ConsoleMessage.MessageType.StartGroup||this.type===ConsoleModel.ConsoleMessage.MessageType.StartGroupCollapsed||this.type===ConsoleModel.ConsoleMessage.MessageType.EndGroup;} -isGroupStartMessage(){return this.type===ConsoleModel.ConsoleMessage.MessageType.StartGroup||this.type===ConsoleModel.ConsoleMessage.MessageType.StartGroupCollapsed;} -isErrorOrWarning(){return(this.level===ConsoleModel.ConsoleMessage.MessageLevel.Warning||this.level===ConsoleModel.ConsoleMessage.MessageLevel.Error);} -isGroupable(){return(this.source!==ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI&&this.type!==ConsoleModel.ConsoleMessage.MessageType.Command&&this.type!==ConsoleModel.ConsoleMessage.MessageType.Result&&this.type!==ConsoleModel.ConsoleMessage.MessageType.System);} -groupCategoryKey(){return[this.source,this.level,this.type,this._pageLoadSequenceNumber].join(':');} -isEqual(msg){if(!msg) -return false;if(!this._isEqualStackTraces(this.stackTrace,msg.stackTrace)) -return false;if(this.parameters){if(!msg.parameters||this.parameters.length!==msg.parameters.length) -return false;for(var i=0;i<msg.parameters.length;++i){if(msg.parameters[i].type==='object'&&msg.parameters[i].subtype!=='error') -return false;if(this.parameters[i].type!==msg.parameters[i].type||this.parameters[i].value!==msg.parameters[i].value||this.parameters[i].description!==msg.parameters[i].description) -return false;}} -return(this.runtimeModel()===msg.runtimeModel())&&(this.source===msg.source)&&(this.type===msg.type)&&(this.level===msg.level)&&(this.line===msg.line)&&(this.url===msg.url)&&(this.messageText===msg.messageText)&&(this.request===msg.request)&&(this.executionContextId===msg.executionContextId);} -_isEqualStackTraces(stackTrace1,stackTrace2){if(!stackTrace1!==!stackTrace2) -return false;if(!stackTrace1) -return true;var callFrames1=stackTrace1.callFrames;var callFrames2=stackTrace2.callFrames;if(callFrames1.length!==callFrames2.length) -return false;for(var i=0,n=callFrames1.length;i<n;++i){if(callFrames1[i].url!==callFrames2[i].url||callFrames1[i].functionName!==callFrames2[i].functionName||callFrames1[i].lineNumber!==callFrames2[i].lineNumber||callFrames1[i].columnNumber!==callFrames2[i].columnNumber) -return false;} -return this._isEqualStackTraces(stackTrace1.parent,stackTrace2.parent);}};ConsoleModel.ConsoleMessage.MessageSource={XML:'xml',JS:'javascript',Network:'network',ConsoleAPI:'console-api',Storage:'storage',AppCache:'appcache',Rendering:'rendering',CSS:'css',Security:'security',Deprecation:'deprecation',Worker:'worker',Violation:'violation',Intervention:'intervention',Recommendation:'recommendation',Other:'other'};ConsoleModel.ConsoleMessage.MessageType={Log:'log',Debug:'debug',Info:'info',Error:'error',Warning:'warning',Dir:'dir',DirXML:'dirxml',Table:'table',Trace:'trace',Clear:'clear',StartGroup:'startGroup',StartGroupCollapsed:'startGroupCollapsed',EndGroup:'endGroup',Assert:'assert',Result:'result',Profile:'profile',ProfileEnd:'profileEnd',Command:'command',System:'system'};ConsoleModel.ConsoleMessage.MessageLevel={Verbose:'verbose',Info:'info',Warning:'warning',Error:'error'};ConsoleModel.ConsoleMessage.MessageSourceDisplayName=new Map([[ConsoleModel.ConsoleMessage.MessageSource.XML,'xml'],[ConsoleModel.ConsoleMessage.MessageSource.JS,'javascript'],[ConsoleModel.ConsoleMessage.MessageSource.Network,'network'],[ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI,'console-api'],[ConsoleModel.ConsoleMessage.MessageSource.Storage,'storage'],[ConsoleModel.ConsoleMessage.MessageSource.AppCache,'appcache'],[ConsoleModel.ConsoleMessage.MessageSource.Rendering,'rendering'],[ConsoleModel.ConsoleMessage.MessageSource.CSS,'css'],[ConsoleModel.ConsoleMessage.MessageSource.Security,'security'],[ConsoleModel.ConsoleMessage.MessageSource.Deprecation,'deprecation'],[ConsoleModel.ConsoleMessage.MessageSource.Worker,'worker'],[ConsoleModel.ConsoleMessage.MessageSource.Violation,'violation'],[ConsoleModel.ConsoleMessage.MessageSource.Intervention,'intervention'],[ConsoleModel.ConsoleMessage.MessageSource.Recommendation,'recommendation'],[ConsoleModel.ConsoleMessage.MessageSource.Other,'other']]);ConsoleModel.ConsoleModel._events=Symbol('ConsoleModel.ConsoleModel.events');ConsoleModel.consoleModel;;self['Bindings']=self['Bindings']||{};Bindings.LiveLocation=function(){};Bindings.LiveLocation.prototype={update(){},uiLocation(){},dispose(){},isBlackboxed(){}};Bindings.LiveLocationWithPool=class{constructor(updateDelegate,locationPool){this._updateDelegate=updateDelegate;this._locationPool=locationPool;this._locationPool._add(this);} -update(){this._updateDelegate(this);} -uiLocation(){throw'Not implemented';} -dispose(){this._locationPool._delete(this);this._updateDelegate=null;} -isBlackboxed(){throw'Not implemented';}};Bindings.LiveLocationPool=class{constructor(){this._locations=new Set();} -_add(location){this._locations.add(location);} -_delete(location){this._locations.delete(location);} -disposeAll(){for(var location of this._locations) -location.dispose();}};;Bindings.ResourceMapping=class{constructor(targetManager,workspace){this._workspace=workspace;this._modelToInfo=new Map();targetManager.observeModels(SDK.ResourceTreeModel,this);} -modelAdded(resourceTreeModel){var info=new Bindings.ResourceMapping.ModelInfo(this._workspace,resourceTreeModel);this._modelToInfo.set(resourceTreeModel,info);} -modelRemoved(resourceTreeModel){var info=this._modelToInfo.get(resourceTreeModel);info.dispose();this._modelToInfo.delete(resourceTreeModel);} -_infoForTarget(target){var resourceTreeModel=target.model(SDK.ResourceTreeModel);return resourceTreeModel?this._modelToInfo.get(resourceTreeModel):null;} -cssLocationToUILocation(cssLocation){var info=this._infoForTarget(cssLocation.cssModel().target());if(!info) -return null;var uiSourceCode=info._project.uiSourceCodeForURL(cssLocation.url);return uiSourceCode?uiSourceCode.uiLocation(cssLocation.lineNumber,cssLocation.columnNumber):null;} -jsLocationToUILocation(jsLocation){var script=jsLocation.script();if(!script) -return null;var info=this._infoForTarget(jsLocation.debuggerModel.target());if(!info) -return null;var uiSourceCode=info._project.uiSourceCodeForURL(script.sourceURL);return uiSourceCode?uiSourceCode.uiLocation(jsLocation.lineNumber,jsLocation.columnNumber):null;} -uiLocationToJSLocation(uiSourceCode,lineNumber,columnNumber){if(!uiSourceCode[Bindings.ResourceMapping._symbol]) -return null;var target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);if(!target) -return null;var debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel) -return null;return debuggerModel.createRawLocationByURL(uiSourceCode.url(),lineNumber,columnNumber);} -_resetForTest(target){var resourceTreeModel=target.model(SDK.ResourceTreeModel);var info=resourceTreeModel?this._modelToInfo.get(resourceTreeModel):null;if(info) -info._resetForTest();}};Bindings.ResourceMapping.ModelInfo=class{constructor(workspace,resourceTreeModel){var target=resourceTreeModel.target();this._project=new Bindings.ContentProviderBasedProject(workspace,'resources:'+target.id(),Workspace.projectTypes.Network,'',false);Bindings.NetworkProject.setTargetForProject(this._project,target);this._bindings=new Map();this._eventListeners=[resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.ResourceAdded,this._resourceAdded,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameWillNavigate,this._frameWillNavigate,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameDetached,this._frameDetached,this)];} -_acceptsResource(resource){var resourceType=resource.resourceType();if(resourceType!==Common.resourceTypes.Image&&resourceType!==Common.resourceTypes.Font&&resourceType!==Common.resourceTypes.Document&&resourceType!==Common.resourceTypes.Manifest) -return false;if(resourceType===Common.resourceTypes.Image&&resource.mimeType&&!resource.mimeType.startsWith('image')) -return false;if(resourceType===Common.resourceTypes.Font&&resource.mimeType&&!resource.mimeType.includes('font')) -return false;if((resourceType===Common.resourceTypes.Image||resourceType===Common.resourceTypes.Font)&&resource.contentURL().startsWith('data:')) -return false;return true;} -_resourceAdded(event){var resource=(event.data);if(!this._acceptsResource(resource)) -return;var binding=this._bindings.get(resource.url);if(!binding){binding=new Bindings.ResourceMapping.Binding(this._project,resource);this._bindings.set(resource.url,binding);}else{binding.addResource(resource);}} -_removeFrameResources(frame){for(var resource of frame.resources()){if(!this._acceptsResource(resource)) -continue;var binding=this._bindings.get(resource.url);if(binding._resources.size===1){binding.dispose();this._bindings.delete(resource.url);}else{binding.removeResource(resource);}}} -_frameWillNavigate(event){var frame=(event.data);this._removeFrameResources(frame);} -_frameDetached(event){var frame=(event.data);this._removeFrameResources(frame);} -_resetForTest(){for(var binding of this._bindings.valuesArray()) -binding.dispose();this._bindings.clear();} -dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);for(var binding of this._bindings.valuesArray()) -binding.dispose();this._bindings.clear();this._project.removeProject();}};Bindings.ResourceMapping.Binding=class{constructor(project,resource){this._resources=new Set([resource]);this._project=project;this._uiSourceCode=this._project.createUISourceCode(resource.url,resource.contentType());this._uiSourceCode[Bindings.ResourceMapping._symbol]=true;Bindings.NetworkProject.setInitialFrameAttribution(this._uiSourceCode,resource.frameId);this._project.addUISourceCodeWithProvider(this._uiSourceCode,this,Bindings.resourceMetadata(resource),resource.mimeType);} -addResource(resource){this._resources.add(resource);Bindings.NetworkProject.addFrameAttribution(this._uiSourceCode,resource.frameId);} -removeResource(resource){this._resources.delete(resource);Bindings.NetworkProject.removeFrameAttribution(this._uiSourceCode,resource.frameId);} -dispose(){this._project.removeFile(this._uiSourceCode.url());} -contentURL(){return this._resources.firstValue().contentURL();} -contentType(){return this._resources.firstValue().contentType();} -contentEncoded(){return this._resources.firstValue().contentEncoded();} -requestContent(){return this._resources.firstValue().requestContent();} -searchInContent(query,caseSensitive,isRegex){return this._resources.firstValue().searchInContent(query,caseSensitive,isRegex);}};Bindings.ResourceMapping._symbol=Symbol('Bindings.ResourceMapping._symbol');;Bindings.CompilerScriptMapping=class{constructor(debuggerModel,workspace,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._sourceMapManager=this._debuggerModel.sourceMapManager();this._workspace=workspace;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;var target=debuggerModel.target();this._regularProject=new Bindings.ContentProviderBasedProject(workspace,'jsSourceMaps::'+target.id(),Workspace.projectTypes.Network,'',false);this._contentScriptsProject=new Bindings.ContentProviderBasedProject(workspace,'jsSourceMaps:extensions:'+target.id(),Workspace.projectTypes.ContentScripts,'',false);Bindings.NetworkProject.setTargetForProject(this._regularProject,target);Bindings.NetworkProject.setTargetForProject(this._contentScriptsProject,target);this._stubUISourceCodes=new Map();this._stubProject=new Bindings.ContentProviderBasedProject(workspace,'jsSourceMaps:stub:'+target.id(),Workspace.projectTypes.Service,'',true);this._eventListeners=[this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapWillAttach,this._sourceMapWillAttach,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapFailedToAttach,this._sourceMapFailedToAttach,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapAttached,this._sourceMapAttached,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapDetached,this._sourceMapDetached,this),];} -_addStubUISourceCode(script){var stubUISourceCode=this._stubProject.addContentProvider(script.sourceURL+':sourcemap',Common.StaticContentProvider.fromString(script.sourceURL,Common.resourceTypes.Script,'\n\n\n\n\n// Please wait a bit.\n// Compiled script is not shown while source map is being loaded!'),'text/javascript');this._stubUISourceCodes.set(script,stubUISourceCode);} -_removeStubUISourceCode(script){var uiSourceCode=this._stubUISourceCodes.get(script);this._stubUISourceCodes.delete(script);this._stubProject.removeFile(uiSourceCode.url());this._debuggerWorkspaceBinding.updateLocations(script);} -static uiSourceCodeOrigin(uiSourceCode){var sourceMap=uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol];if(!sourceMap) -return null;return sourceMap.compiledURL();} -mapsToSourceCode(rawLocation){var script=rawLocation.script();var sourceMap=script?this._sourceMapManager.sourceMapForClient(script):null;if(!sourceMap) -return true;return!!sourceMap.findEntry(rawLocation.lineNumber,rawLocation.columnNumber);} -uiSourceCodeForURL(url,isContentScript){return isContentScript?this._contentScriptsProject.uiSourceCodeForURL(url):this._regularProject.uiSourceCodeForURL(url);} -rawLocationToUILocation(rawLocation){var script=rawLocation.script();if(!script) -return null;var lineNumber=rawLocation.lineNumber-script.lineOffset;var columnNumber=rawLocation.columnNumber;if(!lineNumber) -columnNumber-=script.columnOffset;var stubUISourceCode=this._stubUISourceCodes.get(script);if(stubUISourceCode) -return new Workspace.UILocation(stubUISourceCode,lineNumber,columnNumber);var sourceMap=this._sourceMapManager.sourceMapForClient(script);if(!sourceMap) -return null;var entry=sourceMap.findEntry(lineNumber,columnNumber);if(!entry||!entry.sourceURL) -return null;var uiSourceCode=script.isContentScript()?this._contentScriptsProject.uiSourceCodeForURL(entry.sourceURL):this._regularProject.uiSourceCodeForURL(entry.sourceURL);if(!uiSourceCode) -return null;return uiSourceCode.uiLocation((entry.sourceLineNumber),(entry.sourceColumnNumber));} -uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){var sourceMap=uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol];if(!sourceMap) -return null;var scripts=this._sourceMapManager.clientsForSourceMap(sourceMap);var script=scripts.length?scripts[0]:null;if(!script) -return null;var entry=sourceMap.sourceLineMapping(uiSourceCode.url(),lineNumber,columnNumber);if(!entry) -return null;return this._debuggerModel.createRawLocation(script,entry.lineNumber+script.lineOffset,!entry.lineNumber?entry.columnNumber+script.columnOffset:entry.columnNumber);} -_sourceMapWillAttach(event){var script=(event.data);this._addStubUISourceCode(script);this._debuggerWorkspaceBinding.updateLocations(script);} -_sourceMapFailedToAttach(event){var script=(event.data);this._removeStubUISourceCode(script);} -_sourceMapAttached(event){var script=(event.data.client);var sourceMap=(event.data.sourceMap);this._removeStubUISourceCode(script);if(Bindings.blackboxManager.isBlackboxedURL(script.sourceURL,script.isContentScript())) -return;Bindings.blackboxManager.sourceMapLoaded(script,sourceMap);this._populateSourceMapSources(script,sourceMap);this._sourceMapAttachedForTest(sourceMap);} -_sourceMapDetached(event){var script=(event.data.client);var frameId=script[Bindings.CompilerScriptMapping._frameIdSymbol];var sourceMap=(event.data.sourceMap);var scripts=this._sourceMapManager.clientsForSourceMap(sourceMap);var hasOtherScripts=scripts.some(someScript=>someScript.isContentScript()===script.isContentScript());var project=script.isContentScript()?this._contentScriptsProject:this._regularProject;for(var sourceURL of sourceMap.sourceURLs()){var uiSourceCode=(project.uiSourceCodeForURL(sourceURL));if(hasOtherScripts) -Bindings.NetworkProject.removeFrameAttribution(uiSourceCode,frameId);else -project.removeFile(sourceURL);} -this._debuggerWorkspaceBinding.updateLocations(script);} -sourceMapForScript(script){return this._sourceMapManager.sourceMapForClient(script);} -maybeLoadSourceMap(script){var sourceMap=this._sourceMapManager.sourceMapForClient(script);if(!sourceMap) -return;this._populateSourceMapSources(script,sourceMap);} -_sourceMapAttachedForTest(sourceMap){} -_populateSourceMapSources(script,sourceMap){var frameId=Bindings.frameIdForScript(script);script[Bindings.CompilerScriptMapping._frameIdSymbol]=frameId;var project=script.isContentScript()?this._contentScriptsProject:this._regularProject;for(var sourceURL of sourceMap.sourceURLs()){var uiSourceCode=project.uiSourceCodeForURL(sourceURL);if(uiSourceCode){Bindings.NetworkProject.addFrameAttribution(uiSourceCode,frameId);continue;} -var contentProvider=sourceMap.sourceContentProvider(sourceURL,Common.resourceTypes.SourceMapScript);var mimeType=Common.ResourceType.mimeFromURL(sourceURL)||contentProvider.contentType().canonicalMimeType();var embeddedContent=sourceMap.embeddedContentByURL(sourceURL);var metadata=typeof embeddedContent==='string'?new Workspace.UISourceCodeMetadata(null,embeddedContent.length):null;uiSourceCode=project.createUISourceCode(sourceURL,contentProvider.contentType());uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol]=sourceMap;Bindings.NetworkProject.setInitialFrameAttribution(uiSourceCode,frameId);project.addUISourceCodeWithProvider(uiSourceCode,contentProvider,metadata,mimeType);} -this._debuggerWorkspaceBinding.updateLocations(script);} -static uiLineHasMapping(uiSourceCode,lineNumber){var sourceMap=uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol];if(!sourceMap) -return true;return!!sourceMap.sourceLineMapping(uiSourceCode.url(),lineNumber,0);} -dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);this._regularProject.dispose();this._contentScriptsProject.dispose();this._stubProject.dispose();}};Bindings.CompilerScriptMapping._frameIdSymbol=Symbol('Bindings.CompilerScriptMapping._frameIdSymbol');Bindings.CompilerScriptMapping._sourceMapSymbol=Symbol('Bindings.CompilerScriptMapping._sourceMapSymbol');;Bindings.ResourceScriptMapping=class{constructor(debuggerModel,workspace,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._workspace=workspace;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._boundUISourceCodes=new Set();this._uiSourceCodeToScriptFile=new Map();this._eventListeners=[debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._debuggerReset,this),debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource,this._parsedScriptSource,this),debuggerModel.addEventListener(SDK.DebuggerModel.Events.FailedToParseScriptSource,this._parsedScriptSource,this),workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._uiSourceCodeAdded,this),workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,this._uiSourceCodeRemoved,this)];} -rawLocationToUILocation(rawLocation){var debuggerModelLocation=(rawLocation);var script=debuggerModelLocation.script();if(!script) -return null;var uiSourceCode=this._workspaceUISourceCodeForScript(script);if(!uiSourceCode) -return null;var scriptFile=this.scriptFile(uiSourceCode);if(scriptFile&&((scriptFile.hasDivergedFromVM()&&!scriptFile.isMergingToVM())||scriptFile.isDivergingFromVM())) -return null;if(scriptFile&&!scriptFile._hasScripts([rawLocation.script()])) -return null;var lineNumber=debuggerModelLocation.lineNumber-(script.isInlineScriptWithSourceURL()?script.lineOffset:0);var columnNumber=debuggerModelLocation.columnNumber||0;if(script.isInlineScriptWithSourceURL()&&!lineNumber&&columnNumber) -columnNumber-=script.columnOffset;return uiSourceCode.uiLocation(lineNumber,columnNumber);} -uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){var scripts=this._scriptsForUISourceCode(uiSourceCode);if(!scripts.length) -return null;var script=scripts[scripts.length-1];if(script.isInlineScriptWithSourceURL()){return this._debuggerModel.createRawLocationByURL(script.sourceURL,lineNumber+script.lineOffset,lineNumber?columnNumber:columnNumber+script.columnOffset);} -return this._debuggerModel.createRawLocationByURL(script.sourceURL,lineNumber,columnNumber);} -_parsedScriptSource(event){var script=(event.data);if(script.isAnonymousScript()) -return;var uiSourceCode=this._workspaceUISourceCodeForScript(script);if(!uiSourceCode) -return;this._bindUISourceCodeToScripts(uiSourceCode,[script]);} -scriptFile(uiSourceCode){return this._uiSourceCodeToScriptFile.get(uiSourceCode)||null;} -_setScriptFile(uiSourceCode,scriptFile){if(scriptFile) -this._uiSourceCodeToScriptFile.set(uiSourceCode,scriptFile);else -this._uiSourceCodeToScriptFile.remove(uiSourceCode);} -_uiSourceCodeAdded(event){var uiSourceCode=(event.data);if(uiSourceCode.project().isServiceProject()) -return;var scripts=this._scriptsForUISourceCode(uiSourceCode);if(!scripts.length) -return;this._bindUISourceCodeToScripts(uiSourceCode,scripts);} -_uiSourceCodeRemoved(event){var uiSourceCode=(event.data);if(uiSourceCode.project().isServiceProject()||!this._boundUISourceCodes.has(uiSourceCode)) -return;this._unbindUISourceCode(uiSourceCode);} -_updateLocations(uiSourceCode){var scripts=this._scriptsForUISourceCode(uiSourceCode);if(!scripts.length) -return;for(var i=0;i<scripts.length;++i) -this._debuggerWorkspaceBinding.updateLocations(scripts[i]);} -_workspaceUISourceCodeForScript(script){if(script.isAnonymousScript()) -return null;return Bindings.NetworkProject.uiSourceCodeForScriptURL(this._workspace,script.sourceURL,script);} -_scriptsForUISourceCode(uiSourceCode){var target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);if(target!==this._debuggerModel.target()) -return[];return this._debuggerModel.scriptsForSourceURL(uiSourceCode.url());} -_bindUISourceCodeToScripts(uiSourceCode,scripts){console.assert(scripts.length);var boundScriptFile=this.scriptFile(uiSourceCode);if(boundScriptFile&&boundScriptFile._hasScripts(scripts)) -return;var scriptFile=new Bindings.ResourceScriptFile(this,uiSourceCode,scripts);this._setScriptFile(uiSourceCode,scriptFile);for(var i=0;i<scripts.length;++i) -this._debuggerWorkspaceBinding.updateLocations(scripts[i]);this._boundUISourceCodes.add(uiSourceCode);} -_unbindUISourceCode(uiSourceCode){var scriptFile=this.scriptFile(uiSourceCode);if(scriptFile){scriptFile.dispose();this._setScriptFile(uiSourceCode,null);} -this._boundUISourceCodes.delete(uiSourceCode);if(scriptFile._script) -this._debuggerWorkspaceBinding.updateLocations(scriptFile._script);} -_debuggerReset(){for(var uiSourceCode of this._boundUISourceCodes.valuesArray()) -this._unbindUISourceCode(uiSourceCode);this._boundUISourceCodes.clear();console.assert(!this._uiSourceCodeToScriptFile.size);} -dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);this._debuggerReset();}};Bindings.ResourceScriptFile=class extends Common.Object{constructor(resourceScriptMapping,uiSourceCode,scripts){super();console.assert(scripts.length);this._resourceScriptMapping=resourceScriptMapping;this._uiSourceCode=uiSourceCode;if(this._uiSourceCode.contentType().isScript()) -this._script=scripts[scripts.length-1];this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this);this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this);} -_hasScripts(scripts){return this._script&&this._script===scripts[0];} -_isDiverged(){if(this._uiSourceCode.isDirty()) -return true;if(!this._script) -return false;if(typeof this._scriptSource==='undefined') -return false;var workingCopy=this._uiSourceCode.workingCopy();if(!workingCopy) -return false;if(!workingCopy.startsWith(this._scriptSource.trimRight())) -return true;var suffix=this._uiSourceCode.workingCopy().substr(this._scriptSource.length);return!!suffix.length&&!suffix.match(SDK.Script.sourceURLRegex);} -_workingCopyChanged(event){this._update();} -_workingCopyCommitted(event){if(this._uiSourceCode.project().canSetFileContent()) -return;if(!this._script) -return;var debuggerModel=this._resourceScriptMapping._debuggerModel;var source=this._uiSourceCode.workingCopy();debuggerModel.setScriptSource(this._script.scriptId,source,scriptSourceWasSet.bind(this));function scriptSourceWasSet(error,exceptionDetails){if(!error&&!exceptionDetails) -this._scriptSource=source;this._update();if(!error&&!exceptionDetails) -return;if(!exceptionDetails){Common.console.addMessage(Common.UIString('LiveEdit failed: %s',error),Common.Console.MessageLevel.Warning);return;} -var messageText=Common.UIString('LiveEdit compile failed: %s',exceptionDetails.text);this._uiSourceCode.addLineMessage(Workspace.UISourceCode.Message.Level.Error,messageText,exceptionDetails.lineNumber,exceptionDetails.columnNumber);}} -_update(){if(this._isDiverged()&&!this._hasDivergedFromVM) -this._divergeFromVM();else if(!this._isDiverged()&&this._hasDivergedFromVM) -this._mergeToVM();} -_divergeFromVM(){this._isDivergingFromVM=true;this._resourceScriptMapping._updateLocations(this._uiSourceCode);delete this._isDivergingFromVM;this._hasDivergedFromVM=true;this.dispatchEventToListeners(Bindings.ResourceScriptFile.Events.DidDivergeFromVM,this._uiSourceCode);} -_mergeToVM(){delete this._hasDivergedFromVM;this._isMergingToVM=true;this._resourceScriptMapping._updateLocations(this._uiSourceCode);delete this._isMergingToVM;this.dispatchEventToListeners(Bindings.ResourceScriptFile.Events.DidMergeToVM,this._uiSourceCode);} -hasDivergedFromVM(){return this._hasDivergedFromVM;} -isDivergingFromVM(){return this._isDivergingFromVM;} -isMergingToVM(){return this._isMergingToVM;} -checkMapping(){if(!this._script||typeof this._scriptSource!=='undefined'){this._mappingCheckedForTest();return;} -this._script.requestContent().then(callback.bind(this));function callback(source){this._scriptSource=source;this._update();this._mappingCheckedForTest();}} -_mappingCheckedForTest(){} -dispose(){this._uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this);this._uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this);} -addSourceMapURL(sourceMapURL){if(!this._script) -return;this._script.debuggerModel.setSourceMapURL(this._script,sourceMapURL);} -hasSourceMapURL(){return this._script&&!!this._script.sourceMapURL;}};Bindings.ResourceScriptFile.Events={DidMergeToVM:Symbol('DidMergeToVM'),DidDivergeFromVM:Symbol('DidDivergeFromVM'),};;Bindings.SASSSourceMapping=class{constructor(target,sourceMapManager,workspace){this._sourceMapManager=sourceMapManager;this._project=new Bindings.ContentProviderBasedProject(workspace,'cssSourceMaps:'+target.id(),Workspace.projectTypes.Network,'',false);Bindings.NetworkProject.setTargetForProject(this._project,target);this._eventListeners=[this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapAttached,this._sourceMapAttached,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapDetached,this._sourceMapDetached,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapChanged,this._sourceMapChanged,this)];} -_sourceMapAttachedForTest(sourceMap){} -_sourceMapAttached(event){var header=(event.data.client);var sourceMap=(event.data.sourceMap);for(var sassURL of sourceMap.sourceURLs()){var uiSourceCode=this._project.uiSourceCodeForURL(sassURL);if(uiSourceCode){Bindings.NetworkProject.addFrameAttribution(uiSourceCode,header.frameId);continue;} -var contentProvider=sourceMap.sourceContentProvider(sassURL,Common.resourceTypes.SourceMapStyleSheet);var mimeType=Common.ResourceType.mimeFromURL(sassURL)||contentProvider.contentType().canonicalMimeType();var embeddedContent=sourceMap.embeddedContentByURL(sassURL);var metadata=typeof embeddedContent==='string'?new Workspace.UISourceCodeMetadata(null,embeddedContent.length):null;uiSourceCode=this._project.createUISourceCode(sassURL,contentProvider.contentType());Bindings.NetworkProject.setInitialFrameAttribution(uiSourceCode,header.frameId);uiSourceCode[Bindings.SASSSourceMapping._sourceMapSymbol]=sourceMap;this._project.addUISourceCodeWithProvider(uiSourceCode,contentProvider,metadata,mimeType);} -Bindings.cssWorkspaceBinding.updateLocations(header);this._sourceMapAttachedForTest(sourceMap);} -_sourceMapDetached(event){var header=(event.data.client);var sourceMap=(event.data.sourceMap);var headers=this._sourceMapManager.clientsForSourceMap(sourceMap);for(var sassURL of sourceMap.sourceURLs()){if(headers.length){var uiSourceCode=(this._project.uiSourceCodeForURL(sassURL));Bindings.NetworkProject.removeFrameAttribution(uiSourceCode,header.frameId);}else{this._project.removeFile(sassURL);}} -Bindings.cssWorkspaceBinding.updateLocations(header);} -_sourceMapChanged(event){var sourceMap=(event.data.sourceMap);var newSources=(event.data.newSources);var headers=this._sourceMapManager.clientsForSourceMap(sourceMap);for(var sourceURL of newSources.keys()){var uiSourceCode=this._project.uiSourceCodeForURL(sourceURL);if(!uiSourceCode){console.error('Failed to update source for '+sourceURL);continue;} -var sassText=(newSources.get(sourceURL));uiSourceCode.setWorkingCopy(sassText);} -for(var header of headers) -Bindings.cssWorkspaceBinding.updateLocations(header);} -rawLocationToUILocation(rawLocation){var header=rawLocation.header();if(!header) -return null;var sourceMap=this._sourceMapManager.sourceMapForClient(header);if(!sourceMap) -return null;var entry=sourceMap.findEntry(rawLocation.lineNumber,rawLocation.columnNumber);if(!entry||!entry.sourceURL) -return null;var uiSourceCode=this._project.uiSourceCodeForURL(entry.sourceURL);if(!uiSourceCode) -return null;return uiSourceCode.uiLocation(entry.sourceLineNumber||0,entry.sourceColumnNumber);} -uiLocationToRawLocations(uiLocation){var sourceMap=uiLocation.uiSourceCode[Bindings.SASSSourceMapping._sourceMapSymbol];if(!sourceMap) -return[];var entries=sourceMap.findReverseEntries(uiLocation.uiSourceCode.url(),uiLocation.lineNumber,uiLocation.columnNumber);var locations=[];for(var header of this._sourceMapManager.clientsForSourceMap(sourceMap)) -locations.pushAll(entries.map(entry=>new SDK.CSSLocation(header,entry.lineNumber,entry.columnNumber)));return locations;} -dispose(){this._project.dispose();Common.EventTarget.removeEventListeners(this._eventListeners);}};Bindings.SASSSourceMapping._sourceMapSymbol=Symbol('sourceMap');;Bindings.StylesSourceMapping=class{constructor(cssModel,workspace){this._cssModel=cssModel;var target=this._cssModel.target();this._project=new Bindings.ContentProviderBasedProject(workspace,'css:'+target.id(),Workspace.projectTypes.Network,'',false);Bindings.NetworkProject.setTargetForProject(this._project,target);this._styleFiles=new Map();this._eventListeners=[this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._styleSheetAdded,this),this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._styleSheetRemoved,this),this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._styleSheetChanged,this),];} -rawLocationToUILocation(rawLocation){var header=rawLocation.header();if(!header||!this._acceptsHeader(header)) -return null;var styleFile=this._styleFiles.get(header.resourceURL());if(!styleFile) -return null;var lineNumber=rawLocation.lineNumber;var columnNumber=rawLocation.columnNumber;if(header.isInline&&header.hasSourceURL){lineNumber-=header.lineNumberInSource(0);columnNumber-=header.columnNumberInSource(lineNumber,0);} -return styleFile._uiSourceCode.uiLocation(lineNumber,columnNumber);} -uiLocationToRawLocations(uiLocation){var styleFile=uiLocation.uiSourceCode[Bindings.StyleFile._symbol];if(!styleFile) -return[];var rawLocations=[];for(var header of styleFile._headers){var lineNumber=uiLocation.lineNumber;var columnNumber=uiLocation.columnNumber;if(header.isInline&&header.hasSourceURL){columnNumber=header.columnNumberInSource(lineNumber,columnNumber);lineNumber=header.lineNumberInSource(lineNumber);} -rawLocations.push(new SDK.CSSLocation(header,lineNumber,columnNumber));} -return rawLocations;} -_acceptsHeader(header){if(header.isInline&&!header.hasSourceURL&&header.origin!=='inspector') -return false;if(!header.resourceURL()) -return false;return true;} -_styleSheetAdded(event){var header=(event.data);if(!this._acceptsHeader(header)) -return;var url=header.resourceURL();var styleFile=this._styleFiles.get(url);if(!styleFile){styleFile=new Bindings.StyleFile(this._cssModel,this._project,header);this._styleFiles.set(url,styleFile);}else{styleFile.addHeader(header);}} -_styleSheetRemoved(event){var header=(event.data);if(!this._acceptsHeader(header)) -return;var url=header.resourceURL();var styleFile=this._styleFiles.get(url);if(styleFile._headers.size===1){styleFile.dispose();this._styleFiles.delete(url);}else{styleFile.removeHeader(header);}} -_styleSheetChanged(event){var header=this._cssModel.styleSheetHeaderForId(event.data.styleSheetId);if(!header||!this._acceptsHeader(header)) -return;var styleFile=this._styleFiles.get(header.resourceURL());styleFile._styleSheetChanged(header);} -dispose(){for(var styleFile of this._styleFiles.values()) -styleFile.dispose();this._styleFiles.clear();Common.EventTarget.removeEventListeners(this._eventListeners);this._project.removeProject();}};Bindings.StyleFile=class{constructor(cssModel,project,header){this._cssModel=cssModel;this._project=project;this._headers=new Set([header]);var target=cssModel.target();var url=header.resourceURL();var metadata=Bindings.metadataForURL(target,header.frameId,url);this._uiSourceCode=this._project.createUISourceCode(url,header.contentType());this._uiSourceCode[Bindings.StyleFile._symbol]=this;Bindings.NetworkProject.setInitialFrameAttribution(this._uiSourceCode,header.frameId);this._project.addUISourceCodeWithProvider(this._uiSourceCode,this,metadata,'text/css');this._eventListeners=[this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this),this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this)];this._throttler=new Common.Throttler(Bindings.StyleFile.updateTimeout);this._terminated=false;} -addHeader(header){this._headers.add(header);Bindings.NetworkProject.addFrameAttribution(this._uiSourceCode,header.frameId);} -removeHeader(header){this._headers.delete(header);Bindings.NetworkProject.removeFrameAttribution(this._uiSourceCode,header.frameId);} -_styleSheetChanged(header){console.assert(this._headers.has(header));if(this._isUpdatingHeaders||!this._headers.has(header)) -return;var mirrorContentBound=this._mirrorContent.bind(this,header,true);this._throttler.schedule(mirrorContentBound,false);} -_workingCopyCommitted(event){if(this._isAddingRevision) -return;var mirrorContentBound=this._mirrorContent.bind(this,this._uiSourceCode,true);this._throttler.schedule(mirrorContentBound,true);} -_workingCopyChanged(event){if(this._isAddingRevision) -return;var mirrorContentBound=this._mirrorContent.bind(this,this._uiSourceCode,false);this._throttler.schedule(mirrorContentBound,false);} -async _mirrorContent(fromProvider,majorChange){if(this._terminated){this._styleFileSyncedForTest();return;} -var newContent=null;if(fromProvider===this._uiSourceCode){newContent=this._uiSourceCode.workingCopy();}else{newContent=await fromProvider.requestContent();} -if(newContent===null||this._terminated){this._styleFileSyncedForTest();return;} -if(fromProvider!==this._uiSourceCode){this._isAddingRevision=true;this._uiSourceCode.addRevision(newContent);this._isAddingRevision=false;} -this._isUpdatingHeaders=true;var promises=[];for(var header of this._headers){if(header===fromProvider) -continue;promises.push(this._cssModel.setStyleSheetText(header.id,newContent,majorChange));} -await Promise.all(promises);this._isUpdatingHeaders=false;this._styleFileSyncedForTest();} -_styleFileSyncedForTest(){} -dispose(){if(this._terminated) -return;this._terminated=true;this._project.removeFile(this._uiSourceCode.url());Common.EventTarget.removeEventListeners(this._eventListeners);} -contentURL(){return this._headers.firstValue().originalContentProvider().contentURL();} -contentType(){return this._headers.firstValue().originalContentProvider().contentType();} -contentEncoded(){return this._headers.firstValue().originalContentProvider().contentEncoded();} -requestContent(){return this._headers.firstValue().originalContentProvider().requestContent();} -searchInContent(query,caseSensitive,isRegex){return this._headers.firstValue().originalContentProvider().searchInContent(query,caseSensitive,isRegex);}};Bindings.StyleFile._symbol=Symbol('Bindings.StyleFile._symbol');Bindings.StyleFile.updateTimeout=200;;Bindings.CSSWorkspaceBinding=class{constructor(targetManager,workspace){this._workspace=workspace;this._modelToInfo=new Map();this._sourceMappings=[];targetManager.observeModels(SDK.CSSModel,this);} -modelAdded(cssModel){this._modelToInfo.set(cssModel,new Bindings.CSSWorkspaceBinding.ModelInfo(cssModel,this._workspace));} -modelRemoved(cssModel){this._modelToInfo.get(cssModel)._dispose();this._modelToInfo.delete(cssModel);} -updateLocations(header){this._modelToInfo.get(header.cssModel())._updateLocations(header);} -createLiveLocation(rawLocation,updateDelegate,locationPool){return this._modelToInfo.get(rawLocation.cssModel())._createLiveLocation(rawLocation,updateDelegate,locationPool);} -propertyUILocation(cssProperty,forName){var style=cssProperty.ownerStyle;if(!style||style.type!==SDK.CSSStyleDeclaration.Type.Regular||!style.styleSheetId) -return null;var header=style.cssModel().styleSheetHeaderForId(style.styleSheetId);if(!header) -return null;var range=forName?cssProperty.nameRange():cssProperty.valueRange();if(!range) -return null;var lineNumber=range.startLine;var columnNumber=range.startColumn;var rawLocation=new SDK.CSSLocation(header,header.lineNumberInSource(lineNumber),header.columnNumberInSource(lineNumber,columnNumber));return this.rawLocationToUILocation(rawLocation);} -rawLocationToUILocation(rawLocation){for(var i=this._sourceMappings.length-1;i>=0;--i){var uiLocation=this._sourceMappings[i].rawLocationToUILocation(rawLocation);if(uiLocation) -return uiLocation;} -return this._modelToInfo.get(rawLocation.cssModel())._rawLocationToUILocation(rawLocation);} -uiLocationToRawLocations(uiLocation){for(var i=this._sourceMappings.length-1;i>=0;--i){var rawLocations=this._sourceMappings[i].uiLocationToRawLocations(uiLocation);if(rawLocations.length) -return rawLocations;} -var rawLocations=[];for(var modelInfo of this._modelToInfo.values()) -rawLocations.pushAll(modelInfo._uiLocationToRawLocations(uiLocation));return rawLocations;} -addSourceMapping(sourceMapping){this._sourceMappings.push(sourceMapping);}};Bindings.CSSWorkspaceBinding.SourceMapping=function(){};Bindings.CSSWorkspaceBinding.SourceMapping.prototype={rawLocationToUILocation(rawLocation){},uiLocationToRawLocations(uiLocation){},};Bindings.CSSWorkspaceBinding.ModelInfo=class{constructor(cssModel,workspace){this._eventListeners=[cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._styleSheetAdded,this),cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._styleSheetRemoved,this)];this._stylesSourceMapping=new Bindings.StylesSourceMapping(cssModel,workspace);var sourceMapManager=cssModel.sourceMapManager();this._sassSourceMapping=new Bindings.SASSSourceMapping(cssModel.target(),sourceMapManager,workspace);this._locations=new Multimap();this._unboundLocations=new Multimap();} -_createLiveLocation(rawLocation,updateDelegate,locationPool){var location=new Bindings.CSSWorkspaceBinding.LiveLocation(rawLocation,this,updateDelegate,locationPool);var header=rawLocation.header();if(header){location._header=header;this._locations.set(header,location);location.update();}else{this._unboundLocations.set(rawLocation.url,location);} -return location;} -_disposeLocation(location){if(location._header) -this._locations.delete(location._header,location);else -this._unboundLocations.delete(location._url,location);} -_updateLocations(header){for(var location of this._locations.get(header)) -location.update();} -_styleSheetAdded(event){var header=(event.data);if(!header.sourceURL) -return;for(var location of this._unboundLocations.get(header.sourceURL)){location._header=header;this._locations.set(header,location);location.update();} -this._unboundLocations.deleteAll(header.sourceURL);} -_styleSheetRemoved(event){var header=(event.data);for(var location of this._locations.get(header)){location._header=null;this._unboundLocations.set(location._url,location);location.update();} -this._locations.deleteAll(header);} -_rawLocationToUILocation(rawLocation){var uiLocation=null;uiLocation=uiLocation||this._sassSourceMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||this._stylesSourceMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||Bindings.resourceMapping.cssLocationToUILocation(rawLocation);return uiLocation;} -_uiLocationToRawLocations(uiLocation){var rawLocations=this._sassSourceMapping.uiLocationToRawLocations(uiLocation);if(rawLocations.length) -return rawLocations;return this._stylesSourceMapping.uiLocationToRawLocations(uiLocation);} -_dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);this._stylesSourceMapping.dispose();this._sassSourceMapping.dispose();}};Bindings.CSSWorkspaceBinding.LiveLocation=class extends Bindings.LiveLocationWithPool{constructor(rawLocation,info,updateDelegate,locationPool){super(updateDelegate,locationPool);this._url=rawLocation.url;this._lineNumber=rawLocation.lineNumber;this._columnNumber=rawLocation.columnNumber;this._info=info;this._header=null;} -uiLocation(){if(!this._header) -return null;var rawLocation=new SDK.CSSLocation(this._header,this._lineNumber,this._columnNumber);return Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation);} -dispose(){super.dispose();this._info._disposeLocation(this);} -isBlackboxed(){return false;}};Bindings.cssWorkspaceBinding;;Bindings.DebuggerWorkspaceBinding=class{constructor(targetManager,workspace){this._workspace=workspace;this._sourceMappings=[];this._debuggerModelToData=new Map();targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.GlobalObjectCleared,this._globalObjectCleared,this);targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerResumed,this._debuggerResumed,this);targetManager.observeModels(SDK.DebuggerModel,this);} -addSourceMapping(sourceMapping){this._sourceMappings.push(sourceMapping);} -modelAdded(debuggerModel){this._debuggerModelToData.set(debuggerModel,new Bindings.DebuggerWorkspaceBinding.ModelData(debuggerModel,this));} -modelRemoved(debuggerModel){var modelData=this._debuggerModelToData.get(debuggerModel);modelData._dispose();this._debuggerModelToData.remove(debuggerModel);} -updateLocations(script){var modelData=this._debuggerModelToData.get(script.debuggerModel);if(modelData) -modelData._updateLocations(script);} -createLiveLocation(rawLocation,updateDelegate,locationPool){var modelData=this._debuggerModelToData.get(rawLocation.script().debuggerModel);return modelData._createLiveLocation(rawLocation,updateDelegate,locationPool);} -createStackTraceTopFrameLiveLocation(rawLocations,updateDelegate,locationPool){console.assert(rawLocations.length);var location=new Bindings.DebuggerWorkspaceBinding.StackTraceTopFrameLocation(rawLocations,this,updateDelegate,locationPool);location.update();return location;} -createCallFrameLiveLocation(location,updateDelegate,locationPool){var script=location.script();if(!script) -return null;var debuggerModel=location.debuggerModel;var liveLocation=this.createLiveLocation(location,updateDelegate,locationPool);this._registerCallFrameLiveLocation(debuggerModel,liveLocation);return liveLocation;} -rawLocationToUILocation(rawLocation){for(var i=0;i<this._sourceMappings.length;++i){var uiLocation=this._sourceMappings[i].rawLocationToUILocation(rawLocation);if(uiLocation) -return uiLocation;} -var modelData=this._debuggerModelToData.get(rawLocation.debuggerModel);return modelData._rawLocationToUILocation(rawLocation);} -uiSourceCodeForSourceMapSourceURL(debuggerModel,url,isContentScript){var modelData=this._debuggerModelToData.get(debuggerModel);if(!modelData) -return null;return modelData._compilerMapping.uiSourceCodeForURL(url,isContentScript);} -uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){for(var i=0;i<this._sourceMappings.length;++i){var rawLocation=this._sourceMappings[i].uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);if(rawLocation) -return rawLocation;} -for(var modelData of this._debuggerModelToData.values()){var rawLocation=modelData._uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);if(rawLocation) -return rawLocation;} -return null;} -normalizeUILocation(uiLocation){var rawLocation=this.uiLocationToRawLocation(uiLocation.uiSourceCode,uiLocation.lineNumber,uiLocation.columnNumber);if(rawLocation) -return this.rawLocationToUILocation(rawLocation)||uiLocation;return uiLocation;} -scriptFile(uiSourceCode,debuggerModel){var modelData=this._debuggerModelToData.get(debuggerModel);return modelData?modelData._resourceMapping.scriptFile(uiSourceCode):null;} -sourceMapForScript(script){var modelData=this._debuggerModelToData.get(script.debuggerModel);if(!modelData) -return null;return modelData._compilerMapping.sourceMapForScript(script);} -maybeLoadSourceMap(script){var modelData=this._debuggerModelToData.get(script.debuggerModel);if(!modelData) -return;modelData._compilerMapping.maybeLoadSourceMap(script);} -_globalObjectCleared(event){var debuggerModel=(event.data);this._reset(debuggerModel);} -_reset(debuggerModel){var modelData=this._debuggerModelToData.get(debuggerModel);modelData.callFrameLocations.valuesArray().forEach(location=>this._removeLiveLocation(location));modelData.callFrameLocations.clear();} -_registerCallFrameLiveLocation(debuggerModel,location){var locations=this._debuggerModelToData.get(debuggerModel).callFrameLocations;locations.add(location);} -_removeLiveLocation(location){var modelData=this._debuggerModelToData.get(location._script.debuggerModel);if(modelData) -modelData._disposeLocation(location);} -_debuggerResumed(event){var debuggerModel=(event.data);this._reset(debuggerModel);}};Bindings.DebuggerWorkspaceBinding.ModelData=class{constructor(debuggerModel,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this.callFrameLocations=new Set();var workspace=debuggerWorkspaceBinding._workspace;this._defaultMapping=new Bindings.DefaultScriptMapping(debuggerModel,workspace,debuggerWorkspaceBinding);this._resourceMapping=new Bindings.ResourceScriptMapping(debuggerModel,workspace,debuggerWorkspaceBinding);this._compilerMapping=new Bindings.CompilerScriptMapping(debuggerModel,workspace,debuggerWorkspaceBinding);this._locations=new Multimap();debuggerModel.setBeforePausedCallback(this._beforePaused.bind(this));} -_createLiveLocation(rawLocation,updateDelegate,locationPool){var script=(rawLocation.script());console.assert(script);var location=new Bindings.DebuggerWorkspaceBinding.Location(script,rawLocation,this._debuggerWorkspaceBinding,updateDelegate,locationPool);this._locations.set(script,location);location.update();return location;} -_disposeLocation(location){this._locations.delete(location._script,location);} -_updateLocations(script){for(var location of this._locations.get(script)) -location.update();} -_rawLocationToUILocation(rawLocation){var uiLocation=null;uiLocation=uiLocation||this._compilerMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||this._resourceMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||Bindings.resourceMapping.jsLocationToUILocation(rawLocation);uiLocation=uiLocation||this._defaultMapping.rawLocationToUILocation(rawLocation);return(uiLocation);} -_uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){var rawLocation=null;rawLocation=rawLocation||this._compilerMapping.uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);rawLocation=rawLocation||this._resourceMapping.uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);rawLocation=rawLocation||Bindings.resourceMapping.uiLocationToJSLocation(uiSourceCode,lineNumber,columnNumber);rawLocation=rawLocation||this._defaultMapping.uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);return rawLocation;} -_beforePaused(debuggerPausedDetails){return!!this._compilerMapping.mapsToSourceCode(debuggerPausedDetails.callFrames[0].location());} -_dispose(){this._debuggerModel.setBeforePausedCallback(null);this._compilerMapping.dispose();this._resourceMapping.dispose();this._defaultMapping.dispose();}};Bindings.DebuggerWorkspaceBinding.Location=class extends Bindings.LiveLocationWithPool{constructor(script,rawLocation,binding,updateDelegate,locationPool){super(updateDelegate,locationPool);this._script=script;this._rawLocation=rawLocation;this._binding=binding;} -uiLocation(){var debuggerModelLocation=this._rawLocation;return this._binding.rawLocationToUILocation(debuggerModelLocation);} -dispose(){super.dispose();this._binding._removeLiveLocation(this);} -isBlackboxed(){return Bindings.blackboxManager.isBlackboxedRawLocation(this._rawLocation);}};Bindings.DebuggerWorkspaceBinding.StackTraceTopFrameLocation=class extends Bindings.LiveLocationWithPool{constructor(rawLocations,binding,updateDelegate,locationPool){super(updateDelegate,locationPool);this._updateScheduled=true;this._current=null;this._locations=rawLocations.map(location=>binding.createLiveLocation(location,this._scheduleUpdate.bind(this),locationPool));this._updateLocation();} -uiLocation(){return this._current.uiLocation();} -isBlackboxed(){return this._current.isBlackboxed();} -dispose(){super.dispose();for(var location of this._locations) -location.dispose();this._locations=null;this._current=null;} -_scheduleUpdate(){if(this._updateScheduled) -return;this._updateScheduled=true;setImmediate(this._updateLocation.bind(this));} -_updateLocation(){this._updateScheduled=false;if(!this._locations) -return;this._current=this._locations.find(location=>!location.isBlackboxed())||this._locations[0];this.update();}};Bindings.DebuggerSourceMapping=function(){};Bindings.DebuggerSourceMapping.prototype={rawLocationToUILocation(rawLocation){},uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){},};Bindings.debuggerWorkspaceBinding;;Bindings.BreakpointManager=class extends Common.Object{constructor(breakpointsSetting,workspace,targetManager,debuggerWorkspaceBinding){super();this._storage=new Bindings.BreakpointManager.Storage(this,breakpointsSetting);this._workspace=workspace;this._targetManager=targetManager;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._breakpointsActive=true;this._breakpointsForUISourceCode=new Map();this._breakpointsForPrimaryUISourceCode=new Map();this._provisionalBreakpoints=new Multimap();this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,this._projectRemoved,this);this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._uiSourceCodeAdded,this);this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,this._uiSourceCodeRemoved,this);targetManager.observeModels(SDK.DebuggerModel,this);} -static _breakpointStorageId(url,lineNumber,columnNumber){if(!url) -return'';return url+':'+lineNumber+':'+columnNumber;} -modelAdded(debuggerModel){if(!this._breakpointsActive) -debuggerModel.setBreakpointsActive(this._breakpointsActive);} -modelRemoved(debuggerModel){} -_provisionalBreakpointsForURL(url){var result=new Map();var breakpoints=this._provisionalBreakpoints.get(url).valuesArray();for(var i=0;i<breakpoints.length;++i) -result.set(breakpoints[i]._breakpointStorageId(),breakpoints[i]);return result;} -copyBreakpoints(fromURL,toSourceCode){var breakpointItems=this._storage.breakpointItems(fromURL);for(var item of breakpointItems) -this.setBreakpoint(toSourceCode,item.lineNumber,item.columnNumber,item.condition,item.enabled);if(fromURL===toSourceCode.url()){var provisionalBreakpoints=this._provisionalBreakpointsForURL(fromURL);for(var breakpoint of provisionalBreakpoints.values()) -breakpoint.remove();}} -removeProvisionalBreakpointsForTest(){var breakpoints=this._provisionalBreakpoints.valuesArray();for(var i=0;i<breakpoints.length;++i) -breakpoints[i].remove();this._provisionalBreakpoints.clear();} -_restoreBreakpoints(uiSourceCode){var url=uiSourceCode.url();if(!url) -return;this._storage.mute();var breakpointItems=this._storage.breakpointItems(url);var provisionalBreakpoints=this._provisionalBreakpointsForURL(url);for(var i=0;i<breakpointItems.length;++i){var breakpointItem=breakpointItems[i];var itemStorageId=Bindings.BreakpointManager._breakpointStorageId(breakpointItem.url,breakpointItem.lineNumber,breakpointItem.columnNumber);var provisionalBreakpoint=provisionalBreakpoints.get(itemStorageId);if(provisionalBreakpoint){if(!this._breakpointsForPrimaryUISourceCode.get(uiSourceCode)) -this._breakpointsForPrimaryUISourceCode.set(uiSourceCode,[]);this._breakpointsForPrimaryUISourceCode.get(uiSourceCode).push(provisionalBreakpoint);provisionalBreakpoint._updateBreakpoint();}else{this._innerSetBreakpoint(uiSourceCode,breakpointItem.lineNumber,breakpointItem.columnNumber,breakpointItem.condition,breakpointItem.enabled);}} -this._provisionalBreakpoints.deleteAll(url);this._storage.unmute();} -_uiSourceCodeAdded(event){var uiSourceCode=(event.data);this._restoreBreakpoints(uiSourceCode);} -_uiSourceCodeRemoved(event){var uiSourceCode=(event.data);this._removeUISourceCode(uiSourceCode);} -_removeUISourceCode(uiSourceCode){var breakpoints=this._breakpointsForPrimaryUISourceCode.get(uiSourceCode)||[];for(var i=0;i<breakpoints.length;++i){breakpoints[i]._resetLocations();if(breakpoints[i].enabled()) -this._provisionalBreakpoints.set(uiSourceCode.url(),breakpoints[i]);} -this._breakpointsForPrimaryUISourceCode.remove(uiSourceCode);} -setBreakpoint(uiSourceCode,lineNumber,columnNumber,condition,enabled){var uiLocation=new Workspace.UILocation(uiSourceCode,lineNumber,columnNumber);var normalizedLocation=this._debuggerWorkspaceBinding.normalizeUILocation(uiLocation);if(normalizedLocation.id()!==uiLocation.id()){Common.Revealer.reveal(normalizedLocation);uiLocation=normalizedLocation;} -this.setBreakpointsActive(true);return this._innerSetBreakpoint(uiLocation.uiSourceCode,uiLocation.lineNumber,uiLocation.columnNumber,condition,enabled);} -_innerSetBreakpoint(uiSourceCode,lineNumber,columnNumber,condition,enabled){var breakpoint=this.findBreakpoint(uiSourceCode,lineNumber,columnNumber);if(breakpoint){breakpoint._updateState(condition,enabled);return breakpoint;} -var projectId=uiSourceCode.project().id();breakpoint=new Bindings.BreakpointManager.Breakpoint(this,projectId,uiSourceCode.url(),lineNumber,columnNumber,condition,enabled);if(!this._breakpointsForPrimaryUISourceCode.get(uiSourceCode)) -this._breakpointsForPrimaryUISourceCode.set(uiSourceCode,[]);this._breakpointsForPrimaryUISourceCode.get(uiSourceCode).push(breakpoint);return breakpoint;} -findBreakpoints(uiSourceCode,lineNumber){var breakpoints=this._breakpointsForUISourceCode.get(uiSourceCode);var lineBreakpoints=breakpoints?breakpoints.get(lineNumber):null;return lineBreakpoints?lineBreakpoints.valuesArray()[0]:[];} -findBreakpoint(uiSourceCode,lineNumber,columnNumber){var breakpoints=this._breakpointsForUISourceCode.get(uiSourceCode);var lineBreakpoints=breakpoints?breakpoints.get(lineNumber):null;var columnBreakpoints=lineBreakpoints?lineBreakpoints.get(columnNumber):null;return columnBreakpoints?columnBreakpoints[0]:null;} -possibleBreakpoints(uiSourceCode,textRange){var startLocation=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(uiSourceCode,textRange.startLine,textRange.startColumn);var endLocation=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(uiSourceCode,textRange.endLine,textRange.endColumn);if(!startLocation||!endLocation||startLocation.debuggerModel!==endLocation.debuggerModel) -return Promise.resolve([]);return startLocation.debuggerModel.getPossibleBreakpoints(startLocation,endLocation,false).then(toUILocations.bind(this));function toUILocations(locations){var sortedLocations=locations.map(location=>this._debuggerWorkspaceBinding.rawLocationToUILocation(location));sortedLocations=sortedLocations.filter(location=>location&&location.uiSourceCode===uiSourceCode);sortedLocations.sort(Workspace.UILocation.comparator);if(!sortedLocations.length) -return[];var result=[sortedLocations[0]];var lastLocation=sortedLocations[0];for(var i=1;i<sortedLocations.length;++i){if(sortedLocations[i].id()===lastLocation.id()) -continue;result.push(sortedLocations[i]);lastLocation=sortedLocations[i];} -return result;}} -breakpointsForUISourceCode(uiSourceCode){var result=[];var uiSourceCodeBreakpoints=this._breakpointsForUISourceCode.get(uiSourceCode);var breakpoints=uiSourceCodeBreakpoints?uiSourceCodeBreakpoints.valuesArray():[];for(var i=0;i<breakpoints.length;++i){var lineBreakpoints=breakpoints[i];var columnBreakpointArrays=lineBreakpoints?lineBreakpoints.valuesArray():[];result=result.concat.apply(result,columnBreakpointArrays);} -return result;} -_allBreakpoints(){var result=[];var uiSourceCodes=this._breakpointsForUISourceCode.keysArray();for(var i=0;i<uiSourceCodes.length;++i) -result=result.concat(this.breakpointsForUISourceCode(uiSourceCodes[i]));return result;} -breakpointLocationsForUISourceCode(uiSourceCode){var uiSourceCodeBreakpoints=this._breakpointsForUISourceCode.get(uiSourceCode);var lineNumbers=uiSourceCodeBreakpoints?uiSourceCodeBreakpoints.keysArray():[];var result=[];for(var i=0;i<lineNumbers.length;++i){var lineBreakpoints=uiSourceCodeBreakpoints.get(lineNumbers[i]);var columnNumbers=lineBreakpoints.keysArray();for(var j=0;j<columnNumbers.length;++j){var columnBreakpoints=lineBreakpoints.get(columnNumbers[j]);var lineNumber=parseInt(lineNumbers[i],10);var columnNumber=parseInt(columnNumbers[j],10);for(var k=0;k<columnBreakpoints.length;++k){var breakpoint=columnBreakpoints[k];var uiLocation=uiSourceCode.uiLocation(lineNumber,columnNumber);result.push({breakpoint:breakpoint,uiLocation:uiLocation});}}} -return result;} -allBreakpointLocations(){var result=[];var uiSourceCodes=this._breakpointsForUISourceCode.keysArray();for(var i=0;i<uiSourceCodes.length;++i) -result=result.concat(this.breakpointLocationsForUISourceCode(uiSourceCodes[i]));return result;} -toggleAllBreakpoints(toggleState){var breakpoints=this._allBreakpoints();for(var i=0;i<breakpoints.length;++i) -breakpoints[i].setEnabled(toggleState);} -removeAllBreakpoints(){var breakpoints=this._allBreakpoints();for(var i=0;i<breakpoints.length;++i) -breakpoints[i].remove();} -removeOtherBreakpoints(selectedBreakpoints){var allBreakpoints=this._allBreakpoints();allBreakpoints.forEach(breakpoint=>{if(!selectedBreakpoints.has(breakpoint)) -breakpoint.remove();});} -_projectRemoved(event){var project=(event.data);var uiSourceCodes=project.uiSourceCodes();for(var i=0;i<uiSourceCodes.length;++i) -this._removeUISourceCode(uiSourceCodes[i]);} -_removeBreakpoint(breakpoint,removeFromStorage){var uiSourceCode=breakpoint.uiSourceCode();var breakpoints=uiSourceCode?this._breakpointsForPrimaryUISourceCode.get(uiSourceCode)||[]:[];breakpoints.remove(breakpoint);if(removeFromStorage) -this._storage._removeBreakpoint(breakpoint);this._provisionalBreakpoints.delete(breakpoint._url,breakpoint);} -_uiLocationAdded(breakpoint,uiLocation){var breakpoints=this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode);if(!breakpoints){breakpoints=new Map();this._breakpointsForUISourceCode.set(uiLocation.uiSourceCode,breakpoints);} -var lineBreakpoints=breakpoints.get(uiLocation.lineNumber);if(!lineBreakpoints){lineBreakpoints=new Map();breakpoints.set(uiLocation.lineNumber,lineBreakpoints);} -var columnBreakpoints=lineBreakpoints.get(uiLocation.columnNumber);if(!columnBreakpoints){columnBreakpoints=[];lineBreakpoints.set(uiLocation.columnNumber,columnBreakpoints);} -columnBreakpoints.push(breakpoint);this.dispatchEventToListeners(Bindings.BreakpointManager.Events.BreakpointAdded,{breakpoint:breakpoint,uiLocation:uiLocation});} -_uiLocationRemoved(breakpoint,uiLocation){var breakpoints=this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode);if(!breakpoints) -return;var lineBreakpoints=breakpoints.get(uiLocation.lineNumber);if(!lineBreakpoints) -return;var columnBreakpoints=lineBreakpoints.get(uiLocation.columnNumber);if(!columnBreakpoints) -return;columnBreakpoints.remove(breakpoint);if(!columnBreakpoints.length) -lineBreakpoints.remove(uiLocation.columnNumber);if(!lineBreakpoints.size) -breakpoints.remove(uiLocation.lineNumber);if(!breakpoints.size) -this._breakpointsForUISourceCode.remove(uiLocation.uiSourceCode);this.dispatchEventToListeners(Bindings.BreakpointManager.Events.BreakpointRemoved,{breakpoint:breakpoint,uiLocation:uiLocation});} -setBreakpointsActive(active){if(this._breakpointsActive===active) -return;this._breakpointsActive=active;var debuggerModels=SDK.targetManager.models(SDK.DebuggerModel);for(var i=0;i<debuggerModels.length;++i) -debuggerModels[i].setBreakpointsActive(active);this.dispatchEventToListeners(Bindings.BreakpointManager.Events.BreakpointsActiveStateChanged,active);} -breakpointsActive(){return this._breakpointsActive;}};Bindings.BreakpointManager.Events={BreakpointAdded:Symbol('breakpoint-added'),BreakpointRemoved:Symbol('breakpoint-removed'),BreakpointsActiveStateChanged:Symbol('BreakpointsActiveStateChanged')};Bindings.BreakpointManager.Breakpoint=class{constructor(breakpointManager,projectId,url,lineNumber,columnNumber,condition,enabled){this._breakpointManager=breakpointManager;this._projectId=projectId;this._url=url;this._lineNumber=lineNumber;this._columnNumber=columnNumber;this._numberOfDebuggerLocationForUILocation=new Map();this._condition;this._enabled;this._isRemoved;this._fakePrimaryLocation;this._currentState=null;this._modelBreakpoints=new Map();this._updateState(condition,enabled);this._breakpointManager._targetManager.observeModels(SDK.DebuggerModel,this);} -modelAdded(debuggerModel){var debuggerWorkspaceBinding=this._breakpointManager._debuggerWorkspaceBinding;this._modelBreakpoints.set(debuggerModel,new Bindings.BreakpointManager.ModelBreakpoint(debuggerModel,this,debuggerWorkspaceBinding));} -modelRemoved(debuggerModel){var modelBreakpoint=this._modelBreakpoints.remove(debuggerModel);modelBreakpoint._cleanUpAfterDebuggerIsGone();modelBreakpoint._removeEventListeners();} -projectId(){return this._projectId;} -url(){return this._url;} -lineNumber(){return this._lineNumber;} -columnNumber(){return this._columnNumber;} -uiSourceCode(){return this._breakpointManager._workspace.uiSourceCode(this._projectId,this._url);} -_replaceUILocation(oldUILocation,newUILocation){if(this._isRemoved) -return;this._removeUILocation(oldUILocation,true);this._removeFakeBreakpointAtPrimaryLocation();var current=(this._numberOfDebuggerLocationForUILocation.get(newUILocation.id())||0)+1;this._numberOfDebuggerLocationForUILocation.set(newUILocation.id(),current);if(current===1) -this._breakpointManager._uiLocationAdded(this,newUILocation);} -_removeUILocation(uiLocation,muteCreationFakeBreakpoint){if(!uiLocation||!this._numberOfDebuggerLocationForUILocation.has(uiLocation.id())) -return;var current=(this._numberOfDebuggerLocationForUILocation.get(uiLocation.id())||0)-1;this._numberOfDebuggerLocationForUILocation.set(uiLocation.id(),current);if(current!==0) -return;this._numberOfDebuggerLocationForUILocation.delete(uiLocation.id());this._breakpointManager._uiLocationRemoved(this,uiLocation);if(!muteCreationFakeBreakpoint) -this._fakeBreakpointAtPrimaryLocation();} -enabled(){return this._enabled;} -setEnabled(enabled){this._updateState(this._condition,enabled);} -condition(){return this._condition;} -setCondition(condition){this._updateState(condition,this._enabled);} -_updateState(condition,enabled){if(this._enabled===enabled&&this._condition===condition) -return;this._enabled=enabled;this._condition=condition;this._breakpointManager._storage._updateBreakpoint(this);this._updateBreakpoint();} -_updateBreakpoint(){this._removeFakeBreakpointAtPrimaryLocation();this._fakeBreakpointAtPrimaryLocation();var modelBreakpoints=this._modelBreakpoints.valuesArray();for(var i=0;i<modelBreakpoints.length;++i) -modelBreakpoints[i]._scheduleUpdateInDebugger();} -remove(keepInStorage){this._isRemoved=true;var removeFromStorage=!keepInStorage;this._removeFakeBreakpointAtPrimaryLocation();var modelBreakpoints=this._modelBreakpoints.valuesArray();for(var i=0;i<modelBreakpoints.length;++i){modelBreakpoints[i]._scheduleUpdateInDebugger();modelBreakpoints[i]._removeEventListeners();} -this._breakpointManager._removeBreakpoint(this,removeFromStorage);this._breakpointManager._targetManager.unobserveModels(SDK.DebuggerModel,this);} -_updateInDebuggerForModel(debuggerModel){this._modelBreakpoints.get(debuggerModel)._scheduleUpdateInDebugger();} -_breakpointStorageId(){return Bindings.BreakpointManager._breakpointStorageId(this._url,this._lineNumber,this._columnNumber);} -_fakeBreakpointAtPrimaryLocation(){if(this._isRemoved||this._numberOfDebuggerLocationForUILocation.size||this._fakePrimaryLocation) -return;var uiSourceCode=this._breakpointManager._workspace.uiSourceCode(this._projectId,this._url);if(!uiSourceCode) -return;this._fakePrimaryLocation=uiSourceCode.uiLocation(this._lineNumber,this._columnNumber);if(this._fakePrimaryLocation) -this._breakpointManager._uiLocationAdded(this,this._fakePrimaryLocation);} -_removeFakeBreakpointAtPrimaryLocation(){if(this._fakePrimaryLocation){this._breakpointManager._uiLocationRemoved(this,this._fakePrimaryLocation);delete this._fakePrimaryLocation;}} -_resetLocations(){this._removeFakeBreakpointAtPrimaryLocation();var modelBreakpoints=this._modelBreakpoints.valuesArray();for(var i=0;i<modelBreakpoints.length;++i) -modelBreakpoints[i]._resetLocations();}};Bindings.BreakpointManager.ModelBreakpoint=class{constructor(debuggerModel,breakpoint,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._breakpoint=breakpoint;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._liveLocations=new Bindings.LiveLocationPool();this._uiLocations=new Map();this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerWasDisabled,this._cleanUpAfterDebuggerIsGone,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerWasEnabled,this._scheduleUpdateInDebugger,this);this._hasPendingUpdate=false;this._isUpdating=false;this._cancelCallback=false;this._currentState=null;if(this._debuggerModel.debuggerEnabled()) -this._scheduleUpdateInDebugger();} -_resetLocations(){for(var uiLocation of this._uiLocations.values()) -this._breakpoint._removeUILocation(uiLocation);this._uiLocations.clear();this._liveLocations.disposeAll();} -_scheduleUpdateInDebugger(){if(this._isUpdating){this._hasPendingUpdate=true;return;} -this._isUpdating=true;this._updateInDebugger(this._didUpdateInDebugger.bind(this));} -_didUpdateInDebugger(){this._isUpdating=false;if(this._hasPendingUpdate){this._hasPendingUpdate=false;this._scheduleUpdateInDebugger();}} -_scriptDiverged(){var uiSourceCode=this._breakpoint.uiSourceCode();if(!uiSourceCode) -return false;var scriptFile=this._debuggerWorkspaceBinding.scriptFile(uiSourceCode,this._debuggerModel);return!!scriptFile&&scriptFile.hasDivergedFromVM();} -async _updateInDebugger(callback){if(this._debuggerModel.target().isDisposed()){this._cleanUpAfterDebuggerIsGone();callback();return;} -var uiSourceCode=this._breakpoint.uiSourceCode();var lineNumber=this._breakpoint._lineNumber;var columnNumber=this._breakpoint._columnNumber;var condition=this._breakpoint.condition();var debuggerLocation=uiSourceCode&&Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);if(debuggerLocation&&debuggerLocation.debuggerModel!==this._debuggerModel) -debuggerLocation=null;var newState;if(this._breakpoint._isRemoved||!this._breakpoint.enabled()||this._scriptDiverged()){newState=null;}else if(debuggerLocation){var script=debuggerLocation.script();if(script.sourceURL){newState=new Bindings.BreakpointManager.Breakpoint.State(script.sourceURL,null,null,debuggerLocation.lineNumber,debuggerLocation.columnNumber,condition);}else{newState=new Bindings.BreakpointManager.Breakpoint.State(null,script.scriptId,script.hash,debuggerLocation.lineNumber,debuggerLocation.columnNumber,condition);}}else if(this._breakpoint._currentState&&this._breakpoint._currentState.url){var position=this._breakpoint._currentState;newState=new Bindings.BreakpointManager.Breakpoint.State(position.url,null,null,position.lineNumber,position.columnNumber,condition);}else if(uiSourceCode){newState=new Bindings.BreakpointManager.Breakpoint.State(uiSourceCode.url(),null,null,lineNumber,columnNumber,condition);} -if(this._debuggerId&&Bindings.BreakpointManager.Breakpoint.State.equals(newState,this._currentState)){callback();return;} -this._breakpoint._currentState=newState;if(this._debuggerId){this._resetLocations();this._debuggerModel.removeBreakpoint(this._debuggerId).then(this._didRemoveFromDebugger.bind(this,callback));this._scheduleUpdateInDebugger();this._currentState=null;return;} -if(!newState){callback();return;} -var result;this._currentState=newState;if(newState.url){result=await this._debuggerModel.setBreakpointByURL(newState.url,newState.lineNumber,newState.columnNumber,newState.condition);}else if(newState.scriptId&&newState.scriptHash){result=await this._debuggerModel.setBreakpointInAnonymousScript(newState.scriptId,newState.scriptHash,newState.lineNumber,newState.columnNumber,newState.condition);} -if(result&&result.breakpointId) -this._didSetBreakpointInDebugger(callback,result.breakpointId,result.locations);else -this._didSetBreakpointInDebugger(callback,null,[]);} -_didSetBreakpointInDebugger(callback,breakpointId,locations){if(this._cancelCallback){this._cancelCallback=false;callback();return;} -if(!breakpointId){this._breakpoint.remove(true);callback();return;} -this._debuggerId=breakpointId;this._debuggerModel.addBreakpointListener(this._debuggerId,this._breakpointResolved,this);for(var i=0;i<locations.length;++i){if(!this._addResolvedLocation(locations[i])) -break;} -callback();} -_didRemoveFromDebugger(callback){if(this._cancelCallback){this._cancelCallback=false;callback();return;} -this._resetLocations();this._debuggerModel.removeBreakpointListener(this._debuggerId,this._breakpointResolved,this);delete this._debuggerId;callback();} -_breakpointResolved(event){this._addResolvedLocation((event.data));} -_locationUpdated(location,liveLocation){var uiLocation=liveLocation.uiLocation();if(!uiLocation) -return;var oldUILocation=this._uiLocations.get(location.id())||null;this._uiLocations.set(location.id(),uiLocation);this._breakpoint._replaceUILocation(oldUILocation,uiLocation);} -_addResolvedLocation(location){var uiLocation=this._debuggerWorkspaceBinding.rawLocationToUILocation(location);if(!uiLocation) -return false;var breakpoint=this._breakpoint._breakpointManager.findBreakpoint(uiLocation.uiSourceCode,uiLocation.lineNumber,uiLocation.columnNumber);if(breakpoint&&breakpoint!==this._breakpoint){this._breakpoint.remove();return false;} -this._debuggerWorkspaceBinding.createLiveLocation(location,this._locationUpdated.bind(this,location),this._liveLocations);return true;} -_cleanUpAfterDebuggerIsGone(){if(this._isUpdating) -this._cancelCallback=true;this._resetLocations();this._currentState=null;if(this._debuggerId) -this._didRemoveFromDebugger(function(){});} -_removeEventListeners(){this._debuggerModel.removeEventListener(SDK.DebuggerModel.Events.DebuggerWasDisabled,this._cleanUpAfterDebuggerIsGone,this);this._debuggerModel.removeEventListener(SDK.DebuggerModel.Events.DebuggerWasEnabled,this._scheduleUpdateInDebugger,this);}};Bindings.BreakpointManager.Breakpoint.State=class{constructor(url,scriptId,scriptHash,lineNumber,columnNumber,condition){this.url=url;this.scriptId=scriptId;this.scriptHash=scriptHash;this.lineNumber=lineNumber;this.columnNumber=columnNumber;this.condition=condition;} -static equals(stateA,stateB){if(!stateA||!stateB) -return false;return stateA.url===stateB.url&&stateA.scriptId===stateB.scriptId&&stateA.scriptHash===stateB.scriptHash&&stateA.lineNumber===stateB.lineNumber&&stateA.columnNumber===stateB.columnNumber&&stateA.condition===stateB.condition;}};Bindings.BreakpointManager.Storage=class{constructor(breakpointManager,setting){this._breakpointManager=breakpointManager;this._setting=setting||Common.settings.createLocalSetting('breakpoints',[]);var breakpoints=this._setting.get();this._breakpoints={};for(var i=0;i<breakpoints.length;++i){var breakpoint=(breakpoints[i]);breakpoint.columnNumber=breakpoint.columnNumber||0;this._breakpoints[breakpoint.url+':'+breakpoint.lineNumber+':'+breakpoint.columnNumber]=breakpoint;}} -mute(){this._muted=true;} -unmute(){delete this._muted;} -breakpointItems(url){var result=[];for(var id in this._breakpoints){var breakpoint=this._breakpoints[id];if(breakpoint.url===url) -result.push(breakpoint);} -return result;} -_updateBreakpoint(breakpoint){if(this._muted||!breakpoint._breakpointStorageId()) -return;this._breakpoints[breakpoint._breakpointStorageId()]=new Bindings.BreakpointManager.Storage.Item(breakpoint);this._save();} -_removeBreakpoint(breakpoint){if(this._muted) -return;delete this._breakpoints[breakpoint._breakpointStorageId()];this._save();} -_save(){var breakpointsArray=[];for(var id in this._breakpoints) -breakpointsArray.push(this._breakpoints[id]);this._setting.set(breakpointsArray);}};Bindings.BreakpointManager.Storage.Item=class{constructor(breakpoint){this.url=breakpoint._url;this.lineNumber=breakpoint.lineNumber();this.columnNumber=breakpoint.columnNumber();this.condition=breakpoint.condition();this.enabled=breakpoint.enabled();}};Bindings.breakpointManager;;Bindings.ContentProviderBasedProject=class extends Workspace.ProjectStore{constructor(workspace,id,type,displayName,isServiceProject){super(workspace,id,type,displayName);this._contentProviders={};this._isServiceProject=isServiceProject;workspace.addProject(this);} -requestFileContent(uiSourceCode,callback){var contentProvider=this._contentProviders[uiSourceCode.url()];(async()=>{callback(await contentProvider.requestContent(),await contentProvider.contentEncoded());})();} -isServiceProject(){return this._isServiceProject;} -requestMetadata(uiSourceCode){return Promise.resolve(uiSourceCode[Bindings.ContentProviderBasedProject._metadata]);} -canSetFileContent(){return false;} -setFileContent(uiSourceCode,newContent,isBase64,callback){callback(null);} -fullDisplayName(uiSourceCode){var parentPath=uiSourceCode.parentURL().replace(/^(?:https?|file)\:\/\//,'');try{parentPath=decodeURI(parentPath);}catch(e){} -return parentPath+'/'+uiSourceCode.displayName(true);} -mimeType(uiSourceCode){return(uiSourceCode[Bindings.ContentProviderBasedProject._mimeType]);} -canRename(){return false;} -rename(uiSourceCode,newName,callback){var path=uiSourceCode.url();this.performRename(path,newName,innerCallback.bind(this));function innerCallback(success,newName){if(success&&newName){var copyOfPath=path.split('/');copyOfPath[copyOfPath.length-1]=newName;var newPath=copyOfPath.join('/');this._contentProviders[newPath]=this._contentProviders[path];delete this._contentProviders[path];this.renameUISourceCode(uiSourceCode,newName);} -callback(success,newName);}} -excludeFolder(path){} -createFile(path,name,content,isBase64){} -deleteFile(uiSourceCode){} -remove(){} -performRename(path,newName,callback){callback(false);} -searchInFileContent(uiSourceCode,query,caseSensitive,isRegex){var contentProvider=this._contentProviders[uiSourceCode.url()];return contentProvider.searchInContent(query,caseSensitive,isRegex);} -async findFilesMatchingSearchRequest(searchConfig,filesMathingFileQuery,progress){var result=[];progress.setTotalWork(filesMathingFileQuery.length);await Promise.all(filesMathingFileQuery.map(searchInContent.bind(this)));progress.done();return result;async function searchInContent(path){var provider=this._contentProviders[path];var allMatchesFound=true;for(var query of searchConfig.queries().slice()){var searchMatches=await provider.searchInContent(query,!searchConfig.ignoreCase(),searchConfig.isRegex());if(!searchMatches.length){allMatchesFound=false;break;}} -if(allMatchesFound) -result.push(path);progress.worked(1);}} -indexContent(progress){setImmediate(progress.done.bind(progress));} -addUISourceCodeWithProvider(uiSourceCode,contentProvider,metadata,mimeType){uiSourceCode[Bindings.ContentProviderBasedProject._mimeType]=mimeType;this._contentProviders[uiSourceCode.url()]=contentProvider;uiSourceCode[Bindings.ContentProviderBasedProject._metadata]=metadata;this.addUISourceCode(uiSourceCode,true);} -addContentProvider(url,contentProvider,mimeType){var uiSourceCode=this.createUISourceCode(url,contentProvider.contentType());this.addUISourceCodeWithProvider(uiSourceCode,contentProvider,null,mimeType);return uiSourceCode;} -removeFile(path){delete this._contentProviders[path];this.removeUISourceCode(path);} -reset(){this._contentProviders={};this.removeProject();this.workspace().addProject(this);} -dispose(){this._contentProviders={};this.removeProject();}};Bindings.ContentProviderBasedProject._metadata=Symbol('ContentProviderBasedProject.Metadata');Bindings.ContentProviderBasedProject._mimeType=Symbol('Bindings.ContentProviderBasedProject._mimeType');;Bindings.DefaultScriptMapping=class{constructor(debuggerModel,workspace,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._project=new Bindings.ContentProviderBasedProject(workspace,'debugger:'+debuggerModel.target().id(),Workspace.projectTypes.Debugger,'',true);this._eventListeners=[debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._debuggerReset,this),debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource,this._parsedScriptSource,this),debuggerModel.addEventListener(SDK.DebuggerModel.Events.FailedToParseScriptSource,this._parsedScriptSource,this),debuggerModel.addEventListener(SDK.DebuggerModel.Events.DiscardedAnonymousScriptSource,this._discardedScriptSource,this)];} -static scriptForUISourceCode(uiSourceCode){return uiSourceCode[Bindings.DefaultScriptMapping._scriptSymbol]||null;} -rawLocationToUILocation(rawLocation){var script=rawLocation.script();if(!script) -return null;var uiSourceCode=script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol];var lineNumber=rawLocation.lineNumber-(script.isInlineScriptWithSourceURL()?script.lineOffset:0);var columnNumber=rawLocation.columnNumber||0;if(script.isInlineScriptWithSourceURL()&&!lineNumber&&columnNumber) -columnNumber-=script.columnOffset;return uiSourceCode.uiLocation(lineNumber,columnNumber);} -uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){var script=uiSourceCode[Bindings.DefaultScriptMapping._scriptSymbol];if(!script) -return null;if(script.isInlineScriptWithSourceURL()){return this._debuggerModel.createRawLocation(script,lineNumber+script.lineOffset,lineNumber?columnNumber:columnNumber+script.columnOffset);} -return this._debuggerModel.createRawLocation(script,lineNumber,columnNumber);} -_parsedScriptSource(event){var script=(event.data);var name=Common.ParsedURL.extractName(script.sourceURL);var url='debugger:///VM'+script.scriptId+(name?' '+name:'');var uiSourceCode=this._project.createUISourceCode(url,Common.resourceTypes.Script);uiSourceCode[Bindings.DefaultScriptMapping._scriptSymbol]=script;script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol]=uiSourceCode;this._project.addUISourceCodeWithProvider(uiSourceCode,script,null,'text/javascript');this._debuggerWorkspaceBinding.updateLocations(script);} -_discardedScriptSource(event){var script=(event.data);var uiSourceCode=script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol];if(!uiSourceCode) -return;delete script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol];delete uiSourceCode[Bindings.DefaultScriptMapping._scriptSymbol];this._project.removeUISourceCode(uiSourceCode.url());} -_debuggerReset(){this._project.reset();} -dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);this._debuggerReset();this._project.dispose();}};Bindings.DefaultScriptMapping._scriptSymbol=Symbol('symbol');Bindings.DefaultScriptMapping._uiSourceCodeSymbol=Symbol('uiSourceCodeSymbol');;Bindings.ChunkedReader=function(){};Bindings.ChunkedReader.prototype={fileSize(){},loadedSize(){},fileName(){},cancel(){},error(){}};Bindings.ChunkedFileReader=class{constructor(blob,chunkSize,chunkTransferredCallback){this._file=blob;this._fileSize=blob.size;this._loadedSize=0;this._chunkSize=chunkSize;this._chunkTransferredCallback=chunkTransferredCallback;this._decoder=new TextDecoder();this._isCanceled=false;this._error=null;} -read(output){if(this._chunkTransferredCallback) -this._chunkTransferredCallback(this);this._output=output;this._reader=new FileReader();this._reader.onload=this._onChunkLoaded.bind(this);this._reader.onerror=this._onError.bind(this);this._loadChunk();return new Promise(resolve=>this._transferFinished=resolve);} -cancel(){this._isCanceled=true;} -loadedSize(){return this._loadedSize;} -fileSize(){return this._fileSize;} -fileName(){return this._file.name;} -error(){return this._error;} -_onChunkLoaded(event){if(this._isCanceled) -return;if(event.target.readyState!==FileReader.DONE) -return;var buffer=event.target.result;this._loadedSize+=buffer.byteLength;var endOfFile=this._loadedSize===this._fileSize;var decodedString=this._decoder.decode(buffer,{stream:!endOfFile});this._output.write(decodedString);if(this._isCanceled) -return;if(this._chunkTransferredCallback) -this._chunkTransferredCallback(this);if(endOfFile){this._file=null;this._reader=null;this._output.close();this._transferFinished(!this._error);return;} -this._loadChunk();} -_loadChunk(){var chunkStart=this._loadedSize;var chunkEnd=Math.min(this._fileSize,chunkStart+this._chunkSize);var nextPart=this._file.slice(chunkStart,chunkEnd);this._reader.readAsArrayBuffer(nextPart);} -_onError(event){this._error=event.target.error;this._transferFinished(false);}};Bindings.FileOutputStream=class{async open(fileName){this._closed=false;this._writeCallbacks=[];this._fileName=fileName;var saveResponse=await Workspace.fileManager.save(this._fileName,'',true);if(saveResponse) -Workspace.fileManager.addEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this);return!!saveResponse;} -write(data){return new Promise(resolve=>{this._writeCallbacks.push(resolve);Workspace.fileManager.append(this._fileName,data);});} -close(){this._closed=true;if(this._writeCallbacks.length) -return;Workspace.fileManager.removeEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this);Workspace.fileManager.close(this._fileName);} -_onAppendDone(event){if(event.data!==this._fileName) -return;this._writeCallbacks.shift()();if(this._writeCallbacks.length) -return;if(!this._closed) -return;Workspace.fileManager.removeEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this);Workspace.fileManager.close(this._fileName);}};;Bindings.BlackboxManager=class{constructor(debuggerWorkspaceBinding){this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.ParsedScriptSource,this._parsedScriptSource,this);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.GlobalObjectCleared,this._globalObjectCleared,this);Common.moduleSetting('skipStackFramesPattern').addChangeListener(this._patternChanged.bind(this));Common.moduleSetting('skipContentScripts').addChangeListener(this._patternChanged.bind(this));this._listeners=new Set();this._debuggerModelData=new Map();this._isBlackboxedURLCache=new Map();SDK.targetManager.observeModels(SDK.DebuggerModel,this);} -addChangeListener(listener){this._listeners.add(listener);} -removeChangeListener(listener){this._listeners.delete(listener);} -modelAdded(debuggerModel){this._setBlackboxPatterns(debuggerModel);} -modelRemoved(debuggerModel){this._debuggerModelData.delete(debuggerModel);this._isBlackboxedURLCache.clear();} -_setBlackboxPatterns(debuggerModel){var regexPatterns=Common.moduleSetting('skipStackFramesPattern').getAsArray();var patterns=([]);for(var item of regexPatterns){if(!item.disabled&&item.pattern) -patterns.push(item.pattern);} -return debuggerModel.setBlackboxPatterns(patterns);} -isBlackboxedRawLocation(location){var script=location.script();if(!script) -return false;var positions=this._scriptPositions(script);if(!positions) -return this._isBlackboxedScript(script);var index=positions.lowerBound(location,comparator);return!!(index%2);function comparator(a,b){if(a.lineNumber!==b.lineNumber) -return a.lineNumber-b.lineNumber;return a.columnNumber-b.columnNumber;}} -isBlackboxedUISourceCode(uiSourceCode){var projectType=uiSourceCode.project().type();var isContentScript=projectType===Workspace.projectTypes.ContentScripts;if(isContentScript&&Common.moduleSetting('skipContentScripts').get()) -return true;var url=this._uiSourceCodeURL(uiSourceCode);return url?this.isBlackboxedURL(url):false;} -isBlackboxedURL(url,isContentScript){if(this._isBlackboxedURLCache.has(url)) -return!!this._isBlackboxedURLCache.get(url);if(isContentScript&&Common.moduleSetting('skipContentScripts').get()) -return true;var regex=Common.moduleSetting('skipStackFramesPattern').asRegExp();var isBlackboxed=regex&®ex.test(url);this._isBlackboxedURLCache.set(url,isBlackboxed);return isBlackboxed;} -sourceMapLoaded(script,sourceMap){if(!sourceMap) -return Promise.resolve();var previousScriptState=this._scriptPositions(script);if(!previousScriptState) -return Promise.resolve();var hasBlackboxedMappings=sourceMap.sourceURLs().some(url=>this.isBlackboxedURL(url));var mappings=hasBlackboxedMappings?sourceMap.mappings().slice():[];if(!mappings.length){if(previousScriptState.length>0) -return this._setScriptState(script,[]);return Promise.resolve();} -mappings.sort(mappingComparator);var currentBlackboxed=false;var isBlackboxed=false;var positions=[];if(mappings[0].lineNumber!==0||mappings[0].columnNumber!==0){positions.push({lineNumber:0,columnNumber:0});currentBlackboxed=true;} -for(var mapping of mappings){if(mapping.sourceURL&¤tBlackboxed!==this.isBlackboxedURL(mapping.sourceURL)){positions.push({lineNumber:mapping.lineNumber,columnNumber:mapping.columnNumber});currentBlackboxed=!currentBlackboxed;} -isBlackboxed=currentBlackboxed||isBlackboxed;} -return this._setScriptState(script,!isBlackboxed?[]:positions);function mappingComparator(a,b){if(a.lineNumber!==b.lineNumber) -return a.lineNumber-b.lineNumber;return a.columnNumber-b.columnNumber;}} -_uiSourceCodeURL(uiSourceCode){return uiSourceCode.project().type()===Workspace.projectTypes.Debugger?null:uiSourceCode.url();} -canBlackboxUISourceCode(uiSourceCode){var url=this._uiSourceCodeURL(uiSourceCode);return url?!!this._urlToRegExpString(url):false;} -blackboxUISourceCode(uiSourceCode){var url=this._uiSourceCodeURL(uiSourceCode);if(url) -this._blackboxURL(url);} -unblackboxUISourceCode(uiSourceCode){var url=this._uiSourceCodeURL(uiSourceCode);if(url) -this._unblackboxURL(url);} -blackboxContentScripts(){Common.moduleSetting('skipContentScripts').set(true);} -unblackboxContentScripts(){Common.moduleSetting('skipContentScripts').set(false);} -_blackboxURL(url){var regexPatterns=Common.moduleSetting('skipStackFramesPattern').getAsArray();var regexValue=this._urlToRegExpString(url);if(!regexValue) -return;var found=false;for(var i=0;i<regexPatterns.length;++i){var item=regexPatterns[i];if(item.pattern===regexValue){item.disabled=false;found=true;break;}} -if(!found) -regexPatterns.push({pattern:regexValue});Common.moduleSetting('skipStackFramesPattern').setAsArray(regexPatterns);} -_unblackboxURL(url){var regexPatterns=Common.moduleSetting('skipStackFramesPattern').getAsArray();var regexValue=Bindings.blackboxManager._urlToRegExpString(url);if(!regexValue) -return;regexPatterns=regexPatterns.filter(function(item){return item.pattern!==regexValue;});for(var i=0;i<regexPatterns.length;++i){var item=regexPatterns[i];if(item.disabled) -continue;try{var regex=new RegExp(item.pattern);if(regex.test(url)) -item.disabled=true;}catch(e){}} -Common.moduleSetting('skipStackFramesPattern').setAsArray(regexPatterns);} -_patternChanged(){this._isBlackboxedURLCache.clear();var promises=[];for(var debuggerModel of SDK.targetManager.models(SDK.DebuggerModel)){promises.push(this._setBlackboxPatterns(debuggerModel));for(var script of debuggerModel.scripts()) -promises.push(this._addScript(script).then(loadSourceMap.bind(this,script)));} -Promise.all(promises).then(()=>{var listeners=Array.from(this._listeners);for(var listener of listeners) -listener();this._patternChangeFinishedForTests();});function loadSourceMap(script){return this.sourceMapLoaded(script,this._debuggerWorkspaceBinding.sourceMapForScript(script));}} -_patternChangeFinishedForTests(){} -_globalObjectCleared(event){var debuggerModel=(event.data);this._debuggerModelData.delete(debuggerModel);this._isBlackboxedURLCache.clear();} -_parsedScriptSource(event){var script=(event.data);this._addScript(script);} -_addScript(script){if(!script.sourceURL&&!script.sourceMapURL) -return Promise.resolve();var blackboxed=this._isBlackboxedScript(script);return this._setScriptState(script,blackboxed?[{lineNumber:0,columnNumber:0}]:[]);} -_isBlackboxedScript(script){return this.isBlackboxedURL(script.sourceURL,script.isContentScript());} -_scriptPositions(script){if(this._debuggerModelData.has(script.debuggerModel)) -return this._debuggerModelData.get(script.debuggerModel).get(script.scriptId)||null;return null;} -_setScriptPositions(script,positions){var debuggerModel=script.debuggerModel;if(!this._debuggerModelData.has(debuggerModel)) -this._debuggerModelData.set(debuggerModel,new Map());this._debuggerModelData.get(debuggerModel).set(script.scriptId,positions);} -_setScriptState(script,positions){var previousScriptState=this._scriptPositions(script);if(previousScriptState){var hasChanged=false;hasChanged=previousScriptState.length!==positions.length;for(var i=0;!hasChanged&&i<positions.length;++i){hasChanged=positions[i].lineNumber!==previousScriptState[i].lineNumber||positions[i].columnNumber!==previousScriptState[i].columnNumber;} -if(!hasChanged) -return Promise.resolve();}else{if(positions.length===0) -return Promise.resolve().then(updateState.bind(this,false));} -return script.setBlackboxedRanges(positions).then(updateState.bind(this));function updateState(success){if(success){this._setScriptPositions(script,positions);this._debuggerWorkspaceBinding.updateLocations(script);var isBlackboxed=positions.length!==0;if(!isBlackboxed&&script.sourceMapURL) -this._debuggerWorkspaceBinding.maybeLoadSourceMap(script);}else{var hasPositions=!!this._scriptPositions(script);if(!hasPositions) -this._setScriptPositions(script,[]);}}} -_urlToRegExpString(url){var parsedURL=new Common.ParsedURL(url);if(parsedURL.isAboutBlank()||parsedURL.isDataURL()) -return'';if(!parsedURL.isValid) -return'^'+url.escapeForRegExp()+'$';var name=parsedURL.lastPathComponent;if(name) -name='/'+name;else if(parsedURL.folderPathComponents) -name=parsedURL.folderPathComponents+'/';if(!name) -name=parsedURL.host;if(!name) -return'';var scheme=parsedURL.scheme;var prefix='';if(scheme&&scheme!=='http'&&scheme!=='https'){prefix='^'+scheme+'://';if(scheme==='chrome-extension') -prefix+=parsedURL.host+'\\b';prefix+='.*';} -return prefix+name.escapeForRegExp()+(url.endsWith(name)?'$':'\\b');}};Bindings.blackboxManager;;Bindings.NetworkProjectManager=class extends Common.Object{constructor(targetManager,workspace){super();this._workspace=workspace;targetManager.observeTargets(this);} -targetAdded(target){new Bindings.NetworkProject(target,this._workspace);} -targetRemoved(target){Bindings.NetworkProject.forTarget(target)._dispose();}};Bindings.NetworkProjectManager.Events={FrameAttributionAdded:Symbol('FrameAttributionAdded'),FrameAttributionRemoved:Symbol('FrameAttributionRemoved')};Bindings.NetworkProject=class{constructor(target,workspace){this._target=target;this._workspace=workspace;this._workspaceProjects=new Map();target[Bindings.NetworkProject._networkProjectSymbol]=this;this._eventListeners=[];this._debuggerModel=target.model(SDK.DebuggerModel);this._acceptedScripts=new Set();if(this._debuggerModel){var runtimeModel=this._debuggerModel.runtimeModel();this._eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.ExecutionContextDestroyed,this._executionContextDestroyed,this),this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._globalObjectCleared,this),this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource,this._parsedScriptSource,this),this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.FailedToParseScriptSource,this._parsedScriptSource,this));}} -static projectId(target,frameId,isContentScripts){return target.id()+':'+frameId+':'+(isContentScripts?'contentscripts':'');} -static forTarget(target){return target[Bindings.NetworkProject._networkProjectSymbol];} -static _resolveFrame(uiSourceCode,frameId){var target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);var resourceTreeModel=target&&target.model(SDK.ResourceTreeModel);return resourceTreeModel?resourceTreeModel.frameForId(frameId):null;} -static setInitialFrameAttribution(uiSourceCode,frameId){var frame=Bindings.NetworkProject._resolveFrame(uiSourceCode,frameId);if(!frame) -return;var attribution=new Map();attribution.set(frameId,{frame:frame,count:1});uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol]=attribution;} -static addFrameAttribution(uiSourceCode,frameId){var frame=Bindings.NetworkProject._resolveFrame(uiSourceCode,frameId);if(!frame) -return;var frameAttribution=uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol];var attributionInfo=frameAttribution.get(frameId)||{frame:frame,count:0};attributionInfo.count+=1;frameAttribution.set(frameId,attributionInfo);if(attributionInfo.count!==1) -return;var data={uiSourceCode:uiSourceCode,frame:frame};Bindings.networkProjectManager.dispatchEventToListeners(Bindings.NetworkProjectManager.Events.FrameAttributionAdded,data);} -static removeFrameAttribution(uiSourceCode,frameId){var frameAttribution=uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol];var attributionInfo=frameAttribution.get(frameId);console.assert(attributionInfo,'Failed to remove frame attribution for url: '+uiSourceCode.url());attributionInfo.count-=1;if(attributionInfo.count>0) -return;frameAttribution.delete(frameId);var data={uiSourceCode:uiSourceCode,frame:attributionInfo.frame};Bindings.networkProjectManager.dispatchEventToListeners(Bindings.NetworkProjectManager.Events.FrameAttributionRemoved,data);} -static targetForUISourceCode(uiSourceCode){return uiSourceCode.project()[Bindings.NetworkProject._targetSymbol]||null;} -static setTargetForProject(project,target){project[Bindings.NetworkProject._targetSymbol]=target;} -static framesForUISourceCode(uiSourceCode){var target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);var resourceTreeModel=target&&target.model(SDK.ResourceTreeModel);var attribution=uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol];if(!resourceTreeModel||!attribution) -return[];var frames=Array.from(attribution.keys()).map(frameId=>resourceTreeModel.frameForId(frameId));return frames.filter(frame=>!!frame);} -_workspaceProject(frameId,isContentScripts){var projectId=Bindings.NetworkProject.projectId(this._target,frameId,isContentScripts);var projectType=isContentScripts?Workspace.projectTypes.ContentScripts:Workspace.projectTypes.Network;var project=this._workspaceProjects.get(projectId);if(project) -return project;project=new Bindings.ContentProviderBasedProject(this._workspace,projectId,projectType,'',false);project[Bindings.NetworkProject._targetSymbol]=this._target;this._workspaceProjects.set(projectId,project);return project;} -_removeFileForURL(url,frameId,isContentScript){var project=this._workspaceProjects.get(Bindings.NetworkProject.projectId(this._target,frameId,isContentScript));if(!project) -return;project.removeFile(url);} -_addUISourceCodeWithProvider(uiSourceCode,contentProvider,metadata,mimeType){(uiSourceCode.project()).addUISourceCodeWithProvider(uiSourceCode,contentProvider,metadata,mimeType);} -_acceptsScript(script){if(!script.sourceURL||script.isLiveEdit()||(script.isInlineScript()&&!script.hasSourceURL)) -return false;if(script.isContentScript()&&!script.hasSourceURL){var parsedURL=new Common.ParsedURL(script.sourceURL);if(!parsedURL.isValid) -return false;} -return true;} -_parsedScriptSource(event){var script=(event.data);if(!this._acceptsScript(script)) -return;this._acceptedScripts.add(script);var originalContentProvider=script.originalContentProvider();var frameId=Bindings.frameIdForScript(script);script[Bindings.NetworkProject._frameIdSymbol]=frameId;var uiSourceCode=this._createFile(originalContentProvider,frameId,script.isContentScript());var metadata=Bindings.metadataForURL(this._target,frameId,uiSourceCode.url());this._addUISourceCodeWithProvider(uiSourceCode,originalContentProvider,metadata,'text/javascript');} -_executionContextDestroyed(event){var executionContext=(event.data);var scripts=this._debuggerModel.scriptsForExecutionContext(executionContext);this._removeScripts(scripts);} -_removeScripts(scripts){for(var script of scripts){if(!this._acceptedScripts.has(script)) -continue;this._acceptedScripts.delete(script);var frameId=script[Bindings.NetworkProject._frameIdSymbol];this._removeFileForURL(script.contentURL(),frameId,script.isContentScript());}} -_globalObjectCleared(event){this._removeScripts(Array.from(this._acceptedScripts));} -_createFile(contentProvider,frameId,isContentScript){var url=contentProvider.contentURL();var project=this._workspaceProject(frameId,isContentScript);var uiSourceCode=project.createUISourceCode(url,contentProvider.contentType());if(frameId) -Bindings.NetworkProject.setInitialFrameAttribution(uiSourceCode,frameId);return uiSourceCode;} -_dispose(){for(var project of this._workspaceProjects.values()) -project.removeProject();Common.EventTarget.removeEventListeners(this._eventListeners);delete this._target[Bindings.NetworkProject._networkProjectSymbol];this._workspaceProjects.clear();} -_resetForTest(){for(var project of this._workspaceProjects.values()) -project.removeProject();this._workspaceProjects.clear();} -static uiSourceCodeForScriptURL(workspace,url,script){var target=script.debuggerModel.target();var executionContext=script.executionContext();var frameId=executionContext?executionContext.frameId||'':'';return workspace.uiSourceCode(Bindings.NetworkProject.projectId(target,frameId,false),url)||workspace.uiSourceCode(Bindings.NetworkProject.projectId(target,frameId,true),url);}};Bindings.NetworkProject._networkProjectSymbol=Symbol('networkProject');Bindings.NetworkProject._targetSymbol=Symbol('target');Bindings.NetworkProject._frameIdSymbol=Symbol('frameid');Bindings.NetworkProject._frameAttributionSymbol=Symbol('Bindings.NetworkProject._frameAttributionSymbol');;Bindings.PresentationConsoleMessageHelper=class{constructor(workspace){this._workspace=workspace;this._pendingConsoleMessages={};this._presentationConsoleMessages=[];ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.ConsoleCleared,this._consoleCleared,this);ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.MessageAdded,this._onConsoleMessageAdded,this);ConsoleModel.consoleModel.messages().forEach(this._consoleMessageAdded,this);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.ParsedScriptSource,event=>setImmediate(this._parsedScriptSource.bind(this,event)));SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.FailedToParseScriptSource,event=>setImmediate(this._parsedScriptSource.bind(this,event)));SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.GlobalObjectCleared,this._debuggerReset,this);this._locationPool=new Bindings.LiveLocationPool();} -_onConsoleMessageAdded(event){var message=(event.data);this._consoleMessageAdded(message);} -_consoleMessageAdded(message){if(!message.isErrorOrWarning()) -return;var rawLocation=this._rawLocation(message);if(rawLocation) -this._addConsoleMessageToScript(message,rawLocation);else -this._addPendingConsoleMessage(message);} -_rawLocation(message){if(!message.runtimeModel()) -return null;var debuggerModel=message.runtimeModel().debuggerModel();if(message.scriptId) -return debuggerModel.createRawLocationByScriptId(message.scriptId,message.line,message.column);var callFrame=message.stackTrace&&message.stackTrace.callFrames?message.stackTrace.callFrames[0]:null;if(callFrame){return debuggerModel.createRawLocationByScriptId(callFrame.scriptId,callFrame.lineNumber,callFrame.columnNumber);} -if(message.url) -return debuggerModel.createRawLocationByURL(message.url,message.line,message.column);return null;} -_addConsoleMessageToScript(message,rawLocation){if(message.source===ConsoleModel.ConsoleMessage.MessageSource.Violation) -return;this._presentationConsoleMessages.push(new Bindings.PresentationConsoleMessage(message,rawLocation,this._locationPool));} -_addPendingConsoleMessage(message){if(!message.url) -return;if(!this._pendingConsoleMessages[message.url]) -this._pendingConsoleMessages[message.url]=[];this._pendingConsoleMessages[message.url].push(message);} -_parsedScriptSource(event){var script=(event.data);var messages=this._pendingConsoleMessages[script.sourceURL];if(!messages) -return;var pendingMessages=[];for(var i=0;i<messages.length;i++){var message=messages[i];var rawLocation=this._rawLocation(message);if(!rawLocation) -continue;if(script.debuggerModel.runtimeModel()===message.runtimeModel()&&script.scriptId===rawLocation.scriptId) -this._addConsoleMessageToScript(message,rawLocation);else -pendingMessages.push(message);} -if(pendingMessages.length) -this._pendingConsoleMessages[script.sourceURL]=pendingMessages;else -delete this._pendingConsoleMessages[script.sourceURL];} -_consoleCleared(){this._pendingConsoleMessages={};for(var i=0;i<this._presentationConsoleMessages.length;++i) -this._presentationConsoleMessages[i].dispose();this._presentationConsoleMessages=[];this._locationPool.disposeAll();} -_debuggerReset(){this._consoleCleared();}};Bindings.PresentationConsoleMessage=class{constructor(message,rawLocation,locationPool){this._text=message.messageText;this._level=message.level===ConsoleModel.ConsoleMessage.MessageLevel.Error?Workspace.UISourceCode.Message.Level.Error:Workspace.UISourceCode.Message.Level.Warning;Bindings.debuggerWorkspaceBinding.createLiveLocation(rawLocation,this._updateLocation.bind(this),locationPool);} -_updateLocation(liveLocation){if(this._uiMessage) -this._uiMessage.remove();var uiLocation=liveLocation.uiLocation();if(!uiLocation) -return;this._uiMessage=uiLocation.uiSourceCode.addLineMessage(this._level,this._text,uiLocation.lineNumber,uiLocation.columnNumber);} -dispose(){if(this._uiMessage) -this._uiMessage.remove();}};Bindings.presentationConsoleMessageHelper;;Bindings.resourceForURL=function(url){for(var resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)){var resource=resourceTreeModel.resourceForURL(url);if(resource) -return resource;} -return null;};Bindings.forAllResources=function(callback){for(var resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) -resourceTreeModel.forAllResources(callback);};Bindings.displayNameForURL=function(url){if(!url) -return'';var resource=Bindings.resourceForURL(url);if(resource) -return resource.displayName;var uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);if(uiSourceCode) -return uiSourceCode.displayName();var mainTarget=SDK.targetManager.mainTarget();var inspectedURL=mainTarget&&mainTarget.inspectedURL();if(!inspectedURL) -return url.trimURL('');var parsedURL=inspectedURL.asParsedURL();var lastPathComponent=parsedURL?parsedURL.lastPathComponent:parsedURL;var index=inspectedURL.indexOf(lastPathComponent);if(index!==-1&&index+lastPathComponent.length===inspectedURL.length){var baseURL=inspectedURL.substring(0,index);if(url.startsWith(baseURL)) -return url.substring(index);} -if(!parsedURL) -return url;var displayName=url.trimURL(parsedURL.host);return displayName==='/'?parsedURL.host+'/':displayName;};Bindings.metadataForURL=function(target,frameId,url){var resourceTreeModel=target.model(SDK.ResourceTreeModel);if(!resourceTreeModel) -return null;var frame=resourceTreeModel.frameForId(frameId);if(!frame) -return null;return Bindings.resourceMetadata(frame.resourceForURL(url));};Bindings.resourceMetadata=function(resource){if(!resource||(typeof resource.contentSize()!=='number'&&!resource.lastModified())) -return null;return new Workspace.UISourceCodeMetadata(resource.lastModified(),resource.contentSize());};Bindings.frameIdForScript=function(script){var executionContext=script.executionContext();if(executionContext) -return executionContext.frameId||'';var resourceTreeModel=script.debuggerModel.target().model(SDK.ResourceTreeModel);if(!resourceTreeModel||!resourceTreeModel.mainFrame) -return'';return resourceTreeModel.mainFrame.id;};;Bindings.TempFile=class{constructor(){this._lastBlob=null;} -write(pieces){if(this._lastBlob) -pieces.unshift(this._lastBlob);this._lastBlob=new Blob(pieces,{type:'text/plain'});} -read(){return this.readRange();} -size(){return this._lastBlob?this._lastBlob.size:0;} -async readRange(startOffset,endOffset){if(!this._lastBlob){Common.console.error('Attempt to read a temp file that was never written');return Promise.resolve('');} -var blob=typeof startOffset==='number'||typeof endOffset==='number'?this._lastBlob.slice((startOffset),(endOffset)):this._lastBlob;var reader=new FileReader();try{await new Promise((resolve,reject)=>{reader.onloadend=resolve;reader.onerror=reject;reader.readAsText(blob);});}catch(error){Common.console.error('Failed to read from temp file: '+error.message);} -return reader.result;} -copyToOutputStream(outputStream,progress){if(!this._lastBlob){outputStream.close();return Promise.resolve((null));} -var reader=new Bindings.ChunkedFileReader((this._lastBlob),10*1000*1000,progress);return reader.read(outputStream).then(success=>success?null:reader.error());} -remove(){this._lastBlob=null;}};Bindings.TempFileBackingStorage=class{constructor(){this._file=null;this._strings;this._stringsLength;this.reset();} -appendString(string){this._strings.push(string);this._stringsLength+=string.length;var flushStringLength=10*1024*1024;if(this._stringsLength>flushStringLength) -this._flush();} -appendAccessibleString(string){this._flush();var startOffset=this._file.size();this._strings.push(string);this._flush();return this._file.readRange.bind(this._file,startOffset,this._file.size());} -_flush(){if(!this._strings.length) -return;if(!this._file) -this._file=new Bindings.TempFile();this._stringsLength=0;this._file.write(this._strings.splice(0));} -finishWriting(){this._flush();} -reset(){if(this._file) -this._file.remove();this._file=null;this._strings=[];this._stringsLength=0;} -writeToStream(outputStream){return this._file?this._file.copyToOutputStream(outputStream):Promise.resolve(null);}};Bindings.TempFileBackingStorage.Chunk;;self['Components']=self['Components']||{};Components.DOMBreakpointsSidebarPane=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('components/domBreakpointsSidebarPane.css');this._listElement=this.contentElement.createChild('div','breakpoint-list hidden');this._emptyElement=this.contentElement.createChild('div','gray-info-message');this._emptyElement.textContent=Common.UIString('No breakpoints');this._items=new Map();SDK.targetManager.addModelListener(SDK.DOMDebuggerModel,SDK.DOMDebuggerModel.Events.DOMBreakpointAdded,this._breakpointAdded,this);SDK.targetManager.addModelListener(SDK.DOMDebuggerModel,SDK.DOMDebuggerModel.Events.DOMBreakpointToggled,this._breakpointToggled,this);SDK.targetManager.addModelListener(SDK.DOMDebuggerModel,SDK.DOMDebuggerModel.Events.DOMBreakpointsRemoved,this._breakpointsRemoved,this);for(var domDebuggerModel of SDK.targetManager.models(SDK.DOMDebuggerModel)){domDebuggerModel.retrieveDOMBreakpoints();for(var breakpoint of domDebuggerModel.domBreakpoints()) -this._addBreakpoint(breakpoint);} -this._highlightedElement=null;this._update();} -static createBreakpointHitMessage(details){var messageWrapper=createElement('span');var domDebuggerModel=details.debuggerModel.target().model(SDK.DOMDebuggerModel);if(!details.auxData||!domDebuggerModel) -return messageWrapper;var data=domDebuggerModel.resolveDOMBreakpointData((details.auxData));if(!data) -return messageWrapper;var mainElement=messageWrapper.createChild('div','status-main');mainElement.appendChild(UI.Icon.create('smallicon-info','status-icon'));mainElement.appendChild(createTextNode(String.sprintf('Paused on %s',Components.DOMBreakpointsSidebarPane.BreakpointTypeNouns.get(data.type))));var subElement=messageWrapper.createChild('div','status-sub monospace');var linkifiedNode=Components.DOMPresentationUtils.linkifyNodeReference(data.node);subElement.appendChild(linkifiedNode);if(data.targetNode){var targetNodeLink=Components.DOMPresentationUtils.linkifyNodeReference(data.targetNode);var message;if(data.insertion) -message=data.targetNode===data.node?'Child %s added':'Descendant %s added';else -message='Descendant %s removed';subElement.appendChild(createElement('br'));subElement.appendChild(UI.formatLocalized(message,[targetNodeLink]));} -return messageWrapper;} -_breakpointAdded(event){this._addBreakpoint((event.data));} -_breakpointToggled(event){var breakpoint=(event.data);var item=this._items.get(breakpoint);if(item) -item.checkbox.checked=breakpoint.enabled;} -_breakpointsRemoved(event){var breakpoints=(event.data);for(var breakpoint of breakpoints){var item=this._items.get(breakpoint);if(item){this._items.delete(breakpoint);this._listElement.removeChild(item.element);}} -if(!this._listElement.firstChild){this._emptyElement.classList.remove('hidden');this._listElement.classList.add('hidden');}} -_addBreakpoint(breakpoint){var element=createElementWithClass('div','breakpoint-entry');element.addEventListener('contextmenu',this._contextMenu.bind(this,breakpoint),true);var checkboxLabel=UI.CheckboxLabel.create('',breakpoint.enabled);var checkboxElement=checkboxLabel.checkboxElement;checkboxElement.addEventListener('click',this._checkboxClicked.bind(this,breakpoint),false);element.appendChild(checkboxLabel);var labelElement=createElementWithClass('div','dom-breakpoint');element.appendChild(labelElement);var linkifiedNode=Components.DOMPresentationUtils.linkifyNodeReference(breakpoint.node);linkifiedNode.classList.add('monospace');linkifiedNode.style.display='block';labelElement.appendChild(linkifiedNode);var description=createElement('div');description.textContent=Components.DOMBreakpointsSidebarPane.BreakpointTypeLabels.get(breakpoint.type);labelElement.appendChild(description);var item={breakpoint:breakpoint,element:element,checkbox:checkboxElement};element._item=item;this._items.set(breakpoint,item);var currentElement=this._listElement.firstChild;while(currentElement){if(currentElement._item&¤tElement._item.breakpoint.type<breakpoint.type) -break;currentElement=currentElement.nextSibling;} -this._listElement.insertBefore(element,currentElement);this._emptyElement.classList.add('hidden');this._listElement.classList.remove('hidden');} -_contextMenu(breakpoint,event){var contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Remove breakpoint'),()=>{breakpoint.domDebuggerModel.removeDOMBreakpoint(breakpoint.node,breakpoint.type);});contextMenu.defaultSection().appendItem(Common.UIString('Remove all DOM breakpoints'),()=>{breakpoint.domDebuggerModel.removeAllDOMBreakpoints();});contextMenu.show();} -_checkboxClicked(breakpoint){var item=this._items.get(breakpoint);if(!item) -return;breakpoint.domDebuggerModel.toggleDOMBreakpoint(breakpoint,item.checkbox.checked);} -flavorChanged(object){this._update();} -_update(){var details=UI.context.flavor(SDK.DebuggerPausedDetails);if(!details||!details.auxData||details.reason!==SDK.DebuggerModel.BreakReason.DOM){if(this._highlightedElement){this._highlightedElement.classList.remove('breakpoint-hit');delete this._highlightedElement;} -return;} -var domDebuggerModel=details.debuggerModel.target().model(SDK.DOMDebuggerModel);if(!domDebuggerModel) -return;var data=domDebuggerModel.resolveDOMBreakpointData((details.auxData));if(!data) -return;var element=null;for(var item of this._items.values()){if(item.breakpoint.node===data.node&&item.breakpoint.type===data.type) -element=item.element;} -if(!element) -return;UI.viewManager.showView('sources.domBreakpoints');element.classList.add('breakpoint-hit');this._highlightedElement=element;}};Components.DOMBreakpointsSidebarPane.Item;Components.DOMBreakpointsSidebarPane.BreakpointTypeLabels=new Map([[SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified,Common.UIString('Subtree modified')],[SDK.DOMDebuggerModel.DOMBreakpoint.Type.AttributeModified,Common.UIString('Attribute modified')],[SDK.DOMDebuggerModel.DOMBreakpoint.Type.NodeRemoved,Common.UIString('Node removed')],]);Components.DOMBreakpointsSidebarPane.BreakpointTypeNouns=new Map([[SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified,Common.UIString('subtree modifications')],[SDK.DOMDebuggerModel.DOMBreakpoint.Type.AttributeModified,Common.UIString('attribute modifications')],[SDK.DOMDebuggerModel.DOMBreakpoint.Type.NodeRemoved,Common.UIString('node removal')],]);Components.DOMBreakpointsSidebarPane.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,object){var node=(object);if(node.pseudoType()) -return;var domDebuggerModel=node.domModel().target().model(SDK.DOMDebuggerModel);if(!domDebuggerModel) -return;function toggleBreakpoint(type){if(domDebuggerModel.hasDOMBreakpoint(node,type)) -domDebuggerModel.removeDOMBreakpoint(node,type);else -domDebuggerModel.setDOMBreakpoint(node,type);} -var breakpointsMenu=contextMenu.debugSection().appendSubMenuItem(Common.UIString('Break on'));for(var key in SDK.DOMDebuggerModel.DOMBreakpoint.Type){var type=SDK.DOMDebuggerModel.DOMBreakpoint.Type[key];var label=Components.DOMBreakpointsSidebarPane.BreakpointTypeNouns.get(type);breakpointsMenu.defaultSection().appendCheckboxItem(label,toggleBreakpoint.bind(null,type),domDebuggerModel.hasDOMBreakpoint(node,type));}}};;Components.DOMPresentationUtils={};Components.DOMPresentationUtils.decorateNodeLabel=function(node,parentElement,tooltipContent){var originalNode=node;var isPseudo=node.nodeType()===Node.ELEMENT_NODE&&node.pseudoType();if(isPseudo&&node.parentNode) -node=node.parentNode;var title=node.nodeNameInCorrectCase();var nameElement=parentElement.createChild('span','node-label-name');nameElement.textContent=title;var idAttribute=node.getAttribute('id');if(idAttribute){var idElement=parentElement.createChild('span','node-label-id');var part='#'+idAttribute;title+=part;idElement.createTextChild(part);nameElement.classList.add('extra');} -var classAttribute=node.getAttribute('class');if(classAttribute){var classes=classAttribute.split(/\s+/);var foundClasses={};if(classes.length){var classesElement=parentElement.createChild('span','extra node-label-class');for(var i=0;i<classes.length;++i){var className=classes[i];if(className&&!(className in foundClasses)){var part='.'+className;title+=part;classesElement.createTextChild(part);foundClasses[className]=true;}}}} -if(isPseudo){var pseudoElement=parentElement.createChild('span','extra node-label-pseudo');var pseudoText='::'+originalNode.pseudoType();pseudoElement.createTextChild(pseudoText);title+=pseudoText;} -parentElement.title=tooltipContent||title;};Components.DOMPresentationUtils.createSpansForNodeTitle=function(container,nodeTitle){var match=nodeTitle.match(/([^#.]+)(#[^.]+)?(\..*)?/);container.createChild('span','webkit-html-tag-name').textContent=match[1];if(match[2]) -container.createChild('span','webkit-html-attribute-value').textContent=match[2];if(match[3]) -container.createChild('span','webkit-html-attribute-name').textContent=match[3];};Components.DOMPresentationUtils.linkifyNodeReference=function(node,idref,tooltipContent){if(!node) -return createTextNode(Common.UIString('<node>'));var root=createElementWithClass('span','monospace');var shadowRoot=UI.createShadowRootWithCoreStyles(root,'components/domUtils.css');var link=shadowRoot.createChild('div','node-link');if(idref) -link.createChild('span','node-label-id').createTextChild('#'+idref);else -Components.DOMPresentationUtils.decorateNodeLabel(node,link,tooltipContent);link.addEventListener('click',Common.Revealer.reveal.bind(Common.Revealer,node,undefined),false);link.addEventListener('mouseover',node.highlight.bind(node,undefined,undefined),false);link.addEventListener('mouseleave',()=>SDK.OverlayModel.hideDOMNodeHighlight(),false);return root;};Components.DOMPresentationUtils.linkifyDeferredNodeReference=function(deferredNode){var root=createElement('div');var shadowRoot=UI.createShadowRootWithCoreStyles(root,'components/domUtils.css');var link=shadowRoot.createChild('div','node-link');link.createChild('content');link.addEventListener('click',deferredNode.resolve.bind(deferredNode,onDeferredNodeResolved),false);link.addEventListener('mousedown',e=>e.consume(),false);function onDeferredNodeResolved(node){Common.Revealer.reveal(node);} -return root;};Components.DOMPresentationUtils.buildImagePreviewContents=function(target,originalImageURL,showDimensions,precomputedFeatures){var resourceTreeModel=target.model(SDK.ResourceTreeModel);if(!resourceTreeModel) -return Promise.resolve((null));var resource=resourceTreeModel.resourceForURL(originalImageURL);var imageURL=originalImageURL;if(!isImageResource(resource)&&precomputedFeatures&&precomputedFeatures.currentSrc){imageURL=precomputedFeatures.currentSrc;resource=resourceTreeModel.resourceForURL(imageURL);} -if(!isImageResource(resource)) -return Promise.resolve((null));var fulfill;var promise=new Promise(x=>fulfill=x);var imageElement=createElement('img');imageElement.addEventListener('load',buildContent,false);imageElement.addEventListener('error',()=>fulfill(null),false);resource.populateImageSource(imageElement);return promise;function isImageResource(resource){return!!resource&&resource.resourceType()===Common.resourceTypes.Image;} -function buildContent(){var container=createElement('table');UI.appendStyle(container,'components/imagePreview.css');container.className='image-preview-container';var naturalWidth=precomputedFeatures?precomputedFeatures.naturalWidth:imageElement.naturalWidth;var naturalHeight=precomputedFeatures?precomputedFeatures.naturalHeight:imageElement.naturalHeight;var offsetWidth=precomputedFeatures?precomputedFeatures.offsetWidth:naturalWidth;var offsetHeight=precomputedFeatures?precomputedFeatures.offsetHeight:naturalHeight;var description;if(showDimensions){if(offsetHeight===naturalHeight&&offsetWidth===naturalWidth){description=Common.UIString('%d \xd7 %d pixels',offsetWidth,offsetHeight);}else{description=Common.UIString('%d \xd7 %d pixels (Natural: %d \xd7 %d pixels)',offsetWidth,offsetHeight,naturalWidth,naturalHeight);}} -container.createChild('tr').createChild('td','image-container').appendChild(imageElement);if(description) -container.createChild('tr').createChild('td').createChild('span','description').textContent=description;if(imageURL!==originalImageURL){container.createChild('tr').createChild('td').createChild('span','description').textContent=String.sprintf('currentSrc: %s',imageURL.trimMiddle(100));} -fulfill(container);}};Components.DOMPresentationUtils.buildStackTracePreviewContents=function(target,linkifier,stackTrace){var element=createElement('span');element.style.display='inline-block';var shadowRoot=UI.createShadowRootWithCoreStyles(element,'components/domUtils.css');var contentElement=shadowRoot.createChild('table','stack-preview-container');function appendStackTrace(stackTrace){for(var stackFrame of stackTrace.callFrames){var row=createElement('tr');row.createChild('td').textContent='\n';row.createChild('td','function-name').textContent=UI.beautifyFunctionName(stackFrame.functionName);var link=linkifier.maybeLinkifyConsoleCallFrame(target,stackFrame);if(link){row.createChild('td').textContent=' @ ';row.createChild('td').appendChild(link);} -contentElement.appendChild(row);}} -if(!stackTrace) -return element;appendStackTrace(stackTrace);var asyncStackTrace=stackTrace.parent;while(asyncStackTrace){if(!asyncStackTrace.callFrames.length){asyncStackTrace=asyncStackTrace.parent;continue;} -var row=contentElement.createChild('tr');row.createChild('td').textContent='\n';row.createChild('td','stack-preview-async-description').textContent=UI.asyncStackTraceLabel(asyncStackTrace.description);row.createChild('td');row.createChild('td');appendStackTrace(asyncStackTrace);asyncStackTrace=asyncStackTrace.parent;} -return element;};Components.DOMPresentationUtils.fullQualifiedSelector=function(node,justSelector){if(node.nodeType()!==Node.ELEMENT_NODE) -return node.localName()||node.nodeName().toLowerCase();return Components.DOMPresentationUtils.cssPath(node,justSelector);};Components.DOMPresentationUtils.simpleSelector=function(node){var lowerCaseName=node.localName()||node.nodeName().toLowerCase();if(node.nodeType()!==Node.ELEMENT_NODE) -return lowerCaseName;if(lowerCaseName==='input'&&node.getAttribute('type')&&!node.getAttribute('id')&&!node.getAttribute('class')) -return lowerCaseName+'[type="'+node.getAttribute('type')+'"]';if(node.getAttribute('id')) -return lowerCaseName+'#'+node.getAttribute('id');if(node.getAttribute('class')){return(lowerCaseName==='div'?'':lowerCaseName)+'.'+ -node.getAttribute('class').trim().replace(/\s+/g,'.');} -return lowerCaseName;};Components.DOMPresentationUtils.cssPath=function(node,optimized){if(node.nodeType()!==Node.ELEMENT_NODE) -return'';var steps=[];var contextNode=node;while(contextNode){var step=Components.DOMPresentationUtils._cssPathStep(contextNode,!!optimized,contextNode===node);if(!step) -break;steps.push(step);if(step.optimized) -break;contextNode=contextNode.parentNode;} -steps.reverse();return steps.join(' > ');};Components.DOMPresentationUtils._cssPathStep=function(node,optimized,isTargetNode){if(node.nodeType()!==Node.ELEMENT_NODE) -return null;var id=node.getAttribute('id');if(optimized){if(id) -return new Components.DOMNodePathStep(idSelector(id),true);var nodeNameLower=node.nodeName().toLowerCase();if(nodeNameLower==='body'||nodeNameLower==='head'||nodeNameLower==='html') -return new Components.DOMNodePathStep(node.nodeNameInCorrectCase(),true);} -var nodeName=node.nodeNameInCorrectCase();if(id) -return new Components.DOMNodePathStep(nodeName+idSelector(id),true);var parent=node.parentNode;if(!parent||parent.nodeType()===Node.DOCUMENT_NODE) -return new Components.DOMNodePathStep(nodeName,true);function prefixedElementClassNames(node){var classAttribute=node.getAttribute('class');if(!classAttribute) -return[];return classAttribute.split(/\s+/g).filter(Boolean).map(function(name){return'$'+name;});} -function idSelector(id){return'#'+escapeIdentifierIfNeeded(id);} -function escapeIdentifierIfNeeded(ident){if(isCSSIdentifier(ident)) -return ident;var shouldEscapeFirst=/^(?:[0-9]|-[0-9-]?)/.test(ident);var lastIndex=ident.length-1;return ident.replace(/./g,function(c,i){return((shouldEscapeFirst&&i===0)||!isCSSIdentChar(c))?escapeAsciiChar(c,i===lastIndex):c;});} -function escapeAsciiChar(c,isLast){return'\\'+toHexByte(c)+(isLast?'':' ');} -function toHexByte(c){var hexByte=c.charCodeAt(0).toString(16);if(hexByte.length===1) -hexByte='0'+hexByte;return hexByte;} -function isCSSIdentChar(c){if(/[a-zA-Z0-9_-]/.test(c)) -return true;return c.charCodeAt(0)>=0xA0;} -function isCSSIdentifier(value){return/^-{0,2}[a-zA-Z_][a-zA-Z0-9_-]*$/.test(value);} -var prefixedOwnClassNamesArray=prefixedElementClassNames(node);var needsClassNames=false;var needsNthChild=false;var ownIndex=-1;var elementIndex=-1;var siblings=parent.children();for(var i=0;(ownIndex===-1||!needsNthChild)&&i<siblings.length;++i){var sibling=siblings[i];if(sibling.nodeType()!==Node.ELEMENT_NODE) -continue;elementIndex+=1;if(sibling===node){ownIndex=elementIndex;continue;} -if(needsNthChild) -continue;if(sibling.nodeNameInCorrectCase()!==nodeName) -continue;needsClassNames=true;var ownClassNames=new Set(prefixedOwnClassNamesArray);if(!ownClassNames.size){needsNthChild=true;continue;} -var siblingClassNamesArray=prefixedElementClassNames(sibling);for(var j=0;j<siblingClassNamesArray.length;++j){var siblingClass=siblingClassNamesArray[j];if(!ownClassNames.has(siblingClass)) -continue;ownClassNames.delete(siblingClass);if(!ownClassNames.size){needsNthChild=true;break;}}} -var result=nodeName;if(isTargetNode&&nodeName.toLowerCase()==='input'&&node.getAttribute('type')&&!node.getAttribute('id')&&!node.getAttribute('class')) -result+='[type="'+node.getAttribute('type')+'"]';if(needsNthChild){result+=':nth-child('+(ownIndex+1)+')';}else if(needsClassNames){for(var prefixedName of prefixedOwnClassNamesArray) -result+='.'+escapeIdentifierIfNeeded(prefixedName.substr(1));} -return new Components.DOMNodePathStep(result,false);};Components.DOMPresentationUtils.xPath=function(node,optimized){if(node.nodeType()===Node.DOCUMENT_NODE) -return'/';var steps=[];var contextNode=node;while(contextNode){var step=Components.DOMPresentationUtils._xPathValue(contextNode,optimized);if(!step) -break;steps.push(step);if(step.optimized) -break;contextNode=contextNode.parentNode;} -steps.reverse();return(steps.length&&steps[0].optimized?'':'/')+steps.join('/');};Components.DOMPresentationUtils._xPathValue=function(node,optimized){var ownValue;var ownIndex=Components.DOMPresentationUtils._xPathIndex(node);if(ownIndex===-1) -return null;switch(node.nodeType()){case Node.ELEMENT_NODE:if(optimized&&node.getAttribute('id')) -return new Components.DOMNodePathStep('//*[@id="'+node.getAttribute('id')+'"]',true);ownValue=node.localName();break;case Node.ATTRIBUTE_NODE:ownValue='@'+node.nodeName();break;case Node.TEXT_NODE:case Node.CDATA_SECTION_NODE:ownValue='text()';break;case Node.PROCESSING_INSTRUCTION_NODE:ownValue='processing-instruction()';break;case Node.COMMENT_NODE:ownValue='comment()';break;case Node.DOCUMENT_NODE:ownValue='';break;default:ownValue='';break;} -if(ownIndex>0) -ownValue+='['+ownIndex+']';return new Components.DOMNodePathStep(ownValue,node.nodeType()===Node.DOCUMENT_NODE);};Components.DOMPresentationUtils._xPathIndex=function(node){function areNodesSimilar(left,right){if(left===right) -return true;if(left.nodeType()===Node.ELEMENT_NODE&&right.nodeType()===Node.ELEMENT_NODE) -return left.localName()===right.localName();if(left.nodeType()===right.nodeType()) -return true;var leftType=left.nodeType()===Node.CDATA_SECTION_NODE?Node.TEXT_NODE:left.nodeType();var rightType=right.nodeType()===Node.CDATA_SECTION_NODE?Node.TEXT_NODE:right.nodeType();return leftType===rightType;} -var siblings=node.parentNode?node.parentNode.children():null;if(!siblings) -return 0;var hasSameNamedElements;for(var i=0;i<siblings.length;++i){if(areNodesSimilar(node,siblings[i])&&siblings[i]!==node){hasSameNamedElements=true;break;}} -if(!hasSameNamedElements) -return 0;var ownIndex=1;for(var i=0;i<siblings.length;++i){if(areNodesSimilar(node,siblings[i])){if(siblings[i]===node) -return ownIndex;++ownIndex;}} -return-1;};Components.DOMNodePathStep=class{constructor(value,optimized){this.value=value;this.optimized=optimized||false;} -toString(){return this.value;}};Components.DOMPresentationUtils.MarkerDecorator=function(){};Components.DOMPresentationUtils.MarkerDecorator.prototype={decorate(node){}};Components.DOMPresentationUtils.GenericDecorator=class{constructor(extension){this._title=Common.UIString(extension.title());this._color=extension.descriptor()['color'];} -decorate(node){return{title:this._title,color:this._color};}};;Components.DockController=class extends Common.Object{constructor(canDock){super();this._canDock=canDock;this._closeButton=new UI.ToolbarButton(Common.UIString('Close'),'largeicon-delete');this._closeButton.addEventListener(UI.ToolbarButton.Events.Click,InspectorFrontendHost.closeWindow.bind(InspectorFrontendHost));if(!canDock){this._dockSide=Components.DockController.State.Undocked;this._closeButton.setVisible(false);return;} -this._states=[Components.DockController.State.DockedToRight,Components.DockController.State.DockedToBottom,Components.DockController.State.DockedToLeft,Components.DockController.State.Undocked];this._currentDockStateSetting=Common.settings.moduleSetting('currentDockState');this._currentDockStateSetting.addChangeListener(this._dockSideChanged,this);this._lastDockStateSetting=Common.settings.createSetting('lastDockState','bottom');if(this._states.indexOf(this._currentDockStateSetting.get())===-1) -this._currentDockStateSetting.set('right');if(this._states.indexOf(this._lastDockStateSetting.get())===-1) -this._currentDockStateSetting.set('bottom');} -initialize(){if(!this._canDock) -return;this._titles=[Common.UIString('Dock to right'),Common.UIString('Dock to bottom'),Common.UIString('Dock to left'),Common.UIString('Undock into separate window')];this._dockSideChanged();} -_dockSideChanged(){this.setDockSide(this._currentDockStateSetting.get());} -dockSide(){return this._dockSide;} -canDock(){return this._canDock;} -isVertical(){return this._dockSide===Components.DockController.State.DockedToRight||this._dockSide===Components.DockController.State.DockedToLeft;} -setDockSide(dockSide){if(this._states.indexOf(dockSide)===-1) -dockSide=this._states[0];if(this._dockSide===dockSide) -return;if(this._dockSide) -this._lastDockStateSetting.set(this._dockSide);this._savedFocus=document.deepActiveElement();var eventData={from:this._dockSide,to:dockSide};this.dispatchEventToListeners(Components.DockController.Events.BeforeDockSideChanged,eventData);console.timeStamp('DockController.setIsDocked');this._dockSide=dockSide;this._currentDockStateSetting.set(dockSide);InspectorFrontendHost.setIsDocked(dockSide!==Components.DockController.State.Undocked,this._setIsDockedResponse.bind(this,eventData));this._closeButton.setVisible(this._dockSide!==Components.DockController.State.Undocked);this.dispatchEventToListeners(Components.DockController.Events.DockSideChanged,eventData);} -_setIsDockedResponse(eventData){this.dispatchEventToListeners(Components.DockController.Events.AfterDockSideChanged,eventData);if(this._savedFocus){this._savedFocus.focus();this._savedFocus=null;}} -_toggleDockSide(){if(this._lastDockStateSetting.get()===this._currentDockStateSetting.get()){var index=this._states.indexOf(this._currentDockStateSetting.get())||0;this._lastDockStateSetting.set(this._states[(index+1)%this._states.length]);} -this.setDockSide(this._lastDockStateSetting.get());}};Components.DockController.State={DockedToBottom:'bottom',DockedToRight:'right',DockedToLeft:'left',Undocked:'undocked'};Components.DockController.Events={BeforeDockSideChanged:Symbol('BeforeDockSideChanged'),DockSideChanged:Symbol('DockSideChanged'),AfterDockSideChanged:Symbol('AfterDockSideChanged')};Components.DockController.ToggleDockActionDelegate=class{handleAction(context,actionId){Components.dockController._toggleDockSide();return true;}};Components.DockController.CloseButtonProvider=class{item(){return Components.dockController._closeButton;}};Components.dockController;;Components.Linkifier=class{constructor(maxLengthForDisplayedURLs,useLinkDecorator){this._maxLength=maxLengthForDisplayedURLs||UI.MaxLengthForDisplayedURLs;this._anchorsByTarget=new Map();this._locationPoolByTarget=new Map();this._useLinkDecorator=!!useLinkDecorator;Components.Linkifier._instances.add(this);SDK.targetManager.observeTargets(this);} -static setLinkDecorator(decorator){console.assert(!Components.Linkifier._decorator,'Cannot re-register link decorator.');Components.Linkifier._decorator=decorator;decorator.addEventListener(Components.LinkDecorator.Events.LinkIconChanged,onLinkIconChanged);for(var linkifier of Components.Linkifier._instances) -linkifier._updateAllAnchorDecorations();function onLinkIconChanged(event){var uiSourceCode=(event.data);var links=uiSourceCode[Components.Linkifier._sourceCodeAnchors]||[];for(var link of links) -Components.Linkifier._updateLinkDecorations(link);}} -_updateAllAnchorDecorations(){for(var anchors of this._anchorsByTarget.values()){for(var anchor of anchors) -Components.Linkifier._updateLinkDecorations(anchor);}} -static _bindUILocation(anchor,uiLocation){Components.Linkifier._linkInfo(anchor).uiLocation=uiLocation;if(!uiLocation) -return;var uiSourceCode=uiLocation.uiSourceCode;var sourceCodeAnchors=uiSourceCode[Components.Linkifier._sourceCodeAnchors];if(!sourceCodeAnchors){sourceCodeAnchors=new Set();uiSourceCode[Components.Linkifier._sourceCodeAnchors]=sourceCodeAnchors;} -sourceCodeAnchors.add(anchor);} -static _unbindUILocation(anchor){var info=Components.Linkifier._linkInfo(anchor);if(!info.uiLocation) -return;var uiSourceCode=info.uiLocation.uiSourceCode;info.uiLocation=null;var sourceCodeAnchors=uiSourceCode[Components.Linkifier._sourceCodeAnchors];if(sourceCodeAnchors) -sourceCodeAnchors.delete(anchor);} -targetAdded(target){this._anchorsByTarget.set(target,[]);this._locationPoolByTarget.set(target,new Bindings.LiveLocationPool());} -targetRemoved(target){var locationPool=(this._locationPoolByTarget.remove(target));locationPool.disposeAll();var anchors=this._anchorsByTarget.remove(target);for(var anchor of anchors){var info=Components.Linkifier._linkInfo(anchor);info.liveLocation=null;Components.Linkifier._unbindUILocation(anchor);if(info.fallback){anchor.href=info.fallback.href;anchor.title=info.fallback.title;anchor.className=info.fallback.className;anchor.textContent=info.fallback.textContent;anchor[Components.Linkifier._infoSymbol]=info.fallback[Components.Linkifier._infoSymbol];}}} -maybeLinkifyScriptLocation(target,scriptId,sourceURL,lineNumber,columnNumber,classes){var fallbackAnchor=null;if(sourceURL){fallbackAnchor=Components.Linkifier.linkifyURL(sourceURL,{className:classes,lineNumber:lineNumber,columnNumber:columnNumber,maxLength:this._maxLength});} -if(!target||target.isDisposed()) -return fallbackAnchor;var debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel) -return fallbackAnchor;var rawLocation=(scriptId?debuggerModel.createRawLocationByScriptId(scriptId,lineNumber,columnNumber||0):null)||debuggerModel.createRawLocationByURL(sourceURL,lineNumber,columnNumber||0);if(!rawLocation) -return fallbackAnchor;var anchor=Components.Linkifier._createLink('',classes||'');var info=Components.Linkifier._linkInfo(anchor);info.enableDecorator=this._useLinkDecorator;info.fallback=fallbackAnchor;info.liveLocation=Bindings.debuggerWorkspaceBinding.createLiveLocation(rawLocation,this._updateAnchor.bind(this,anchor),(this._locationPoolByTarget.get(rawLocation.debuggerModel.target())));var anchors=(this._anchorsByTarget.get(rawLocation.debuggerModel.target()));anchors.push(anchor);return anchor;} -linkifyScriptLocation(target,scriptId,sourceURL,lineNumber,columnNumber,classes){var scriptLink=this.maybeLinkifyScriptLocation(target,scriptId,sourceURL,lineNumber,columnNumber,classes);return scriptLink||Components.Linkifier.linkifyURL(sourceURL,{className:classes,lineNumber:lineNumber,columnNumber:columnNumber,maxLength:this._maxLength});} -linkifyRawLocation(rawLocation,fallbackUrl,classes){return this.linkifyScriptLocation(rawLocation.debuggerModel.target(),rawLocation.scriptId,fallbackUrl,rawLocation.lineNumber,rawLocation.columnNumber,classes);} -maybeLinkifyConsoleCallFrame(target,callFrame,classes){return this.maybeLinkifyScriptLocation(target,callFrame.scriptId,callFrame.url,callFrame.lineNumber,callFrame.columnNumber,classes);} -linkifyStackTraceTopFrame(target,stackTrace,classes){console.assert(stackTrace.callFrames&&stackTrace.callFrames.length);var topFrame=stackTrace.callFrames[0];var fallbackAnchor=Components.Linkifier.linkifyURL(topFrame.url,{className:classes,lineNumber:topFrame.lineNumber,columnNumber:topFrame.columnNumber,maxLength:this._maxLength});if(target.isDisposed()) -return fallbackAnchor;var debuggerModel=target.model(SDK.DebuggerModel);var rawLocations=debuggerModel.createRawLocationsByStackTrace(stackTrace);if(rawLocations.length===0) -return fallbackAnchor;var anchor=Components.Linkifier._createLink('',classes||'');var info=Components.Linkifier._linkInfo(anchor);info.enableDecorator=this._useLinkDecorator;info.fallback=fallbackAnchor;info.liveLocation=Bindings.debuggerWorkspaceBinding.createStackTraceTopFrameLiveLocation(rawLocations,this._updateAnchor.bind(this,anchor),(this._locationPoolByTarget.get(target)));var anchors=(this._anchorsByTarget.get(target));anchors.push(anchor);return anchor;} -linkifyCSSLocation(rawLocation,classes){var anchor=Components.Linkifier._createLink('',classes||'');var info=Components.Linkifier._linkInfo(anchor);info.enableDecorator=this._useLinkDecorator;info.liveLocation=Bindings.cssWorkspaceBinding.createLiveLocation(rawLocation,this._updateAnchor.bind(this,anchor),(this._locationPoolByTarget.get(rawLocation.cssModel().target())));var anchors=(this._anchorsByTarget.get(rawLocation.cssModel().target()));anchors.push(anchor);return anchor;} -reset(){for(var target of this._anchorsByTarget.keysArray()){this.targetRemoved(target);this.targetAdded(target);}} -dispose(){for(var target of this._anchorsByTarget.keysArray()) -this.targetRemoved(target);SDK.targetManager.unobserveTargets(this);Components.Linkifier._instances.delete(this);} -_updateAnchor(anchor,liveLocation){Components.Linkifier._unbindUILocation(anchor);var uiLocation=liveLocation.uiLocation();if(!uiLocation) -return;Components.Linkifier._bindUILocation(anchor,uiLocation);var text=uiLocation.linkText(true);Components.Linkifier._setTrimmedText(anchor,text,this._maxLength);var titleText=uiLocation.uiSourceCode.url();if(typeof uiLocation.lineNumber==='number') -titleText+=':'+(uiLocation.lineNumber+1);anchor.title=titleText;anchor.classList.toggle('webkit-html-blackbox-link',liveLocation.isBlackboxed());Components.Linkifier._updateLinkDecorations(anchor);} -static _updateLinkDecorations(anchor){var info=Components.Linkifier._linkInfo(anchor);if(!info||!info.enableDecorator) -return;if(!Components.Linkifier._decorator||!info.uiLocation) -return;if(info.icon&&info.icon.parentElement) -anchor.removeChild(info.icon);var icon=Components.Linkifier._decorator.linkIcon(info.uiLocation.uiSourceCode);if(icon){icon.style.setProperty('margin-right','2px');anchor.insertBefore(icon,anchor.firstChild);} -info.icon=icon;} -static linkifyURL(url,options){options=options||{};var text=options.text;var className=options.className||'';var lineNumber=options.lineNumber;var columnNumber=options.columnNumber;var preventClick=options.preventClick;var maxLength=options.maxLength||UI.MaxLengthForDisplayedURLs;if(!url||url.trim().toLowerCase().startsWith('javascript:')){var element=createElementWithClass('span',className);element.textContent=text||url||Common.UIString('(unknown)');return element;} -var linkText=text||Bindings.displayNameForURL(url);if(typeof lineNumber==='number'&&!text) -linkText+=':'+(lineNumber+1);var title=linkText!==url?url:'';var link=Components.Linkifier._createLink(linkText,className,maxLength,title,url,preventClick);var info=Components.Linkifier._linkInfo(link);if(typeof lineNumber==='number') -info.lineNumber=lineNumber;if(typeof columnNumber==='number') -info.columnNumber=columnNumber;return link;} -static linkifyRevealable(revealable,text,fallbackHref){var link=Components.Linkifier._createLink(text,'',UI.MaxLengthForDisplayedURLs,undefined,fallbackHref);Components.Linkifier._linkInfo(link).revealable=revealable;return link;} -static _createLink(text,className,maxLength,title,href,preventClick){var link=createElementWithClass('span',className);link.classList.add('devtools-link');if(title) -link.title=title;if(href) -link.href=href;Components.Linkifier._setTrimmedText(link,text,maxLength);link[Components.Linkifier._infoSymbol]={icon:null,enableDecorator:false,uiLocation:null,liveLocation:null,url:href||null,lineNumber:null,columnNumber:null,revealable:null,fallback:null};if(!preventClick) -link.addEventListener('click',Components.Linkifier._handleClick,false);else -link.classList.add('devtools-link-prevent-click');return link;} -static _setTrimmedText(link,text,maxLength){link.removeChildren();if(maxLength&&text.length>maxLength){var middleSplit=splitMiddle(text,maxLength);appendTextWithoutHashes(middleSplit[0]);appendHiddenText(middleSplit[1]);appendTextWithoutHashes(middleSplit[2]);}else{appendTextWithoutHashes(text);} -function appendHiddenText(string){var ellipsisNode=link.createChild('span','devtools-link-ellipsis').createTextChild('\u2026');ellipsisNode[Components.Linkifier._untruncatedNodeTextSymbol]=string;} -function appendTextWithoutHashes(string){var hashSplit=TextUtils.TextUtils.splitStringByRegexes(string,[/[a-f0-9]{20,}/g]);for(var match of hashSplit){if(match.regexIndex===-1){link.createTextChild(match.value);}else{link.createTextChild(match.value.substring(0,7));appendHiddenText(match.value.substring(7));}}} -function splitMiddle(string,maxLength){var leftIndex=Math.floor(maxLength/2);var rightIndex=string.length-Math.ceil(maxLength/2)+1;if(string.codePointAt(rightIndex-1)>=0x10000){rightIndex++;leftIndex++;} -if(leftIndex>0&&string.codePointAt(leftIndex-1)>=0x10000) -leftIndex--;return[string.substring(0,leftIndex),string.substring(leftIndex,rightIndex),string.substring(rightIndex)];}} -static untruncatedNodeText(node){return node[Components.Linkifier._untruncatedNodeTextSymbol]||node.textContent;} -static _linkInfo(link){return(link?link[Components.Linkifier._infoSymbol]||null:null);} -static _handleClick(event){var link=(event.currentTarget);event.consume(true);if(UI.isBeingEdited((event.target))) -return;var actions=Components.Linkifier._linkActions(link);if(actions.length) -actions[0].handler.call(null);} -static _linkHandlerSetting(){if(!Components.Linkifier._linkHandlerSettingInstance){Components.Linkifier._linkHandlerSettingInstance=Common.settings.createSetting('openLinkHandler',Common.UIString('auto'));} -return Components.Linkifier._linkHandlerSettingInstance;} -static registerLinkHandler(title,handler){Components.Linkifier._linkHandlers.set(title,handler);self.runtime.sharedInstance(Components.Linkifier.LinkHandlerSettingUI)._update();} -static unregisterLinkHandler(title){Components.Linkifier._linkHandlers.delete(title);self.runtime.sharedInstance(Components.Linkifier.LinkHandlerSettingUI)._update();} -static _linkActions(link){var info=Components.Linkifier._linkInfo(link);var result=[];if(!info) -return result;var url='';var uiLocation=null;if(info.uiLocation){uiLocation=info.uiLocation;url=uiLocation.uiSourceCode.contentURL();}else if(info.url){url=info.url;var uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);uiLocation=uiSourceCode?uiSourceCode.uiLocation(info.lineNumber||0,info.columnNumber||0):null;} -var resource=url?Bindings.resourceForURL(url):null;var request=url?NetworkLog.networkLog.requestForURL(url):null;var contentProvider=uiLocation?uiLocation.uiSourceCode:resource;if(info.revealable){result.push({section:'reveal',title:Common.UIString('Reveal'),handler:()=>Common.Revealer.reveal(info.revealable)});} -if(uiLocation){result.push({section:'reveal',title:Common.UIString('Open in Sources panel'),handler:()=>Common.Revealer.reveal(uiLocation)});} -if(resource){result.push({section:'reveal',title:Common.UIString('Open in Application panel'),handler:()=>Common.Revealer.reveal(resource)});} -if(request){result.push({section:'reveal',title:Common.UIString('Open in Network panel'),handler:()=>Common.Revealer.reveal(request)});} -if(contentProvider){var lineNumber=uiLocation?uiLocation.lineNumber:info.lineNumber||0;for(var title of Components.Linkifier._linkHandlers.keys()){var handler=Components.Linkifier._linkHandlers.get(title);var action={section:'reveal',title:Common.UIString('Open using %s',title),handler:handler.bind(null,contentProvider,lineNumber)};if(title===Components.Linkifier._linkHandlerSetting().get()) -result.unshift(action);else -result.push(action);}} -if(resource||info.url){result.push({section:'reveal',title:UI.openLinkExternallyLabel(),handler:()=>InspectorFrontendHost.openInNewTab(url)});result.push({section:'clipboard',title:UI.copyLinkAddressLabel(),handler:()=>InspectorFrontendHost.copyText(url)});} -return result;}};Components.Linkifier._instances=new Set();Components.Linkifier._decorator=null;Components.Linkifier._sourceCodeAnchors=Symbol('Linkifier.anchors');Components.Linkifier._infoSymbol=Symbol('Linkifier.info');Components.Linkifier._untruncatedNodeTextSymbol=Symbol('Linkifier.untruncatedNodeText');Components._LinkInfo;Components.LinkifyURLOptions;Components.Linkifier.MaxLengthToIgnoreLinkifier=10000;Components.Linkifier.LinkHandler;Components.Linkifier._linkHandlers=new Map();Components.LinkDecorator=function(){};Components.LinkDecorator.prototype={linkIcon(uiSourceCode){}};Components.LinkDecorator.Events={LinkIconChanged:Symbol('LinkIconChanged')};Components.Linkifier.LinkContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){var targetNode=(target);while(targetNode&&!targetNode[Components.Linkifier._infoSymbol]) -targetNode=targetNode.parentNodeOrShadowHost();var link=(targetNode);var actions=Components.Linkifier._linkActions(link);for(var action of actions) -contextMenu.section(action.section).appendItem(action.title,action.handler);}};Components.Linkifier.LinkHandlerSettingUI=class{constructor(){this._element=createElementWithClass('select','chrome-select');this._element.addEventListener('change',this._onChange.bind(this),false);this._update();} -_update(){this._element.removeChildren();var names=Components.Linkifier._linkHandlers.keysArray();names.unshift(Common.UIString('auto'));for(var name of names){var option=createElement('option');option.textContent=name;option.selected=name===Components.Linkifier._linkHandlerSetting().get();this._element.appendChild(option);} -this._element.disabled=names.length<=1;} -_onChange(event){var value=event.target.value;Components.Linkifier._linkHandlerSetting().set(value);} -settingElement(){return UI.SettingsUI.createCustomSetting(Common.UIString('Link handling:'),this._element);}};Components.Linkifier.ContentProviderContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){var contentProvider=(target);if(!contentProvider.contentURL()) -return;contextMenu.revealSection().appendItem(UI.openLinkExternallyLabel(),()=>InspectorFrontendHost.openInNewTab(contentProvider.contentURL()));for(var title of Components.Linkifier._linkHandlers.keys()){var handler=Components.Linkifier._linkHandlers.get(title);contextMenu.revealSection().appendItem(Common.UIString('Open using %s',title),handler.bind(null,contentProvider,0));} -if(contentProvider instanceof SDK.NetworkRequest) -return;contextMenu.clipboardSection().appendItem(UI.copyLinkAddressLabel(),()=>InspectorFrontendHost.copyText(contentProvider.contentURL()));}};;Components.reload=function(){if(Components.dockController.canDock()&&Components.dockController.dockSide()===Components.DockController.State.Undocked) -InspectorFrontendHost.setIsDocked(true,function(){});window.location.reload();};;self['Persistence']=self['Persistence']||{};Persistence.IsolatedFileSystem=class{constructor(manager,path,embedderPath,domFileSystem,type){this._manager=manager;this._path=path;this._embedderPath=embedderPath;this._domFileSystem=domFileSystem;this._type=type;this._excludedFoldersSetting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});this._excludedFolders=new Set(this._excludedFoldersSetting.get()[path]||[]);this._initialFilePaths=new Set();this._initialGitFolders=new Set();} -static create(manager,path,embedderPath,type,name,rootURL){var domFileSystem=InspectorFrontendHost.isolatedFileSystem(name,rootURL);if(!domFileSystem) -return Promise.resolve((null));var fileSystem=new Persistence.IsolatedFileSystem(manager,path,embedderPath,domFileSystem,type);return fileSystem._initializeFilePaths().then(()=>fileSystem).catchException((null));} -static errorMessage(error){return Common.UIString('File system error: %s',error.message);} -getMetadata(path){var fulfill;var promise=new Promise(f=>fulfill=f);this._domFileSystem.root.getFile(path,undefined,fileEntryLoaded,errorHandler);return promise;function fileEntryLoaded(entry){entry.getMetadata(fulfill,errorHandler);} -function errorHandler(error){var errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when getting file metadata \''+path);fulfill(null);}} -initialFilePaths(){return this._initialFilePaths.valuesArray();} -initialGitFolders(){return this._initialGitFolders.valuesArray();} -path(){return this._path;} -embedderPath(){return this._embedderPath;} -type(){return this._type;} -_initializeFilePaths(){var fulfill;var promise=new Promise(x=>fulfill=x);var pendingRequests=1;var boundInnerCallback=innerCallback.bind(this);this._requestEntries('',boundInnerCallback);return promise;function innerCallback(entries){for(var i=0;i<entries.length;++i){var entry=entries[i];if(!entry.isDirectory){if(this._isFileExcluded(entry.fullPath)) -continue;this._initialFilePaths.add(entry.fullPath.substr(1));}else{if(entry.fullPath.endsWith('/.git')){var lastSlash=entry.fullPath.lastIndexOf('/');var parentFolder=entry.fullPath.substring(1,lastSlash);this._initialGitFolders.add(parentFolder);} -if(this._isFileExcluded(entry.fullPath+'/')) -continue;++pendingRequests;this._requestEntries(entry.fullPath,boundInnerCallback);}} -if((--pendingRequests===0)) -fulfill();}} -async _createFoldersIfNotExist(folderPath){var dirEntry=await new Promise(resolve=>this._domFileSystem.root.getDirectory(folderPath,undefined,resolve,()=>resolve(null)));if(dirEntry) -return dirEntry;var paths=folderPath.split('/');var activePath='';for(var path of paths){activePath=activePath+'/'+path;dirEntry=await this._innerCreateFolderIfNeeded(activePath);if(!dirEntry) -return null;} -return dirEntry;} -_innerCreateFolderIfNeeded(path){return new Promise(resolve=>{this._domFileSystem.root.getDirectory(path,{create:true},dirEntry=>resolve(dirEntry),error=>{var errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' trying to create directory \''+path+'\'');resolve(null);});});} -async createFile(path,name){var dirEntry=await this._createFoldersIfNotExist(path);if(!dirEntry) -return null;var fileEntry=await createFileCandidate.call(this,name||'NewFile');if(!fileEntry) -return null;return fileEntry.fullPath.substr(1);function createFileCandidate(name,newFileIndex){return new Promise(resolve=>{var nameCandidate=name+(newFileIndex||'');dirEntry.getFile(nameCandidate,{create:true,exclusive:true},resolve,error=>{if(error.name==='InvalidModificationError'){resolve(createFileCandidate.call(this,name,(newFileIndex?newFileIndex+1:1)));return;} -var errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when testing if file exists \''+(this._path+'/'+path+'/'+nameCandidate)+'\'');resolve(null);});});}} -deleteFile(path){this._domFileSystem.root.getFile(path,undefined,fileEntryLoaded.bind(this),errorHandler.bind(this));function fileEntryLoaded(fileEntry){fileEntry.remove(fileEntryRemoved,errorHandler.bind(this));} -function fileEntryRemoved(){} -function errorHandler(error){var errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when deleting file \''+(this._path+'/'+path)+'\'');}} -requestFileBlob(path){return new Promise(resolve=>{this._domFileSystem.root.getFile(path,undefined,entry=>{entry.file(resolve,errorHandler.bind(this));},errorHandler.bind(this));function errorHandler(error){if(error.name==='NotFoundError'){resolve(null);return;} -var errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when getting content for file \''+(this._path+'/'+path)+'\'');resolve(null);}});} -async requestFileContent(path,callback){var blob=await this.requestFileBlob(path);if(!blob) -return null;var reader=new FileReader();var extension=Common.ParsedURL.extractExtension(path);var encoded=Persistence.IsolatedFileSystem.BinaryExtensions.has(extension);reader.onloadend=content=>{if(reader.error){console.error('Can\'t read file: '+path+': '+reader.error);callback(null,false);return;} -var result;try{result=reader.result;}catch(e){result=null;console.error('Can\'t read file: '+path+': '+e);} -if(result===undefined||result===null){callback(null,false);return;} -callback(encoded?btoa(result):result,encoded);};if(encoded) -reader.readAsBinaryString(blob);else -reader.readAsText(blob);} -setFileContent(path,content,isBase64,callback){Host.userMetrics.actionTaken(Host.UserMetrics.Action.FileSavedInWorkspace);this._domFileSystem.root.getFile(path,{create:true},fileEntryLoaded.bind(this),errorHandler.bind(this));function fileEntryLoaded(entry){entry.createWriter(fileWriterCreated.bind(this),errorHandler.bind(this));} -async function fileWriterCreated(fileWriter){fileWriter.onerror=errorHandler.bind(this);fileWriter.onwriteend=fileWritten;var blob;if(isBase64) -blob=await(await fetch(`data:application/octet-stream;base64,${content}`)).blob();else -blob=new Blob([content],{type:'text/plain'});fileWriter.write(blob);function fileWritten(){fileWriter.onwriteend=callback;fileWriter.truncate(blob.size);}} -function errorHandler(error){var errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when setting content for file \''+(this._path+'/'+path)+'\'');callback();}} -renameFile(path,newName,callback){newName=newName?newName.trim():newName;if(!newName||newName.indexOf('/')!==-1){callback(false);return;} -var fileEntry;var dirEntry;this._domFileSystem.root.getFile(path,undefined,fileEntryLoaded.bind(this),errorHandler.bind(this));function fileEntryLoaded(entry){if(entry.name===newName){callback(false);return;} -fileEntry=entry;fileEntry.getParent(dirEntryLoaded.bind(this),errorHandler.bind(this));} -function dirEntryLoaded(entry){dirEntry=entry;dirEntry.getFile(newName,null,newFileEntryLoaded,newFileEntryLoadErrorHandler.bind(this));} -function newFileEntryLoaded(entry){callback(false);} -function newFileEntryLoadErrorHandler(error){if(error.name!=='NotFoundError'){callback(false);return;} -fileEntry.moveTo(dirEntry,newName,fileRenamed,errorHandler.bind(this));} -function fileRenamed(entry){callback(true,entry.name);} -function errorHandler(error){var errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when renaming file \''+(this._path+'/'+path)+'\' to \''+newName+'\'');callback(false);}} -_readDirectory(dirEntry,callback){var dirReader=dirEntry.createReader();var entries=[];function innerCallback(results){if(!results.length){callback(entries.sort());}else{entries=entries.concat(toArray(results));dirReader.readEntries(innerCallback,errorHandler);}} -function toArray(list){return Array.prototype.slice.call(list||[],0);} -dirReader.readEntries(innerCallback,errorHandler);function errorHandler(error){var errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when reading directory \''+dirEntry.fullPath+'\'');callback([]);}} -_requestEntries(path,callback){this._domFileSystem.root.getDirectory(path,undefined,innerCallback.bind(this),errorHandler);function innerCallback(dirEntry){this._readDirectory(dirEntry,callback);} -function errorHandler(error){var errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when requesting entry \''+path+'\'');callback([]);}} -_saveExcludedFolders(){var settingValue=this._excludedFoldersSetting.get();settingValue[this._path]=this._excludedFolders.valuesArray();this._excludedFoldersSetting.set(settingValue);} -addExcludedFolder(path){this._excludedFolders.add(path);this._saveExcludedFolders();this._manager.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderAdded,path);} -removeExcludedFolder(path){this._excludedFolders.delete(path);this._saveExcludedFolders();this._manager.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderRemoved,path);} -fileSystemRemoved(){var settingValue=this._excludedFoldersSetting.get();delete settingValue[this._path];this._excludedFoldersSetting.set(settingValue);} -_isFileExcluded(folderPath){if(this._excludedFolders.has(folderPath)) -return true;var regex=this._manager.workspaceFolderExcludePatternSetting().asRegExp();return!!(regex&®ex.test(folderPath));} -excludedFolders(){return this._excludedFolders;} -searchInPath(query,progress){return new Promise(resolve=>{var requestId=this._manager.registerCallback(innerCallback);InspectorFrontendHost.searchInPath(requestId,this._embedderPath,query);function innerCallback(files){resolve(files.map(path=>Common.ParsedURL.platformPathToURL(path)));progress.worked(1);}});} -indexContent(progress){progress.setTotalWork(1);var requestId=this._manager.registerProgress(progress);InspectorFrontendHost.indexPath(requestId,this._embedderPath);}};Persistence.IsolatedFileSystem.ImageExtensions=new Set(['jpeg','jpg','svg','gif','webp','png','ico','tiff','tif','bmp']);Persistence.IsolatedFileSystem.BinaryExtensions=new Set(['cmd','com','exe','a','ar','iso','tar','bz2','gz','lz','lzma','z','7z','apk','arc','cab','dmg','jar','pak','rar','zip','3gp','aac','aiff','flac','m4a','mmf','mp3','ogg','oga','raw','sln','wav','wma','webm','mkv','flv','vob','ogv','gifv','avi','mov','qt','mp4','m4p','m4v','mpg','mpeg','jpeg','jpg','gif','webp','png','ico','tiff','tif','bmp']);;Persistence.IsolatedFileSystemManager=class extends Common.Object{constructor(){super();this._fileSystems=new Map();this._callbacks=new Map();this._progresses=new Map();InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemRemoved,this._onFileSystemRemoved,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemAdded,this._onFileSystemAdded,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,this._onFileSystemFilesChanged,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingTotalWorkCalculated,this._onIndexingTotalWorkCalculated,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingWorked,this._onIndexingWorked,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingDone,this._onIndexingDone,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SearchCompleted,this._onSearchCompleted,this);this._initExcludePatterSetting();this._fileSystemRequestResolve=null;this._fileSystemsLoadedPromise=this._requestFileSystems();} -_requestFileSystems(){var fulfill;var promise=new Promise(f=>fulfill=f);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemsLoaded,onFileSystemsLoaded,this);InspectorFrontendHost.requestFileSystems();return promise;function onFileSystemsLoaded(event){var fileSystems=(event.data);var promises=[];for(var i=0;i<fileSystems.length;++i) -promises.push(this._innerAddFileSystem(fileSystems[i],false));Promise.all(promises).then(onFileSystemsAdded);} -function onFileSystemsAdded(fileSystems){fulfill(fileSystems.filter(fs=>!!fs));}} -addFileSystem(type){return new Promise(resolve=>{this._fileSystemRequestResolve=resolve;InspectorFrontendHost.addFileSystem(type||'');});} -removeFileSystem(fileSystem){InspectorFrontendHost.removeFileSystem(fileSystem.embedderPath());} -waitForFileSystems(){return this._fileSystemsLoadedPromise;} -_innerAddFileSystem(fileSystem,dispatchEvent){var embedderPath=fileSystem.fileSystemPath;var fileSystemURL=Common.ParsedURL.platformPathToURL(fileSystem.fileSystemPath);var promise=Persistence.IsolatedFileSystem.create(this,fileSystemURL,embedderPath,fileSystem.type,fileSystem.fileSystemName,fileSystem.rootURL);return promise.then(storeFileSystem.bind(this));function storeFileSystem(fileSystem){if(!fileSystem) -return null;this._fileSystems.set(fileSystemURL,fileSystem);if(dispatchEvent) -this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,fileSystem);return fileSystem;}} -async _onFileSystemAdded(event){var errorMessage=(event.data['errorMessage']);var fileSystem=(event.data['fileSystem']);if(errorMessage){Common.console.error(Common.UIString('Unable to add filesystem: %s',errorMessage));if(!this._fileSystemRequestResolve) -return;this._fileSystemRequestResolve.call(null,null);this._fileSystemRequestResolve=null;}else if(fileSystem){fileSystem=await this._innerAddFileSystem(fileSystem,true);if(this._fileSystemRequestResolve){this._fileSystemRequestResolve.call(null,fileSystem);this._fileSystemRequestResolve=null;}}} -_onFileSystemRemoved(event){var embedderPath=(event.data);var fileSystemPath=Common.ParsedURL.platformPathToURL(embedderPath);var isolatedFileSystem=this._fileSystems.get(fileSystemPath);if(!isolatedFileSystem) -return;this._fileSystems.delete(fileSystemPath);isolatedFileSystem.fileSystemRemoved();this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,isolatedFileSystem);} -_onFileSystemFilesChanged(event){var paths=(event.data);var urlPaths={};urlPaths.changed=paths.changed.map(embedderPath=>Common.ParsedURL.platformPathToURL(embedderPath));urlPaths.added=paths.added.map(embedderPath=>Common.ParsedURL.platformPathToURL(embedderPath));urlPaths.removed=paths.removed.map(embedderPath=>Common.ParsedURL.platformPathToURL(embedderPath));this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemFilesChanged,urlPaths);} -fileSystems(){return this._fileSystems.valuesArray();} -fileSystem(fileSystemPath){return this._fileSystems.get(fileSystemPath)||null;} -_initExcludePatterSetting(){var defaultCommonExcludedFolders=['/node_modules/','/bower_components/','/\\.devtools','/\\.git/','/\\.sass-cache/','/\\.hg/','/\\.idea/','/\\.svn/','/\\.cache/','/\\.project/'];var defaultWinExcludedFolders=['/Thumbs.db$','/ehthumbs.db$','/Desktop.ini$','/\\$RECYCLE.BIN/'];var defaultMacExcludedFolders=['/\\.DS_Store$','/\\.Trashes$','/\\.Spotlight-V100$','/\\.AppleDouble$','/\\.LSOverride$','/Icon$','/\\._.*$'];var defaultLinuxExcludedFolders=['/.*~$'];var defaultExcludedFolders=defaultCommonExcludedFolders;if(Host.isWin()) -defaultExcludedFolders=defaultExcludedFolders.concat(defaultWinExcludedFolders);else if(Host.isMac()) -defaultExcludedFolders=defaultExcludedFolders.concat(defaultMacExcludedFolders);else -defaultExcludedFolders=defaultExcludedFolders.concat(defaultLinuxExcludedFolders);var defaultExcludedFoldersPattern=defaultExcludedFolders.join('|');this._workspaceFolderExcludePatternSetting=Common.settings.createRegExpSetting('workspaceFolderExcludePattern',defaultExcludedFoldersPattern,Host.isWin()?'i':'');} -workspaceFolderExcludePatternSetting(){return this._workspaceFolderExcludePatternSetting;} -registerCallback(callback){var requestId=++Persistence.IsolatedFileSystemManager._lastRequestId;this._callbacks.set(requestId,callback);return requestId;} -registerProgress(progress){var requestId=++Persistence.IsolatedFileSystemManager._lastRequestId;this._progresses.set(requestId,progress);return requestId;} -_onIndexingTotalWorkCalculated(event){var requestId=(event.data['requestId']);var totalWork=(event.data['totalWork']);var progress=this._progresses.get(requestId);if(!progress) -return;progress.setTotalWork(totalWork);} -_onIndexingWorked(event){var requestId=(event.data['requestId']);var worked=(event.data['worked']);var progress=this._progresses.get(requestId);if(!progress) -return;progress.worked(worked);if(progress.isCanceled()){InspectorFrontendHost.stopIndexing(requestId);this._onIndexingDone(event);}} -_onIndexingDone(event){var requestId=(event.data['requestId']);var progress=this._progresses.get(requestId);if(!progress) -return;progress.done();this._progresses.delete(requestId);} -_onSearchCompleted(event){var requestId=(event.data['requestId']);var files=(event.data['files']);var callback=this._callbacks.get(requestId);if(!callback) -return;callback.call(null,files);this._callbacks.delete(requestId);}};Persistence.IsolatedFileSystemManager.FileSystem;Persistence.IsolatedFileSystemManager.FilesChangedData;Persistence.IsolatedFileSystemManager.Events={FileSystemAdded:Symbol('FileSystemAdded'),FileSystemRemoved:Symbol('FileSystemRemoved'),FileSystemFilesChanged:Symbol('FileSystemFilesChanged'),ExcludedFolderAdded:Symbol('ExcludedFolderAdded'),ExcludedFolderRemoved:Symbol('ExcludedFolderRemoved')};Persistence.IsolatedFileSystemManager._lastRequestId=0;Persistence.isolatedFileSystemManager;;Persistence.FileSystemWorkspaceBinding=class{constructor(isolatedFileSystemManager,workspace){this._isolatedFileSystemManager=isolatedFileSystemManager;this._workspace=workspace;this._eventListeners=[this._isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,this._onFileSystemAdded,this),this._isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,this._onFileSystemRemoved,this),this._isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemFilesChanged,this._fileSystemFilesChanged,this)];this._boundFileSystems=new Map();this._isolatedFileSystemManager.waitForFileSystems().then(this._onFileSystemsLoaded.bind(this));} -static projectId(fileSystemPath){return fileSystemPath;} -static relativePath(uiSourceCode){var baseURL=(uiSourceCode.project())._fileSystemBaseURL;return uiSourceCode.url().substring(baseURL.length).split('/');} -static fileSystemType(project){var fileSystem=(project)._fileSystem;return fileSystem.type();} -static completeURL(project,relativePath){var fsProject=(project);return fsProject._fileSystemBaseURL+relativePath;} -static _contentTypeForExtension(extension){if(Persistence.FileSystemWorkspaceBinding._styleSheetExtensions.has(extension)) -return Common.resourceTypes.Stylesheet;if(Persistence.FileSystemWorkspaceBinding._documentExtensions.has(extension)) -return Common.resourceTypes.Document;if(Persistence.FileSystemWorkspaceBinding._imageExtensions.has(extension)) -return Common.resourceTypes.Image;if(Persistence.FileSystemWorkspaceBinding._scriptExtensions.has(extension)) -return Common.resourceTypes.Script;return Persistence.FileSystemWorkspaceBinding._binaryExtensions.has(extension)?Common.resourceTypes.Other:Common.resourceTypes.Document;} -static fileSystemPath(projectId){return projectId;} -fileSystemManager(){return this._isolatedFileSystemManager;} -_onFileSystemsLoaded(fileSystems){for(var fileSystem of fileSystems) -this._addFileSystem(fileSystem);} -_onFileSystemAdded(event){var fileSystem=(event.data);this._addFileSystem(fileSystem);} -_addFileSystem(fileSystem){var boundFileSystem=new Persistence.FileSystemWorkspaceBinding.FileSystem(this,fileSystem,this._workspace);this._boundFileSystems.set(fileSystem.path(),boundFileSystem);} -_onFileSystemRemoved(event){var fileSystem=(event.data);var boundFileSystem=this._boundFileSystems.get(fileSystem.path());boundFileSystem.dispose();this._boundFileSystems.remove(fileSystem.path());} -_fileSystemFilesChanged(event){var paths=(event.data);forEachFile.call(this,paths.changed,(path,fileSystem)=>fileSystem._fileChanged(path));forEachFile.call(this,paths.added,(path,fileSystem)=>fileSystem._fileChanged(path));forEachFile.call(this,paths.removed,(path,fileSystem)=>fileSystem.removeUISourceCode(path));function forEachFile(filePaths,callback){for(var filePath of filePaths){for(var fileSystemPath of this._boundFileSystems.keys()){if(!filePath.startsWith(fileSystemPath)) -continue;callback(filePath,this._boundFileSystems.get(fileSystemPath));}}}} -dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);for(var fileSystem of this._boundFileSystems.values()){fileSystem.dispose();this._boundFileSystems.remove(fileSystem._fileSystem.path());}}};Persistence.FileSystemWorkspaceBinding._styleSheetExtensions=new Set(['css','scss','sass','less']);Persistence.FileSystemWorkspaceBinding._documentExtensions=new Set(['htm','html','asp','aspx','phtml','jsp']);Persistence.FileSystemWorkspaceBinding._scriptExtensions=new Set(['asp','aspx','c','cc','cljs','coffee','cpp','cs','dart','java','js','jsp','jsx','h','m','mm','py','sh','ts','tsx','ls']);Persistence.FileSystemWorkspaceBinding._imageExtensions=Persistence.IsolatedFileSystem.ImageExtensions;Persistence.FileSystemWorkspaceBinding._binaryExtensions=Persistence.IsolatedFileSystem.BinaryExtensions;Persistence.FileSystemWorkspaceBinding.FileSystem=class extends Workspace.ProjectStore{constructor(fileSystemWorkspaceBinding,isolatedFileSystem,workspace){var fileSystemPath=isolatedFileSystem.path();var id=Persistence.FileSystemWorkspaceBinding.projectId(fileSystemPath);console.assert(!workspace.project(id));var displayName=fileSystemPath.substr(fileSystemPath.lastIndexOf('/')+1);super(workspace,id,Workspace.projectTypes.FileSystem,displayName);this._fileSystem=isolatedFileSystem;this._fileSystemBaseURL=this._fileSystem.path()+'/';this._fileSystemParentURL=this._fileSystemBaseURL.substr(0,fileSystemPath.lastIndexOf('/')+1);this._fileSystemWorkspaceBinding=fileSystemWorkspaceBinding;this._fileSystemPath=fileSystemPath;workspace.addProject(this);this.populate();} -fileSystemPath(){return this._fileSystemPath;} -mimeType(uiSourceCode){return Common.ResourceType.mimeFromURL(uiSourceCode.url())||'text/plain';} -initialGitFolders(){return this._fileSystem.initialGitFolders().map(folder=>this._fileSystemPath+'/'+folder);} -_filePathForUISourceCode(uiSourceCode){return uiSourceCode.url().substring(this._fileSystemPath.length);} -isServiceProject(){return false;} -requestMetadata(uiSourceCode){if(uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata]) -return uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata];var relativePath=this._filePathForUISourceCode(uiSourceCode);var promise=this._fileSystem.getMetadata(relativePath).then(onMetadata);uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata]=promise;return promise;function onMetadata(metadata){if(!metadata) -return null;return new Workspace.UISourceCodeMetadata(metadata.modificationTime,metadata.size);}} -requestFileBlob(uiSourceCode){return this._fileSystem.requestFileBlob(this._filePathForUISourceCode(uiSourceCode));} -requestFileContent(uiSourceCode,callback){var filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.requestFileContent(filePath,callback);} -canSetFileContent(){return true;} -setFileContent(uiSourceCode,newContent,isBase64,callback){var filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.setFileContent(filePath,newContent,isBase64,callback.bind(this,''));} -fullDisplayName(uiSourceCode){var baseURL=(uiSourceCode.project())._fileSystemParentURL;return uiSourceCode.url().substring(baseURL.length);} -canRename(){return true;} -rename(uiSourceCode,newName,callback){if(newName===uiSourceCode.name()){callback(true,uiSourceCode.name(),uiSourceCode.url(),uiSourceCode.contentType());return;} -var filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.renameFile(filePath,newName,innerCallback.bind(this));function innerCallback(success,newName){if(!success||!newName){callback(false,newName);return;} -console.assert(newName);var slash=filePath.lastIndexOf('/');var parentPath=filePath.substring(0,slash);filePath=parentPath+'/'+newName;filePath=filePath.substr(1);var extension=this._extensionForPath(newName);var newURL=this._fileSystemBaseURL+filePath;var newContentType=Persistence.FileSystemWorkspaceBinding._contentTypeForExtension(extension);this.renameUISourceCode(uiSourceCode,newName);callback(true,newName,newURL,newContentType);}} -searchInFileContent(uiSourceCode,query,caseSensitive,isRegex){return new Promise(resolve=>{var filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.requestFileContent(filePath,contentCallback);function contentCallback(content){resolve(content?Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex):[]);}});} -async findFilesMatchingSearchRequest(searchConfig,filesMathingFileQuery,progress){var result=filesMathingFileQuery;var queriesToRun=searchConfig.queries().slice();if(!queriesToRun.length) -queriesToRun.push('');progress.setTotalWork(queriesToRun.length);for(var query of queriesToRun){var files=await this._fileSystem.searchInPath(searchConfig.isRegex()?'':query,progress);result=result.intersectOrdered(files.sort(),String.naturalOrderComparator);progress.worked(1);} -progress.done();return result;} -indexContent(progress){this._fileSystem.indexContent(progress);} -_extensionForPath(path){var extensionIndex=path.lastIndexOf('.');if(extensionIndex===-1) -return'';return path.substring(extensionIndex+1).toLowerCase();} -populate(){var chunkSize=1000;var filePaths=this._fileSystem.initialFilePaths();reportFileChunk.call(this,0);function reportFileChunk(from){var to=Math.min(from+chunkSize,filePaths.length);for(var i=from;i<to;++i) -this._addFile(filePaths[i]);if(to<filePaths.length) -setTimeout(reportFileChunk.bind(this,to),100);}} -excludeFolder(url){var relativeFolder=url.substring(this._fileSystemBaseURL.length);if(!relativeFolder.startsWith('/')) -relativeFolder='/'+relativeFolder;if(!relativeFolder.endsWith('/')) -relativeFolder+='/';this._fileSystem.addExcludedFolder(relativeFolder);var uiSourceCodes=this.uiSourceCodes().slice();for(var i=0;i<uiSourceCodes.length;++i){var uiSourceCode=uiSourceCodes[i];if(uiSourceCode.url().startsWith(url)) -this.removeUISourceCode(uiSourceCode.url());}} -async createFile(path,name,content,isBase64){var filePath=await this._fileSystem.createFile(path,name);if(!filePath) -return null;if(content) -await new Promise(resolve=>this._fileSystem.setFileContent(filePath,content,isBase64||false,resolve));return this._addFile(filePath);} -deleteFile(uiSourceCode){var relativePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.deleteFile(relativePath);this.removeUISourceCode(uiSourceCode.url());} -remove(){this._fileSystemWorkspaceBinding._isolatedFileSystemManager.removeFileSystem(this._fileSystem);} -_addFile(filePath){var extension=this._extensionForPath(filePath);var contentType=Persistence.FileSystemWorkspaceBinding._contentTypeForExtension(extension);var uiSourceCode=this.createUISourceCode(this._fileSystemBaseURL+filePath,contentType);this.addUISourceCode(uiSourceCode);return uiSourceCode;} -_fileChanged(path){var uiSourceCode=this.uiSourceCodeForURL(path);if(!uiSourceCode){var contentType=Persistence.FileSystemWorkspaceBinding._contentTypeForExtension(this._extensionForPath(path));this.addUISourceCode(this.createUISourceCode(path,contentType));return;} -uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata]=null;uiSourceCode.checkContentUpdated();} -dispose(){this.removeProject();}};Persistence.FileSystemWorkspaceBinding._metadata=Symbol('FileSystemWorkspaceBinding.Metadata');;Persistence.DefaultMapping=class{constructor(workspace,fileSystemMapping,onBindingCreated,onBindingRemoved){this._workspace=workspace;this._fileSystemMapping=fileSystemMapping;this._bindings=new Set();this._onBindingCreated=onBindingCreated;this._onBindingRemoved=onBindingRemoved;this._eventListeners=[workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._onUISourceCodeAdded,this),workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,this._onUISourceCodeRemoved,this),workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,this._onProjectRemoved,this),this._fileSystemMapping.addEventListener(Persistence.FileSystemMapping.Events.FileMappingAdded,this._remap,this),this._fileSystemMapping.addEventListener(Persistence.FileSystemMapping.Events.FileMappingRemoved,this._remap,this)];this._remap();} -_remap(){for(var binding of this._bindings.valuesArray()) -this._unbind(binding.network);var networkProjects=this._workspace.projectsForType(Workspace.projectTypes.Network);for(var networkProject of networkProjects){for(var uiSourceCode of networkProject.uiSourceCodes()) -this._bind(uiSourceCode);}} -_onUISourceCodeAdded(event){var uiSourceCode=(event.data);this._bind(uiSourceCode);} -_onUISourceCodeRemoved(event){var uiSourceCode=(event.data);this._unbind(uiSourceCode);} -_onProjectRemoved(event){var project=(event.data);for(var uiSourceCode of project.uiSourceCodes()) -this._unbind(uiSourceCode);} -_createBinding(uiSourceCode){if(uiSourceCode.project().type()===Workspace.projectTypes.FileSystem){var fileSystemPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(uiSourceCode.project().id());var networkURL=this._fileSystemMapping.networkURLForFileSystemURL(fileSystemPath,uiSourceCode.url());var networkSourceCode=networkURL?this._workspace.uiSourceCodeForURL(networkURL):null;return networkSourceCode?new Persistence.PersistenceBinding(networkSourceCode,uiSourceCode,false):null;} -if(uiSourceCode.project().type()===Workspace.projectTypes.Network){var file=this._fileSystemMapping.fileForURL(uiSourceCode.url());var projectId=file?Persistence.FileSystemWorkspaceBinding.projectId(file.fileSystemPath):null;var fileSourceCode=file&&projectId?this._workspace.uiSourceCode(projectId,file.fileURL):null;return fileSourceCode?new Persistence.PersistenceBinding(uiSourceCode,fileSourceCode,false):null;} -return null;} -_bind(uiSourceCode){console.assert(!uiSourceCode[Persistence.DefaultMapping._binding],'Cannot bind already bound UISourceCode!');var binding=this._createBinding(uiSourceCode);if(!binding) -return;if(binding.network[Persistence.DefaultMapping._binding]||binding.fileSystem[Persistence.DefaultMapping._binding]) -return;this._bindings.add(binding);binding.network[Persistence.DefaultMapping._binding]=binding;binding.fileSystem[Persistence.DefaultMapping._binding]=binding;binding.fileSystem.addEventListener(Workspace.UISourceCode.Events.TitleChanged,this._onFileSystemUISourceCodeRenamed,this);this._onBindingCreated.call(null,binding);} -_unbind(uiSourceCode){var binding=uiSourceCode[Persistence.DefaultMapping._binding];if(!binding) -return;this._bindings.delete(binding);binding.network[Persistence.DefaultMapping._binding]=null;binding.fileSystem[Persistence.DefaultMapping._binding]=null;binding.fileSystem.removeEventListener(Workspace.UISourceCode.Events.TitleChanged,this._onFileSystemUISourceCodeRenamed,this);this._onBindingRemoved.call(null,binding);} -_onFileSystemUISourceCodeRenamed(event){var uiSourceCode=(event.data);var binding=uiSourceCode[Persistence.DefaultMapping._binding];this._unbind(binding.network);this._bind(binding.network);} -dispose(){for(var binding of this._bindings.valuesArray()) -this._unbind(binding.network);Common.EventTarget.removeEventListeners(this._eventListeners);}};Persistence.DefaultMapping._binding=Symbol('DefaultMapping.Binding');;Persistence.Automapping=class{constructor(workspace,onBindingCreated,onBindingRemoved){this._workspace=workspace;this._onBindingCreated=onBindingCreated;this._onBindingRemoved=onBindingRemoved;this._bindings=new Set();this._enabled=true;this._fileSystemUISourceCodes=new Map();this._sweepThrottler=new Common.Throttler(100);var pathEncoder=new Persistence.Automapping.PathEncoder();this._filesIndex=new Persistence.Automapping.FilePathIndex(pathEncoder);this._projectFoldersIndex=new Persistence.Automapping.FolderIndex(pathEncoder);this._activeFoldersIndex=new Persistence.Automapping.FolderIndex(pathEncoder);this._eventListeners=[this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,event=>this._onUISourceCodeAdded((event.data))),this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,event=>this._onUISourceCodeRemoved((event.data))),this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRenamed,this._onUISourceCodeRenamed,this),this._workspace.addEventListener(Workspace.Workspace.Events.ProjectAdded,event=>this._onProjectAdded((event.data)),this),this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,event=>this._onProjectRemoved((event.data)),this),];for(var fileSystem of workspace.projects()) -this._onProjectAdded(fileSystem);for(var uiSourceCode of workspace.uiSourceCodes()) -this._onUISourceCodeAdded(uiSourceCode);} -setEnabled(enabled){if(this._enabled===enabled) -return;this._enabled=enabled;this._scheduleRemap();} -_scheduleRemap(){for(var binding of this._bindings.valuesArray()) -this._unbindNetwork(binding.network);this._scheduleSweep();} -_scheduleSweep(){this._sweepThrottler.schedule(sweepUnmapped.bind(this));function sweepUnmapped(){var networkProjects=this._workspace.projectsForType(Workspace.projectTypes.Network);for(var networkProject of networkProjects){for(var uiSourceCode of networkProject.uiSourceCodes()) -this._bindNetwork(uiSourceCode);} -this._onSweepHappenedForTest();return Promise.resolve();}} -_onSweepHappenedForTest(){} -_onProjectRemoved(project){for(var uiSourceCode of project.uiSourceCodes()) -this._onUISourceCodeRemoved(uiSourceCode);if(project.type()!==Workspace.projectTypes.FileSystem) -return;var fileSystem=(project);for(var gitFolder of fileSystem.initialGitFolders()) -this._projectFoldersIndex.removeFolder(gitFolder);this._projectFoldersIndex.removeFolder(fileSystem.fileSystemPath());this._scheduleRemap();} -_onProjectAdded(project){if(project.type()!==Workspace.projectTypes.FileSystem) -return;var fileSystem=(project);for(var gitFolder of fileSystem.initialGitFolders()) -this._projectFoldersIndex.addFolder(gitFolder);this._projectFoldersIndex.addFolder(fileSystem.fileSystemPath());project.uiSourceCodes().forEach(this._onUISourceCodeAdded.bind(this));this._scheduleRemap();} -_onUISourceCodeAdded(uiSourceCode){var project=uiSourceCode.project();if(project.type()===Workspace.projectTypes.FileSystem){if(Persistence.FileSystemWorkspaceBinding.fileSystemType(project)) -return;this._filesIndex.addPath(uiSourceCode.url());this._fileSystemUISourceCodes.set(uiSourceCode.url(),uiSourceCode);this._scheduleSweep();}else if(project.type()===Workspace.projectTypes.Network){this._bindNetwork(uiSourceCode);}} -_onUISourceCodeRemoved(uiSourceCode){if(uiSourceCode.project().type()===Workspace.projectTypes.FileSystem){this._filesIndex.removePath(uiSourceCode.url());this._fileSystemUISourceCodes.delete(uiSourceCode.url());var binding=uiSourceCode[Persistence.Automapping._binding];if(binding) -this._unbindNetwork(binding.network);}else if(uiSourceCode.project().type()===Workspace.projectTypes.Network){this._unbindNetwork(uiSourceCode);}} -_onUISourceCodeRenamed(event){var uiSourceCode=(event.data.uiSourceCode);var oldURL=(event.data.oldURL);if(uiSourceCode.project().type()!==Workspace.projectTypes.FileSystem) -return;this._filesIndex.removePath(oldURL);this._fileSystemUISourceCodes.delete(oldURL);var binding=uiSourceCode[Persistence.Automapping._binding];if(binding) -this._unbindNetwork(binding.network);this._filesIndex.addPath(uiSourceCode.url());this._fileSystemUISourceCodes.set(uiSourceCode.url(),uiSourceCode);this._scheduleSweep();} -_bindNetwork(networkSourceCode){if(networkSourceCode[Persistence.Automapping._processingPromise]||networkSourceCode[Persistence.Automapping._binding]||!this._enabled) -return;var createBindingPromise=this._createBinding(networkSourceCode).then(onBinding.bind(this));networkSourceCode[Persistence.Automapping._processingPromise]=createBindingPromise;function onBinding(binding){if(networkSourceCode[Persistence.Automapping._processingPromise]!==createBindingPromise) -return;networkSourceCode[Persistence.Automapping._processingPromise]=null;if(!binding||this._disposed){this._onBindingFailedForTest();return;} -if(binding.network[Persistence.Automapping._binding]||binding.fileSystem[Persistence.Automapping._binding]) -return;this._bindings.add(binding);binding.network[Persistence.Automapping._binding]=binding;binding.fileSystem[Persistence.Automapping._binding]=binding;if(binding.exactMatch){var projectFolder=this._projectFoldersIndex.closestParentFolder(binding.fileSystem.url());var newFolderAdded=projectFolder?this._activeFoldersIndex.addFolder(projectFolder):false;if(newFolderAdded) -this._scheduleSweep();} -this._onBindingCreated.call(null,binding);}} -_onBindingFailedForTest(){} -_unbindNetwork(networkSourceCode){if(networkSourceCode[Persistence.Automapping._processingPromise]){networkSourceCode[Persistence.Automapping._processingPromise]=null;return;} -var binding=networkSourceCode[Persistence.Automapping._binding];if(!binding) -return;this._bindings.delete(binding);binding.network[Persistence.Automapping._binding]=null;binding.fileSystem[Persistence.Automapping._binding]=null;if(binding.exactMatch){var projectFolder=this._projectFoldersIndex.closestParentFolder(binding.fileSystem.url());if(projectFolder) -this._activeFoldersIndex.removeFolder(projectFolder);} -this._onBindingRemoved.call(null,binding);} -_createBinding(networkSourceCode){if(networkSourceCode.url().startsWith('file://')){var fileSourceCode=this._fileSystemUISourceCodes.get(networkSourceCode.url());var binding=fileSourceCode?new Persistence.PersistenceBinding(networkSourceCode,fileSourceCode,false):null;return Promise.resolve(binding);} -var networkPath=Common.ParsedURL.extractPath(networkSourceCode.url());if(networkPath===null) -return Promise.resolve((null));if(networkPath.endsWith('/')) -networkPath+='index.html';var similarFiles=this._filesIndex.similarFiles(networkPath).map(path=>this._fileSystemUISourceCodes.get(path));if(!similarFiles.length) -return Promise.resolve((null));return this._pullMetadatas(similarFiles.concat(networkSourceCode)).then(onMetadatas.bind(this));function onMetadatas(){var activeFiles=similarFiles.filter(file=>!!this._activeFoldersIndex.closestParentFolder(file.url()));var networkMetadata=networkSourceCode[Persistence.Automapping._metadata];if(!networkMetadata||(!networkMetadata.modificationTime&&typeof networkMetadata.contentSize!=='number')){if(activeFiles.length!==1) -return null;return new Persistence.PersistenceBinding(networkSourceCode,activeFiles[0],false);} -var exactMatches=this._filterWithMetadata(activeFiles,networkMetadata);if(!exactMatches.length) -exactMatches=this._filterWithMetadata(similarFiles,networkMetadata);if(exactMatches.length!==1) -return null;return new Persistence.PersistenceBinding(networkSourceCode,exactMatches[0],true);}} -_pullMetadatas(uiSourceCodes){var promises=uiSourceCodes.map(file=>fetchMetadata(file));return Promise.all(promises);function fetchMetadata(file){return file.requestMetadata().then(metadata=>file[Persistence.Automapping._metadata]=metadata);}} -_filterWithMetadata(files,networkMetadata){return files.filter(file=>{var fileMetadata=file[Persistence.Automapping._metadata];if(!fileMetadata) -return false;var timeMatches=!networkMetadata.modificationTime||Math.abs(networkMetadata.modificationTime-fileMetadata.modificationTime)<1000;var contentMatches=!networkMetadata.contentSize||fileMetadata.contentSize===networkMetadata.contentSize;return timeMatches&&contentMatches;});} -dispose(){if(this._disposed) -return;this._disposed=true;Common.EventTarget.removeEventListeners(this._eventListeners);for(var binding of this._bindings.valuesArray()) -this._unbindNetwork(binding.network);}};Persistence.Automapping._binding=Symbol('Automapping.Binding');Persistence.Automapping._processingPromise=Symbol('Automapping.ProcessingPromise');Persistence.Automapping._metadata=Symbol('Automapping.Metadata');Persistence.Automapping.PathEncoder=class{constructor(){this._encoder=new Common.CharacterIdMap();} -encode(path){return path.split('/').map(token=>this._encoder.toChar(token)).join('');} -decode(path){return path.split('').map(token=>this._encoder.fromChar(token)).join('/');}};Persistence.Automapping.FilePathIndex=class{constructor(encoder){this._encoder=encoder;this._reversedIndex=new Common.Trie();} -addPath(path){var encodedPath=this._encoder.encode(path);this._reversedIndex.add(encodedPath.reverse());} -removePath(path){var encodedPath=this._encoder.encode(path);this._reversedIndex.remove(encodedPath.reverse());} -similarFiles(networkPath){var encodedPath=this._encoder.encode(networkPath);var longestCommonPrefix=this._reversedIndex.longestPrefix(encodedPath.reverse(),false);if(!longestCommonPrefix) -return[];return this._reversedIndex.words(longestCommonPrefix).map(encodedPath=>this._encoder.decode(encodedPath.reverse()));}};Persistence.Automapping.FolderIndex=class{constructor(encoder){this._encoder=encoder;this._index=new Common.Trie();this._folderCount=new Map();} -addFolder(path){if(path.endsWith('/')) -path=path.substring(0,path.length-1);var encodedPath=this._encoder.encode(path);this._index.add(encodedPath);var count=this._folderCount.get(encodedPath)||0;this._folderCount.set(encodedPath,count+1);return count===0;} -removeFolder(path){if(path.endsWith('/')) -path=path.substring(0,path.length-1);var encodedPath=this._encoder.encode(path);var count=this._folderCount.get(encodedPath)||0;if(!count) -return false;if(count>1){this._folderCount.set(encodedPath,count-1);return false;} -this._index.remove(encodedPath);this._folderCount.delete(encodedPath);return true;} -closestParentFolder(path){var encodedPath=this._encoder.encode(path);var commonPrefix=this._index.longestPrefix(encodedPath,true);return this._encoder.decode(commonPrefix);}};;Persistence.NetworkPersistenceManager=class extends Common.Object{constructor(workspace){super();this._bindingSymbol=Symbol('NetworkPersistenceBinding');this._boundInterceptingURLs=Symbol('BoundInterceptingURLs');this._enabledSetting=Common.settings.moduleSetting('persistenceNetworkOverridesEnabled');this._enabledSetting.addChangeListener(this._enabledChanged,this);this._workspace=workspace;this._domainForFileSystemPathSetting=Common.settings.createSetting('domainForFileSystemPath',[]);this._domainForFileSystemMap=new Map(this._domainForFileSystemPathSetting.get());this._fileSystemForDomain=new Map(this._domainForFileSystemPathSetting.get().map(value=>[value[1],value[0]]));this._fileSystemUISourceCodeForUrlMap=new Map();this._interceptionHandlerBound=this._interceptionHandler.bind(this);this._activeProject=null;Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,event=>this._onFileSystemRemoved((event.data)));this._eventDescriptors=[];this._enabledChanged();} -static inspectedPageDomain(){var maintarget=SDK.targetManager.mainTarget();var inspectedURL=maintarget?maintarget.inspectedURL():'';var parsedURL=new Common.ParsedURL(inspectedURL);var scheme=parsedURL.scheme;if(parsedURL.isValid&&(scheme==='http'||scheme==='https')) -return parsedURL.domain()||null;return null;} -addFileSystemOverridesProject(domain,project){if(this.projectForDomain(domain)) -return;var fileSystemPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(project.id());this._domainForFileSystemMap.set(fileSystemPath,domain);this._fileSystemForDomain.set(domain,fileSystemPath);this._domainForFileSystemPathSetting.set(Array.from(this._domainForFileSystemMap.entries()));this._onProjectAdded(project);for(var uiSourceCode of project.uiSourceCodes()) -this._onUISourceCodeAdded(uiSourceCode);this.dispatchEventToListeners(Persistence.NetworkPersistenceManager.Events.ProjectDomainChanged,project);} -activeProject(){return this._activeProject;} -domainForProject(project){if(project.type()!==Workspace.projectTypes.FileSystem) -return null;var fileSystemPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(project.id());if(!fileSystemPath) -return null;return this._domainForFileSystemMap.get(fileSystemPath)||null;} -projectForDomain(domain){if(!domain) -return null;var fileSystemPath=this._fileSystemForDomain.get(domain);if(!fileSystemPath) -return null;return this._workspace.project(Persistence.FileSystemWorkspaceBinding.projectId(fileSystemPath))||null;} -projectForActiveDomain(){return this.projectForDomain(Persistence.NetworkPersistenceManager.inspectedPageDomain());} -_enabledChanged(){if(this._enabledSetting.get()){this._eventDescriptors=[this._workspace.addEventListener(Workspace.Workspace.Events.ProjectAdded,event=>this._onProjectAdded((event.data))),this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,event=>this._onProjectRemoved((event.data))),SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._updateActiveProject,this),Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRenamed,event=>{var uiSourceCode=(event.data.uiSourceCode);this._onUISourceCodeRemoved(uiSourceCode);this._onUISourceCodeAdded(uiSourceCode);}),Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,event=>this._onUISourceCodeAdded((event.data))),Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,event=>this._onUISourceCodeRemoved((event.data))),Workspace.workspace.addEventListener(Workspace.Workspace.Events.WorkingCopyCommitted,event=>this._onUISourceCodeWorkingCopyCommitted((event.data.uiSourceCode)))];this._updateActiveProject();}else{Common.EventTarget.removeEventListeners(this._eventDescriptors);this._updateActiveProject();}} -_updateActiveProject(){var mainTarget=SDK.targetManager.mainTarget();if(!this._enabledSetting.get()||!mainTarget){this._setActiveProject(null);return;} -this._setActiveProject(this.projectForDomain(Persistence.NetworkPersistenceManager.inspectedPageDomain()));} -_setActiveProject(project){if(this._activeProject===project) -return;var oldProject=this._activeProject;this._activeProject=project;if(oldProject) -oldProject.uiSourceCodes().forEach(this._onUISourceCodeRemoved.bind(this));if(project) -project.uiSourceCodes().forEach(this._onUISourceCodeAdded.bind(this));Persistence.persistence.setAutomappingEnabled(!this._activeProject);} -_encodeUrlPathToLocalPath(urlPath){var encodedParts=[];for(var pathPart of fileNamePartsFromUrlPath(urlPath)){if(!pathPart) -continue;var encodedName=encodeURI(pathPart).replace(/[\/:\?\*]/g,match=>'%'+match[0].charCodeAt(0).toString(16));if(Persistence.NetworkPersistenceManager._reservedFileNames.has(encodedName.toLowerCase())) -encodedName=encodedName.split('').map(char=>'%'+char.charCodeAt(0).toString(16)).join('');var lastChar=encodedName.charAt(encodedName.length-1);if(lastChar==='.') -encodedName=encodedName.substr(0,encodedName.length-1)+'%2e';encodedParts.push(encodedName);} -return encodedParts.join('/');function fileNamePartsFromUrlPath(urlPath){var hashIndex=urlPath.indexOf('#');if(hashIndex!==-1) -urlPath=urlPath.substr(0,hashIndex);var queryIndex=urlPath.indexOf('?');if(queryIndex===-1) -return urlPath.split(/[\/\\]/g);if(queryIndex===0) -return[urlPath];var endSection=urlPath.substr(queryIndex);var parts=urlPath.substr(0,urlPath.length-endSection.length).split(/[\/\\]/g);parts[parts.length-1]+=endSection;return parts;}} -_decodeLocalPathToUrlPath(path){try{return unescape(path);}catch(e){console.error(e);} -return path;} -_networkUISourceCode(fileSystemUISourceCode){if(fileSystemUISourceCode.project()!==this._activeProject) -return null;var networkProjects=this._workspace.projectsForType(Workspace.projectTypes.Network);var urls=this._urlsForFileSystemUISourceCode(fileSystemUISourceCode);for(var networkProject of networkProjects){for(var url of urls){var networkUISourceCode=networkProject.uiSourceCodeForURL(url);if(!networkUISourceCode) -continue;return networkUISourceCode;}} -return null;} -_unbind(uiSourceCode){var binding=uiSourceCode[this._bindingSymbol];if(!binding) -return;delete binding.network[this._bindingSymbol];delete binding.fileSystem[this._bindingSymbol];Persistence.persistence.removeBinding(binding);} -_bind(networkUISourceCode,fileSystemUISourceCode){if(networkUISourceCode[this._bindingSymbol]||fileSystemUISourceCode[this._bindingSymbol]) -return;var binding=new Persistence.PersistenceBinding(networkUISourceCode,fileSystemUISourceCode,true);networkUISourceCode[this._bindingSymbol]=binding;fileSystemUISourceCode[this._bindingSymbol]=binding;Persistence.persistence.addBinding(binding);} -_onUISourceCodeWorkingCopyCommitted(uiSourceCode){this.saveUISourceCodeForOverrides(uiSourceCode);} -canSaveUISourceCodeForOverrides(uiSourceCode){return this._activeProject&&uiSourceCode.project().type()===Workspace.projectTypes.Network&&!uiSourceCode[this._bindingSymbol];} -async saveUISourceCodeForOverrides(uiSourceCode){if(!this.canSaveUISourceCodeForOverrides(uiSourceCode)) -return;var urlDomain=uiSourceCode.url().replace(/^https?:\/\//,'');var fileName=urlDomain.substr(urlDomain.lastIndexOf('/')+1);var relativeFolderPath=urlDomain.substr(0,urlDomain.length-fileName.length);if(!fileName) -fileName='index.html';var content=await uiSourceCode.requestContent();var encoded=await uiSourceCode.contentEncoded();this._activeProject.createFile(relativeFolderPath,this._encodeUrlPathToLocalPath(fileName),content,encoded);} -_urlsForFileSystemUISourceCode(uiSourceCode){var directoryPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(uiSourceCode.project().id());var domainPath=this._decodeLocalPathToUrlPath(uiSourceCode.url().substr(directoryPath.length+1));var entries=['http://'+domainPath,'https://'+domainPath];var indexFileName='index.html';if(domainPath.endsWith(indexFileName)){domainPath=domainPath.substr(0,domainPath.length-indexFileName.length);entries.push('http://'+domainPath,'https://'+domainPath);} -return entries;} -_onUISourceCodeAdded(uiSourceCode){if(uiSourceCode.project().type()===Workspace.projectTypes.Network){if(uiSourceCode[this._bindingSymbol]) -return;var fileSystemUISourceCode=this._fileSystemUISourceCodeForUrlMap.get(uiSourceCode.url());if(!fileSystemUISourceCode) -return;this._bind(uiSourceCode,fileSystemUISourceCode);return;} -if(uiSourceCode.project()!==this._activeProject) -return;var urls=this._urlsForFileSystemUISourceCode(uiSourceCode);uiSourceCode[this._boundInterceptingURLs]=[];for(var url of urls){uiSourceCode[this._boundInterceptingURLs].push(url);this._fileSystemUISourceCodeForUrlMap.set(url,uiSourceCode);} -SDK.multitargetNetworkManager.setInterceptionHandlerForPatterns(Array.from(this._fileSystemUISourceCodeForUrlMap.keys()),this._interceptionHandlerBound);var networkUISourceCode=this._networkUISourceCode(uiSourceCode);if(networkUISourceCode) -this._bind(networkUISourceCode,uiSourceCode);} -_onFileSystemRemoved(fileSystem){var domain=this._domainForFileSystemMap.get(fileSystem.path());if(!domain) -return;this._domainForFileSystemMap.delete(fileSystem.path());this._fileSystemForDomain.delete(domain);this._domainForFileSystemPathSetting.set(Array.from(this._domainForFileSystemMap.entries()));} -_onUISourceCodeRemoved(uiSourceCode){if(uiSourceCode.project().type()===Workspace.projectTypes.Network){this._unbind(uiSourceCode);return;} -var boundURLs=uiSourceCode[this._boundInterceptingURLs];if(boundURLs){for(var url of boundURLs) -this._fileSystemUISourceCodeForUrlMap.delete(url);delete uiSourceCode[this._boundInterceptingURLs];SDK.multitargetNetworkManager.setInterceptionHandlerForPatterns(Array.from(this._fileSystemUISourceCodeForUrlMap.keys()),this._interceptionHandlerBound);} -this._unbind(uiSourceCode);} -_onProjectAdded(project){if(project.type()!==Workspace.projectTypes.FileSystem||Persistence.FileSystemWorkspaceBinding.fileSystemType(project)!=='overrides') -return;var fileSystemPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(project.id());var domain=this._domainForFileSystemMap.get(fileSystemPath);if(!domain) -return;this._updateActiveProject();} -_onProjectRemoved(project){if(project!==this._activeProject) -return;for(var uiSourceCode of project.uiSourceCodes()) -this._onUISourceCodeRemoved(uiSourceCode);this._updateActiveProject();} -async _interceptionHandler(interceptedRequest){var fileSystemUISourceCode=this._fileSystemUISourceCodeForUrlMap.get(interceptedRequest.request.url);if(!fileSystemUISourceCode) -return;if(interceptedRequest.request.method!=='GET'&&interceptedRequest.request.method!=='POST') -return;var expectedResourceType=Common.resourceTypes[interceptedRequest.resourceType]||Common.resourceTypes.Other;var mimeType=fileSystemUISourceCode.mimeType();if(Common.ResourceType.fromMimeType(mimeType)!==expectedResourceType) -mimeType=expectedResourceType.canonicalMimeType();var project=(fileSystemUISourceCode.project());var blob=await project.requestFileBlob(fileSystemUISourceCode);interceptedRequest.continueRequestWithContent(new Blob([blob],{type:mimeType}));}};Persistence.NetworkPersistenceManager._reservedFileNames=new Set(['con','prn','aux','nul','com1','com2','com3','com4','com5','com6','com7','com8','com9','lpt1','lpt2','lpt3','lpt4','lpt5','lpt6','lpt7','lpt8','lpt9']);Persistence.NetworkPersistenceManager.Events={ProjectDomainChanged:Symbol('ProjectDomainChanged')};Persistence.networkPersistenceManager;;Persistence.Persistence=class extends Common.Object{constructor(workspace,breakpointManager,fileSystemMapping){super();this._workspace=workspace;this._breakpointManager=breakpointManager;this._filePathPrefixesToBindingCount=new Map();this._subscribedBindingEventListeners=new Multimap();if(Runtime.experiments.isEnabled('persistence2')){var linkDecorator=new Persistence.PersistenceUtils.LinkDecorator(this);Components.Linkifier.setLinkDecorator(linkDecorator);this._mapping=new Persistence.Automapping(workspace,this._validateBinding.bind(this),this._onBindingRemoved.bind(this));}else{this._mapping=new Persistence.DefaultMapping(workspace,fileSystemMapping,this._validateBinding.bind(this),this._onBindingRemoved.bind(this));}} -setAutomappingEnabled(enabled){if(this._mapping instanceof Persistence.Automapping) -this._mapping.setEnabled(enabled);} -addBinding(binding){this._establishBinding(binding);} -removeBinding(binding){this._innerRemoveBinding(binding);} -_setMappingForTest(mappingFactory){this._mapping.dispose();this._mapping=mappingFactory(this._validateBinding.bind(this),this._onBindingRemoved.bind(this));} -_validateBinding(binding){if(!Runtime.experiments.isEnabled('persistence2')||binding.network.contentType().isFromSourceMap()||!binding.fileSystem.contentType().isTextType()){this._establishBinding(binding);return;} -Promise.all([binding.network.requestContent(),binding.fileSystem.requestContent()]).then(onContents.bind(this));function onContents(){if(binding._removed) -return;var fileSystemContent=binding.fileSystem.workingCopy();var networkContent=binding.network.workingCopy();var target=Bindings.NetworkProject.targetForUISourceCode(binding.network);var isValid=false;if(target.isNodeJS()){var rewrappedNetworkContent=Persistence.Persistence._rewrapNodeJSContent(binding,binding.fileSystem,fileSystemContent,networkContent);isValid=(fileSystemContent===rewrappedNetworkContent);}else{isValid=(fileSystemContent.trimRight()===networkContent.trimRight());} -if(isValid) -this._establishBinding(binding);else -this._prevalidationFailedForTest(binding);}} -_prevalidationFailedForTest(binding){} -_establishBinding(binding){binding.network[Persistence.Persistence._binding]=binding;binding.fileSystem[Persistence.Persistence._binding]=binding;binding.fileSystem.forceLoadOnCheckContent();binding.network.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.fileSystem.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.network.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);binding.fileSystem.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);this._addFilePathBindingPrefixes(binding.fileSystem.url());this._moveBreakpoints(binding.fileSystem,binding.network);this._notifyBindingEvent(binding.network);this._notifyBindingEvent(binding.fileSystem);this.dispatchEventToListeners(Persistence.Persistence.Events.BindingCreated,binding);} -_innerRemoveBinding(binding){binding._removed=true;if(binding.network[Persistence.Persistence._binding]!==binding) -return;console.assert(binding.network[Persistence.Persistence._binding]===binding.fileSystem[Persistence.Persistence._binding],'ERROR: inconsistent binding for networkURL '+binding.network.url());binding.network[Persistence.Persistence._binding]=null;binding.fileSystem[Persistence.Persistence._binding]=null;binding.network.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.fileSystem.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.network.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);binding.fileSystem.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);this._removeFilePathBindingPrefixes(binding.fileSystem.url());this._breakpointManager.copyBreakpoints(binding.network.url(),binding.fileSystem);this._notifyBindingEvent(binding.network);this._notifyBindingEvent(binding.fileSystem);this.dispatchEventToListeners(Persistence.Persistence.Events.BindingRemoved,binding);} -_onBindingRemoved(binding){this._innerRemoveBinding(binding);} -_onWorkingCopyChanged(event){var uiSourceCode=(event.data);var binding=uiSourceCode[Persistence.Persistence._binding];if(!binding||binding[Persistence.Persistence._muteWorkingCopy]) -return;var other=binding.network===uiSourceCode?binding.fileSystem:binding.network;if(!uiSourceCode.isDirty()){binding[Persistence.Persistence._muteWorkingCopy]=true;other.resetWorkingCopy();binding[Persistence.Persistence._muteWorkingCopy]=false;this._contentSyncedForTest();return;} -var target=Bindings.NetworkProject.targetForUISourceCode(binding.network);if(target.isNodeJS()){var newContent=uiSourceCode.workingCopy();other.requestContent().then(()=>{var nodeJSContent=Persistence.Persistence._rewrapNodeJSContent(binding,other,other.workingCopy(),newContent);setWorkingCopy.call(this,()=>nodeJSContent);});return;} -setWorkingCopy.call(this,()=>uiSourceCode.workingCopy());function setWorkingCopy(workingCopyGetter){binding[Persistence.Persistence._muteWorkingCopy]=true;other.setWorkingCopyGetter(workingCopyGetter);binding[Persistence.Persistence._muteWorkingCopy]=false;this._contentSyncedForTest();}} -_onWorkingCopyCommitted(event){var uiSourceCode=(event.data.uiSourceCode);var binding=uiSourceCode[Persistence.Persistence._binding];if(!binding||binding[Persistence.Persistence._muteCommit]) -return;var newContent=(event.data.content);var other=binding.network===uiSourceCode?binding.fileSystem:binding.network;var target=Bindings.NetworkProject.targetForUISourceCode(binding.network);if(target.isNodeJS()){other.requestContent().then(currentContent=>{var nodeJSContent=Persistence.Persistence._rewrapNodeJSContent(binding,other,currentContent,newContent);setContent.call(this,nodeJSContent);});return;} -setContent.call(this,newContent);function setContent(newContent){binding[Persistence.Persistence._muteCommit]=true;other.addRevision(newContent);binding[Persistence.Persistence._muteCommit]=false;this._contentSyncedForTest();}} -static _rewrapNodeJSContent(binding,uiSourceCode,currentContent,newContent){if(uiSourceCode===binding.fileSystem){if(newContent.startsWith(Persistence.Persistence._NodePrefix)&&newContent.endsWith(Persistence.Persistence._NodeSuffix)){newContent=newContent.substring(Persistence.Persistence._NodePrefix.length,newContent.length-Persistence.Persistence._NodeSuffix.length);} -if(currentContent.startsWith(Persistence.Persistence._NodeShebang)) -newContent=Persistence.Persistence._NodeShebang+newContent;}else{if(newContent.startsWith(Persistence.Persistence._NodeShebang)) -newContent=newContent.substring(Persistence.Persistence._NodeShebang.length);if(currentContent.startsWith(Persistence.Persistence._NodePrefix)&¤tContent.endsWith(Persistence.Persistence._NodeSuffix)) -newContent=Persistence.Persistence._NodePrefix+newContent+Persistence.Persistence._NodeSuffix;} -return newContent;} -_contentSyncedForTest(){} -_moveBreakpoints(from,to){var breakpoints=this._breakpointManager.breakpointsForUISourceCode(from);for(var breakpoint of breakpoints){breakpoint.remove();this._breakpointManager.setBreakpoint(to,breakpoint.lineNumber(),breakpoint.columnNumber(),breakpoint.condition(),breakpoint.enabled());}} -hasUnsavedCommittedChanges(uiSourceCode){if(this._workspace.hasResourceContentTrackingExtensions()) -return false;if(uiSourceCode.project().canSetFileContent()) -return false;if(uiSourceCode[Persistence.Persistence._binding]) -return false;return!!uiSourceCode.history().length;} -binding(uiSourceCode){return uiSourceCode[Persistence.Persistence._binding]||null;} -subscribeForBindingEvent(uiSourceCode,listener){this._subscribedBindingEventListeners.set(uiSourceCode,listener);} -unsubscribeFromBindingEvent(uiSourceCode,listener){this._subscribedBindingEventListeners.delete(uiSourceCode,listener);} -_notifyBindingEvent(uiSourceCode){if(!this._subscribedBindingEventListeners.has(uiSourceCode)) -return;var listeners=Array.from(this._subscribedBindingEventListeners.get(uiSourceCode));for(var listener of listeners) -listener.call(null);} -fileSystem(uiSourceCode){var binding=this.binding(uiSourceCode);return binding?binding.fileSystem:null;} -_addFilePathBindingPrefixes(filePath){var relative='';for(var token of filePath.split('/')){relative+=token+'/';var count=this._filePathPrefixesToBindingCount.get(relative)||0;this._filePathPrefixesToBindingCount.set(relative,count+1);}} -_removeFilePathBindingPrefixes(filePath){var relative='';for(var token of filePath.split('/')){relative+=token+'/';var count=this._filePathPrefixesToBindingCount.get(relative);if(count===1) -this._filePathPrefixesToBindingCount.delete(relative);else -this._filePathPrefixesToBindingCount.set(relative,count-1);}} -filePathHasBindings(filePath){if(!filePath.endsWith('/')) -filePath+='/';return this._filePathPrefixesToBindingCount.has(filePath);} -dispose(){this._mapping.dispose();}};Persistence.Persistence._binding=Symbol('Persistence.Binding');Persistence.Persistence._muteCommit=Symbol('Persistence.MuteCommit');Persistence.Persistence._muteWorkingCopy=Symbol('Persistence.MuteWorkingCopy');Persistence.Persistence._NodePrefix='(function (exports, require, module, __filename, __dirname) { ';Persistence.Persistence._NodeSuffix='\n});';Persistence.Persistence._NodeShebang='#!/usr/bin/env node';Persistence.Persistence.Events={BindingCreated:Symbol('BindingCreated'),BindingRemoved:Symbol('BindingRemoved')};Persistence.PersistenceBinding=class{constructor(network,fileSystem,exactMatch){this.network=network;this.fileSystem=fileSystem;this.exactMatch=exactMatch;this._removed=false;}};Persistence.MappingSystem=function(){};Persistence.MappingSystem.prototype={dispose:function(){}};Persistence.persistence;;Persistence.PersistenceActions={};Persistence.PersistenceActions.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){var contentProvider=(target);async function saveAs(){if(contentProvider instanceof Workspace.UISourceCode) -(contentProvider).commitWorkingCopy();var content=await contentProvider.requestContent();var url=contentProvider.contentURL();Workspace.fileManager.save(url,(content),true);Workspace.fileManager.close(url);} -if(contentProvider.contentType().isDocumentOrScriptOrStyleSheet()) -contextMenu.saveSection().appendItem(Common.UIString('Save as...'),saveAs);var uiSourceCode=Workspace.workspace.uiSourceCodeForURL(contentProvider.contentURL());if(uiSourceCode&&Persistence.networkPersistenceManager.canSaveUISourceCodeForOverrides(uiSourceCode)){contextMenu.saveSection().appendItem(Common.UIString('Save for overrides'),()=>{uiSourceCode.commitWorkingCopy();Persistence.networkPersistenceManager.saveUISourceCodeForOverrides((uiSourceCode));Common.Revealer.reveal(uiSourceCode);});}}};;Persistence.PersistenceUtils=class{static tooltipForUISourceCode(uiSourceCode){var binding=Persistence.persistence.binding(uiSourceCode);if(!binding) -return'';if(uiSourceCode===binding.network) -return Common.UIString('Persisted to file system: %s',binding.fileSystem.url().trimMiddle(150));if(binding.network.contentType().isFromSourceMap()) -return Common.UIString('Linked to source map: %s',binding.network.url().trimMiddle(150));return Common.UIString('Linked to %s',binding.network.url().trimMiddle(150));} -static iconForUISourceCode(uiSourceCode){if(!Runtime.experiments.isEnabled('persistence2')) -return null;var binding=Persistence.persistence.binding(uiSourceCode);if(binding){var icon=UI.Icon.create('mediumicon-file-sync');icon.title=Persistence.PersistenceUtils.tooltipForUISourceCode(binding.fileSystem);if(Persistence.networkPersistenceManager.activeProject()===binding.fileSystem.project()) -icon.style.filter='hue-rotate(160deg)';return icon;} -if(uiSourceCode.project().type()!==Workspace.projectTypes.FileSystem) -return null;var icon=UI.Icon.create('mediumicon-file');icon.title=Persistence.PersistenceUtils.tooltipForUISourceCode(uiSourceCode);return icon;}};Persistence.PersistenceUtils.LinkDecorator=class extends Common.Object{constructor(persistence){super();persistence.addEventListener(Persistence.Persistence.Events.BindingCreated,this._bindingChanged,this);persistence.addEventListener(Persistence.Persistence.Events.BindingRemoved,this._bindingChanged,this);} -_bindingChanged(event){var binding=(event.data);this.dispatchEventToListeners(Components.LinkDecorator.Events.LinkIconChanged,binding.network);} -linkIcon(uiSourceCode){return Persistence.PersistenceUtils.iconForUISourceCode(uiSourceCode);}};;Persistence.FileSystemMapping=class extends Common.Object{constructor(fileSystemManager){super();this._fileSystemMappingSetting=Common.settings.createLocalSetting('fileSystemMapping',{});this._mappingForURLPrefix={};this._urlPrefixes=[];this._fileSystemMappings={};this._loadFromSettings();this._eventListeners=[fileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,this._fileSystemAdded,this),fileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,this._fileSystemRemoved,this),];fileSystemManager.waitForFileSystems().then(this._fileSystemsLoaded.bind(this));} -_fileSystemsLoaded(fileSystems){for(var fileSystem of fileSystems) -this._addFileSystemPath(fileSystem.path());} -_fileSystemAdded(event){var fileSystem=(event.data);this._addFileSystemPath(fileSystem.path());} -_fileSystemRemoved(event){var fileSystem=(event.data);this._removeFileSystemPath(fileSystem.path());} -_loadFromSettings(){var savedMapping=this._fileSystemMappingSetting.get();this._fileSystemMappings={};for(var fileSystemPath in savedMapping){var savedFileSystemMappings=savedMapping[fileSystemPath];fileSystemPath=Common.ParsedURL.platformPathToURL(fileSystemPath);this._fileSystemMappings[fileSystemPath]=[];var fileSystemMappings=this._fileSystemMappings[fileSystemPath];for(var i=0;i<savedFileSystemMappings.length;++i){var savedEntry=savedFileSystemMappings[i];var entry=new Persistence.FileSystemMapping.Entry(fileSystemPath,savedEntry.urlPrefix,savedEntry.pathPrefix);fileSystemMappings.push(entry);}} -this._rebuildIndexes();} -_saveToSettings(){var setting={};for(var fileSystemPath in this._fileSystemMappings){setting[fileSystemPath]=[];var entries=this._fileSystemMappings[fileSystemPath];for(var entry of entries) -setting[fileSystemPath].push(entry);} -this._fileSystemMappingSetting.set(setting);} -_rebuildIndexes(){this._mappingForURLPrefix={};for(var fileSystemMapping of Object.values(this._fileSystemMappings)){for(var entry of fileSystemMapping) -this._mappingForURLPrefix[entry.urlPrefix]=entry;} -this._urlPrefixes=Object.keys(this._mappingForURLPrefix).sort();} -_addFileSystemPath(fileSystemPath){if(this._fileSystemMappings[fileSystemPath]) -return;this._fileSystemMappings[fileSystemPath]=[];this._saveToSettings();} -_removeFileSystemPath(fileSystemPath){if(!this._fileSystemMappings[fileSystemPath]) -return;delete this._fileSystemMappings[fileSystemPath];this._rebuildIndexes();this._saveToSettings();} -addFileMapping(fileSystemPath,urlPrefix,pathPrefix){if(!urlPrefix.endsWith('/')) -urlPrefix+='/';if(!pathPrefix.endsWith('/')) -pathPrefix+='/';if(!pathPrefix.startsWith('/')) -pathPrefix='/'+pathPrefix;this._innerAddFileMapping(fileSystemPath,urlPrefix,pathPrefix);this._saveToSettings();} -_innerAddFileMapping(fileSystemPath,urlPrefix,pathPrefix){var entry=new Persistence.FileSystemMapping.Entry(fileSystemPath,urlPrefix,pathPrefix);this._fileSystemMappings[fileSystemPath].push(entry);this._rebuildIndexes();this.dispatchEventToListeners(Persistence.FileSystemMapping.Events.FileMappingAdded,entry);} -removeFileMapping(fileSystemPath,urlPrefix,pathPrefix){var entry=this._configurableMappingEntryForPathPrefix(fileSystemPath,pathPrefix);if(!entry) -return;this._fileSystemMappings[fileSystemPath].remove(entry);this._rebuildIndexes();this._saveToSettings();this.dispatchEventToListeners(Persistence.FileSystemMapping.Events.FileMappingRemoved,entry);} -_mappingEntryForURL(url){for(var i=this._urlPrefixes.length-1;i>=0;--i){var urlPrefix=this._urlPrefixes[i];if(url.startsWith(urlPrefix)) -return this._mappingForURLPrefix[urlPrefix];} -return null;} -_mappingEntryForPath(fileSystemPath,filePath){var entries=this._fileSystemMappings[fileSystemPath];if(!entries) -return null;var entry=null;for(var i=0;i<entries.length;++i){var pathPrefix=entries[i].pathPrefix;if(entry&&entry.pathPrefix.length>pathPrefix.length) -continue;if(filePath.startsWith(pathPrefix)) -entry=entries[i];} -return entry;} -_configurableMappingEntryForPathPrefix(fileSystemPath,pathPrefix){var entries=this._fileSystemMappings[fileSystemPath];for(var i=0;i<entries.length;++i){if(pathPrefix===entries[i].pathPrefix) -return entries[i];} -return null;} -mappingEntries(fileSystemPath){return this._fileSystemMappings[fileSystemPath].slice();} -hasMappingForNetworkURL(url){return!!this._mappingEntryForURL(url);} -fileForURL(url){var entry=this._mappingEntryForURL(url);if(!entry) -return null;var file={};file.fileSystemPath=entry.fileSystemPath;file.fileURL=entry.fileSystemPath+entry.pathPrefix+url.substr(entry.urlPrefix.length);return file;} -networkURLForFileSystemURL(fileSystemPath,filePath){var relativePath=filePath.substring(fileSystemPath.length);var entry=this._mappingEntryForPath(fileSystemPath,relativePath);if(!entry) -return'';return entry.urlPrefix+relativePath.substring(entry.pathPrefix.length);} -removeMappingForURL(url){var entry=this._mappingEntryForURL(url);if(!entry) -return;this._fileSystemMappings[entry.fileSystemPath].remove(entry);this._saveToSettings();} -addMappingForResource(url,fileSystemPath,filePath){var commonPathSuffixLength=0;for(var i=0;i<filePath.length;++i){var filePathCharacter=filePath[filePath.length-1-i];var urlCharacter=url[url.length-1-i];if(filePathCharacter!==urlCharacter) -break;if(filePathCharacter==='/') -commonPathSuffixLength=i;} -var from=fileSystemPath.length;var to=filePath.length-commonPathSuffixLength;var pathPrefix=filePath.substring(from,to);var urlPrefix=url.substr(0,url.length-commonPathSuffixLength);if(to>=from) -this.addFileMapping(fileSystemPath,urlPrefix,pathPrefix);else -this.addFileMapping(fileSystemPath,urlPrefix+pathPrefix,'/');} -resetForTesting(){this._fileSystemMappings={};} -dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);}};Persistence.FileSystemMapping.Events={FileMappingAdded:Symbol('FileMappingAdded'),FileMappingRemoved:Symbol('FileMappingRemoved')};Persistence.FileSystemMapping.Entry=class{constructor(fileSystemPath,urlPrefix,pathPrefix){this.fileSystemPath=fileSystemPath;this.urlPrefix=urlPrefix;this.pathPrefix=pathPrefix;}};Persistence.fileSystemMapping;;Persistence.EditFileSystemView=class extends UI.VBox{constructor(fileSystemPath){super(true);this.registerRequiredCSS('persistence/editFileSystemView.css');this._fileSystemPath=fileSystemPath;this._eventListeners=[Persistence.fileSystemMapping.addEventListener(Persistence.FileSystemMapping.Events.FileMappingAdded,this._update,this),Persistence.fileSystemMapping.addEventListener(Persistence.FileSystemMapping.Events.FileMappingRemoved,this._update,this),Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderAdded,this._update,this),Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderRemoved,this._update,this)];if(!Runtime.experiments.isEnabled('persistence2')){this._mappingsList=new UI.ListWidget(this);this._mappingsList.element.classList.add('file-system-list');this._mappingsList.registerRequiredCSS('persistence/editFileSystemView.css');var mappingsPlaceholder=createElementWithClass('div','file-system-list-empty');var mappingsHeader=this.contentElement.createChild('div','file-system-header');mappingsHeader.createChild('div','file-system-header-text').textContent=Common.UIString('Mappings');mappingsPlaceholder.textContent=Common.UIString('None');mappingsHeader.appendChild(UI.createTextButton(Common.UIString('Add'),this._addMappingButtonClicked.bind(this),'add-button'));this._mappingsList.setEmptyPlaceholder(mappingsPlaceholder);this._mappingsList.show(this.contentElement);} -var excludedFoldersHeader=this.contentElement.createChild('div','file-system-header');excludedFoldersHeader.createChild('div','file-system-header-text').textContent=Common.UIString('Excluded folders');excludedFoldersHeader.appendChild(UI.createTextButton(Common.UIString('Add'),this._addExcludedFolderButtonClicked.bind(this),'add-button'));this._excludedFoldersList=new UI.ListWidget(this);this._excludedFoldersList.element.classList.add('file-system-list');this._excludedFoldersList.registerRequiredCSS('persistence/editFileSystemView.css');var excludedFoldersPlaceholder=createElementWithClass('div','file-system-list-empty');excludedFoldersPlaceholder.textContent=Common.UIString('None');this._excludedFoldersList.setEmptyPlaceholder(excludedFoldersPlaceholder);this._excludedFoldersList.show(this.contentElement);this.contentElement.tabIndex=0;this._update();} -dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);} -_update(){if(this._muteUpdate) -return;this._mappings=[];this._excludedFoldersList.clear();this._excludedFolders=[];for(var folder of Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).excludedFolders().values()){this._excludedFolders.push(folder);this._excludedFoldersList.appendItem(folder,true);} -if(Runtime.experiments.isEnabled('persistence2')) -return;this._mappingsList.clear();var mappings=Persistence.fileSystemMapping.mappingEntries(this._fileSystemPath);for(var entry of mappings){this._mappingsList.appendItem(entry,true);this._mappings.push(entry);}} -_addMappingButtonClicked(){var entry=new Persistence.FileSystemMapping.Entry(this._fileSystemPath,'','');this._mappingsList.addNewItem(0,entry);} -_addExcludedFolderButtonClicked(){this._excludedFoldersList.addNewItem(0,'');} -renderItem(item,editable){var element=createElementWithClass('div','file-system-list-item');if(item instanceof Persistence.FileSystemMapping.Entry){var entry=(item);var urlPrefixElement=element.createChild('div','file-system-value');urlPrefixElement.textContent=entry.urlPrefix;urlPrefixElement.title=entry.urlPrefix;element.createChild('div','file-system-separator');var pathPrefixElement=element.createChild('div','file-system-value');pathPrefixElement.textContent=entry.pathPrefix;pathPrefixElement.title=entry.pathPrefix;}else{var pathPrefix=(editable?item:Common.UIString('%s (via .devtools)',item));var pathPrefixElement=element.createChild('div','file-system-value');pathPrefixElement.textContent=pathPrefix;pathPrefixElement.title=pathPrefix;} -return element;} -removeItemRequested(item,index){if(item instanceof Persistence.FileSystemMapping.Entry){var entry=this._mappings[index];Persistence.fileSystemMapping.removeFileMapping(entry.fileSystemPath,entry.urlPrefix,entry.pathPrefix);}else{Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).removeExcludedFolder(this._excludedFolders[index]);}} -commitEdit(item,editor,isNew){this._muteUpdate=true;if(item instanceof Persistence.FileSystemMapping.Entry){var entry=(item);if(!isNew) -Persistence.fileSystemMapping.removeFileMapping(this._fileSystemPath,entry.urlPrefix,entry.pathPrefix);Persistence.fileSystemMapping.addFileMapping(this._fileSystemPath,this._normalizePrefix(editor.control('urlPrefix').value),this._normalizePrefix(editor.control('pathPrefix').value));}else{if(!isNew){Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).removeExcludedFolder((item));} -Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).addExcludedFolder(this._normalizePrefix(editor.control('pathPrefix').value));} -this._muteUpdate=false;this._update();} -beginEdit(item){if(item instanceof Persistence.FileSystemMapping.Entry){var entry=(item);var editor=this._createMappingEditor();editor.control('urlPrefix').value=entry.urlPrefix;editor.control('pathPrefix').value=entry.pathPrefix;return editor;}else{var editor=this._createExcludedFolderEditor();editor.control('pathPrefix').value=item;return editor;}} -_createMappingEditor(){if(this._mappingEditor) -return this._mappingEditor;var editor=new UI.ListWidget.Editor();this._mappingEditor=editor;var content=editor.contentElement();var titles=content.createChild('div','file-system-edit-row');titles.createChild('div','file-system-value').textContent=Common.UIString('URL prefix');titles.createChild('div','file-system-separator file-system-separator-invisible');titles.createChild('div','file-system-value').textContent=Common.UIString('Folder path');var fields=content.createChild('div','file-system-edit-row');fields.createChild('div','file-system-value').appendChild(editor.createInput('urlPrefix','text','http://localhost:8000/url',urlPrefixValidator.bind(this)));fields.createChild('div','file-system-separator file-system-separator-invisible');fields.createChild('div','file-system-value').appendChild(editor.createInput('pathPrefix','text','/path/to/folder/',pathPrefixValidator.bind(this)));return editor;function urlPrefixValidator(item,index,input){var prefix=this._normalizePrefix(input.value);for(var i=0;i<this._mappings.length;++i){if(i!==index&&this._mappings[i].urlPrefix===prefix) -return false;} -return!!prefix;} -function pathPrefixValidator(item,index,input){var prefix=this._normalizePrefix(input.value);for(var i=0;i<this._mappings.length;++i){if(i!==index&&this._mappings[i].pathPrefix===prefix) -return false;} -return!!prefix;}} -_createExcludedFolderEditor(){if(this._excludedFolderEditor) -return this._excludedFolderEditor;var editor=new UI.ListWidget.Editor();this._excludedFolderEditor=editor;var content=editor.contentElement();var titles=content.createChild('div','file-system-edit-row');titles.createChild('div','file-system-value').textContent=Common.UIString('Folder path');var fields=content.createChild('div','file-system-edit-row');fields.createChild('div','file-system-value').appendChild(editor.createInput('pathPrefix','text','/path/to/folder/',pathPrefixValidator.bind(this)));return editor;function pathPrefixValidator(item,index,input){var prefix=this._normalizePrefix(input.value);var configurableCount=Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).excludedFolders().size;for(var i=0;i<configurableCount;++i){if(i!==index&&this._excludedFolders[i]===prefix) -return false;} -return!!prefix;}} -_normalizePrefix(prefix){if(!prefix) -return'';return prefix+(prefix[prefix.length-1]==='/'?'':'/');}};;Persistence.WorkspaceSettingsTab=class extends UI.VBox{constructor(){super();this.registerRequiredCSS('persistence/workspaceSettingsTab.css');var header=this.element.createChild('header');header.createChild('h3').createTextChild(Common.UIString('Workspace'));this.containerElement=this.element.createChild('div','help-container-wrapper').createChild('div','settings-tab help-content help-container');Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,this._fileSystemAdded,this);Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,this._fileSystemRemoved,this);var folderExcludePatternInput=this._createFolderExcludePatternInput();folderExcludePatternInput.classList.add('folder-exclude-pattern');this.containerElement.appendChild(folderExcludePatternInput);if(Runtime.experiments.isEnabled('persistence2')){var div=this.containerElement.createChild('div','settings-info-message');div.createTextChild(Common.UIString('Mappings are inferred automatically. Please '));div.appendChild(UI.createExternalLink('https://bugs.chromium.org/p/chromium/issues/entry?template=Defect%20report%20from%20user&components=Platform%3EDevTools%3EAuthoring&comment=DevTools%20failed%20to%20link%20network%20resource%20to%20filesystem.%0A%0APlatform%3A%20%3CLinux%2FWin%2FMac%3E%0AChrome%20version%3A%20%3Cyour%20chrome%20version%3E%0A%0AWhat%20are%20the%20details%20of%20your%20project%3F%0A-%20Source%20code%20(if%20any)%3A%20http%3A%2F%2Fgithub.com%2Fexample%2Fexample%0A-%20Build%20System%3A%20gulp%2Fgrunt%2Fwebpack%2Frollup%2F...%0A-%20HTTP%20server%3A%20node%20HTTP%2Fnginx%2Fapache...%0A%0AAssets%20failed%20to%20link%20(or%20incorrectly%20linked)%3A%0A1.%0A2.%0A3.%0A%0AIf%20possible%2C%20please%20attach%20a%20screenshot%20of%20network%20sources%20navigator%20which%20should%0Ashow%20which%20resources%20failed%20to%20map',Common.UIString('report')));div.createTextChild(Common.UIString(' any bugs.'));} -this._fileSystemsListContainer=this.containerElement.createChild('div','');this.containerElement.appendChild(UI.createTextButton(Common.UIString('Add folder\u2026'),this._addFileSystemClicked.bind(this)));this._elementByPath=new Map();this._mappingViewByPath=new Map();var fileSystems=Persistence.isolatedFileSystemManager.fileSystems();for(var i=0;i<fileSystems.length;++i) -this._addItem(fileSystems[i]);} -_createFolderExcludePatternInput(){var p=createElement('p');var labelElement=p.createChild('label');labelElement.textContent=Common.UIString('Folder exclude pattern');var inputElement=UI.createInput('','text');p.appendChild(inputElement);inputElement.style.width='270px';var folderExcludeSetting=Persistence.isolatedFileSystemManager.workspaceFolderExcludePatternSetting();var setValue=UI.bindInput(inputElement,folderExcludeSetting.set.bind(folderExcludeSetting),regexValidator,false);folderExcludeSetting.addChangeListener(()=>setValue.call(null,folderExcludeSetting.get()));setValue(folderExcludeSetting.get());return p;function regexValidator(value){var regex;try{regex=new RegExp(value);}catch(e){} -return!!regex;}} -_addItem(fileSystem){var element=this._renderFileSystem(fileSystem);this._elementByPath.set(fileSystem.path(),element);this._fileSystemsListContainer.appendChild(element);var mappingView=new Persistence.EditFileSystemView(fileSystem.path());this._mappingViewByPath.set(fileSystem.path(),mappingView);mappingView.element.classList.add('file-system-mapping-view');mappingView.show(element);} -_renderFileSystem(fileSystem){var fileSystemPath=fileSystem.path();var lastIndexOfSlash=fileSystemPath.lastIndexOf(Host.isWin()?'\\':'/');var folderName=fileSystemPath.substr(lastIndexOfSlash+1);var element=createElementWithClass('div','file-system-container');var header=element.createChild('div','file-system-header');header.createChild('div','file-system-name').textContent=folderName;var path=header.createChild('div','file-system-path');path.textContent=fileSystemPath;path.title=fileSystemPath;var toolbar=new UI.Toolbar('');var button=new UI.ToolbarButton(Common.UIString('Remove'),'largeicon-delete');button.addEventListener(UI.ToolbarButton.Events.Click,this._removeFileSystemClicked.bind(this,fileSystem));toolbar.appendToolbarItem(button);header.appendChild(toolbar.element);return element;} -_removeFileSystemClicked(fileSystem){Persistence.isolatedFileSystemManager.removeFileSystem(fileSystem);} -_addFileSystemClicked(){Persistence.isolatedFileSystemManager.addFileSystem();} -_fileSystemAdded(event){var fileSystem=(event.data);this._addItem(fileSystem);} -_fileSystemRemoved(event){var fileSystem=(event.data);var mappingView=this._mappingViewByPath.get(fileSystem.path());if(mappingView){mappingView.dispose();this._mappingViewByPath.delete(fileSystem.path());} -var element=this._elementByPath.get(fileSystem.path());if(element){this._elementByPath.delete(fileSystem.path());element.remove();}}};;self['Extensions']=self['Extensions']||{};function defineCommonExtensionSymbols(apiPrivate){if(!apiPrivate.audits) -apiPrivate.audits={};apiPrivate.audits.Severity={Info:'info',Warning:'warning',Severe:'severe'};if(!apiPrivate.panels) -apiPrivate.panels={};apiPrivate.panels.SearchAction={CancelSearch:'cancelSearch',PerformSearch:'performSearch',NextSearchResult:'nextSearchResult',PreviousSearchResult:'previousSearchResult'};apiPrivate.Events={AuditStarted:'audit-started-',ButtonClicked:'button-clicked-',PanelObjectSelected:'panel-objectSelected-',NetworkRequestFinished:'network-request-finished',OpenResource:'open-resource',PanelSearch:'panel-search-',RecordingStarted:'trace-recording-started-',RecordingStopped:'trace-recording-stopped-',ResourceAdded:'resource-added',ResourceContentCommitted:'resource-content-committed',ViewShown:'view-shown-',ViewHidden:'view-hidden-'};apiPrivate.Commands={AddAuditCategory:'addAuditCategory',AddAuditResult:'addAuditResult',AddRequestHeaders:'addRequestHeaders',AddTraceProvider:'addTraceProvider',ApplyStyleSheet:'applyStyleSheet',CompleteTraceSession:'completeTraceSession',CreatePanel:'createPanel',CreateSidebarPane:'createSidebarPane',CreateToolbarButton:'createToolbarButton',EvaluateOnInspectedPage:'evaluateOnInspectedPage',ForwardKeyboardEvent:'_forwardKeyboardEvent',GetHAR:'getHAR',GetPageResources:'getPageResources',GetRequestContent:'getRequestContent',GetResourceContent:'getResourceContent',InspectedURLChanged:'inspectedURLChanged',OpenResource:'openResource',Reload:'Reload',Subscribe:'subscribe',SetOpenResourceHandler:'setOpenResourceHandler',SetResourceContent:'setResourceContent',SetSidebarContent:'setSidebarContent',SetSidebarHeight:'setSidebarHeight',SetSidebarPage:'setSidebarPage',ShowPanel:'showPanel',StopAuditCategoryRun:'stopAuditCategoryRun',Unsubscribe:'unsubscribe',UpdateAuditProgress:'updateAuditProgress',UpdateButton:'updateButton'};} -function injectedExtensionAPI(extensionInfo,inspectedTabId,themeName,testHook,injectedScriptId){var apiPrivate={};defineCommonExtensionSymbols(apiPrivate);var commands=apiPrivate.Commands;var events=apiPrivate.Events;var userAction=false;function EventSinkImpl(type,customDispatch){this._type=type;this._listeners=[];this._customDispatch=customDispatch;} -EventSinkImpl.prototype={addListener:function(callback){if(typeof callback!=='function') -throw'addListener: callback is not a function';if(this._listeners.length===0) -extensionServer.sendRequest({command:commands.Subscribe,type:this._type});this._listeners.push(callback);extensionServer.registerHandler('notify-'+this._type,this._dispatch.bind(this));},removeListener:function(callback){var listeners=this._listeners;for(var i=0;i<listeners.length;++i){if(listeners[i]===callback){listeners.splice(i,1);break;}} -if(this._listeners.length===0) -extensionServer.sendRequest({command:commands.Unsubscribe,type:this._type});},_fire:function(vararg){var listeners=this._listeners.slice();for(var i=0;i<listeners.length;++i) -listeners[i].apply(null,arguments);},_dispatch:function(request){if(this._customDispatch) -this._customDispatch.call(this,request);else -this._fire.apply(this,request.arguments);}};function InspectorExtensionAPI(){this.audits=new Audits();this.inspectedWindow=new InspectedWindow();this.panels=new Panels();this.network=new Network();this.timeline=new Timeline();defineDeprecatedProperty(this,'webInspector','resources','network');} -function Network(){function dispatchRequestEvent(message){var request=message.arguments[1];request.__proto__=new Request(message.arguments[0]);this._fire(request);} -this.onRequestFinished=new EventSink(events.NetworkRequestFinished,dispatchRequestEvent);defineDeprecatedProperty(this,'network','onFinished','onRequestFinished');this.onNavigated=new EventSink(events.InspectedURLChanged);} -Network.prototype={getHAR:function(callback){function callbackWrapper(result){var entries=(result&&result.entries)||[];for(var i=0;i<entries.length;++i){entries[i].__proto__=new Request(entries[i]._requestId);delete entries[i]._requestId;} -callback(result);} -extensionServer.sendRequest({command:commands.GetHAR},callback&&callbackWrapper);},addRequestHeaders:function(headers){extensionServer.sendRequest({command:commands.AddRequestHeaders,headers:headers,extensionId:window.location.hostname});}};function RequestImpl(id){this._id=id;} -RequestImpl.prototype={getContent:function(callback){function callbackWrapper(response){callback(response.content,response.encoding);} -extensionServer.sendRequest({command:commands.GetRequestContent,id:this._id},callback&&callbackWrapper);}};function Panels(){var panels={elements:new ElementsPanel(),sources:new SourcesPanel(),};function panelGetter(name){return panels[name];} -for(var panel in panels) -this.__defineGetter__(panel,panelGetter.bind(null,panel));this.applyStyleSheet=function(styleSheet){extensionServer.sendRequest({command:commands.ApplyStyleSheet,styleSheet:styleSheet});};} -Panels.prototype={create:function(title,icon,page,callback){var id='extension-panel-'+extensionServer.nextObjectId();var request={command:commands.CreatePanel,id:id,title:title,icon:icon,page:page};extensionServer.sendRequest(request,callback&&callback.bind(this,new ExtensionPanel(id)));},setOpenResourceHandler:function(callback){var hadHandler=extensionServer.hasHandler(events.OpenResource);function callbackWrapper(message){userAction=true;try{callback.call(null,new Resource(message.resource),message.lineNumber);}finally{userAction=false;}} -if(!callback) -extensionServer.unregisterHandler(events.OpenResource);else -extensionServer.registerHandler(events.OpenResource,callbackWrapper);if(hadHandler===!callback) -extensionServer.sendRequest({command:commands.SetOpenResourceHandler,'handlerPresent':!!callback});},openResource:function(url,lineNumber,callback){extensionServer.sendRequest({command:commands.OpenResource,'url':url,'lineNumber':lineNumber},callback);},get SearchAction(){return apiPrivate.panels.SearchAction;}};function ExtensionViewImpl(id){this._id=id;function dispatchShowEvent(message){var frameIndex=message.arguments[0];if(typeof frameIndex==='number') -this._fire(window.parent.frames[frameIndex]);else -this._fire();} -if(id){this.onShown=new EventSink(events.ViewShown+id,dispatchShowEvent);this.onHidden=new EventSink(events.ViewHidden+id);}} -function PanelWithSidebarImpl(hostPanelName){ExtensionViewImpl.call(this,null);this._hostPanelName=hostPanelName;this.onSelectionChanged=new EventSink(events.PanelObjectSelected+hostPanelName);} -PanelWithSidebarImpl.prototype={createSidebarPane:function(title,callback){var id='extension-sidebar-'+extensionServer.nextObjectId();var request={command:commands.CreateSidebarPane,panel:this._hostPanelName,id:id,title:title};function callbackWrapper(){callback(new ExtensionSidebarPane(id));} -extensionServer.sendRequest(request,callback&&callbackWrapper);},__proto__:ExtensionViewImpl.prototype};function declareInterfaceClass(implConstructor){return function(){var impl={__proto__:implConstructor.prototype};implConstructor.apply(impl,arguments);populateInterfaceClass(this,impl);};} -function defineDeprecatedProperty(object,className,oldName,newName){var warningGiven=false;function getter(){if(!warningGiven){console.warn(className+'.'+oldName+' is deprecated. Use '+className+'.'+newName+' instead');warningGiven=true;} -return object[newName];} -object.__defineGetter__(oldName,getter);} -function extractCallbackArgument(args){var lastArgument=args[args.length-1];return typeof lastArgument==='function'?lastArgument:undefined;} -var AuditCategory=declareInterfaceClass(AuditCategoryImpl);var AuditResult=declareInterfaceClass(AuditResultImpl);var Button=declareInterfaceClass(ButtonImpl);var EventSink=declareInterfaceClass(EventSinkImpl);var ExtensionPanel=declareInterfaceClass(ExtensionPanelImpl);var ExtensionSidebarPane=declareInterfaceClass(ExtensionSidebarPaneImpl);var PanelWithSidebar=declareInterfaceClass(PanelWithSidebarImpl);var Request=declareInterfaceClass(RequestImpl);var Resource=declareInterfaceClass(ResourceImpl);var TraceSession=declareInterfaceClass(TraceSessionImpl);function ElementsPanel(){PanelWithSidebar.call(this,'elements');} -ElementsPanel.prototype={__proto__:PanelWithSidebar.prototype};function SourcesPanel(){PanelWithSidebar.call(this,'sources');} -SourcesPanel.prototype={__proto__:PanelWithSidebar.prototype};function ExtensionPanelImpl(id){ExtensionViewImpl.call(this,id);this.onSearch=new EventSink(events.PanelSearch+id);} -ExtensionPanelImpl.prototype={createStatusBarButton:function(iconPath,tooltipText,disabled){var id='button-'+extensionServer.nextObjectId();var request={command:commands.CreateToolbarButton,panel:this._id,id:id,icon:iconPath,tooltip:tooltipText,disabled:!!disabled};extensionServer.sendRequest(request);return new Button(id);},show:function(){if(!userAction) -return;var request={command:commands.ShowPanel,id:this._id};extensionServer.sendRequest(request);},__proto__:ExtensionViewImpl.prototype};function ExtensionSidebarPaneImpl(id){ExtensionViewImpl.call(this,id);} -ExtensionSidebarPaneImpl.prototype={setHeight:function(height){extensionServer.sendRequest({command:commands.SetSidebarHeight,id:this._id,height:height});},setExpression:function(expression,rootTitle,evaluateOptions){var request={command:commands.SetSidebarContent,id:this._id,expression:expression,rootTitle:rootTitle,evaluateOnPage:true,};if(typeof evaluateOptions==='object') -request.evaluateOptions=evaluateOptions;extensionServer.sendRequest(request,extractCallbackArgument(arguments));},setObject:function(jsonObject,rootTitle,callback){extensionServer.sendRequest({command:commands.SetSidebarContent,id:this._id,expression:jsonObject,rootTitle:rootTitle},callback);},setPage:function(page){extensionServer.sendRequest({command:commands.SetSidebarPage,id:this._id,page:page});},__proto__:ExtensionViewImpl.prototype};function ButtonImpl(id){this._id=id;this.onClicked=new EventSink(events.ButtonClicked+id);} -ButtonImpl.prototype={update:function(iconPath,tooltipText,disabled){var request={command:commands.UpdateButton,id:this._id,icon:iconPath,tooltip:tooltipText,disabled:!!disabled};extensionServer.sendRequest(request);}};function Timeline(){} -Timeline.prototype={addTraceProvider:function(categoryName,categoryTooltip){var id='extension-trace-provider-'+extensionServer.nextObjectId();extensionServer.sendRequest({command:commands.AddTraceProvider,id:id,categoryName:categoryName,categoryTooltip:categoryTooltip});return new TraceProvider(id);}};function TraceSessionImpl(id){this._id=id;} -TraceSessionImpl.prototype={complete:function(url,timeOffset){var request={command:commands.CompleteTraceSession,id:this._id,url:url||'',timeOffset:timeOffset||0};extensionServer.sendRequest(request);}};function TraceProvider(id){function dispatchRecordingStarted(message){var sessionId=message.arguments[0];this._fire(new TraceSession(sessionId));} -this.onRecordingStarted=new EventSink(events.RecordingStarted+id,dispatchRecordingStarted);this.onRecordingStopped=new EventSink(events.RecordingStopped+id);} -function Audits(){} -Audits.prototype={addCategory:function(displayName,resultCount){var id='extension-audit-category-'+extensionServer.nextObjectId();if(typeof resultCount!=='undefined'){console.warn('Passing resultCount to audits.addCategory() is deprecated. Use AuditResult.updateProgress() instead.');} -extensionServer.sendRequest({command:commands.AddAuditCategory,id:id,displayName:displayName,resultCount:resultCount});return new AuditCategory(id);}};function AuditCategoryImpl(id){function dispatchAuditEvent(request){var auditResult=new AuditResult(request.arguments[0]);try{this._fire(auditResult);}catch(e){console.error('Uncaught exception in extension audit event handler: '+e);auditResult.done();}} -this._id=id;this.onAuditStarted=new EventSink(events.AuditStarted+id,dispatchAuditEvent);} -function AuditResultImpl(id){this._id=id;this.createURL=this._nodeFactory.bind(this,'url');this.createSnippet=this._nodeFactory.bind(this,'snippet');this.createText=this._nodeFactory.bind(this,'text');this.createObject=this._nodeFactory.bind(this,'object');this.createNode=this._nodeFactory.bind(this,'node');} -AuditResultImpl.prototype={addResult:function(displayName,description,severity,details){if(details&&!(details instanceof AuditResultNode)) -details=new AuditResultNode(Array.isArray(details)?details:[details]);var request={command:commands.AddAuditResult,resultId:this._id,displayName:displayName,description:description,severity:severity,details:details};extensionServer.sendRequest(request);},createResult:function(){return new AuditResultNode(Array.prototype.slice.call(arguments));},updateProgress:function(worked,totalWork){extensionServer.sendRequest({command:commands.UpdateAuditProgress,resultId:this._id,progress:worked/totalWork});},done:function(){extensionServer.sendRequest({command:commands.StopAuditCategoryRun,resultId:this._id});},get Severity(){return apiPrivate.audits.Severity;},createResourceLink:function(url,lineNumber){return{type:'resourceLink',arguments:[url,lineNumber&&lineNumber-1]};},_nodeFactory:function(type){return{type:type,arguments:Array.prototype.slice.call(arguments,1)};}};function AuditResultNode(contents){this.contents=contents;this.children=[];this.expanded=false;} -AuditResultNode.prototype={addChild:function(){var node=new AuditResultNode(Array.prototype.slice.call(arguments));this.children.push(node);return node;}};function InspectedWindow(){function dispatchResourceEvent(message){this._fire(new Resource(message.arguments[0]));} -function dispatchResourceContentEvent(message){this._fire(new Resource(message.arguments[0]),message.arguments[1]);} -this.onResourceAdded=new EventSink(events.ResourceAdded,dispatchResourceEvent);this.onResourceContentCommitted=new EventSink(events.ResourceContentCommitted,dispatchResourceContentEvent);} -InspectedWindow.prototype={reload:function(optionsOrUserAgent){var options=null;if(typeof optionsOrUserAgent==='object'){options=optionsOrUserAgent;}else if(typeof optionsOrUserAgent==='string'){options={userAgent:optionsOrUserAgent};console.warn('Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. '+'Use inspectedWindow.reload({ userAgent: value}) instead.');} -extensionServer.sendRequest({command:commands.Reload,options:options});},eval:function(expression,evaluateOptions){var callback=extractCallbackArgument(arguments);function callbackWrapper(result){if(result.isError||result.isException) -callback(undefined,result);else -callback(result.value);} -var request={command:commands.EvaluateOnInspectedPage,expression:expression};if(typeof evaluateOptions==='object') -request.evaluateOptions=evaluateOptions;extensionServer.sendRequest(request,callback&&callbackWrapper);return null;},getResources:function(callback){function wrapResource(resourceData){return new Resource(resourceData);} -function callbackWrapper(resources){callback(resources.map(wrapResource));} -extensionServer.sendRequest({command:commands.GetPageResources},callback&&callbackWrapper);}};function ResourceImpl(resourceData){this._url=resourceData.url;this._type=resourceData.type;} -ResourceImpl.prototype={get url(){return this._url;},get type(){return this._type;},getContent:function(callback){function callbackWrapper(response){callback(response.content,response.encoding);} -extensionServer.sendRequest({command:commands.GetResourceContent,url:this._url},callback&&callbackWrapper);},setContent:function(content,commit,callback){extensionServer.sendRequest({command:commands.SetResourceContent,url:this._url,content:content,commit:commit},callback);}};function getTabId(){return inspectedTabId;} -var keyboardEventRequestQueue=[];var forwardTimer=null;function forwardKeyboardEvent(event){if(!event.ctrlKey&&!event.altKey&&!event.metaKey&&!/^F\d+$/.test(event.key)&&event.key!=='Escape') -return;var requestPayload={eventType:event.type,ctrlKey:event.ctrlKey,altKey:event.altKey,metaKey:event.metaKey,key:event.key,key:event.key,code:event.code,location:event.location,keyCode:event.keyCode};keyboardEventRequestQueue.push(requestPayload);if(!forwardTimer) -forwardTimer=setTimeout(forwardEventQueue,0);} -function forwardEventQueue(){forwardTimer=null;var request={command:commands.ForwardKeyboardEvent,entries:keyboardEventRequestQueue};extensionServer.sendRequest(request);keyboardEventRequestQueue=[];} -document.addEventListener('keydown',forwardKeyboardEvent,false);document.addEventListener('keypress',forwardKeyboardEvent,false);function ExtensionServerClient(){this._callbacks={};this._handlers={};this._lastRequestId=0;this._lastObjectId=0;this.registerHandler('callback',this._onCallback.bind(this));var channel=new MessageChannel();this._port=channel.port1;this._port.addEventListener('message',this._onMessage.bind(this),false);this._port.start();window.parent.postMessage('registerExtension','*',[channel.port2]);} -ExtensionServerClient.prototype={sendRequest:function(message,callback){if(typeof callback==='function') -message.requestId=this._registerCallback(callback);this._port.postMessage(message);},hasHandler:function(command){return!!this._handlers[command];},registerHandler:function(command,handler){this._handlers[command]=handler;},unregisterHandler:function(command){delete this._handlers[command];},nextObjectId:function(){return injectedScriptId.toString()+'_'+ ++this._lastObjectId;},_registerCallback:function(callback){var id=++this._lastRequestId;this._callbacks[id]=callback;return id;},_onCallback:function(request){if(request.requestId in this._callbacks){var callback=this._callbacks[request.requestId];delete this._callbacks[request.requestId];callback(request.result);}},_onMessage:function(event){var request=event.data;var handler=this._handlers[request.command];if(handler) -handler.call(this,request);}};function populateInterfaceClass(interfaze,implementation){for(var member in implementation){if(member.charAt(0)==='_') -continue;var descriptor=null;for(var owner=implementation;owner&&!descriptor;owner=owner.__proto__) -descriptor=Object.getOwnPropertyDescriptor(owner,member);if(!descriptor) -continue;if(typeof descriptor.value==='function') -interfaze[member]=descriptor.value.bind(implementation);else if(typeof descriptor.get==='function') -interfaze.__defineGetter__(member,descriptor.get.bind(implementation));else -Object.defineProperty(interfaze,member,descriptor);}} -var extensionServer=new ExtensionServerClient();var coreAPI=new InspectorExtensionAPI();var chrome=window.chrome||{};var devtools_descriptor=Object.getOwnPropertyDescriptor(chrome,'devtools');if(!devtools_descriptor||devtools_descriptor.get) -Object.defineProperty(chrome,'devtools',{value:{},enumerable:true});chrome.devtools.inspectedWindow={};chrome.devtools.inspectedWindow.__defineGetter__('tabId',getTabId);chrome.devtools.inspectedWindow.__proto__=coreAPI.inspectedWindow;chrome.devtools.network=coreAPI.network;chrome.devtools.panels=coreAPI.panels;chrome.devtools.panels.themeName=themeName;if(extensionInfo.exposeExperimentalAPIs!==false){chrome.experimental=chrome.experimental||{};chrome.experimental.devtools=chrome.experimental.devtools||{};var properties=Object.getOwnPropertyNames(coreAPI);for(var i=0;i<properties.length;++i){var descriptor=Object.getOwnPropertyDescriptor(coreAPI,properties[i]);if(descriptor) -Object.defineProperty(chrome.experimental.devtools,properties[i],descriptor);} -chrome.experimental.devtools.inspectedWindow=chrome.devtools.inspectedWindow;} -if(extensionInfo.exposeWebInspectorNamespace) -window.webInspector=coreAPI;testHook(extensionServer,coreAPI);} -function buildExtensionAPIInjectedScript(extensionInfo,inspectedTabId,themeName,testHook){var argumentsJSON=[extensionInfo,inspectedTabId||null,themeName].map(_=>JSON.stringify(_)).join(',');if(!testHook) -testHook=()=>{};return'(function(injectedScriptId){ '+defineCommonExtensionSymbols.toString()+';'+'('+injectedExtensionAPI.toString()+')('+argumentsJSON+','+testHook+', injectedScriptId);'+'})';};Extensions.ExtensionAuditCategory=class{constructor(extensionOrigin,id,displayName,ruleCount){this.extensionOrigin=extensionOrigin;this.id=id;this.displayName=displayName;this.ruleCount=ruleCount;}};Extensions.ExtensionAuditCategoryResults=function(){};Extensions.ExtensionAuditCategoryResults.prototype={id(){},addResult(displayName,description,severity,details){},updateProgress(progress){},done(){}};;if(!window.InspectorExtensionRegistry){Extensions.InspectorExtensionRegistryStub=class{getExtensionsAsync(){}};var InspectorExtensionRegistry=new Extensions.InspectorExtensionRegistryStub();};Extensions.ExtensionTraceProvider=class{constructor(extensionOrigin,id,categoryName,categoryTooltip){this._extensionOrigin=extensionOrigin;this._id=id;this._categoryName=categoryName;this._categoryTooltip=categoryTooltip;} -start(session){var sessionId=String(++Extensions.ExtensionTraceProvider._lastSessionId);Extensions.extensionServer.startTraceRecording(this._id,sessionId,session);} -stop(){Extensions.extensionServer.stopTraceRecording(this._id);} -shortDisplayName(){return this._categoryName;} -longDisplayName(){return this._categoryTooltip;} -persistentIdentifier(){return`${this._extensionOrigin}/${this._categoryName}`;}};Extensions.ExtensionTraceProvider._lastSessionId=0;Extensions.TracingSession=function(){};Extensions.TracingSession.prototype={complete:function(url,timeOffsetMicroseconds){}};;Extensions.ExtensionServer=class extends Common.Object{constructor(){super();this._clientObjects={};this._handlers={};this._subscribers={};this._subscriptionStartHandlers={};this._subscriptionStopHandlers={};this._extraHeaders={};this._requests={};this._lastRequestId=0;this._registeredExtensions={};this._status=new Extensions.ExtensionStatus();this._sidebarPanes=[];this._auditCategories=[];this._traceProviders=[];this._traceSessions=new Map();var commands=Extensions.extensionAPI.Commands;this._registerHandler(commands.AddAuditCategory,this._onAddAuditCategory.bind(this));this._registerHandler(commands.AddAuditResult,this._onAddAuditResult.bind(this));this._registerHandler(commands.AddRequestHeaders,this._onAddRequestHeaders.bind(this));this._registerHandler(commands.AddTraceProvider,this._onAddTraceProvider.bind(this));this._registerHandler(commands.ApplyStyleSheet,this._onApplyStyleSheet.bind(this));this._registerHandler(commands.CompleteTraceSession,this._onCompleteTraceSession.bind(this));this._registerHandler(commands.CreatePanel,this._onCreatePanel.bind(this));this._registerHandler(commands.CreateSidebarPane,this._onCreateSidebarPane.bind(this));this._registerHandler(commands.CreateToolbarButton,this._onCreateToolbarButton.bind(this));this._registerHandler(commands.EvaluateOnInspectedPage,this._onEvaluateOnInspectedPage.bind(this));this._registerHandler(commands.ForwardKeyboardEvent,this._onForwardKeyboardEvent.bind(this));this._registerHandler(commands.GetHAR,this._onGetHAR.bind(this));this._registerHandler(commands.GetPageResources,this._onGetPageResources.bind(this));this._registerHandler(commands.GetRequestContent,this._onGetRequestContent.bind(this));this._registerHandler(commands.GetResourceContent,this._onGetResourceContent.bind(this));this._registerHandler(commands.Reload,this._onReload.bind(this));this._registerHandler(commands.SetOpenResourceHandler,this._onSetOpenResourceHandler.bind(this));this._registerHandler(commands.SetResourceContent,this._onSetResourceContent.bind(this));this._registerHandler(commands.SetSidebarHeight,this._onSetSidebarHeight.bind(this));this._registerHandler(commands.SetSidebarContent,this._onSetSidebarContent.bind(this));this._registerHandler(commands.SetSidebarPage,this._onSetSidebarPage.bind(this));this._registerHandler(commands.ShowPanel,this._onShowPanel.bind(this));this._registerHandler(commands.StopAuditCategoryRun,this._onStopAuditCategoryRun.bind(this));this._registerHandler(commands.Subscribe,this._onSubscribe.bind(this));this._registerHandler(commands.OpenResource,this._onOpenResource.bind(this));this._registerHandler(commands.Unsubscribe,this._onUnsubscribe.bind(this));this._registerHandler(commands.UpdateButton,this._onUpdateButton.bind(this));this._registerHandler(commands.UpdateAuditProgress,this._onUpdateAuditProgress.bind(this));window.addEventListener('message',this._onWindowMessage.bind(this),false);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.AddExtensions,this._addExtensions,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SetInspectedTabId,this._setInspectedTabId,this);this._initExtensions();} -initializeExtensions(){this._initializeCommandIssued=true;if(this._pendingExtensionInfos){this._pendingExtensionInfos.forEach(this._addExtension,this);delete this._pendingExtensionInfos;}} -hasExtensions(){return!!Object.keys(this._registeredExtensions).length;} -notifySearchAction(panelId,action,searchString){this._postNotification(Extensions.extensionAPI.Events.PanelSearch+panelId,action,searchString);} -notifyViewShown(identifier,frameIndex){this._postNotification(Extensions.extensionAPI.Events.ViewShown+identifier,frameIndex);} -notifyViewHidden(identifier){this._postNotification(Extensions.extensionAPI.Events.ViewHidden+identifier);} -notifyButtonClicked(identifier){this._postNotification(Extensions.extensionAPI.Events.ButtonClicked+identifier);} -_inspectedURLChanged(event){if(event.data!==SDK.targetManager.mainTarget()) -return;this._requests={};var url=event.data.inspectedURL();this._postNotification(Extensions.extensionAPI.Events.InspectedURLChanged,url);} -startAuditRun(categoryId,auditResults){this._clientObjects[auditResults.id()]=auditResults;this._postNotification('audit-started-'+categoryId,auditResults.id());} -stopAuditRun(auditResults){delete this._clientObjects[auditResults.id()];} -startTraceRecording(providerId,sessionId,session){this._traceSessions.set(sessionId,session);this._postNotification('trace-recording-started-'+providerId,sessionId);} -stopTraceRecording(providerId){this._postNotification('trace-recording-stopped-'+providerId);} -hasSubscribers(type){return!!this._subscribers[type];} -_postNotification(type,vararg){var subscribers=this._subscribers[type];if(!subscribers) -return;var message={command:'notify-'+type,arguments:Array.prototype.slice.call(arguments,1)};for(var i=0;i<subscribers.length;++i) -subscribers[i].postMessage(message);} -_onSubscribe(message,port){var subscribers=this._subscribers[message.type];if(subscribers){subscribers.push(port);}else{this._subscribers[message.type]=[port];if(this._subscriptionStartHandlers[message.type]) -this._subscriptionStartHandlers[message.type]();}} -_onUnsubscribe(message,port){var subscribers=this._subscribers[message.type];if(!subscribers) -return;subscribers.remove(port);if(!subscribers.length){delete this._subscribers[message.type];if(this._subscriptionStopHandlers[message.type]) -this._subscriptionStopHandlers[message.type]();}} -_onAddRequestHeaders(message){var id=message.extensionId;if(typeof id!=='string') -return this._status.E_BADARGTYPE('extensionId',typeof id,'string');var extensionHeaders=this._extraHeaders[id];if(!extensionHeaders){extensionHeaders={};this._extraHeaders[id]=extensionHeaders;} -for(var name in message.headers) -extensionHeaders[name]=message.headers[name];var allHeaders=({});for(var extension in this._extraHeaders){var headers=this._extraHeaders[extension];for(name in headers){if(typeof headers[name]==='string') -allHeaders[name]=headers[name];}} -SDK.multitargetNetworkManager.setExtraHTTPHeaders(allHeaders);} -_onApplyStyleSheet(message){if(!Runtime.experiments.isEnabled('applyCustomStylesheet')) -return;var styleSheet=createElement('style');styleSheet.textContent=message.styleSheet;document.head.appendChild(styleSheet);UI.themeSupport.addCustomStylesheet(message.styleSheet);for(var node=document.body;node;node=node.traverseNextNode(document.body)){if(node instanceof ShadowRoot) -UI.themeSupport.injectCustomStyleSheets(node);}} -_onCreatePanel(message,port){var id=message.id;if(id in this._clientObjects||UI.inspectorView.hasPanel(id)) -return this._status.E_EXISTS(id);var page=this._expandResourcePath(port._extensionOrigin,message.page);var persistentId=port._extensionOrigin+message.title;persistentId=persistentId.replace(/\s/g,'');var panelView=new Extensions.ExtensionServerPanelView(persistentId,message.title,new Extensions.ExtensionPanel(this,persistentId,id,page));this._clientObjects[id]=panelView;UI.inspectorView.addPanel(panelView);return this._status.OK();} -_onShowPanel(message){var panelViewId=message.id;var panelView=this._clientObjects[message.id];if(panelView&&panelView instanceof Extensions.ExtensionServerPanelView) -panelViewId=panelView.viewId();UI.inspectorView.showPanel(panelViewId);} -_onCreateToolbarButton(message,port){var panelView=this._clientObjects[message.panel];if(!panelView||!(panelView instanceof Extensions.ExtensionServerPanelView)) -return this._status.E_NOTFOUND(message.panel);var button=new Extensions.ExtensionButton(this,message.id,this._expandResourcePath(port._extensionOrigin,message.icon),message.tooltip,message.disabled);this._clientObjects[message.id]=button;panelView.widget().then(appendButton);function appendButton(panel){(panel).addToolbarItem(button.toolbarButton());} -return this._status.OK();} -_onUpdateButton(message,port){var button=this._clientObjects[message.id];if(!button||!(button instanceof Extensions.ExtensionButton)) -return this._status.E_NOTFOUND(message.id);button.update(this._expandResourcePath(port._extensionOrigin,message.icon),message.tooltip,message.disabled);return this._status.OK();} -_onCompleteTraceSession(message){var session=this._traceSessions.get(message.id);if(!session) -return this._status.E_NOTFOUND(message.id);this._traceSessions.delete(message.id);session.complete(message.url,message.timeOffset);} -_onCreateSidebarPane(message){if(message.panel!=='elements'&&message.panel!=='sources') -return this._status.E_NOTFOUND(message.panel);var id=message.id;var sidebar=new Extensions.ExtensionSidebarPane(this,message.panel,message.title,id);this._sidebarPanes.push(sidebar);this._clientObjects[id]=sidebar;this.dispatchEventToListeners(Extensions.ExtensionServer.Events.SidebarPaneAdded,sidebar);return this._status.OK();} -sidebarPanes(){return this._sidebarPanes;} -_onSetSidebarHeight(message){var sidebar=this._clientObjects[message.id];if(!sidebar) -return this._status.E_NOTFOUND(message.id);sidebar.setHeight(message.height);return this._status.OK();} -_onSetSidebarContent(message,port){var sidebar=this._clientObjects[message.id];if(!sidebar) -return this._status.E_NOTFOUND(message.id);function callback(error){var result=error?this._status.E_FAILED(error):this._status.OK();this._dispatchCallback(message.requestId,port,result);} -if(message.evaluateOnPage){return sidebar.setExpression(message.expression,message.rootTitle,message.evaluateOptions,port._extensionOrigin,callback.bind(this));} -sidebar.setObject(message.expression,message.rootTitle,callback.bind(this));} -_onSetSidebarPage(message,port){var sidebar=this._clientObjects[message.id];if(!sidebar) -return this._status.E_NOTFOUND(message.id);sidebar.setPage(this._expandResourcePath(port._extensionOrigin,message.page));} -_onOpenResource(message){var uiSourceCode=Workspace.workspace.uiSourceCodeForURL(message.url);if(uiSourceCode){Common.Revealer.reveal(uiSourceCode.uiLocation(message.lineNumber,0));return this._status.OK();} -var resource=Bindings.resourceForURL(message.url);if(resource){Common.Revealer.reveal(resource);return this._status.OK();} -var request=NetworkLog.networkLog.requestForURL(message.url);if(request){Common.Revealer.reveal(request);return this._status.OK();} -return this._status.E_NOTFOUND(message.url);} -_onSetOpenResourceHandler(message,port){var name=this._registeredExtensions[port._extensionOrigin].name||('Extension '+port._extensionOrigin);if(message.handlerPresent) -Components.Linkifier.registerLinkHandler(name,this._handleOpenURL.bind(this,port));else -Components.Linkifier.unregisterLinkHandler(name);} -_handleOpenURL(port,contentProvider,lineNumber){port.postMessage({command:'open-resource',resource:this._makeResource(contentProvider),lineNumber:lineNumber+1});} -_onReload(message){var options=(message.options||{});SDK.multitargetNetworkManager.setUserAgentOverride(typeof options.userAgent==='string'?options.userAgent:'');var injectedScript;if(options.injectedScript) -injectedScript='(function(){'+options.injectedScript+'})()';SDK.ResourceTreeModel.reloadAllPages(!!options.ignoreCache,injectedScript);return this._status.OK();} -_onEvaluateOnInspectedPage(message,port){function callback(error,object,wasThrown){var result;if(error||!object) -result=this._status.E_PROTOCOLERROR(error.toString());else if(wasThrown) -result={isException:true,value:object.description};else -result={value:object.value};this._dispatchCallback(message.requestId,port,result);} -return this.evaluate(message.expression,true,true,message.evaluateOptions,port._extensionOrigin,callback.bind(this));} -_onGetHAR(){var requests=NetworkLog.networkLog.requests();var harLog=(new NetworkLog.HARLog(requests)).build();for(var i=0;i<harLog.entries.length;++i) -harLog.entries[i]._requestId=this._requestId(requests[i]);return harLog;} -_makeResource(contentProvider){return{url:contentProvider.contentURL(),type:contentProvider.contentType().name()};} -_onGetPageResources(){var resources=new Map();function pushResourceData(contentProvider){if(!resources.has(contentProvider.contentURL())) -resources.set(contentProvider.contentURL(),this._makeResource(contentProvider));} -var uiSourceCodes=Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.Network);uiSourceCodes=uiSourceCodes.concat(Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.ContentScripts));uiSourceCodes.forEach(pushResourceData.bind(this));for(var resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) -resourceTreeModel.forAllResources(pushResourceData.bind(this));return resources.valuesArray();} -async _getResourceContent(contentProvider,message,port){var content=await contentProvider.requestContent();var encoded=await contentProvider.contentEncoded();this._dispatchCallback(message.requestId,port,{encoding:encoded?'base64':'',content:content});} -_onGetRequestContent(message,port){var request=this._requestById(message.id);if(!request) -return this._status.E_NOTFOUND(message.id);this._getResourceContent(request,message,port);} -_onGetResourceContent(message,port){var url=(message.url);var contentProvider=Workspace.workspace.uiSourceCodeForURL(url)||Bindings.resourceForURL(url);if(!contentProvider) -return this._status.E_NOTFOUND(url);this._getResourceContent(contentProvider,message,port);} -_onSetResourceContent(message,port){function callbackWrapper(error){var response=error?this._status.E_FAILED(error):this._status.OK();this._dispatchCallback(message.requestId,port,response);} -var url=(message.url);var uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);if(!uiSourceCode||!uiSourceCode.contentType().isDocumentOrScriptOrStyleSheet()){var resource=SDK.ResourceTreeModel.resourceForURL(url);if(!resource) -return this._status.E_NOTFOUND(url);return this._status.E_NOTSUPPORTED('Resource is not editable');} -uiSourceCode.setWorkingCopy(message.content);if(message.commit) -uiSourceCode.commitWorkingCopy();callbackWrapper.call(this,null);} -_requestId(request){if(!request._extensionRequestId){request._extensionRequestId=++this._lastRequestId;this._requests[request._extensionRequestId]=request;} -return request._extensionRequestId;} -_requestById(id){return this._requests[id];} -_onAddAuditCategory(message,port){var category=new Extensions.ExtensionAuditCategory(port._extensionOrigin,message.id,message.displayName,message.resultCount);this._clientObjects[message.id]=category;this._auditCategories.push(category);this.dispatchEventToListeners(Extensions.ExtensionServer.Events.AuditCategoryAdded,category);} -_onAddTraceProvider(message,port){var provider=new Extensions.ExtensionTraceProvider(port._extensionOrigin,message.id,message.categoryName,message.categoryTooltip);this._clientObjects[message.id]=provider;this._traceProviders.push(provider);this.dispatchEventToListeners(Extensions.ExtensionServer.Events.TraceProviderAdded,provider);} -traceProviders(){return this._traceProviders;} -auditCategories(){return this._auditCategories;} -_onAddAuditResult(message){var auditResult=(this._clientObjects[message.resultId]);if(!auditResult) -return this._status.E_NOTFOUND(message.resultId);try{auditResult.addResult(message.displayName,message.description,message.severity,message.details);}catch(e){return e;} -return this._status.OK();} -_onUpdateAuditProgress(message){var auditResult=(this._clientObjects[message.resultId]);if(!auditResult) -return this._status.E_NOTFOUND(message.resultId);auditResult.updateProgress(Math.min(Math.max(0,message.progress),1));} -_onStopAuditCategoryRun(message){var auditRun=(this._clientObjects[message.resultId]);if(!auditRun) -return this._status.E_NOTFOUND(message.resultId);auditRun.done();} -_onForwardKeyboardEvent(message){message.entries.forEach(handleEventEntry);function handleEventEntry(entry){if(!entry.ctrlKey&&!entry.altKey&&!entry.metaKey&&!/^F\d+$/.test(entry.key)&&entry.key!=='Escape') -return;var event=new window.KeyboardEvent(entry.eventType,{key:entry.key,code:entry.code,keyCode:entry.keyCode,location:entry.location,ctrlKey:entry.ctrlKey,altKey:entry.altKey,shiftKey:entry.shiftKey,metaKey:entry.metaKey});event.__keyCode=keyCodeForEntry(entry);document.dispatchEvent(event);} -function keyCodeForEntry(entry){var keyCode=entry.keyCode;if(!keyCode){if(entry.key==='Escape') -keyCode=27;} -return keyCode||0;}} -_dispatchCallback(requestId,port,result){if(requestId) -port.postMessage({command:'callback',requestId:requestId,result:result});} -_initExtensions(){this._registerAutosubscriptionHandler(Extensions.extensionAPI.Events.ResourceAdded,Workspace.workspace,Workspace.Workspace.Events.UISourceCodeAdded,this._notifyResourceAdded);this._registerAutosubscriptionTargetManagerHandler(Extensions.extensionAPI.Events.NetworkRequestFinished,SDK.NetworkManager,SDK.NetworkManager.Events.RequestFinished,this._notifyRequestFinished);function onElementsSubscriptionStarted(){UI.context.addFlavorChangeListener(SDK.DOMNode,this._notifyElementsSelectionChanged,this);} -function onElementsSubscriptionStopped(){UI.context.removeFlavorChangeListener(SDK.DOMNode,this._notifyElementsSelectionChanged,this);} -this._registerSubscriptionHandler(Extensions.extensionAPI.Events.PanelObjectSelected+'elements',onElementsSubscriptionStarted.bind(this),onElementsSubscriptionStopped.bind(this));this._registerResourceContentCommittedHandler(this._notifyUISourceCodeContentCommitted);SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._inspectedURLChanged,this);InspectorExtensionRegistry.getExtensionsAsync();} -_notifyResourceAdded(event){var uiSourceCode=(event.data);this._postNotification(Extensions.extensionAPI.Events.ResourceAdded,this._makeResource(uiSourceCode));} -_notifyUISourceCodeContentCommitted(event){var uiSourceCode=(event.data.uiSourceCode);var content=(event.data.content);this._postNotification(Extensions.extensionAPI.Events.ResourceContentCommitted,this._makeResource(uiSourceCode),content);} -_notifyRequestFinished(event){var request=(event.data);this._postNotification(Extensions.extensionAPI.Events.NetworkRequestFinished,this._requestId(request),(new NetworkLog.HAREntry(request)).build());} -_notifyElementsSelectionChanged(){this._postNotification(Extensions.extensionAPI.Events.PanelObjectSelected+'elements');} -sourceSelectionChanged(url,range){this._postNotification(Extensions.extensionAPI.Events.PanelObjectSelected+'sources',{startLine:range.startLine,startColumn:range.startColumn,endLine:range.endLine,endColumn:range.endColumn,url:url,});} -_addExtensions(event){if(Extensions.extensionServer._overridePlatformExtensionAPIForTest) -window.buildPlatformExtensionAPI=Extensions.extensionServer._overridePlatformExtensionAPIForTest;var extensionInfos=(event.data);if(this._initializeCommandIssued) -extensionInfos.forEach(this._addExtension,this);else -this._pendingExtensionInfos=extensionInfos;} -_setInspectedTabId(event){this._inspectedTabId=(event.data);} -_addExtension(extensionInfo){const urlOriginRegExp=new RegExp('([^:]+:\/\/[^/]*)\/');var startPage=extensionInfo.startPage;var name=extensionInfo.name;try{var originMatch=urlOriginRegExp.exec(startPage);if(!originMatch){console.error('Skipping extension with invalid URL: '+startPage);return false;} -var extensionOrigin=originMatch[1];if(!this._registeredExtensions[extensionOrigin]){var injectedAPI=buildExtensionAPIInjectedScript(extensionInfo,this._inspectedTabId,UI.themeSupport.themeName(),Extensions.extensionServer['_extensionAPITestHook']);InspectorFrontendHost.setInjectedScriptForOrigin(extensionOrigin,injectedAPI);this._registeredExtensions[extensionOrigin]={name:name};} -var iframe=createElement('iframe');iframe.src=startPage;iframe.style.display='none';document.body.appendChild(iframe);}catch(e){console.error('Failed to initialize extension '+startPage+':'+e);return false;} -return true;} -_registerExtension(origin,port){if(!this._registeredExtensions.hasOwnProperty(origin)){if(origin!==window.location.origin) -console.error('Ignoring unauthorized client request from '+origin);return;} -port._extensionOrigin=origin;port.addEventListener('message',this._onmessage.bind(this),false);port.start();} -_onWindowMessage(event){if(event.data==='registerExtension') -this._registerExtension(event.origin,event.ports[0]);} -_onmessage(event){var message=event.data;var result;if(message.command in this._handlers) -result=this._handlers[message.command](message,event.target);else -result=this._status.E_NOTSUPPORTED(message.command);if(result&&message.requestId) -this._dispatchCallback(message.requestId,event.target,result);} -_registerHandler(command,callback){console.assert(command);this._handlers[command]=callback;} -_registerSubscriptionHandler(eventTopic,onSubscribeFirst,onUnsubscribeLast){this._subscriptionStartHandlers[eventTopic]=onSubscribeFirst;this._subscriptionStopHandlers[eventTopic]=onUnsubscribeLast;} -_registerAutosubscriptionHandler(eventTopic,eventTarget,frontendEventType,handler){this._registerSubscriptionHandler(eventTopic,eventTarget.addEventListener.bind(eventTarget,frontendEventType,handler,this),eventTarget.removeEventListener.bind(eventTarget,frontendEventType,handler,this));} -_registerAutosubscriptionTargetManagerHandler(eventTopic,modelClass,frontendEventType,handler){this._registerSubscriptionHandler(eventTopic,SDK.targetManager.addModelListener.bind(SDK.targetManager,modelClass,frontendEventType,handler,this),SDK.targetManager.removeModelListener.bind(SDK.targetManager,modelClass,frontendEventType,handler,this));} -_registerResourceContentCommittedHandler(handler){function addFirstEventListener(){Workspace.workspace.addEventListener(Workspace.Workspace.Events.WorkingCopyCommittedByUser,handler,this);Workspace.workspace.setHasResourceContentTrackingExtensions(true);} -function removeLastEventListener(){Workspace.workspace.setHasResourceContentTrackingExtensions(false);Workspace.workspace.removeEventListener(Workspace.Workspace.Events.WorkingCopyCommittedByUser,handler,this);} -this._registerSubscriptionHandler(Extensions.extensionAPI.Events.ResourceContentCommitted,addFirstEventListener.bind(this),removeLastEventListener.bind(this));} -_expandResourcePath(extensionPath,resourcePath){if(!resourcePath) -return;return extensionPath+this._normalizePath(resourcePath);} -_normalizePath(path){var source=path.split('/');var result=[];for(var i=0;i<source.length;++i){if(source[i]==='.') -continue;if(source[i]==='') -continue;if(source[i]==='..') -result.pop();else -result.push(source[i]);} -return'/'+result.join('/');} -evaluate(expression,exposeCommandLineAPI,returnByValue,options,securityOrigin,callback){var context;function resolveURLToFrame(url){var found;function hasMatchingURL(frame){found=(frame.url===url)?frame:null;return found;} -SDK.ResourceTreeModel.frames().some(hasMatchingURL);return found;} -options=options||{};var frame;if(options.frameURL){frame=resolveURLToFrame(options.frameURL);}else{var target=SDK.targetManager.mainTarget();var resourceTreeModel=target&&target.model(SDK.ResourceTreeModel);frame=resourceTreeModel&&resourceTreeModel.mainFrame;} -if(!frame){if(options.frameURL) -console.warn('evaluate: there is no frame with URL '+options.frameURL);else -console.warn('evaluate: the main frame is not yet available');return this._status.E_NOTFOUND(options.frameURL||'<top>');} -var contextSecurityOrigin;if(options.useContentScriptContext) -contextSecurityOrigin=securityOrigin;else if(options.scriptExecutionContext) -contextSecurityOrigin=options.scriptExecutionContext;var runtimeModel=frame.resourceTreeModel().target().model(SDK.RuntimeModel);var executionContexts=runtimeModel?runtimeModel.executionContexts():[];if(contextSecurityOrigin){for(var i=0;i<executionContexts.length;++i){var executionContext=executionContexts[i];if(executionContext.frameId===frame.id&&executionContext.origin===contextSecurityOrigin&&!executionContext.isDefault) -context=executionContext;} -if(!context){console.warn('The JavaScript context '+contextSecurityOrigin+' was not found in the frame '+frame.url);return this._status.E_NOTFOUND(contextSecurityOrigin);}}else{for(var i=0;i<executionContexts.length;++i){var executionContext=executionContexts[i];if(executionContext.frameId===frame.id&&executionContext.isDefault) -context=executionContext;} -if(!context) -return this._status.E_FAILED(frame.url+' has no execution context');} -context.evaluate({expression:expression,objectGroup:'extension',includeCommandLineAPI:exposeCommandLineAPI,silent:true,returnByValue:returnByValue,generatePreview:false},false,false).then(onEvaluate);function onEvaluate(result){if(result.error){callback(result.error,null,false);return;} -callback(null,result.object||null,!!result.exceptionDetails);}}};Extensions.ExtensionServer.Events={SidebarPaneAdded:Symbol('SidebarPaneAdded'),AuditCategoryAdded:Symbol('AuditCategoryAdded'),TraceProviderAdded:Symbol('TraceProviderAdded')};Extensions.ExtensionServerPanelView=class extends UI.SimpleView{constructor(name,title,panel){super(title);this._name=name;this._panel=panel;} -viewId(){return this._name;} -widget(){return(Promise.resolve(this._panel));}};Extensions.ExtensionStatus=class{constructor(){function makeStatus(code,description){var details=Array.prototype.slice.call(arguments,2);var status={code:code,description:description,details:details};if(code!=='OK'){status.isError=true;console.error('Extension server error: '+String.vsprintf(description,details));} -return status;} -this.OK=makeStatus.bind(null,'OK','OK');this.E_EXISTS=makeStatus.bind(null,'E_EXISTS','Object already exists: %s');this.E_BADARG=makeStatus.bind(null,'E_BADARG','Invalid argument %s: %s');this.E_BADARGTYPE=makeStatus.bind(null,'E_BADARGTYPE','Invalid type for argument %s: got %s, expected %s');this.E_NOTFOUND=makeStatus.bind(null,'E_NOTFOUND','Object not found: %s');this.E_NOTSUPPORTED=makeStatus.bind(null,'E_NOTSUPPORTED','Object does not support requested operation: %s');this.E_PROTOCOLERROR=makeStatus.bind(null,'E_PROTOCOLERROR','Inspector protocol error: %s');this.E_FAILED=makeStatus.bind(null,'E_FAILED','Operation failed: %s');}};Extensions.ExtensionStatus.Record;Extensions.extensionAPI={};defineCommonExtensionSymbols(Extensions.extensionAPI);Extensions.extensionServer;;Extensions.ExtensionPanel=class extends UI.Panel{constructor(server,panelName,id,pageURL){super(panelName);this._server=server;this._id=id;this.setHideOnDetach();this._panelToolbar=new UI.Toolbar('hidden',this.element);this._searchableView=new UI.SearchableView(this);this._searchableView.show(this.element);var extensionView=new Extensions.ExtensionView(server,this._id,pageURL,'extension');extensionView.show(this._searchableView.element);} -addToolbarItem(item){this._panelToolbar.element.classList.remove('hidden');this._panelToolbar.appendToolbarItem(item);} -searchCanceled(){this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.CancelSearch);this._searchableView.updateSearchMatchesCount(0);} -searchableView(){return this._searchableView;} -performSearch(searchConfig,shouldJump,jumpBackwards){var query=searchConfig.query;this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.PerformSearch,query);} -jumpToNextSearchResult(){this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.NextSearchResult);} -jumpToPreviousSearchResult(){this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.PreviousSearchResult);} -supportsCaseSensitiveSearch(){return false;} -supportsRegexSearch(){return false;}};Extensions.ExtensionButton=class{constructor(server,id,iconURL,tooltip,disabled){this._id=id;this._toolbarButton=new UI.ToolbarButton('','');this._toolbarButton.addEventListener(UI.ToolbarButton.Events.Click,server.notifyButtonClicked.bind(server,this._id));this.update(iconURL,tooltip,disabled);} -update(iconURL,tooltip,disabled){if(typeof iconURL==='string') -this._toolbarButton.setBackgroundImage(iconURL);if(typeof tooltip==='string') -this._toolbarButton.setTitle(tooltip);if(typeof disabled==='boolean') -this._toolbarButton.setEnabled(!disabled);} -toolbarButton(){return this._toolbarButton;}};Extensions.ExtensionSidebarPane=class extends UI.SimpleView{constructor(server,panelName,title,id){super(title);this.element.classList.add('fill');this._panelName=panelName;this._server=server;this._id=id;} -id(){return this._id;} -panelName(){return this._panelName;} -setObject(object,title,callback){this._createObjectPropertiesView();this._setObject(SDK.RemoteObject.fromLocalObject(object),title,callback);} -setExpression(expression,title,evaluateOptions,securityOrigin,callback){this._createObjectPropertiesView();this._server.evaluate(expression,true,false,evaluateOptions,securityOrigin,this._onEvaluate.bind(this,title,callback));} -setPage(url){if(this._objectPropertiesView){this._objectPropertiesView.detach();delete this._objectPropertiesView;} -if(this._extensionView) -this._extensionView.detach(true);this._extensionView=new Extensions.ExtensionView(this._server,this._id,url,'extension fill');this._extensionView.show(this.element);if(!this.element.style.height) -this.setHeight('150px');} -setHeight(height){this.element.style.height=height;} -_onEvaluate(title,callback,error,result,wasThrown){if(error||!result) -callback(error.toString());else -this._setObject(result,title,callback);} -_createObjectPropertiesView(){if(this._objectPropertiesView) -return;if(this._extensionView){this._extensionView.detach(true);delete this._extensionView;} -this._objectPropertiesView=new Extensions.ExtensionNotifierView(this._server,this._id);this._objectPropertiesView.show(this.element);} -_setObject(object,title,callback){if(!this._objectPropertiesView){callback('operation cancelled');return;} -this._objectPropertiesView.element.removeChildren();Common.Renderer.renderPromise(object,{title:title,expanded:true,editable:false,}).then(element=>{this._objectPropertiesView.element.appendChild(element);callback();});}};;Extensions.ExtensionView=class extends UI.Widget{constructor(server,id,src,className){super();this.setHideOnDetach();this.element.className='vbox flex-auto';this._server=server;this._id=id;this._iframe=createElement('iframe');this._iframe.addEventListener('load',this._onLoad.bind(this),false);this._iframe.src=src;this._iframe.className=className;this.setDefaultFocusedElement(this._iframe);this.element.appendChild(this._iframe);} -wasShown(){if(typeof this._frameIndex==='number') -this._server.notifyViewShown(this._id,this._frameIndex);} -willHide(){if(typeof this._frameIndex==='number') -this._server.notifyViewHidden(this._id);} -_onLoad(){var frames=(window.frames);this._frameIndex=Array.prototype.indexOf.call(frames,this._iframe.contentWindow);if(this.isShowing()) -this._server.notifyViewShown(this._id,this._frameIndex);}};Extensions.ExtensionNotifierView=class extends UI.VBox{constructor(server,id){super();this._server=server;this._id=id;} -wasShown(){this._server.notifyViewShown(this._id);} -willHide(){this._server.notifyViewHidden(this._id);}};;self['MobileThrottling']=self['MobileThrottling']||{};MobileThrottling.CPUThrottlingRates={NoThrottling:1,MidTierMobile:4,LowEndMobile:6,};MobileThrottling.Conditions;MobileThrottling.NoThrottlingConditions={title:SDK.NetworkManager.NoThrottlingConditions.title,description:Common.UIString('No throttling'),network:SDK.NetworkManager.NoThrottlingConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.NoThrottling,};MobileThrottling.OfflineConditions={title:SDK.NetworkManager.OfflineConditions.title,description:Common.UIString('No internet connectivity'),network:SDK.NetworkManager.OfflineConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.NoThrottling,};MobileThrottling.LowEndMobileConditions={title:Common.UIString('Low-end mobile'),description:Common.UIString('Slow 3G & 6x CPU slowdown'),network:SDK.NetworkManager.Slow3GConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.LowEndMobile,};MobileThrottling.MidTierMobileConditions={title:Common.UIString('Mid-tier mobile'),description:Common.UIString('Fast 3G & 4x CPU slowdown'),network:SDK.NetworkManager.Fast3GConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.MidTierMobile,};MobileThrottling.PlaceholderConditions;MobileThrottling.CustomConditions={title:Common.UIString('Custom'),description:Common.UIString('Check Network and Performance panels'),};MobileThrottling.NetworkThrottlingConditionsGroup;MobileThrottling.MobileThrottlingConditionsGroup;MobileThrottling.ConditionsList;MobileThrottling.mobilePresets=[MobileThrottling.MidTierMobileConditions,MobileThrottling.LowEndMobileConditions,MobileThrottling.CustomConditions];MobileThrottling.advancedMobilePresets=[MobileThrottling.OfflineConditions,];MobileThrottling.networkPresets=[SDK.NetworkManager.Fast3GConditions,SDK.NetworkManager.Slow3GConditions,SDK.NetworkManager.OfflineConditions,];MobileThrottling.cpuThrottlingPresets=[MobileThrottling.CPUThrottlingRates.NoThrottling,MobileThrottling.CPUThrottlingRates.MidTierMobile,MobileThrottling.CPUThrottlingRates.LowEndMobile,];;MobileThrottling.MobileThrottlingSelector=class{constructor(populateCallback,selectCallback){this._populateCallback=populateCallback;this._selectCallback=selectCallback;MobileThrottling.throttlingManager().addEventListener(MobileThrottling.ThrottlingManager.Events.RateChanged,this._conditionsChanged,this);SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,this._conditionsChanged,this);this._options=this._populateOptions();this._conditionsChanged();} -optionSelected(conditions){SDK.multitargetNetworkManager.setNetworkConditions(conditions.network);MobileThrottling.throttlingManager().setCPUThrottlingRate(conditions.cpuThrottlingRate);} -_populateOptions(){var disabledGroup={title:Common.UIString('Disabled'),items:[MobileThrottling.NoThrottlingConditions]};var presetsGroup={title:Common.UIString('Presets'),items:MobileThrottling.mobilePresets};var advancedGroup={title:Common.UIString('Advanced'),items:MobileThrottling.advancedMobilePresets};return this._populateCallback([disabledGroup,presetsGroup,advancedGroup]);} -_conditionsChanged(){var networkConditions=SDK.multitargetNetworkManager.networkConditions();var cpuThrottlingRate=MobileThrottling.throttlingManager().cpuThrottlingRate();for(var index=0;index<this._options.length;++index){var option=this._options[index];if(option&&option.network===networkConditions&&option.cpuThrottlingRate===cpuThrottlingRate){this._selectCallback(index);return;}} -this._selectCallback(this._options.indexOf(MobileThrottling.CustomConditions));}};;MobileThrottling.NetworkThrottlingSelector=class{constructor(populateCallback,selectCallback,customNetworkConditionsSetting){this._populateCallback=populateCallback;this._selectCallback=selectCallback;this._customNetworkConditionsSetting=customNetworkConditionsSetting;this._customNetworkConditionsSetting.addChangeListener(this._populateOptions,this);SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,this._networkConditionsChanged,this);this._options;this._populateOptions();} -revealAndUpdate(){Common.Revealer.reveal(this._customNetworkConditionsSetting);this._networkConditionsChanged();} -optionSelected(conditions){SDK.multitargetNetworkManager.setNetworkConditions(conditions);} -_populateOptions(){var disabledGroup={title:Common.UIString('Disabled'),items:[SDK.NetworkManager.NoThrottlingConditions]};var presetsGroup={title:Common.UIString('Presets'),items:MobileThrottling.networkPresets};var customGroup={title:Common.UIString('Custom'),items:this._customNetworkConditionsSetting.get()};this._options=this._populateCallback([disabledGroup,presetsGroup,customGroup]);if(!this._networkConditionsChanged()){for(var i=this._options.length-1;i>=0;i--){if(this._options[i]){this.optionSelected((this._options[i]));break;}}}} -_networkConditionsChanged(){var value=SDK.multitargetNetworkManager.networkConditions();for(var index=0;index<this._options.length;++index){var option=this._options[index];if(option&&option.download===value.download&&option.upload===value.upload&&option.latency===value.latency&&option.title===value.title){this._selectCallback(index);return true;}} -return false;}};;MobileThrottling.ThrottlingSettingsTab=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('mobile_throttling/throttlingSettingsTab.css');this.contentElement.createChild('div','header').textContent=Common.UIString('Network Throttling Profiles');var addButton=UI.createTextButton(Common.UIString('Add custom profile...'),this._addButtonClicked.bind(this),'add-conditions-button');this.contentElement.appendChild(addButton);this._list=new UI.ListWidget(this);this._list.element.classList.add('conditions-list');this._list.registerRequiredCSS('mobile_throttling/throttlingSettingsTab.css');this._list.show(this.contentElement);this._customSetting=Common.moduleSetting('customNetworkConditions');this._customSetting.addChangeListener(this._conditionsUpdated,this);this.setDefaultFocusedElement(addButton);this.contentElement.tabIndex=0;} -wasShown(){super.wasShown();this._conditionsUpdated();} -_conditionsUpdated(){this._list.clear();var conditions=this._customSetting.get();for(var i=0;i<conditions.length;++i) -this._list.appendItem(conditions[i],true);this._list.appendSeparator();} -_addButtonClicked(){this._list.addNewItem(this._customSetting.get().length,{title:'',download:-1,upload:-1,latency:0});} -renderItem(item,editable){var conditions=(item);var element=createElementWithClass('div','conditions-list-item');var title=element.createChild('div','conditions-list-text conditions-list-title');var titleText=title.createChild('div','conditions-list-title-text');titleText.textContent=conditions.title;titleText.title=conditions.title;element.createChild('div','conditions-list-separator');element.createChild('div','conditions-list-text').textContent=MobileThrottling.throughputText(conditions.download);element.createChild('div','conditions-list-separator');element.createChild('div','conditions-list-text').textContent=MobileThrottling.throughputText(conditions.upload);element.createChild('div','conditions-list-separator');element.createChild('div','conditions-list-text').textContent=Common.UIString('%dms',conditions.latency);return element;} -removeItemRequested(item,index){var list=this._customSetting.get();list.splice(index,1);this._customSetting.set(list);} -commitEdit(item,editor,isNew){var conditions=(item);conditions.title=editor.control('title').value.trim();var download=editor.control('download').value.trim();conditions.download=download?parseInt(download,10)*(1024/8):-1;var upload=editor.control('upload').value.trim();conditions.upload=upload?parseInt(upload,10)*(1024/8):-1;var latency=editor.control('latency').value.trim();conditions.latency=latency?parseInt(latency,10):0;var list=this._customSetting.get();if(isNew) -list.push(conditions);this._customSetting.set(list);} -beginEdit(item){var conditions=(item);var editor=this._createEditor();editor.control('title').value=conditions.title;editor.control('download').value=conditions.download<=0?'':String(conditions.download/(1024/8));editor.control('upload').value=conditions.upload<=0?'':String(conditions.upload/(1024/8));editor.control('latency').value=conditions.latency?String(conditions.latency):'';return editor;} -_createEditor(){if(this._editor) -return this._editor;var editor=new UI.ListWidget.Editor();this._editor=editor;var content=editor.contentElement();var titles=content.createChild('div','conditions-edit-row');titles.createChild('div','conditions-list-text conditions-list-title').textContent=Common.UIString('Profile Name');titles.createChild('div','conditions-list-separator conditions-list-separator-invisible');titles.createChild('div','conditions-list-text').textContent=Common.UIString('Download');titles.createChild('div','conditions-list-separator conditions-list-separator-invisible');titles.createChild('div','conditions-list-text').textContent=Common.UIString('Upload');titles.createChild('div','conditions-list-separator conditions-list-separator-invisible');titles.createChild('div','conditions-list-text').textContent=Common.UIString('Latency');var fields=content.createChild('div','conditions-edit-row');fields.createChild('div','conditions-list-text conditions-list-title').appendChild(editor.createInput('title','text','',titleValidator));fields.createChild('div','conditions-list-separator conditions-list-separator-invisible');var cell=fields.createChild('div','conditions-list-text');cell.appendChild(editor.createInput('download','text',Common.UIString('kb/s'),throughputValidator));cell.createChild('div','conditions-edit-optional').textContent=Common.UIString('optional');fields.createChild('div','conditions-list-separator conditions-list-separator-invisible');cell=fields.createChild('div','conditions-list-text');cell.appendChild(editor.createInput('upload','text',Common.UIString('kb/s'),throughputValidator));cell.createChild('div','conditions-edit-optional').textContent=Common.UIString('optional');fields.createChild('div','conditions-list-separator conditions-list-separator-invisible');cell=fields.createChild('div','conditions-list-text');cell.appendChild(editor.createInput('latency','text',Common.UIString('ms'),latencyValidator));cell.createChild('div','conditions-edit-optional').textContent=Common.UIString('optional');return editor;function titleValidator(item,index,input){var value=input.value.trim();return value.length>0&&value.length<50;} -function throughputValidator(item,index,input){var value=input.value.trim();return!value||(/^[\d]+(\.\d+)?|\.\d+$/.test(value)&&value>=0&&value<=10000000);} -function latencyValidator(item,index,input){var value=input.value.trim();return!value||(/^[\d]+$/.test(value)&&value>=0&&value<=1000000);}}};MobileThrottling.throughputText=function(throughput,plainText){if(throughput<0) -return'';var throughputInKbps=throughput/(1024/8);var delimiter=plainText?'':' ';if(throughputInKbps<1024) -return Common.UIString('%d%skb/s',throughputInKbps,delimiter);if(throughputInKbps<1024*10) -return Common.UIString('%.1f%sMb/s',throughputInKbps/1024,delimiter);return Common.UIString('%d%sMb/s',(throughputInKbps/1024)|0,delimiter);};;MobileThrottling.ThrottlingManager=class extends Common.Object{constructor(){super();this._cpuThrottlingRate=MobileThrottling.CPUThrottlingRates.NoThrottling;this._cpuThrottlingControls=new Set();this._cpuThrottlingRates=MobileThrottling.cpuThrottlingPresets;this._customNetworkConditionsSetting=Common.moduleSetting('customNetworkConditions');this._currentNetworkThrottlingConditions=SDK.NetworkManager.NoThrottlingConditions;this._lastNetworkThrottlingConditions;SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,()=>{this._lastNetworkThrottlingConditions=this._currentNetworkThrottlingConditions;this._currentNetworkThrottlingConditions=SDK.multitargetNetworkManager.networkConditions();});SDK.targetManager.observeModels(SDK.EmulationModel,this);} -decorateSelectWithNetworkThrottling(selectElement){var options=[];var selector=new MobileThrottling.NetworkThrottlingSelector(populate,select,this._customNetworkConditionsSetting);selectElement.addEventListener('change',optionSelected,false);return selector;function populate(groups){selectElement.removeChildren();options=[];for(var i=0;i<groups.length;++i){var group=groups[i];var groupElement=selectElement.createChild('optgroup');groupElement.label=group.title;for(var conditions of group.items){var title=conditions.title;var option=new Option(title,title);groupElement.appendChild(option);options.push(conditions);} -if(i===groups.length-1){groupElement.appendChild(new Option(Common.UIString('Add\u2026'),Common.UIString('Add\u2026')));options.push(null);}} -return options;} -function optionSelected(){if(selectElement.selectedIndex===selectElement.options.length-1) -selector.revealAndUpdate();else -selector.optionSelected(options[selectElement.selectedIndex]);} -function select(index){if(selectElement.selectedIndex!==index) -selectElement.selectedIndex=index;}} -createOfflineToolbarCheckbox(){var checkbox=new UI.ToolbarCheckbox(Common.UIString('Offline'),Common.UIString('Force disconnected from network'),forceOffline.bind(this));SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,networkConditionsChanged);checkbox.setChecked(SDK.multitargetNetworkManager.networkConditions()===SDK.NetworkManager.OfflineConditions);function forceOffline(){if(checkbox.checked()) -SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);else -SDK.multitargetNetworkManager.setNetworkConditions(this._lastNetworkThrottlingConditions);} -function networkConditionsChanged(){checkbox.setChecked(SDK.multitargetNetworkManager.networkConditions()===SDK.NetworkManager.OfflineConditions);} -return checkbox;} -createMobileThrottlingButton(){var button=new UI.ToolbarMenuButton(appendItems);button.setTitle(Common.UIString('Throttling'));button.setGlyph('');button.turnIntoSelect();button.setDarkText();var options=[];var selectedIndex=-1;var selector=new MobileThrottling.MobileThrottlingSelector(populate,select);return button;function appendItems(contextMenu){for(var index=0;index<options.length;++index){var conditions=options[index];if(!conditions) -continue;if(conditions.title===MobileThrottling.CustomConditions.title&&conditions.description===MobileThrottling.CustomConditions.description) -continue;contextMenu.defaultSection().appendCheckboxItem(Common.UIString(conditions.title),selector.optionSelected.bind(selector,(conditions)),selectedIndex===index);}} -function populate(groups){options=[];for(var group of groups){for(var conditions of group.items) -options.push(conditions);options.push(null);} -return options;} -function select(index){selectedIndex=index;button.setText(options[index].title);button.setTitle(options[index].description);}} -cpuThrottlingRate(){return this._cpuThrottlingRate;} -setCPUThrottlingRate(rate){this._cpuThrottlingRate=rate;for(var emulationModel of SDK.targetManager.models(SDK.EmulationModel)) -emulationModel.setCPUThrottlingRate(this._cpuThrottlingRate);var icon=null;if(this._cpuThrottlingRate!==MobileThrottling.CPUThrottlingRates.NoThrottling){Host.userMetrics.actionTaken(Host.UserMetrics.Action.CpuThrottlingEnabled);icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('CPU throttling is enabled');} -var index=this._cpuThrottlingRates.indexOf(this._cpuThrottlingRate);for(var control of this._cpuThrottlingControls) -control.setSelectedIndex(index);UI.inspectorView.setPanelIcon('timeline',icon);this.dispatchEventToListeners(MobileThrottling.ThrottlingManager.Events.RateChanged,this._cpuThrottlingRate);} -modelAdded(emulationModel){if(this._cpuThrottlingRate!==MobileThrottling.CPUThrottlingRates.NoThrottling) -emulationModel.setCPUThrottlingRate(this._cpuThrottlingRate);} -modelRemoved(emulationModel){} -createCPUThrottlingSelector(){var control=new UI.ToolbarComboBox(event=>this.setCPUThrottlingRate(this._cpuThrottlingRates[event.target.selectedIndex]));this._cpuThrottlingControls.add(control);var currentRate=this._cpuThrottlingRate;for(var i=0;i<this._cpuThrottlingRates.length;++i){var rate=this._cpuThrottlingRates[i];var title=rate===1?Common.UIString('No throttling'):Common.UIString('%d\xD7 slowdown',rate);var option=control.createOption(title);control.addOption(option);if(currentRate===rate) -control.setSelectedIndex(i);} -return control;}};MobileThrottling.ThrottlingManager.Events={RateChanged:Symbol('RateChanged')};MobileThrottling.ThrottlingManager.ActionDelegate=class{handleAction(context,actionId){if(actionId==='network-conditions.network-online'){SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.NoThrottlingConditions);return true;} -if(actionId==='network-conditions.network-offline'){SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);return true;} -return false;}};MobileThrottling.throttlingManager=function(){return self.singleton(MobileThrottling.ThrottlingManager);};;self['Emulation']=self['Emulation']||{};Emulation.AdvancedApp=class{constructor(){Components.dockController.addEventListener(Components.DockController.Events.BeforeDockSideChanged,this._openToolboxWindow,this);} -static _instance(){if(!Emulation.AdvancedApp._appInstance) -Emulation.AdvancedApp._appInstance=new Emulation.AdvancedApp();return Emulation.AdvancedApp._appInstance;} -presentUI(document){var rootView=new UI.RootView();this._rootSplitWidget=new UI.SplitWidget(false,true,'InspectorView.splitViewState',555,300,true);this._rootSplitWidget.show(rootView.element);this._rootSplitWidget.setSidebarWidget(UI.inspectorView);this._rootSplitWidget.setDefaultFocusedChild(UI.inspectorView);UI.inspectorView.setOwnerSplit(this._rootSplitWidget);this._inspectedPagePlaceholder=Emulation.InspectedPagePlaceholder.instance();this._inspectedPagePlaceholder.addEventListener(Emulation.InspectedPagePlaceholder.Events.Update,this._onSetInspectedPageBounds.bind(this),this);this._deviceModeView=new Emulation.DeviceModeWrapper(this._inspectedPagePlaceholder);Components.dockController.addEventListener(Components.DockController.Events.BeforeDockSideChanged,this._onBeforeDockSideChange,this);Components.dockController.addEventListener(Components.DockController.Events.DockSideChanged,this._onDockSideChange,this);Components.dockController.addEventListener(Components.DockController.Events.AfterDockSideChanged,this._onAfterDockSideChange,this);this._onDockSideChange();console.timeStamp('AdvancedApp.attachToBody');rootView.attachToDocument(document);rootView.focus();this._inspectedPagePlaceholder.update();} -_openToolboxWindow(event){if((event.data.to)!==Components.DockController.State.Undocked) -return;if(this._toolboxWindow) -return;var url=window.location.href.replace('inspector.html','toolbox.html');this._toolboxWindow=window.open(url,undefined);} -toolboxLoaded(toolboxDocument){UI.initializeUIUtils(toolboxDocument,Common.settings.createSetting('uiTheme','default'));UI.installComponentRootStyles((toolboxDocument.body));UI.ContextMenu.installHandler(toolboxDocument);UI.Tooltip.installHandler(toolboxDocument);this._toolboxRootView=new UI.RootView();this._toolboxRootView.attachToDocument(toolboxDocument);this._updateDeviceModeView();} -_updateDeviceModeView(){if(this._isDocked()) -this._rootSplitWidget.setMainWidget(this._deviceModeView);else if(this._toolboxRootView) -this._deviceModeView.show(this._toolboxRootView.element);} -_onBeforeDockSideChange(event){if((event.data.to)===Components.DockController.State.Undocked&&this._toolboxRootView){this._rootSplitWidget.hideSidebar();this._inspectedPagePlaceholder.update();} -this._changingDockSide=true;} -_onDockSideChange(event){this._updateDeviceModeView();var toDockSide=event?(event.data.to):Components.dockController.dockSide();if(toDockSide===Components.DockController.State.Undocked){this._updateForUndocked();}else if(this._toolboxRootView&&event&&(event.data.from)===Components.DockController.State.Undocked){this._rootSplitWidget.hideSidebar();}else{this._updateForDocked(toDockSide);}} -_onAfterDockSideChange(event){if(!this._changingDockSide) -return;if((event.data.from)===Components.DockController.State.Undocked){this._updateForDocked((event.data.to));} -this._changingDockSide=false;this._inspectedPagePlaceholder.update();} -_updateForDocked(dockSide){this._rootSplitWidget.resizerElement().style.transform=dockSide===Components.DockController.State.DockedToRight?'translateX(2px)':dockSide===Components.DockController.State.DockedToLeft?'translateX(-2px)':'';this._rootSplitWidget.setVertical(dockSide===Components.DockController.State.DockedToRight||dockSide===Components.DockController.State.DockedToLeft);this._rootSplitWidget.setSecondIsSidebar(dockSide===Components.DockController.State.DockedToRight||dockSide===Components.DockController.State.DockedToBottom);this._rootSplitWidget.toggleResizer(this._rootSplitWidget.resizerElement(),true);this._rootSplitWidget.toggleResizer(UI.inspectorView.topResizerElement(),dockSide===Components.DockController.State.DockedToBottom);this._rootSplitWidget.showBoth();} -_updateForUndocked(){this._rootSplitWidget.toggleResizer(this._rootSplitWidget.resizerElement(),false);this._rootSplitWidget.toggleResizer(UI.inspectorView.topResizerElement(),false);this._rootSplitWidget.hideMain();} -_isDocked(){return Components.dockController.dockSide()!==Components.DockController.State.Undocked;} -_onSetInspectedPageBounds(event){if(this._changingDockSide) -return;var window=this._inspectedPagePlaceholder.element.window();if(!window.innerWidth||!window.innerHeight) -return;if(!this._inspectedPagePlaceholder.isShowing()) -return;var bounds=(event.data);console.timeStamp('AdvancedApp.setInspectedPageBounds');InspectorFrontendHost.setInspectedPageBounds(bounds);}};Emulation.AdvancedApp._appInstance;Emulation.AdvancedAppProvider=class{createApp(){return Emulation.AdvancedApp._instance();}};;Emulation.EmulatedDevice=class{constructor(){this.title='';this.type=Emulation.EmulatedDevice.Type.Unknown;this.vertical={width:0,height:0,outlineInsets:null,outlineImage:null};this.horizontal={width:0,height:0,outlineInsets:null,outlineImage:null};this.deviceScaleFactor=1;this.capabilities=[Emulation.EmulatedDevice.Capability.Touch,Emulation.EmulatedDevice.Capability.Mobile];this.userAgent='';this.modes=[];this._show=Emulation.EmulatedDevice._Show.Default;this._showByDefault=true;this._extension=null;} -static fromJSONV1(json){try{function parseValue(object,key,type,defaultValue){if(typeof object!=='object'||object===null||!object.hasOwnProperty(key)){if(typeof defaultValue!=='undefined') -return defaultValue;throw new Error('Emulated device is missing required property \''+key+'\'');} -var value=object[key];if(typeof value!==type||value===null) -throw new Error('Emulated device property \''+key+'\' has wrong type \''+typeof value+'\'');return value;} -function parseIntValue(object,key){var value=(parseValue(object,key,'number'));if(value!==Math.abs(value)) -throw new Error('Emulated device value \''+key+'\' must be integer');return value;} -function parseInsets(json){return new UI.Insets(parseIntValue(json,'left'),parseIntValue(json,'top'),parseIntValue(json,'right'),parseIntValue(json,'bottom'));} -function parseOrientation(json){var result={};result.width=parseIntValue(json,'width');if(result.width<0||result.width>Emulation.DeviceModeModel.MaxDeviceSize||result.width<Emulation.DeviceModeModel.MinDeviceSize) -throw new Error('Emulated device has wrong width: '+result.width);result.height=parseIntValue(json,'height');if(result.height<0||result.height>Emulation.DeviceModeModel.MaxDeviceSize||result.height<Emulation.DeviceModeModel.MinDeviceSize) -throw new Error('Emulated device has wrong height: '+result.height);var outlineInsets=parseValue(json['outline'],'insets','object',null);if(outlineInsets){result.outlineInsets=parseInsets(outlineInsets);if(result.outlineInsets.left<0||result.outlineInsets.top<0) -throw new Error('Emulated device has wrong outline insets');result.outlineImage=(parseValue(json['outline'],'image','string'));} -return(result);} -var result=new Emulation.EmulatedDevice();result.title=(parseValue(json,'title','string'));result.type=(parseValue(json,'type','string'));var rawUserAgent=(parseValue(json,'user-agent','string'));result.userAgent=SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(rawUserAgent);var capabilities=parseValue(json,'capabilities','object',[]);if(!Array.isArray(capabilities)) -throw new Error('Emulated device capabilities must be an array');result.capabilities=[];for(var i=0;i<capabilities.length;++i){if(typeof capabilities[i]!=='string') -throw new Error('Emulated device capability must be a string');result.capabilities.push(capabilities[i]);} -result.deviceScaleFactor=(parseValue(json['screen'],'device-pixel-ratio','number'));if(result.deviceScaleFactor<0||result.deviceScaleFactor>100) -throw new Error('Emulated device has wrong deviceScaleFactor: '+result.deviceScaleFactor);result.vertical=parseOrientation(parseValue(json['screen'],'vertical','object'));result.horizontal=parseOrientation(parseValue(json['screen'],'horizontal','object'));var modes=parseValue(json,'modes','object',[]);if(!Array.isArray(modes)) -throw new Error('Emulated device modes must be an array');result.modes=[];for(var i=0;i<modes.length;++i){var mode={};mode.title=(parseValue(modes[i],'title','string'));mode.orientation=(parseValue(modes[i],'orientation','string'));if(mode.orientation!==Emulation.EmulatedDevice.Vertical&&mode.orientation!==Emulation.EmulatedDevice.Horizontal) -throw new Error('Emulated device mode has wrong orientation \''+mode.orientation+'\'');var orientation=result.orientationByName(mode.orientation);mode.insets=parseInsets(parseValue(modes[i],'insets','object'));if(mode.insets.top<0||mode.insets.left<0||mode.insets.right<0||mode.insets.bottom<0||mode.insets.top+mode.insets.bottom>orientation.height||mode.insets.left+mode.insets.right>orientation.width) -throw new Error('Emulated device mode \''+mode.title+'\'has wrong mode insets');mode.image=(parseValue(modes[i],'image','string',null));result.modes.push(mode);} -result._showByDefault=(parseValue(json,'show-by-default','boolean',undefined));result._show=(parseValue(json,'show','string',Emulation.EmulatedDevice._Show.Default));return result;}catch(e){return null;}} -static deviceComparator(device1,device2){var order1=(device1._extension&&device1._extension.descriptor()['order'])||-1;var order2=(device2._extension&&device2._extension.descriptor()['order'])||-1;if(order1>order2) -return 1;if(order2>order1) -return-1;return device1.title<device2.title?-1:(device1.title>device2.title?1:0);} -extension(){return this._extension;} -setExtension(extension){this._extension=extension;} -modesForOrientation(orientation){var result=[];for(var index=0;index<this.modes.length;index++){if(this.modes[index].orientation===orientation) -result.push(this.modes[index]);} -return result;} -_toJSON(){var json={};json['title']=this.title;json['type']=this.type;json['user-agent']=this.userAgent;json['capabilities']=this.capabilities;json['screen']={};json['screen']['device-pixel-ratio']=this.deviceScaleFactor;json['screen']['vertical']=this._orientationToJSON(this.vertical);json['screen']['horizontal']=this._orientationToJSON(this.horizontal);json['modes']=[];for(var i=0;i<this.modes.length;++i){var mode={};mode['title']=this.modes[i].title;mode['orientation']=this.modes[i].orientation;mode['insets']={};mode['insets']['left']=this.modes[i].insets.left;mode['insets']['top']=this.modes[i].insets.top;mode['insets']['right']=this.modes[i].insets.right;mode['insets']['bottom']=this.modes[i].insets.bottom;if(this.modes[i].image) -mode['image']=this.modes[i].image;json['modes'].push(mode);} -json['show-by-default']=this._showByDefault;json['show']=this._show;return json;} -_orientationToJSON(orientation){var json={};json['width']=orientation.width;json['height']=orientation.height;if(orientation.outlineInsets){json['outline']={};json['outline']['insets']={};json['outline']['insets']['left']=orientation.outlineInsets.left;json['outline']['insets']['top']=orientation.outlineInsets.top;json['outline']['insets']['right']=orientation.outlineInsets.right;json['outline']['insets']['bottom']=orientation.outlineInsets.bottom;json['outline']['image']=orientation.outlineImage;} -return json;} -modeImage(mode){if(!mode.image) -return'';if(!this._extension) -return mode.image;return this._extension.module().substituteURL(mode.image);} -outlineImage(mode){var orientation=this.orientationByName(mode.orientation);if(!orientation.outlineImage) -return'';if(!this._extension) -return orientation.outlineImage;return this._extension.module().substituteURL(orientation.outlineImage);} -orientationByName(name){return name===Emulation.EmulatedDevice.Vertical?this.vertical:this.horizontal;} -show(){if(this._show===Emulation.EmulatedDevice._Show.Default) -return this._showByDefault;return this._show===Emulation.EmulatedDevice._Show.Always;} -setShow(show){this._show=show?Emulation.EmulatedDevice._Show.Always:Emulation.EmulatedDevice._Show.Never;} -copyShowFrom(other){this._show=other._show;} -touch(){return this.capabilities.indexOf(Emulation.EmulatedDevice.Capability.Touch)!==-1;} -mobile(){return this.capabilities.indexOf(Emulation.EmulatedDevice.Capability.Mobile)!==-1;}};Emulation.EmulatedDevice.Mode;Emulation.EmulatedDevice.Orientation;Emulation.EmulatedDevice.Horizontal='horizontal';Emulation.EmulatedDevice.Vertical='vertical';Emulation.EmulatedDevice.Type={Phone:'phone',Tablet:'tablet',Notebook:'notebook',Desktop:'desktop',Unknown:'unknown'};Emulation.EmulatedDevice.Capability={Touch:'touch',Mobile:'mobile'};Emulation.EmulatedDevice._Show={Always:'Always',Default:'Default',Never:'Never'};Emulation.EmulatedDevicesList=class extends Common.Object{constructor(){super();this._standardSetting=Common.settings.createSetting('standardEmulatedDeviceList',[]);this._standard=[];this._listFromJSONV1(this._standardSetting.get(),this._standard);this._updateStandardDevices();this._customSetting=Common.settings.createSetting('customEmulatedDeviceList',[]);this._custom=[];if(!this._listFromJSONV1(this._customSetting.get(),this._custom)) -this.saveCustomDevices();} -static instance(){if(!Emulation.EmulatedDevicesList._instance) -Emulation.EmulatedDevicesList._instance=new Emulation.EmulatedDevicesList();return(Emulation.EmulatedDevicesList._instance);} -_updateStandardDevices(){var devices=[];var extensions=self.runtime.extensions('emulated-device');for(var i=0;i<extensions.length;++i){var device=Emulation.EmulatedDevice.fromJSONV1(extensions[i].descriptor()['device']);device.setExtension(extensions[i]);devices.push(device);} -this._copyShowValues(this._standard,devices);this._standard=devices;this.saveStandardDevices();} -_listFromJSONV1(jsonArray,result){if(!Array.isArray(jsonArray)) -return false;var success=true;for(var i=0;i<jsonArray.length;++i){var device=Emulation.EmulatedDevice.fromJSONV1(jsonArray[i]);if(device){result.push(device);if(!device.modes.length){device.modes.push({title:'',orientation:Emulation.EmulatedDevice.Horizontal,insets:new UI.Insets(0,0,0,0),image:null});device.modes.push({title:'',orientation:Emulation.EmulatedDevice.Vertical,insets:new UI.Insets(0,0,0,0),image:null});}}else{success=false;}} -return success;} -standard(){return this._standard;} -custom(){return this._custom;} -revealCustomSetting(){Common.Revealer.reveal(this._customSetting);} -addCustomDevice(device){this._custom.push(device);this.saveCustomDevices();} -removeCustomDevice(device){this._custom.remove(device);this.saveCustomDevices();} -saveCustomDevices(){var json=this._custom.map(function(device){return device._toJSON();});this._customSetting.set(json);this.dispatchEventToListeners(Emulation.EmulatedDevicesList.Events.CustomDevicesUpdated);} -saveStandardDevices(){var json=this._standard.map(function(device){return device._toJSON();});this._standardSetting.set(json);this.dispatchEventToListeners(Emulation.EmulatedDevicesList.Events.StandardDevicesUpdated);} -_copyShowValues(from,to){var deviceById=new Map();for(var i=0;i<from.length;++i) -deviceById.set(from[i].title,from[i]);for(var i=0;i<to.length;++i){var title=to[i].title;if(deviceById.has(title)) -to[i].copyShowFrom((deviceById.get(title)));}}};Emulation.EmulatedDevicesList.Events={CustomDevicesUpdated:Symbol('CustomDevicesUpdated'),StandardDevicesUpdated:Symbol('StandardDevicesUpdated')};Emulation.EmulatedDevicesList._instance;;Emulation.DevicesSettingsTab=class extends UI.VBox{constructor(){super();this.element.classList.add('settings-tab-container');this.element.classList.add('devices-settings-tab');this.registerRequiredCSS('emulation/devicesSettingsTab.css');var header=this.element.createChild('header');header.createChild('h3').createTextChild(Common.UIString('Emulated Devices'));this.containerElement=this.element.createChild('div','help-container-wrapper').createChild('div','settings-tab help-content help-container');var buttonsRow=this.containerElement.createChild('div','devices-button-row');this._addCustomButton=UI.createTextButton(Common.UIString('Add custom device...'),this._addCustomDevice.bind(this));buttonsRow.appendChild(this._addCustomButton);this._list=new UI.ListWidget(this);this._list.registerRequiredCSS('emulation/devicesSettingsTab.css');this._list.element.classList.add('devices-list');this._list.show(this.containerElement);this._muteUpdate=false;this._emulatedDevicesList=Emulation.EmulatedDevicesList.instance();this._emulatedDevicesList.addEventListener(Emulation.EmulatedDevicesList.Events.CustomDevicesUpdated,this._devicesUpdated,this);this._emulatedDevicesList.addEventListener(Emulation.EmulatedDevicesList.Events.StandardDevicesUpdated,this._devicesUpdated,this);this.setDefaultFocusedElement(this._addCustomButton);} -wasShown(){super.wasShown();this._devicesUpdated();} -_devicesUpdated(){if(this._muteUpdate) -return;this._list.clear();var devices=this._emulatedDevicesList.custom().slice();for(var i=0;i<devices.length;++i) -this._list.appendItem(devices[i],true);this._list.appendSeparator();devices=this._emulatedDevicesList.standard().slice();devices.sort(Emulation.EmulatedDevice.deviceComparator);for(var i=0;i<devices.length;++i) -this._list.appendItem(devices[i],false);} -_muteAndSaveDeviceList(custom){this._muteUpdate=true;if(custom) -this._emulatedDevicesList.saveCustomDevices();else -this._emulatedDevicesList.saveStandardDevices();this._muteUpdate=false;} -_addCustomDevice(){var device=new Emulation.EmulatedDevice();device.deviceScaleFactor=0;device.horizontal.width=700;device.horizontal.height=400;device.vertical.width=400;device.vertical.height=700;this._list.addNewItem(this._emulatedDevicesList.custom().length,device);} -_toNumericInputValue(value){return value?String(value):'';} -renderItem(item,editable){var device=(item);var element=createElementWithClass('div','devices-list-item');var checkbox=element.createChild('input','devices-list-checkbox');checkbox.type='checkbox';checkbox.checked=device.show();element.createChild('div','devices-list-title').textContent=device.title;element.addEventListener('click',onItemClicked.bind(this),false);return element;function onItemClicked(event){var show=!checkbox.checked;device.setShow(show);this._muteAndSaveDeviceList(editable);checkbox.checked=show;event.consume();}} -removeItemRequested(item,index){this._emulatedDevicesList.removeCustomDevice((item));} -commitEdit(item,editor,isNew){var device=(item);device.title=editor.control('title').value.trim();device.vertical.width=editor.control('width').value?parseInt(editor.control('width').value,10):0;device.vertical.height=editor.control('height').value?parseInt(editor.control('height').value,10):0;device.horizontal.width=device.vertical.height;device.horizontal.height=device.vertical.width;device.deviceScaleFactor=editor.control('scale').value?parseFloat(editor.control('scale').value):0;device.userAgent=editor.control('user-agent').value;device.modes=[];device.modes.push({title:'',orientation:Emulation.EmulatedDevice.Vertical,insets:new UI.Insets(0,0,0,0),image:null});device.modes.push({title:'',orientation:Emulation.EmulatedDevice.Horizontal,insets:new UI.Insets(0,0,0,0),image:null});device.capabilities=[];var uaType=editor.control('ua-type').value;if(uaType===Emulation.DeviceModeModel.UA.Mobile||uaType===Emulation.DeviceModeModel.UA.MobileNoTouch) -device.capabilities.push(Emulation.EmulatedDevice.Capability.Mobile);if(uaType===Emulation.DeviceModeModel.UA.Mobile||uaType===Emulation.DeviceModeModel.UA.DesktopTouch) -device.capabilities.push(Emulation.EmulatedDevice.Capability.Touch);if(isNew) -this._emulatedDevicesList.addCustomDevice(device);else -this._emulatedDevicesList.saveCustomDevices();this._addCustomButton.scrollIntoViewIfNeeded();this._addCustomButton.focus();} -beginEdit(item){var device=(item);var editor=this._createEditor();editor.control('title').value=device.title;editor.control('width').value=this._toNumericInputValue(device.vertical.width);editor.control('height').value=this._toNumericInputValue(device.vertical.height);editor.control('scale').value=this._toNumericInputValue(device.deviceScaleFactor);editor.control('user-agent').value=device.userAgent;var uaType;if(device.mobile()) -uaType=device.touch()?Emulation.DeviceModeModel.UA.Mobile:Emulation.DeviceModeModel.UA.MobileNoTouch;else -uaType=device.touch()?Emulation.DeviceModeModel.UA.DesktopTouch:Emulation.DeviceModeModel.UA.Desktop;editor.control('ua-type').value=uaType;return editor;} -_createEditor(){if(this._editor) -return this._editor;var editor=new UI.ListWidget.Editor();this._editor=editor;var content=editor.contentElement();var fields=content.createChild('div','devices-edit-fields');fields.createChild('div','hbox').appendChild(editor.createInput('title','text',Common.UIString('Device name'),titleValidator));var screen=fields.createChild('div','hbox');screen.appendChild(editor.createInput('width','text',Common.UIString('Width'),sizeValidator));screen.appendChild(editor.createInput('height','text',Common.UIString('height'),sizeValidator));var dpr=editor.createInput('scale','text',Common.UIString('Device pixel ratio'),scaleValidator);dpr.classList.add('device-edit-fixed');screen.appendChild(dpr);var ua=fields.createChild('div','hbox');ua.appendChild(editor.createInput('user-agent','text',Common.UIString('User agent string'),()=>true));var uaType=editor.createSelect('ua-type',[Emulation.DeviceModeModel.UA.Mobile,Emulation.DeviceModeModel.UA.MobileNoTouch,Emulation.DeviceModeModel.UA.Desktop,Emulation.DeviceModeModel.UA.DesktopTouch],()=>true);uaType.classList.add('device-edit-fixed');ua.appendChild(uaType);return editor;function titleValidator(item,index,input){var value=input.value.trim();return value.length>0&&value.length<50;} -function sizeValidator(item,index,input){return Emulation.DeviceModeModel.deviceSizeValidator(input.value);} -function scaleValidator(item,index,input){return Emulation.DeviceModeModel.deviceScaleFactorValidator(input.value);}}};;Emulation.InspectedPagePlaceholder=class extends UI.Widget{constructor(){super(true);this.registerRequiredCSS('emulation/inspectedPagePlaceholder.css');UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this.onResize,this);this.restoreMinimumSize();} -onResize(){if(this._updateId) -this.element.window().cancelAnimationFrame(this._updateId);this._updateId=this.element.window().requestAnimationFrame(this.update.bind(this,false));} -restoreMinimumSize(){this.setMinimumSize(150,150);} -clearMinimumSize(){this.setMinimumSize(1,1);} -_dipPageRect(){var zoomFactor=UI.zoomManager.zoomFactor();var rect=this.element.getBoundingClientRect();var bodyRect=this.element.ownerDocument.body.getBoundingClientRect();var left=Math.max(rect.left*zoomFactor,bodyRect.left*zoomFactor);var top=Math.max(rect.top*zoomFactor,bodyRect.top*zoomFactor);var bottom=Math.min(rect.bottom*zoomFactor,bodyRect.bottom*zoomFactor);var right=Math.min(rect.right*zoomFactor,bodyRect.right*zoomFactor);return{x:left,y:top,width:right-left,height:bottom-top};} -update(force){delete this._updateId;var rect=this._dipPageRect();var bounds={x:Math.round(rect.x),y:Math.round(rect.y),height:Math.max(1,Math.round(rect.height)),width:Math.max(1,Math.round(rect.width)),};if(force){--bounds.height;this.dispatchEventToListeners(Emulation.InspectedPagePlaceholder.Events.Update,bounds);++bounds.height;} -this.dispatchEventToListeners(Emulation.InspectedPagePlaceholder.Events.Update,bounds);}};Emulation.InspectedPagePlaceholder.instance=function(){return self.singleton(Emulation.InspectedPagePlaceholder);};Emulation.InspectedPagePlaceholder.Events={Update:Symbol('Update')};;Emulation.MediaQueryInspector=class extends UI.Widget{constructor(getWidthCallback,setWidthCallback){super(true);this.registerRequiredCSS('emulation/mediaQueryInspector.css');this.contentElement.classList.add('media-inspector-view');this.contentElement.addEventListener('click',this._onMediaQueryClicked.bind(this),false);this.contentElement.addEventListener('contextmenu',this._onContextMenu.bind(this),false);this._mediaThrottler=new Common.Throttler(0);this._getWidthCallback=getWidthCallback;this._setWidthCallback=setWidthCallback;this._scale=1;SDK.targetManager.observeModels(SDK.CSSModel,this);UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._renderMediaQueries.bind(this),this);} -modelAdded(cssModel){if(this._cssModel) -return;this._cssModel=cssModel;this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._scheduleMediaQueriesUpdate,this);this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._scheduleMediaQueriesUpdate,this);this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._scheduleMediaQueriesUpdate,this);this._cssModel.addEventListener(SDK.CSSModel.Events.MediaQueryResultChanged,this._scheduleMediaQueriesUpdate,this);} -modelRemoved(cssModel){if(cssModel!==this._cssModel) -return;this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._scheduleMediaQueriesUpdate,this);this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._scheduleMediaQueriesUpdate,this);this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._scheduleMediaQueriesUpdate,this);this._cssModel.removeEventListener(SDK.CSSModel.Events.MediaQueryResultChanged,this._scheduleMediaQueriesUpdate,this);delete this._cssModel;} -setAxisTransform(scale){if(Math.abs(this._scale-scale)<1e-8) -return;this._scale=scale;this._renderMediaQueries();} -_onMediaQueryClicked(event){var mediaQueryMarker=event.target.enclosingNodeOrSelfWithClass('media-inspector-bar');if(!mediaQueryMarker) -return;var model=mediaQueryMarker._model;if(model.section()===Emulation.MediaQueryInspector.Section.Max){this._setWidthCallback(model.maxWidthExpression().computedLength());return;} -if(model.section()===Emulation.MediaQueryInspector.Section.Min){this._setWidthCallback(model.minWidthExpression().computedLength());return;} -var currentWidth=this._getWidthCallback();if(currentWidth!==model.minWidthExpression().computedLength()) -this._setWidthCallback(model.minWidthExpression().computedLength());else -this._setWidthCallback(model.maxWidthExpression().computedLength());} -_onContextMenu(event){if(!this._cssModel||!this._cssModel.isEnabled()) -return;var mediaQueryMarker=event.target.enclosingNodeOrSelfWithClass('media-inspector-bar');if(!mediaQueryMarker) -return;var locations=mediaQueryMarker._locations;var uiLocations=new Map();for(var i=0;i<locations.length;++i){var uiLocation=Bindings.cssWorkspaceBinding.rawLocationToUILocation(locations[i]);if(!uiLocation) -continue;var descriptor=String.sprintf('%s:%d:%d',uiLocation.uiSourceCode.url(),uiLocation.lineNumber+1,uiLocation.columnNumber+1);uiLocations.set(descriptor,uiLocation);} -var contextMenuItems=uiLocations.keysArray().sort();var contextMenu=new UI.ContextMenu(event);var subMenuItem=contextMenu.defaultSection().appendSubMenuItem(Common.UIString('Reveal in source code'));for(var i=0;i<contextMenuItems.length;++i){var title=contextMenuItems[i];subMenuItem.defaultSection().appendItem(title,this._revealSourceLocation.bind(this,(uiLocations.get(title))));} -contextMenu.show();} -_revealSourceLocation(location){Common.Revealer.reveal(location);} -_scheduleMediaQueriesUpdate(){if(!this.isShowing()) -return;this._mediaThrottler.schedule(this._refetchMediaQueries.bind(this));} -_refetchMediaQueries(){if(!this.isShowing()||!this._cssModel) -return Promise.resolve();return this._cssModel.mediaQueriesPromise().then(this._rebuildMediaQueries.bind(this));} -_squashAdjacentEqual(models){var filtered=[];for(var i=0;i<models.length;++i){var last=filtered.peekLast();if(!last||!last.equals(models[i])) -filtered.push(models[i]);} -return filtered;} -_rebuildMediaQueries(cssMedias){var queryModels=[];for(var i=0;i<cssMedias.length;++i){var cssMedia=cssMedias[i];if(!cssMedia.mediaList) -continue;for(var j=0;j<cssMedia.mediaList.length;++j){var mediaQuery=cssMedia.mediaList[j];var queryModel=Emulation.MediaQueryInspector.MediaQueryUIModel.createFromMediaQuery(cssMedia,mediaQuery);if(queryModel&&queryModel.rawLocation()) -queryModels.push(queryModel);}} -queryModels.sort(compareModels);queryModels=this._squashAdjacentEqual(queryModels);var allEqual=this._cachedQueryModels&&this._cachedQueryModels.length===queryModels.length;for(var i=0;allEqual&&i<queryModels.length;++i) -allEqual=allEqual&&this._cachedQueryModels[i].equals(queryModels[i]);if(allEqual) -return;this._cachedQueryModels=queryModels;this._renderMediaQueries();function compareModels(model1,model2){return model1.compareTo(model2);}} -_renderMediaQueries(){if(!this._cachedQueryModels||!this.isShowing()) -return;var markers=[];var lastMarker=null;for(var i=0;i<this._cachedQueryModels.length;++i){var model=this._cachedQueryModels[i];if(lastMarker&&lastMarker.model.dimensionsEqual(model)){lastMarker.locations.push(model.rawLocation());lastMarker.active=lastMarker.active||model.active();}else{lastMarker={active:model.active(),model:model,locations:[model.rawLocation()]};markers.push(lastMarker);}} -this.contentElement.removeChildren();var container=null;for(var i=0;i<markers.length;++i){if(!i||markers[i].model.section()!==markers[i-1].model.section()) -container=this.contentElement.createChild('div','media-inspector-marker-container');var marker=markers[i];var bar=this._createElementFromMediaQueryModel(marker.model);bar._model=marker.model;bar._locations=marker.locations;bar.classList.toggle('media-inspector-marker-inactive',!marker.active);container.appendChild(bar);}} -_zoomFactor(){return UI.zoomManager.zoomFactor()/this._scale;} -wasShown(){this._scheduleMediaQueriesUpdate();} -_createElementFromMediaQueryModel(model){var zoomFactor=this._zoomFactor();var minWidthValue=model.minWidthExpression()?model.minWidthExpression().computedLength()/zoomFactor:0;var maxWidthValue=model.maxWidthExpression()?model.maxWidthExpression().computedLength()/zoomFactor:0;var result=createElementWithClass('div','media-inspector-bar');if(model.section()===Emulation.MediaQueryInspector.Section.Max){result.createChild('div','media-inspector-marker-spacer');var markerElement=result.createChild('div','media-inspector-marker media-inspector-marker-max-width');markerElement.style.width=maxWidthValue+'px';markerElement.title=model.mediaText();appendLabel(markerElement,model.maxWidthExpression(),false,false);appendLabel(markerElement,model.maxWidthExpression(),true,true);result.createChild('div','media-inspector-marker-spacer');} -if(model.section()===Emulation.MediaQueryInspector.Section.MinMax){result.createChild('div','media-inspector-marker-spacer');var leftElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-max-width');leftElement.style.width=(maxWidthValue-minWidthValue)*0.5+'px';leftElement.title=model.mediaText();appendLabel(leftElement,model.minWidthExpression(),true,false);appendLabel(leftElement,model.maxWidthExpression(),false,true);result.createChild('div','media-inspector-marker-spacer').style.flex='0 0 '+minWidthValue+'px';var rightElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-max-width');rightElement.style.width=(maxWidthValue-minWidthValue)*0.5+'px';rightElement.title=model.mediaText();appendLabel(rightElement,model.minWidthExpression(),true,false);appendLabel(rightElement,model.maxWidthExpression(),false,true);result.createChild('div','media-inspector-marker-spacer');} -if(model.section()===Emulation.MediaQueryInspector.Section.Min){var leftElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-width media-inspector-marker-min-width-left');leftElement.title=model.mediaText();appendLabel(leftElement,model.minWidthExpression(),false,false);result.createChild('div','media-inspector-marker-spacer').style.flex='0 0 '+minWidthValue+'px';var rightElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-width media-inspector-marker-min-width-right');rightElement.title=model.mediaText();appendLabel(rightElement,model.minWidthExpression(),true,true);} -function appendLabel(marker,expression,atLeft,leftAlign){marker.createChild('div','media-inspector-marker-label-container '+(atLeft?'media-inspector-marker-label-container-left':'media-inspector-marker-label-container-right')).createChild('span','media-inspector-marker-label '+ -(leftAlign?'media-inspector-label-left':'media-inspector-label-right')).textContent=expression.value()+expression.unit();} -return result;}};Emulation.MediaQueryInspector.Section={Max:0,MinMax:1,Min:2};Emulation.MediaQueryInspector.MediaQueryUIModel=class{constructor(cssMedia,minWidthExpression,maxWidthExpression,active){this._cssMedia=cssMedia;this._minWidthExpression=minWidthExpression;this._maxWidthExpression=maxWidthExpression;this._active=active;if(maxWidthExpression&&!minWidthExpression) -this._section=Emulation.MediaQueryInspector.Section.Max;else if(minWidthExpression&&maxWidthExpression) -this._section=Emulation.MediaQueryInspector.Section.MinMax;else -this._section=Emulation.MediaQueryInspector.Section.Min;} -static createFromMediaQuery(cssMedia,mediaQuery){var maxWidthExpression=null;var maxWidthPixels=Number.MAX_VALUE;var minWidthExpression=null;var minWidthPixels=Number.MIN_VALUE;var expressions=mediaQuery.expressions();for(var i=0;i<expressions.length;++i){var expression=expressions[i];var feature=expression.feature();if(feature.indexOf('width')===-1) -continue;var pixels=expression.computedLength();if(feature.startsWith('max-')&&pixels<maxWidthPixels){maxWidthExpression=expression;maxWidthPixels=pixels;}else if(feature.startsWith('min-')&&pixels>minWidthPixels){minWidthExpression=expression;minWidthPixels=pixels;}} -if(minWidthPixels>maxWidthPixels||(!maxWidthExpression&&!minWidthExpression)) -return null;return new Emulation.MediaQueryInspector.MediaQueryUIModel(cssMedia,minWidthExpression,maxWidthExpression,mediaQuery.active());} -equals(other){return this.compareTo(other)===0;} -dimensionsEqual(other){return this.section()===other.section()&&(!this.minWidthExpression()||(this.minWidthExpression().computedLength()===other.minWidthExpression().computedLength()))&&(!this.maxWidthExpression()||(this.maxWidthExpression().computedLength()===other.maxWidthExpression().computedLength()));} -compareTo(other){if(this.section()!==other.section()) -return this.section()-other.section();if(this.dimensionsEqual(other)){var myLocation=this.rawLocation();var otherLocation=other.rawLocation();if(!myLocation&&!otherLocation) -return this.mediaText().compareTo(other.mediaText());if(myLocation&&!otherLocation) -return 1;if(!myLocation&&otherLocation) -return-1;if(this.active()!==other.active()) -return this.active()?-1:1;return myLocation.url.compareTo(otherLocation.url)||myLocation.lineNumber-otherLocation.lineNumber||myLocation.columnNumber-otherLocation.columnNumber;} -if(this.section()===Emulation.MediaQueryInspector.Section.Max) -return other.maxWidthExpression().computedLength()-this.maxWidthExpression().computedLength();if(this.section()===Emulation.MediaQueryInspector.Section.Min) -return this.minWidthExpression().computedLength()-other.minWidthExpression().computedLength();return this.minWidthExpression().computedLength()-other.minWidthExpression().computedLength()||other.maxWidthExpression().computedLength()-this.maxWidthExpression().computedLength();} -section(){return this._section;} -mediaText(){return this._cssMedia.text;} -rawLocation(){if(!this._rawLocation) -this._rawLocation=this._cssMedia.rawLocation();return this._rawLocation;} -minWidthExpression(){return this._minWidthExpression;} -maxWidthExpression(){return this._maxWidthExpression;} -active(){return this._active;}};;Emulation.SensorsView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('emulation/sensors.css');this.contentElement.classList.add('sensors-view');this._geolocationSetting=Common.settings.createSetting('emulation.geolocationOverride','');this._geolocation=SDK.EmulationModel.Geolocation.parseSetting(this._geolocationSetting.get());this._geolocationOverrideEnabled=false;this._createGeolocationSection(this._geolocation);this.contentElement.createChild('div').classList.add('panel-section-separator');this._deviceOrientationSetting=Common.settings.createSetting('emulation.deviceOrientationOverride','');this._deviceOrientation=SDK.EmulationModel.DeviceOrientation.parseSetting(this._deviceOrientationSetting.get());this._deviceOrientationOverrideEnabled=false;this._createDeviceOrientationSection();this.contentElement.createChild('div').classList.add('panel-section-separator');this._appendTouchControl();} -static instance(){if(!Emulation.SensorsView._instanceObject) -Emulation.SensorsView._instanceObject=new Emulation.SensorsView();return Emulation.SensorsView._instanceObject;} -_createGeolocationSection(geolocation){var geogroup=this.contentElement.createChild('section','sensors-group');geogroup.createChild('div','sensors-group-title').textContent=Common.UIString('Geolocation');var fields=geogroup.createChild('div','geo-fields');const noOverrideOption={title:Common.UIString('No override'),location:Emulation.SensorsView.NonPresetOptions.NoOverride};const customLocationOption={title:Common.UIString('Custom location...'),location:Emulation.SensorsView.NonPresetOptions.Custom};this._locationSelectElement=this.contentElement.createChild('select','chrome-select');this._locationSelectElement.appendChild(new Option(noOverrideOption.title,noOverrideOption.location));this._locationSelectElement.appendChild(new Option(customLocationOption.title,customLocationOption.location));var locationGroups=Emulation.SensorsView.PresetLocations;for(var i=0;i<locationGroups.length;++i){var group=locationGroups[i].value;var groupElement=this._locationSelectElement.createChild('optgroup');groupElement.label=locationGroups[i].title;for(var j=0;j<group.length;++j) -groupElement.appendChild(new Option(group[j].title,group[j].location));} -this._locationSelectElement.selectedIndex=0;fields.appendChild(this._locationSelectElement);this._locationSelectElement.addEventListener('change',this._geolocationSelectChanged.bind(this));this._fieldsetElement=fields.createChild('fieldset');this._fieldsetElement.disabled=!this._geolocationOverrideEnabled;this._fieldsetElement.id='geolocation-override-section';var latitudeGroup=this._fieldsetElement.createChild('div','latlong-group');var longitudeGroup=this._fieldsetElement.createChild('div','latlong-group');this._latitudeInput=UI.createInput('','number');latitudeGroup.appendChild(this._latitudeInput);this._latitudeInput.setAttribute('step','any');this._latitudeInput.value=0;this._latitudeSetter=UI.bindInput(this._latitudeInput,this._applyGeolocationUserInput.bind(this),SDK.EmulationModel.Geolocation.latitudeValidator,true);this._latitudeSetter(String(geolocation.latitude));this._longitudeInput=UI.createInput('','number');longitudeGroup.appendChild(this._longitudeInput);this._longitudeInput.setAttribute('step','any');this._longitudeInput.value=0;this._longitudeSetter=UI.bindInput(this._longitudeInput,this._applyGeolocationUserInput.bind(this),SDK.EmulationModel.Geolocation.longitudeValidator,true);this._longitudeSetter(String(geolocation.longitude));latitudeGroup.createChild('div','latlong-title').textContent=Common.UIString('Latitude');longitudeGroup.createChild('div','latlong-title').textContent=Common.UIString('Longitude');} -_geolocationSelectChanged(){this._fieldsetElement.disabled=false;var value=this._locationSelectElement.options[this._locationSelectElement.selectedIndex].value;if(value===Emulation.SensorsView.NonPresetOptions.NoOverride){this._geolocationOverrideEnabled=false;this._fieldsetElement.disabled=true;}else if(value===Emulation.SensorsView.NonPresetOptions.Custom){this._geolocationOverrideEnabled=true;}else if(value===Emulation.SensorsView.NonPresetOptions.Unavailable){this._geolocationOverrideEnabled=true;this._geolocation=new SDK.EmulationModel.Geolocation(0,0,true);}else{this._geolocationOverrideEnabled=true;var coordinates=JSON.parse(value);this._geolocation=new SDK.EmulationModel.Geolocation(coordinates[0],coordinates[1],false);this._latitudeSetter(coordinates[0]);this._longitudeSetter(coordinates[1]);} -this._applyGeolocation();if(value===Emulation.SensorsView.NonPresetOptions.Custom) -this._latitudeInput.focus();} -_applyGeolocationUserInput(){var geolocation=SDK.EmulationModel.Geolocation.parseUserInput(this._latitudeInput.value.trim(),this._longitudeInput.value.trim(),'');if(!geolocation) -return;this._setSelectElementLabel(this._locationSelectElement,Emulation.SensorsView.NonPresetOptions.Custom);this._geolocation=geolocation;this._applyGeolocation();} -_applyGeolocation(){if(this._geolocationOverrideEnabled) -this._geolocationSetting.set(this._geolocation.toSetting());for(var emulationModel of SDK.targetManager.models(SDK.EmulationModel)) -emulationModel.emulateGeolocation(this._geolocationOverrideEnabled?this._geolocation:null);} -_createDeviceOrientationSection(){var orientationGroup=this.contentElement.createChild('section','sensors-group');orientationGroup.createChild('div','sensors-group-title').textContent=Common.UIString('Orientation');var orientationContent=orientationGroup.createChild('div','orientation-content');var fields=orientationContent.createChild('div','orientation-fields');const orientationOffOption={title:Common.UIString('Off'),orientation:Emulation.SensorsView.NonPresetOptions.NoOverride};const customOrientationOption={title:Common.UIString('Custom orientation...'),orientation:Emulation.SensorsView.NonPresetOptions.Custom};this._orientationSelectElement=this.contentElement.createChild('select','chrome-select');this._orientationSelectElement.appendChild(new Option(orientationOffOption.title,orientationOffOption.orientation));this._orientationSelectElement.appendChild(new Option(customOrientationOption.title,customOrientationOption.orientation));var orientationGroups=Emulation.SensorsView.PresetOrientations;for(var i=0;i<orientationGroups.length;++i){var groupElement=this._orientationSelectElement.createChild('optgroup');groupElement.label=orientationGroups[i].title;var group=orientationGroups[i].value;for(var j=0;j<group.length;++j) -groupElement.appendChild(new Option(group[j].title,group[j].orientation));} -this._orientationSelectElement.selectedIndex=0;fields.appendChild(this._orientationSelectElement);this._orientationSelectElement.addEventListener('change',this._orientationSelectChanged.bind(this));this._deviceOrientationFieldset=this._createDeviceOrientationOverrideElement(this._deviceOrientation);this._stageElement=orientationContent.createChild('div','orientation-stage');this._stageElement.title=Common.UIString('Shift+drag horizontally to rotate around the y-axis');this._orientationLayer=this._stageElement.createChild('div','orientation-layer');this._boxElement=this._orientationLayer.createChild('section','orientation-box orientation-element');this._boxElement.createChild('section','orientation-front orientation-element');this._boxElement.createChild('section','orientation-top orientation-element');this._boxElement.createChild('section','orientation-back orientation-element');this._boxElement.createChild('section','orientation-left orientation-element');this._boxElement.createChild('section','orientation-right orientation-element');this._boxElement.createChild('section','orientation-bottom orientation-element');UI.installDragHandle(this._stageElement,this._onBoxDragStart.bind(this),this._onBoxDrag.bind(this),null,'-webkit-grabbing','-webkit-grab');fields.appendChild(this._deviceOrientationFieldset);this._enableOrientationFields(true);this._setBoxOrientation(this._deviceOrientation,false);} -_enableOrientationFields(disable){if(disable){this._deviceOrientationFieldset.disabled=true;this._stageElement.classList.add('disabled');}else{this._deviceOrientationFieldset.disabled=false;this._stageElement.classList.remove('disabled');}} -_orientationSelectChanged(){var value=this._orientationSelectElement.options[this._orientationSelectElement.selectedIndex].value;this._enableOrientationFields(false);if(value===Emulation.SensorsView.NonPresetOptions.NoOverride){this._deviceOrientationOverrideEnabled=false;this._enableOrientationFields(true);}else if(value===Emulation.SensorsView.NonPresetOptions.Custom){this._deviceOrientationOverrideEnabled=true;this._alphaElement.focus();}else{var parsedValue=JSON.parse(value);this._deviceOrientationOverrideEnabled=true;this._deviceOrientation=new SDK.EmulationModel.DeviceOrientation(parsedValue[0],parsedValue[1],parsedValue[2]);this._setDeviceOrientation(this._deviceOrientation,Emulation.SensorsView.DeviceOrientationModificationSource.SelectPreset);}} -_applyDeviceOrientation(){if(this._deviceOrientationOverrideEnabled) -this._deviceOrientationSetting.set(this._deviceOrientation.toSetting());for(var emulationModel of SDK.targetManager.models(SDK.EmulationModel)) -emulationModel.emulateDeviceOrientation(this._deviceOrientationOverrideEnabled?this._deviceOrientation:null);} -_setSelectElementLabel(selectElement,labelValue){var optionValues=Array.prototype.map.call(selectElement.options,x=>x.value);selectElement.selectedIndex=optionValues.indexOf(labelValue);} -_applyDeviceOrientationUserInput(){this._setDeviceOrientation(SDK.EmulationModel.DeviceOrientation.parseUserInput(this._alphaElement.value.trim(),this._betaElement.value.trim(),this._gammaElement.value.trim()),Emulation.SensorsView.DeviceOrientationModificationSource.UserInput);this._setSelectElementLabel(this._orientationSelectElement,Emulation.SensorsView.NonPresetOptions.Custom);} -_resetDeviceOrientation(){this._setDeviceOrientation(new SDK.EmulationModel.DeviceOrientation(0,90,0),Emulation.SensorsView.DeviceOrientationModificationSource.ResetButton);this._setSelectElementLabel(this._orientationSelectElement,'[0, 90, 0]');} -_setDeviceOrientation(deviceOrientation,modificationSource){if(!deviceOrientation) -return;function roundAngle(angle){return Math.round(angle*10000)/10000;} -if(modificationSource!==Emulation.SensorsView.DeviceOrientationModificationSource.UserInput){this._alphaSetter(roundAngle(deviceOrientation.alpha));this._betaSetter(roundAngle(deviceOrientation.beta));this._gammaSetter(roundAngle(deviceOrientation.gamma));} -var animate=modificationSource!==Emulation.SensorsView.DeviceOrientationModificationSource.UserDrag;this._setBoxOrientation(deviceOrientation,animate);this._deviceOrientation=deviceOrientation;this._applyDeviceOrientation();} -_createAxisInput(parentElement,input,label){var div=parentElement.createChild('div','orientation-axis-input-container');div.appendChild(input);div.createTextChild(label);input.type='number';return UI.bindInput(input,this._applyDeviceOrientationUserInput.bind(this),SDK.EmulationModel.DeviceOrientation.validator,true);} -_createDeviceOrientationOverrideElement(deviceOrientation){var fieldsetElement=createElement('fieldset');fieldsetElement.classList.add('device-orientation-override-section');var cellElement=fieldsetElement.createChild('td','orientation-inputs-cell');this._alphaElement=UI.createInput();this._alphaElement.setAttribute('step','any');this._alphaSetter=this._createAxisInput(cellElement,this._alphaElement,Common.UIString('\u03B1 (alpha)'));this._alphaSetter(String(deviceOrientation.alpha));this._betaElement=UI.createInput();this._betaElement.setAttribute('step','any');this._betaSetter=this._createAxisInput(cellElement,this._betaElement,Common.UIString('\u03B2 (beta)'));this._betaSetter(String(deviceOrientation.beta));this._gammaElement=UI.createInput();this._gammaElement.setAttribute('step','any');this._gammaSetter=this._createAxisInput(cellElement,this._gammaElement,Common.UIString('\u03B3 (gamma)'));this._gammaSetter(String(deviceOrientation.gamma));cellElement.appendChild(UI.createTextButton(Common.UIString('Reset'),this._resetDeviceOrientation.bind(this),'orientation-reset-button'));return fieldsetElement;} -_setBoxOrientation(deviceOrientation,animate){if(animate) -this._stageElement.classList.add('is-animating');else -this._stageElement.classList.remove('is-animating');var matrix=new WebKitCSSMatrix();this._boxMatrix=matrix.rotate(-deviceOrientation.beta,deviceOrientation.gamma,-deviceOrientation.alpha);var eulerAngles=new UI.Geometry.EulerAngles(deviceOrientation.alpha,deviceOrientation.beta,deviceOrientation.gamma);this._orientationLayer.style.transform=eulerAngles.toRotate3DString();} -_onBoxDrag(event){var mouseMoveVector=this._calculateRadiusVector(event.x,event.y);if(!mouseMoveVector) -return true;event.consume(true);var axis,angle;if(event.shiftKey){axis=new UI.Geometry.Vector(0,0,-1);angle=(this._mouseDownVector.x-mouseMoveVector.x)*Emulation.SensorsView.ShiftDragOrientationSpeed;}else{axis=UI.Geometry.crossProduct(this._mouseDownVector,mouseMoveVector);angle=UI.Geometry.calculateAngle(this._mouseDownVector,mouseMoveVector);} -var currentMatrix=new WebKitCSSMatrix();currentMatrix=currentMatrix.rotate(-90,0,0).rotateAxisAngle(axis.x,axis.y,axis.z,angle).rotate(90,0,0).multiply(this._originalBoxMatrix);var eulerAngles=UI.Geometry.EulerAngles.fromRotationMatrix(currentMatrix);var newOrientation=new SDK.EmulationModel.DeviceOrientation(-eulerAngles.alpha,-eulerAngles.beta,eulerAngles.gamma);this._setDeviceOrientation(newOrientation,Emulation.SensorsView.DeviceOrientationModificationSource.UserDrag);this._setSelectElementLabel(this._orientationSelectElement,Emulation.SensorsView.NonPresetOptions.Custom);return false;} -_onBoxDragStart(event){if(!this._deviceOrientationOverrideEnabled) -return false;this._mouseDownVector=this._calculateRadiusVector(event.x,event.y);this._originalBoxMatrix=this._boxMatrix;if(!this._mouseDownVector) -return false;event.consume(true);return true;} -_calculateRadiusVector(x,y){var rect=this._stageElement.getBoundingClientRect();var radius=Math.max(rect.width,rect.height)/2;var sphereX=(x-rect.left-rect.width/2)/radius;var sphereY=(y-rect.top-rect.height/2)/radius;var sqrSum=sphereX*sphereX+sphereY*sphereY;if(sqrSum>0.5) -return new UI.Geometry.Vector(sphereX,sphereY,0.5/Math.sqrt(sqrSum));return new UI.Geometry.Vector(sphereX,sphereY,Math.sqrt(1-sqrSum));} -_appendTouchControl(){var groupElement=this.contentElement.createChild('div','sensors-group');var title=groupElement.createChild('div','sensors-group-title');var fieldsElement=groupElement.createChild('div','sensors-group-fields');title.textContent=Common.UIString('Touch');var select=fieldsElement.createChild('select','chrome-select');select.appendChild(new Option(Common.UIString('Device-based'),'auto'));select.appendChild(new Option(Common.UIString('Force enabled'),'enabled'));select.addEventListener('change',applyTouch,false);var reloadWarning=groupElement.createChild('div','reload-warning hidden');reloadWarning.textContent=Common.UIString('*Requires reload');function applyTouch(){for(var emulationModel of SDK.targetManager.models(SDK.EmulationModel)) -emulationModel.overrideEmulateTouch(select.value==='enabled');reloadWarning.classList.remove('hidden');var resourceTreeModel=SDK.targetManager.models(SDK.ResourceTreeModel)[0];if(resourceTreeModel){resourceTreeModel.once(SDK.ResourceTreeModel.Events.MainFrameNavigated).then(()=>reloadWarning.classList.add('hidden'));}}}};Emulation.SensorsView.DeviceOrientationModificationSource={UserInput:'userInput',UserDrag:'userDrag',ResetButton:'resetButton',SelectPreset:'selectPreset'};Emulation.SensorsView.NonPresetOptions={'NoOverride':'noOverride','Custom':'custom','Unavailable':'unavailable'};Emulation.SensorsView.PresetLocations=[{title:'Presets',value:[{title:Common.UIString('Berlin'),location:'[52.520007, 13.404954]'},{title:Common.UIString('London'),location:'[51.507351, -0.127758]'},{title:Common.UIString('Moscow'),location:'[55.755826, 37.617300]'},{title:Common.UIString('Mountain View'),location:'[37.386052, -122.083851]'},{title:Common.UIString('Mumbai'),location:'[19.075984, 72.877656]'},{title:Common.UIString('San Francisco'),location:'[37.774929, -122.419416]'},{title:Common.UIString('Shanghai'),location:'[31.230416, 121.473701]'},{title:Common.UIString('São Paulo'),location:'[-23.550520, -46.633309]'},{title:Common.UIString('Tokyo'),location:'[35.689487, 139.691706]'},]},{title:'Error',value:[{title:Common.UIString('Location unavailable'),location:Emulation.SensorsView.NonPresetOptions.Unavailable}]}];Emulation.SensorsView.PresetOrientations=[{title:'Presets',value:[{title:Common.UIString('Portrait'),orientation:'[0, 90, 0]'},{title:Common.UIString('Portrait upside down'),orientation:'[180, -90, 0]'},{title:Common.UIString('Landscape left'),orientation:'[0, 90, -90]'},{title:Common.UIString('Landscape right'),orientation:'[0, 90, 90]'},{title:Common.UIString('Display up'),orientation:'[0, 0, 0]'},{title:Common.UIString('Display down'),orientation:'[0, 180, 0]'}]}];Emulation.SensorsView.ShowActionDelegate=class{handleAction(context,actionId){UI.viewManager.showView('sensors');return true;}};Emulation.SensorsView.ShiftDragOrientationSpeed=16;;Emulation.DeviceModeModel=class extends Common.Object{constructor(){super();this._screenRect=new UI.Rect(0,0,1,1);this._visiblePageRect=new UI.Rect(0,0,1,1);this._availableSize=new UI.Size(1,1);this._preferredSize=new UI.Size(1,1);this._initialized=false;this._appliedDeviceSize=new UI.Size(1,1);this._appliedDeviceScaleFactor=window.devicePixelRatio;this._appliedUserAgentType=Emulation.DeviceModeModel.UA.Desktop;this._scaleSetting=Common.settings.createSetting('emulation.deviceScale',1);if(!this._scaleSetting.get()) -this._scaleSetting.set(1);this._scaleSetting.addChangeListener(this._scaleSettingChanged,this);this._widthSetting=Common.settings.createSetting('emulation.deviceWidth',400);if(this._widthSetting.get()<Emulation.DeviceModeModel.MinDeviceSize) -this._widthSetting.set(Emulation.DeviceModeModel.MinDeviceSize);if(this._widthSetting.get()>Emulation.DeviceModeModel.MaxDeviceSize) -this._widthSetting.set(Emulation.DeviceModeModel.MaxDeviceSize);this._widthSetting.addChangeListener(this._widthSettingChanged,this);this._heightSetting=Common.settings.createSetting('emulation.deviceHeight',0);if(this._heightSetting.get()&&this._heightSetting.get()<Emulation.DeviceModeModel.MinDeviceSize) -this._heightSetting.set(Emulation.DeviceModeModel.MinDeviceSize);if(this._heightSetting.get()>Emulation.DeviceModeModel.MaxDeviceSize) -this._heightSetting.set(Emulation.DeviceModeModel.MaxDeviceSize);this._heightSetting.addChangeListener(this._heightSettingChanged,this);this._uaSetting=Common.settings.createSetting('emulation.deviceUA',Emulation.DeviceModeModel.UA.Mobile);this._uaSetting.addChangeListener(this._uaSettingChanged,this);this._deviceScaleFactorSetting=Common.settings.createSetting('emulation.deviceScaleFactor',0);this._deviceScaleFactorSetting.addChangeListener(this._deviceScaleFactorSettingChanged,this);this._deviceOutlineSetting=Common.settings.moduleSetting('emulation.showDeviceOutline');this._deviceOutlineSetting.addChangeListener(this._deviceOutlineSettingChanged,this);this._toolbarControlsEnabledSetting=Common.settings.createSetting('emulation.toolbarControlsEnabled',true,Common.SettingStorageType.Session);this._type=Emulation.DeviceModeModel.Type.None;this._device=null;this._mode=null;this._fitScale=1;this._emulationModel=null;this._onModelAvailable=null;SDK.targetManager.observeModels(SDK.EmulationModel,this);} -static deviceSizeValidator(value){if(/^[\d]+$/.test(value)&&value>=Emulation.DeviceModeModel.MinDeviceSize&&value<=Emulation.DeviceModeModel.MaxDeviceSize) -return true;return false;} -static deviceScaleFactorValidator(value){if(!value||(/^[\d]+(\.\d+)?|\.\d+$/.test(value)&&value>=0&&value<=10)) -return true;return false;} -setAvailableSize(availableSize,preferredSize){this._availableSize=availableSize;this._preferredSize=preferredSize;this._initialized=true;this._calculateAndEmulate(false);} -emulate(type,device,mode,scale){var resetPageScaleFactor=this._type!==type||this._device!==device||this._mode!==mode;this._type=type;if(type===Emulation.DeviceModeModel.Type.Device){console.assert(device&&mode,'Must pass device and mode for device emulation');this._mode=mode;this._device=device;if(this._initialized){var orientation=device.orientationByName(mode.orientation);this._scaleSetting.set(scale||this._calculateFitScale(orientation.width,orientation.height,this._currentOutline(),this._currentInsets()));}}else{this._device=null;this._mode=null;} -if(type!==Emulation.DeviceModeModel.Type.None) -Host.userMetrics.actionTaken(Host.UserMetrics.Action.DeviceModeEnabled);this._calculateAndEmulate(resetPageScaleFactor);} -setWidth(width){var max=Math.min(Emulation.DeviceModeModel.MaxDeviceSize,this._preferredScaledWidth());width=Math.max(Math.min(width,max),1);this._widthSetting.set(width);} -setWidthAndScaleToFit(width){width=Math.max(Math.min(width,Emulation.DeviceModeModel.MaxDeviceSize),1);this._scaleSetting.set(this._calculateFitScale(width,this._heightSetting.get()));this._widthSetting.set(width);} -setHeight(height){var max=Math.min(Emulation.DeviceModeModel.MaxDeviceSize,this._preferredScaledHeight());height=Math.max(Math.min(height,max),0);if(height===this._preferredScaledHeight()) -height=0;this._heightSetting.set(height);} -setHeightAndScaleToFit(height){height=Math.max(Math.min(height,Emulation.DeviceModeModel.MaxDeviceSize),0);this._scaleSetting.set(this._calculateFitScale(this._widthSetting.get(),height));this._heightSetting.set(height);} -setScale(scale){this._scaleSetting.set(scale);} -device(){return this._device;} -mode(){return this._mode;} -type(){return this._type;} -screenImage(){return(this._device&&this._mode)?this._device.modeImage(this._mode):'';} -outlineImage(){return(this._device&&this._mode&&this._deviceOutlineSetting.get())?this._device.outlineImage(this._mode):'';} -outlineRect(){return this._outlineRect;} -screenRect(){return this._screenRect;} -visiblePageRect(){return this._visiblePageRect;} -scale(){return this._scale;} -fitScale(){return this._fitScale;} -appliedDeviceSize(){return this._appliedDeviceSize;} -appliedDeviceScaleFactor(){return this._appliedDeviceScaleFactor;} -appliedUserAgentType(){return this._appliedUserAgentType;} -isFullHeight(){return!this._heightSetting.get();} -_isMobile(){switch(this._type){case Emulation.DeviceModeModel.Type.Device:return this._device.mobile();case Emulation.DeviceModeModel.Type.None:return false;case Emulation.DeviceModeModel.Type.Responsive:return this._uaSetting.get()===Emulation.DeviceModeModel.UA.Mobile||this._uaSetting.get()===Emulation.DeviceModeModel.UA.MobileNoTouch;} -return false;} -enabledSetting(){return Common.settings.createSetting('emulation.showDeviceMode',false);} -scaleSetting(){return this._scaleSetting;} -uaSetting(){return this._uaSetting;} -deviceScaleFactorSetting(){return this._deviceScaleFactorSetting;} -deviceOutlineSetting(){return this._deviceOutlineSetting;} -toolbarControlsEnabledSetting(){return this._toolbarControlsEnabledSetting;} -reset(){this._deviceScaleFactorSetting.set(0);this._scaleSetting.set(1);this.setWidth(400);this.setHeight(0);this._uaSetting.set(Emulation.DeviceModeModel.UA.Mobile);} -modelAdded(emulationModel){if(!this._emulationModel&&emulationModel.supportsDeviceEmulation()){this._emulationModel=emulationModel;if(this._onModelAvailable){var callback=this._onModelAvailable;this._onModelAvailable=null;callback();}}} -modelRemoved(emulationModel){if(this._emulationModel===emulationModel) -this._emulationModel=null;} -inspectedURL(){return this._emulationModel?this._emulationModel.target().inspectedURL():null;} -_scaleSettingChanged(){this._calculateAndEmulate(false);} -_widthSettingChanged(){this._calculateAndEmulate(false);} -_heightSettingChanged(){this._calculateAndEmulate(false);} -_uaSettingChanged(){this._calculateAndEmulate(true);} -_deviceScaleFactorSettingChanged(){this._calculateAndEmulate(false);} -_deviceOutlineSettingChanged(){this._calculateAndEmulate(false);} -_preferredScaledWidth(){return Math.floor(this._preferredSize.width/(this._scaleSetting.get()||1));} -_preferredScaledHeight(){return Math.floor(this._preferredSize.height/(this._scaleSetting.get()||1));} -_currentOutline(){var outline=new UI.Insets(0,0,0,0);if(this._type!==Emulation.DeviceModeModel.Type.Device) -return outline;var orientation=this._device.orientationByName(this._mode.orientation);if(this._deviceOutlineSetting.get()) -outline=orientation.outlineInsets||outline;return outline;} -_currentInsets(){if(this._type!==Emulation.DeviceModeModel.Type.Device) -return new UI.Insets(0,0,0,0);return this._mode.insets;} -_calculateAndEmulate(resetPageScaleFactor){if(!this._emulationModel) -this._onModelAvailable=this._calculateAndEmulate.bind(this,resetPageScaleFactor);var mobile=this._isMobile();if(this._type===Emulation.DeviceModeModel.Type.Device){var orientation=this._device.orientationByName(this._mode.orientation);var outline=this._currentOutline();var insets=this._currentInsets();this._fitScale=this._calculateFitScale(orientation.width,orientation.height,outline,insets);if(mobile){this._appliedUserAgentType=this._device.touch()?Emulation.DeviceModeModel.UA.Mobile:Emulation.DeviceModeModel.UA.MobileNoTouch;}else{this._appliedUserAgentType=this._device.touch()?Emulation.DeviceModeModel.UA.DesktopTouch:Emulation.DeviceModeModel.UA.Desktop;} -this._applyDeviceMetrics(new UI.Size(orientation.width,orientation.height),insets,outline,this._scaleSetting.get(),this._device.deviceScaleFactor,mobile,this._mode.orientation===Emulation.EmulatedDevice.Horizontal?Protocol.Emulation.ScreenOrientationType.LandscapePrimary:Protocol.Emulation.ScreenOrientationType.PortraitPrimary,resetPageScaleFactor);this._applyUserAgent(this._device.userAgent);this._applyTouch(this._device.touch(),mobile);}else if(this._type===Emulation.DeviceModeModel.Type.None){this._fitScale=this._calculateFitScale(this._availableSize.width,this._availableSize.height);this._appliedUserAgentType=Emulation.DeviceModeModel.UA.Desktop;this._applyDeviceMetrics(this._availableSize,new UI.Insets(0,0,0,0),new UI.Insets(0,0,0,0),1,0,mobile,null,resetPageScaleFactor);this._applyUserAgent('');this._applyTouch(false,false);}else if(this._type===Emulation.DeviceModeModel.Type.Responsive){var screenWidth=this._widthSetting.get();if(!screenWidth||screenWidth>this._preferredScaledWidth()) -screenWidth=this._preferredScaledWidth();var screenHeight=this._heightSetting.get();if(!screenHeight||screenHeight>this._preferredScaledHeight()) -screenHeight=this._preferredScaledHeight();var defaultDeviceScaleFactor=mobile?Emulation.DeviceModeModel.defaultMobileScaleFactor:0;this._fitScale=this._calculateFitScale(this._widthSetting.get(),this._heightSetting.get());this._appliedUserAgentType=this._uaSetting.get();this._applyDeviceMetrics(new UI.Size(screenWidth,screenHeight),new UI.Insets(0,0,0,0),new UI.Insets(0,0,0,0),this._scaleSetting.get(),this._deviceScaleFactorSetting.get()||defaultDeviceScaleFactor,mobile,screenHeight>=screenWidth?Protocol.Emulation.ScreenOrientationType.PortraitPrimary:Protocol.Emulation.ScreenOrientationType.LandscapePrimary,resetPageScaleFactor);this._applyUserAgent(mobile?Emulation.DeviceModeModel._defaultMobileUserAgent:'');this._applyTouch(this._uaSetting.get()===Emulation.DeviceModeModel.UA.DesktopTouch||this._uaSetting.get()===Emulation.DeviceModeModel.UA.Mobile,this._uaSetting.get()===Emulation.DeviceModeModel.UA.Mobile);} -var overlayModel=this._emulationModel?this._emulationModel.overlayModel():null;if(overlayModel) -overlayModel.setShowViewportSizeOnResize(this._type===Emulation.DeviceModeModel.Type.None);this.dispatchEventToListeners(Emulation.DeviceModeModel.Events.Updated);} -_calculateFitScale(screenWidth,screenHeight,outline,insets){var outlineWidth=outline?outline.left+outline.right:0;var outlineHeight=outline?outline.top+outline.bottom:0;var insetsWidth=insets?insets.left+insets.right:0;var insetsHeight=insets?insets.top+insets.bottom:0;var scale=Math.min(screenWidth?this._preferredSize.width/(screenWidth+outlineWidth):1,screenHeight?this._preferredSize.height/(screenHeight+outlineHeight):1);scale=Math.min(Math.floor(scale*100),100);var sharpScale=scale;while(sharpScale>scale*0.7){var sharp=true;if(screenWidth) -sharp=sharp&&Number.isInteger((screenWidth-insetsWidth)*sharpScale/100);if(screenHeight) -sharp=sharp&&Number.isInteger((screenHeight-insetsHeight)*sharpScale/100);if(sharp) -return sharpScale/100;sharpScale-=1;} -return scale/100;} -setSizeAndScaleToFit(width,height){this._scaleSetting.set(this._calculateFitScale(width,height));this.setWidth(width);} -_applyUserAgent(userAgent){SDK.multitargetNetworkManager.setUserAgentOverride(userAgent);} -_applyDeviceMetrics(screenSize,insets,outline,scale,deviceScaleFactor,mobile,screenOrientation,resetPageScaleFactor){screenSize.width=Math.max(1,Math.floor(screenSize.width));screenSize.height=Math.max(1,Math.floor(screenSize.height));var pageWidth=screenSize.width-insets.left-insets.right;var pageHeight=screenSize.height-insets.top-insets.bottom;this._emulatedPageSize=new UI.Size(pageWidth,pageHeight);var positionX=insets.left;var positionY=insets.top;var screenOrientationAngle=screenOrientation===Protocol.Emulation.ScreenOrientationType.LandscapePrimary?90:0;this._appliedDeviceSize=screenSize;this._appliedDeviceScaleFactor=deviceScaleFactor||window.devicePixelRatio;this._screenRect=new UI.Rect(Math.max(0,(this._availableSize.width-screenSize.width*scale)/2),outline.top*scale,screenSize.width*scale,screenSize.height*scale);this._outlineRect=new UI.Rect(this._screenRect.left-outline.left*scale,0,(outline.left+screenSize.width+outline.right)*scale,(outline.top+screenSize.height+outline.bottom)*scale);this._visiblePageRect=new UI.Rect(positionX*scale,positionY*scale,Math.min(pageWidth*scale,this._availableSize.width-this._screenRect.left-positionX*scale),Math.min(pageHeight*scale,this._availableSize.height-this._screenRect.top-positionY*scale));this._scale=scale;if(scale===1&&this._availableSize.width>=screenSize.width&&this._availableSize.height>=screenSize.height){pageWidth=0;pageHeight=0;} -if(this._visiblePageRect.width===pageWidth*scale&&this._visiblePageRect.height===pageHeight*scale&&Number.isInteger(pageWidth*scale)&&Number.isInteger(pageHeight*scale)){pageWidth=0;pageHeight=0;} -if(!this._emulationModel) -return;if(resetPageScaleFactor) -this._emulationModel.resetPageScaleFactor();if(pageWidth||pageHeight||mobile||deviceScaleFactor||scale!==1||screenOrientation){var metrics={width:pageWidth,height:pageHeight,deviceScaleFactor:deviceScaleFactor,mobile:mobile,scale:scale,screenWidth:screenSize.width,screenHeight:screenSize.height,positionX:positionX,positionY:positionY,dontSetVisibleSize:true};if(screenOrientation) -metrics.screenOrientation={type:screenOrientation,angle:screenOrientationAngle};this._emulationModel.emulateDevice(metrics);}else{this._emulationModel.emulateDevice(null);}} -async captureScreenshot(fullSize,clip){var screenCaptureModel=this._emulationModel?this._emulationModel.target().model(SDK.ScreenCaptureModel):null;if(!screenCaptureModel) -return null;var overlayModel=this._emulationModel?this._emulationModel.overlayModel():null;if(overlayModel) -overlayModel.setShowViewportSizeOnResize(false);var deviceMetrics;if(fullSize){var metrics=await screenCaptureModel.fetchLayoutMetrics();if(!metrics) -return null;deviceMetrics={width:Math.floor(metrics.contentWidth),height:Math.floor(metrics.contentHeight),deviceScaleFactor:this._appliedDeviceScaleFactor,mobile:this._isMobile(),};clip={x:0,y:0,width:deviceMetrics.width,height:deviceMetrics.height,scale:1};if(this._device){var screenOrientation=this._mode.orientation===Emulation.EmulatedDevice.Horizontal?Protocol.Emulation.ScreenOrientationType.LandscapePrimary:Protocol.Emulation.ScreenOrientationType.PortraitPrimary;var screenOrientationAngle=screenOrientation===Protocol.Emulation.ScreenOrientationType.LandscapePrimary?90:0;deviceMetrics.screenOrientation={type:screenOrientation,angle:screenOrientationAngle};} -await this._emulationModel.resetPageScaleFactor();await this._emulationModel.emulateDevice(deviceMetrics);} -var screenshot=await screenCaptureModel.captureScreenshot('png',100,clip);if(fullSize){if(this._device){var orientation=this._device.orientationByName(this._mode.orientation);deviceMetrics.width=orientation.width;deviceMetrics.height=orientation.height;}else{deviceMetrics.width=0;deviceMetrics.height=0;} -await this._emulationModel.emulateDevice(deviceMetrics);} -this._calculateAndEmulate(false);return screenshot;} -_applyTouch(touchEnabled,mobile){for(var emulationModel of SDK.targetManager.models(SDK.EmulationModel)) -emulationModel.emulateTouch(touchEnabled,mobile);}};Emulation.DeviceModeModel.Events={Updated:'Updated'};Emulation.DeviceModeModel.Type={None:'None',Responsive:'Responsive',Device:'Device'};Emulation.DeviceModeModel.UA={Mobile:Common.UIString('Mobile'),MobileNoTouch:Common.UIString('Mobile (no touch)'),Desktop:Common.UIString('Desktop'),DesktopTouch:Common.UIString('Desktop (touch)')};Emulation.DeviceModeModel.MinDeviceSize=50;Emulation.DeviceModeModel.MaxDeviceSize=9999;Emulation.DeviceModeModel._defaultMobileUserAgent='Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36';Emulation.DeviceModeModel._defaultMobileUserAgent=SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(Emulation.DeviceModeModel._defaultMobileUserAgent);Emulation.DeviceModeModel.defaultMobileScaleFactor=2;;Emulation.DeviceModeToolbar=class{constructor(model,showMediaInspectorSetting,showRulersSetting){this._model=model;this._showMediaInspectorSetting=showMediaInspectorSetting;this._showRulersSetting=showRulersSetting;this._deviceOutlineSetting=this._model.deviceOutlineSetting();this._showDeviceScaleFactorSetting=Common.settings.createSetting('emulation.showDeviceScaleFactor',false);this._showDeviceScaleFactorSetting.addChangeListener(this._updateDeviceScaleFactorVisibility,this);this._showUserAgentTypeSetting=Common.settings.createSetting('emulation.showUserAgentType',false);this._showUserAgentTypeSetting.addChangeListener(this._updateUserAgentTypeVisibility,this);this._lastMode=new Map();this._lastScale=new Map();this._element=createElementWithClass('div','device-mode-toolbar');var leftContainer=this._element.createChild('div','device-mode-toolbar-spacer');leftContainer.createChild('div','device-mode-toolbar-spacer');var leftToolbar=new UI.Toolbar('',leftContainer);leftToolbar.makeWrappable();this._fillLeftToolbar(leftToolbar);var mainToolbar=new UI.Toolbar('',this._element);mainToolbar.makeWrappable();this._fillMainToolbar(mainToolbar);var rightContainer=this._element.createChild('div','device-mode-toolbar-spacer');var rightToolbar=new UI.Toolbar('device-mode-toolbar-fixed-size',rightContainer);rightToolbar.makeWrappable();this._fillRightToolbar(rightToolbar);var modeToolbar=new UI.Toolbar('device-mode-toolbar-fixed-size',rightContainer);modeToolbar.makeWrappable();this._fillModeToolbar(modeToolbar);rightContainer.createChild('div','device-mode-toolbar-spacer');var optionsToolbar=new UI.Toolbar('',rightContainer);optionsToolbar.makeWrappable(true);this._fillOptionsToolbar(optionsToolbar);this._emulatedDevicesList=Emulation.EmulatedDevicesList.instance();this._emulatedDevicesList.addEventListener(Emulation.EmulatedDevicesList.Events.CustomDevicesUpdated,this._deviceListChanged,this);this._emulatedDevicesList.addEventListener(Emulation.EmulatedDevicesList.Events.StandardDevicesUpdated,this._deviceListChanged,this);this._persistenceSetting=Common.settings.createSetting('emulation.deviceModeValue',{device:'',orientation:'',mode:''});this._model.toolbarControlsEnabledSetting().addChangeListener(updateToolbarsEnabled);updateToolbarsEnabled();function updateToolbarsEnabled(){var enabled=model.toolbarControlsEnabledSetting().get();leftToolbar.setEnabled(enabled);mainToolbar.setEnabled(enabled);rightToolbar.setEnabled(enabled);modeToolbar.setEnabled(enabled);optionsToolbar.setEnabled(enabled);}} -_fillLeftToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));this._deviceSelectItem=new UI.ToolbarMenuButton(this._appendDeviceMenuItems.bind(this));this._deviceSelectItem.setGlyph('');this._deviceSelectItem.turnIntoSelect(95);this._deviceSelectItem.setDarkText();toolbar.appendToolbarItem(this._deviceSelectItem);} -_fillMainToolbar(toolbar){var widthInput=UI.createInput('device-mode-size-input','text');widthInput.maxLength=4;widthInput.title=Common.UIString('Width');this._updateWidthInput=UI.bindInput(widthInput,this._applyWidth.bind(this),Emulation.DeviceModeModel.deviceSizeValidator,true);this._widthInput=widthInput;this._widthItem=this._wrapToolbarItem(widthInput);toolbar.appendToolbarItem(this._widthItem);var xElement=createElementWithClass('div','device-mode-x');xElement.textContent='\u00D7';this._xItem=this._wrapToolbarItem(xElement);toolbar.appendToolbarItem(this._xItem);var heightInput=UI.createInput('device-mode-size-input','text');heightInput.maxLength=4;heightInput.title=Common.UIString('Height (leave empty for full)');this._updateHeightInput=UI.bindInput(heightInput,this._applyHeight.bind(this),validateHeight,true);this._heightInput=heightInput;this._heightItem=this._wrapToolbarItem(heightInput);toolbar.appendToolbarItem(this._heightItem);function validateHeight(value){return!value||Emulation.DeviceModeModel.deviceSizeValidator(value);}} -_applyWidth(value){var width=value?Number(value):0;this._model.setWidthAndScaleToFit(width);} -_applyHeight(value){var height=value?Number(value):0;this._model.setHeightAndScaleToFit(height);} -_fillRightToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));this._scaleItem=new UI.ToolbarMenuButton(this._appendScaleMenuItems.bind(this));this._scaleItem.setTitle(Common.UIString('Zoom'));this._scaleItem.setGlyph('');this._scaleItem.turnIntoSelect();this._scaleItem.setDarkText();toolbar.appendToolbarItem(this._scaleItem);toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));this._deviceScaleItem=new UI.ToolbarMenuButton(this._appendDeviceScaleMenuItems.bind(this));this._deviceScaleItem.setVisible(this._showDeviceScaleFactorSetting.get());this._deviceScaleItem.setTitle(Common.UIString('Device pixel ratio'));this._deviceScaleItem.setGlyph('');this._deviceScaleItem.turnIntoSelect();this._deviceScaleItem.setDarkText();toolbar.appendToolbarItem(this._deviceScaleItem);toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));this._uaItem=new UI.ToolbarMenuButton(this._appendUserAgentMenuItems.bind(this));this._uaItem.setVisible(this._showUserAgentTypeSetting.get());this._uaItem.setTitle(Common.UIString('Device type'));this._uaItem.setGlyph('');this._uaItem.turnIntoSelect();this._uaItem.setDarkText();toolbar.appendToolbarItem(this._uaItem);this._throttlingConditionsItem=MobileThrottling.throttlingManager().createMobileThrottlingButton();toolbar.appendToolbarItem(this._throttlingConditionsItem);} -_fillModeToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));this._modeButton=new UI.ToolbarButton('','largeicon-rotate-screen');this._modeButton.addEventListener(UI.ToolbarButton.Events.Click,this._modeMenuClicked,this);toolbar.appendToolbarItem(this._modeButton);} -_fillOptionsToolbar(toolbar){var moreOptionsButton=new UI.ToolbarMenuButton(this._appendOptionsMenuItems.bind(this));moreOptionsButton.setTitle(Common.UIString('More options'));toolbar.appendToolbarItem(moreOptionsButton);toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));} -_appendScaleMenuItems(contextMenu){if(this._model.type()===Emulation.DeviceModeModel.Type.Device){contextMenu.headerSection().appendItem(Common.UIString('Fit to window (%.0f%%)',this._model.fitScale()*100),this._onScaleMenuChanged.bind(this,this._model.fitScale()),false);} -var boundAppendScaleItem=appendScaleItem.bind(this);boundAppendScaleItem(Common.UIString('50%'),0.5);boundAppendScaleItem(Common.UIString('75%'),0.75);boundAppendScaleItem(Common.UIString('100%'),1);boundAppendScaleItem(Common.UIString('125%'),1.25);boundAppendScaleItem(Common.UIString('150%'),1.5);function appendScaleItem(title,value){contextMenu.defaultSection().appendCheckboxItem(title,this._onScaleMenuChanged.bind(this,value),this._model.scaleSetting().get()===value,false);}} -_onScaleMenuChanged(value){var device=this._model.device();if(device) -this._lastScale.set(device,value);this._model.scaleSetting().set(value);} -_appendDeviceScaleMenuItems(contextMenu){var deviceScaleFactorSetting=this._model.deviceScaleFactorSetting();var defaultValue=this._model.uaSetting().get()===Emulation.DeviceModeModel.UA.Mobile||this._model.uaSetting().get()===Emulation.DeviceModeModel.UA.MobileNoTouch?Emulation.DeviceModeModel.defaultMobileScaleFactor:window.devicePixelRatio;appendDeviceScaleFactorItem(contextMenu.headerSection(),Common.UIString('Default: %.1f',defaultValue),0);appendDeviceScaleFactorItem(contextMenu.defaultSection(),Common.UIString('1'),1);appendDeviceScaleFactorItem(contextMenu.defaultSection(),Common.UIString('2'),2);appendDeviceScaleFactorItem(contextMenu.defaultSection(),Common.UIString('3'),3);function appendDeviceScaleFactorItem(section,title,value){section.appendCheckboxItem(title,deviceScaleFactorSetting.set.bind(deviceScaleFactorSetting,value),deviceScaleFactorSetting.get()===value);}} -_appendUserAgentMenuItems(contextMenu){var uaSetting=this._model.uaSetting();appendUAItem(Emulation.DeviceModeModel.UA.Mobile,Emulation.DeviceModeModel.UA.Mobile);appendUAItem(Emulation.DeviceModeModel.UA.MobileNoTouch,Emulation.DeviceModeModel.UA.MobileNoTouch);appendUAItem(Emulation.DeviceModeModel.UA.Desktop,Emulation.DeviceModeModel.UA.Desktop);appendUAItem(Emulation.DeviceModeModel.UA.DesktopTouch,Emulation.DeviceModeModel.UA.DesktopTouch);function appendUAItem(title,value){contextMenu.defaultSection().appendCheckboxItem(title,uaSetting.set.bind(uaSetting,value),uaSetting.get()===value);}} -_appendOptionsMenuItems(contextMenu){var model=this._model;appendToggleItem(contextMenu.headerSection(),this._deviceOutlineSetting,Common.UIString('Hide device frame'),Common.UIString('Show device frame'),model.type()!==Emulation.DeviceModeModel.Type.Device);appendToggleItem(contextMenu.headerSection(),this._showMediaInspectorSetting,Common.UIString('Hide media queries'),Common.UIString('Show media queries'));appendToggleItem(contextMenu.headerSection(),this._showRulersSetting,Common.UIString('Hide rulers'),Common.UIString('Show rulers'));appendToggleItem(contextMenu.defaultSection(),this._showDeviceScaleFactorSetting,Common.UIString('Remove device pixel ratio'),Common.UIString('Add device pixel ratio'));appendToggleItem(contextMenu.defaultSection(),this._showUserAgentTypeSetting,Common.UIString('Remove device type'),Common.UIString('Add device type'));contextMenu.appendItemsAtLocation('deviceModeMenu');contextMenu.footerSection().appendItem(Common.UIString('Reset to defaults'),this._reset.bind(this));function appendToggleItem(section,setting,title1,title2,disabled){if(typeof disabled==='undefined') -disabled=model.type()===Emulation.DeviceModeModel.Type.None;section.appendItem(setting.get()?title1:title2,setting.set.bind(setting,!setting.get()),disabled);}} -_reset(){this._deviceOutlineSetting.set(false);this._showDeviceScaleFactorSetting.set(false);this._showUserAgentTypeSetting.set(false);this._showMediaInspectorSetting.set(false);this._showRulersSetting.set(false);this._model.reset();} -_wrapToolbarItem(element){var container=createElement('div');var shadowRoot=UI.createShadowRootWithCoreStyles(container,'emulation/deviceModeToolbar.css');shadowRoot.appendChild(element);return new UI.ToolbarItem(container);} -_emulateDevice(device){this._model.emulate(Emulation.DeviceModeModel.Type.Device,device,this._lastMode.get(device)||device.modes[0],this._lastScale.get(device));} -_switchToResponsive(){this._model.emulate(Emulation.DeviceModeModel.Type.Responsive,null,null);} -_filterDevices(devices){devices=devices.filter(function(d){return d.show();});devices.sort(Emulation.EmulatedDevice.deviceComparator);return devices;} -_standardDevices(){return this._filterDevices(this._emulatedDevicesList.standard());} -_customDevices(){return this._filterDevices(this._emulatedDevicesList.custom());} -_allDevices(){return this._standardDevices().concat(this._customDevices());} -_appendDeviceMenuItems(contextMenu){contextMenu.headerSection().appendCheckboxItem(Common.UIString('Responsive'),this._switchToResponsive.bind(this),this._model.type()===Emulation.DeviceModeModel.Type.Responsive,false);appendGroup.call(this,this._standardDevices());appendGroup.call(this,this._customDevices());contextMenu.footerSection().appendItem(Common.UIString('Edit\u2026'),this._emulatedDevicesList.revealCustomSetting.bind(this._emulatedDevicesList),false);function appendGroup(devices){if(!devices.length) -return;var section=contextMenu.section();for(var device of devices){section.appendCheckboxItem(device.title,this._emulateDevice.bind(this,device),this._model.device()===device,false);}}} -_deviceListChanged(){var device=this._model.device();if(!device) -return;var devices=this._allDevices();if(devices.indexOf(device)===-1){if(devices.length) -this._emulateDevice(devices[0]);else -this._model.emulate(Emulation.DeviceModeModel.Type.Responsive,null,null);}} -_updateDeviceScaleFactorVisibility(){this._deviceScaleItem.setVisible(this._showDeviceScaleFactorSetting.get());} -_updateUserAgentTypeVisibility(){this._uaItem.setVisible(this._showUserAgentTypeSetting.get());} -_modeMenuClicked(event){var device=this._model.device();var model=this._model;if(device.modes.length===2&&device.modes[0].orientation!==device.modes[1].orientation){model.emulate(model.type(),model.device(),model.mode()===device.modes[0]?device.modes[1]:device.modes[0]);return;} -var contextMenu=new UI.ContextMenu((event.data),false,this._modeButton.element.totalOffsetLeft(),this._modeButton.element.totalOffsetTop()+this._modeButton.element.offsetHeight);addOrientation(Emulation.EmulatedDevice.Vertical,Common.UIString('Portrait'));addOrientation(Emulation.EmulatedDevice.Horizontal,Common.UIString('Landscape'));contextMenu.show();function addOrientation(orientation,title){var modes=device.modesForOrientation(orientation);if(!modes.length) -return;if(modes.length===1){addMode(modes[0],title);}else{for(var index=0;index<modes.length;index++) -addMode(modes[index],title+' \u2013 '+modes[index].title);}} -function addMode(mode,title){contextMenu.defaultSection().appendCheckboxItem(title,applyMode.bind(null,mode),model.mode()===mode,false);} -function applyMode(mode){model.emulate(model.type(),model.device(),mode);}} -element(){return this._element;} -update(){if(this._model.type()!==this._cachedModelType){this._cachedModelType=this._model.type();this._widthInput.disabled=this._model.type()!==Emulation.DeviceModeModel.Type.Responsive;this._heightInput.disabled=this._model.type()!==Emulation.DeviceModeModel.Type.Responsive;this._deviceScaleItem.setEnabled(this._model.type()===Emulation.DeviceModeModel.Type.Responsive);this._uaItem.setEnabled(this._model.type()===Emulation.DeviceModeModel.Type.Responsive);} -var size=this._model.appliedDeviceSize();this._updateHeightInput(this._model.type()===Emulation.DeviceModeModel.Type.Responsive&&this._model.isFullHeight()?'':String(size.height));this._updateWidthInput(String(size.width));this._heightInput.placeholder=size.height;if(this._model.scale()!==this._cachedScale){this._scaleItem.setText(Common.UIString('%.0f%%',this._model.scale()*100));this._cachedScale=this._model.scale();} -var deviceScale=this._model.appliedDeviceScaleFactor();if(deviceScale!==this._cachedDeviceScale){this._deviceScaleItem.setText(Common.UIString('DPR: %.1f',deviceScale));this._cachedDeviceScale=deviceScale;} -var uaType=this._model.appliedUserAgentType();if(uaType!==this._cachedUaType){this._uaItem.setText(uaType);this._cachedUaType=uaType;} -var deviceItemTitle=Common.UIString('None');if(this._model.type()===Emulation.DeviceModeModel.Type.Responsive) -deviceItemTitle=Common.UIString('Responsive');if(this._model.type()===Emulation.DeviceModeModel.Type.Device) -deviceItemTitle=this._model.device().title;this._deviceSelectItem.setText(deviceItemTitle);if(this._model.device()!==this._cachedModelDevice){var device=this._model.device();this._modeButton.setVisible(!!device);if(device){var modeCount=device?device.modes.length:0;this._modeButton.setEnabled(modeCount>=2);this._modeButton.setTitle(modeCount===2?Common.UIString('Rotate'):Common.UIString('Screen options'));} -this._cachedModelDevice=device;} -if(this._model.type()===Emulation.DeviceModeModel.Type.Device){this._lastMode.set((this._model.device()),(this._model.mode()));} -if(this._model.mode()!==this._cachedModelMode&&this._model.type()!==Emulation.DeviceModeModel.Type.None){this._cachedModelMode=this._model.mode();var value=this._persistenceSetting.get();if(this._model.device()){value.device=this._model.device().title;value.orientation=this._model.mode()?this._model.mode().orientation:'';value.mode=this._model.mode()?this._model.mode().title:'';}else{value.device='';value.orientation='';value.mode='';} -this._persistenceSetting.set(value);}} -restore(){for(var device of this._allDevices()){if(device.title===this._persistenceSetting.get().device){for(var mode of device.modes){if(mode.orientation===this._persistenceSetting.get().orientation&&mode.title===this._persistenceSetting.get().mode){this._lastMode.set(device,mode);this._emulateDevice(device);return;}}}} -this._model.emulate(Emulation.DeviceModeModel.Type.Responsive,null,null);}};;Emulation.DeviceModeView=class extends UI.VBox{constructor(){super(true);this.setMinimumSize(150,150);this.element.classList.add('device-mode-view');this.registerRequiredCSS('emulation/deviceModeView.css');UI.Tooltip.addNativeOverrideContainer(this.contentElement);this._model=self.singleton(Emulation.DeviceModeModel);this._model.addEventListener(Emulation.DeviceModeModel.Events.Updated,this._updateUI,this);this._mediaInspector=new Emulation.MediaQueryInspector(()=>this._model.appliedDeviceSize().width,this._model.setWidth.bind(this._model));this._showMediaInspectorSetting=Common.settings.moduleSetting('showMediaQueryInspector');this._showMediaInspectorSetting.addChangeListener(this._updateUI,this);this._showRulersSetting=Common.settings.moduleSetting('emulation.showRulers');this._showRulersSetting.addChangeListener(this._updateUI,this);this._topRuler=new Emulation.DeviceModeView.Ruler(true,this._model.setWidthAndScaleToFit.bind(this._model));this._topRuler.element.classList.add('device-mode-ruler-top');this._leftRuler=new Emulation.DeviceModeView.Ruler(false,this._model.setHeightAndScaleToFit.bind(this._model));this._leftRuler.element.classList.add('device-mode-ruler-left');this._createUI();UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._zoomChanged,this);} -_createUI(){this._toolbar=new Emulation.DeviceModeToolbar(this._model,this._showMediaInspectorSetting,this._showRulersSetting);this.contentElement.appendChild(this._toolbar.element());this._contentClip=this.contentElement.createChild('div','device-mode-content-clip vbox');this._responsivePresetsContainer=this._contentClip.createChild('div','device-mode-presets-container');this._populatePresetsContainer();this._mediaInspectorContainer=this._contentClip.createChild('div','device-mode-media-container');this._contentArea=this._contentClip.createChild('div','device-mode-content-area');this._outlineImage=this._contentArea.createChild('img','device-mode-outline-image hidden fill');this._outlineImage.addEventListener('load',this._onImageLoaded.bind(this,this._outlineImage,true),false);this._outlineImage.addEventListener('error',this._onImageLoaded.bind(this,this._outlineImage,false),false);this._screenArea=this._contentArea.createChild('div','device-mode-screen-area');this._screenImage=this._screenArea.createChild('img','device-mode-screen-image hidden');this._screenImage.addEventListener('load',this._onImageLoaded.bind(this,this._screenImage,true),false);this._screenImage.addEventListener('error',this._onImageLoaded.bind(this,this._screenImage,false),false);this._bottomRightResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-bottom-right-resizer');this._bottomRightResizerElement.createChild('div','');this._createResizer(this._bottomRightResizerElement,2,1);this._bottomLeftResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-bottom-left-resizer');this._bottomLeftResizerElement.createChild('div','');this._createResizer(this._bottomLeftResizerElement,-2,1);this._rightResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-right-resizer');this._rightResizerElement.createChild('div','');this._createResizer(this._rightResizerElement,2,0);this._leftResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-left-resizer');this._leftResizerElement.createChild('div','');this._createResizer(this._leftResizerElement,-2,0);this._bottomResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-bottom-resizer');this._bottomResizerElement.createChild('div','');this._createResizer(this._bottomResizerElement,0,1);this._bottomResizerElement.addEventListener('dblclick',this._model.setHeight.bind(this._model,0),false);this._bottomResizerElement.title=Common.UIString('Double-click for full height');this._pageArea=this._screenArea.createChild('div','device-mode-page-area');this._pageArea.createChild('content');} -_populatePresetsContainer(){var sizes=[320,375,425,768,1024,1440,2560];var titles=[Common.UIString('Mobile S'),Common.UIString('Mobile M'),Common.UIString('Mobile L'),Common.UIString('Tablet'),Common.UIString('Laptop'),Common.UIString('Laptop L'),Common.UIString('4K')];this._presetBlocks=[];var inner=this._responsivePresetsContainer.createChild('div','device-mode-presets-container-inner');for(var i=sizes.length-1;i>=0;--i){var outer=inner.createChild('div','fill device-mode-preset-bar-outer');var block=outer.createChild('div','device-mode-preset-bar');block.createChild('span').textContent=titles[i]+' \u2013 '+sizes[i]+'px';block.addEventListener('click',applySize.bind(this,sizes[i]),false);block.__width=sizes[i];this._presetBlocks.push(block);} -function applySize(width,e){this._model.emulate(Emulation.DeviceModeModel.Type.Responsive,null,null);this._model.setSizeAndScaleToFit(width,0);e.consume();}} -_createResizer(element,widthFactor,heightFactor){var resizer=new UI.ResizerWidget();resizer.addElement(element);var cursor=widthFactor?'ew-resize':'ns-resize';if(widthFactor*heightFactor>0) -cursor='nwse-resize';if(widthFactor*heightFactor<0) -cursor='nesw-resize';resizer.setCursor(cursor);resizer.addEventListener(UI.ResizerWidget.Events.ResizeStart,this._onResizeStart,this);resizer.addEventListener(UI.ResizerWidget.Events.ResizeUpdate,this._onResizeUpdate.bind(this,widthFactor,heightFactor));resizer.addEventListener(UI.ResizerWidget.Events.ResizeEnd,this._onResizeEnd,this);return resizer;} -_onResizeStart(event){this._slowPositionStart=null;this._resizeStart=this._model.screenRect().size();} -_onResizeUpdate(widthFactor,heightFactor,event){if(event.data.shiftKey!==!!this._slowPositionStart) -this._slowPositionStart=event.data.shiftKey?{x:event.data.currentX,y:event.data.currentY}:null;var cssOffsetX=event.data.currentX-event.data.startX;var cssOffsetY=event.data.currentY-event.data.startY;if(this._slowPositionStart){cssOffsetX=(event.data.currentX-this._slowPositionStart.x)/10+this._slowPositionStart.x-event.data.startX;cssOffsetY=(event.data.currentY-this._slowPositionStart.y)/10+this._slowPositionStart.y-event.data.startY;} -if(widthFactor){var dipOffsetX=cssOffsetX*UI.zoomManager.zoomFactor();var newWidth=this._resizeStart.width+dipOffsetX*widthFactor;newWidth=Math.round(newWidth/this._model.scale());if(newWidth>=Emulation.DeviceModeModel.MinDeviceSize&&newWidth<=Emulation.DeviceModeModel.MaxDeviceSize) -this._model.setWidth(newWidth);} -if(heightFactor){var dipOffsetY=cssOffsetY*UI.zoomManager.zoomFactor();var newHeight=this._resizeStart.height+dipOffsetY*heightFactor;newHeight=Math.round(newHeight/this._model.scale());if(newHeight>=Emulation.DeviceModeModel.MinDeviceSize&&newHeight<=Emulation.DeviceModeModel.MaxDeviceSize) -this._model.setHeight(newHeight);}} -_onResizeEnd(event){delete this._resizeStart;Host.userMetrics.actionTaken(Host.UserMetrics.Action.ResizedViewInResponsiveMode);} -_updateUI(){function applyRect(element,rect){element.style.left=rect.left+'px';element.style.top=rect.top+'px';element.style.width=rect.width+'px';element.style.height=rect.height+'px';} -if(!this.isShowing()) -return;var zoomFactor=UI.zoomManager.zoomFactor();var callDoResize=false;var showRulers=this._showRulersSetting.get()&&this._model.type()!==Emulation.DeviceModeModel.Type.None;var contentAreaResized=false;var updateRulers=false;var cssScreenRect=this._model.screenRect().scale(1/zoomFactor);if(!cssScreenRect.isEqual(this._cachedCssScreenRect)){applyRect(this._screenArea,cssScreenRect);updateRulers=true;callDoResize=true;this._cachedCssScreenRect=cssScreenRect;} -var cssVisiblePageRect=this._model.visiblePageRect().scale(1/zoomFactor);if(!cssVisiblePageRect.isEqual(this._cachedCssVisiblePageRect)){applyRect(this._pageArea,cssVisiblePageRect);callDoResize=true;this._cachedCssVisiblePageRect=cssVisiblePageRect;} -var outlineRect=this._model.outlineRect().scale(1/zoomFactor);if(!outlineRect.isEqual(this._cachedOutlineRect)){applyRect(this._outlineImage,outlineRect);callDoResize=true;this._cachedOutlineRect=outlineRect;} -this._contentClip.classList.toggle('device-mode-outline-visible',!!this._model.outlineImage());var resizable=this._model.type()===Emulation.DeviceModeModel.Type.Responsive;if(resizable!==this._cachedResizable){this._rightResizerElement.classList.toggle('hidden',!resizable);this._leftResizerElement.classList.toggle('hidden',!resizable);this._bottomResizerElement.classList.toggle('hidden',!resizable);this._bottomRightResizerElement.classList.toggle('hidden',!resizable);this._bottomLeftResizerElement.classList.toggle('hidden',!resizable);this._cachedResizable=resizable;} -var mediaInspectorVisible=this._showMediaInspectorSetting.get()&&this._model.type()!==Emulation.DeviceModeModel.Type.None;if(mediaInspectorVisible!==this._cachedMediaInspectorVisible){if(mediaInspectorVisible) -this._mediaInspector.show(this._mediaInspectorContainer);else -this._mediaInspector.detach();contentAreaResized=true;callDoResize=true;this._cachedMediaInspectorVisible=mediaInspectorVisible;} -if(showRulers!==this._cachedShowRulers){this._contentClip.classList.toggle('device-mode-rulers-visible',showRulers);if(showRulers){this._topRuler.show(this._contentArea);this._leftRuler.show(this._contentArea);}else{this._topRuler.detach();this._leftRuler.detach();} -contentAreaResized=true;callDoResize=true;this._cachedShowRulers=showRulers;} -if(this._model.scale()!==this._cachedScale){updateRulers=true;callDoResize=true;for(var block of this._presetBlocks) -block.style.width=block.__width*this._model.scale()+'px';this._cachedScale=this._model.scale();} -this._toolbar.update();this._loadImage(this._screenImage,this._model.screenImage());this._loadImage(this._outlineImage,this._model.outlineImage());this._mediaInspector.setAxisTransform(this._model.scale());if(callDoResize) -this.doResize();if(updateRulers){this._topRuler.render(this._model.scale());this._leftRuler.render(this._model.scale());this._topRuler.element.positionAt(this._cachedCssScreenRect?this._cachedCssScreenRect.left:0,this._cachedCssScreenRect?this._cachedCssScreenRect.top:0);this._leftRuler.element.positionAt(this._cachedCssScreenRect?this._cachedCssScreenRect.left:0,this._cachedCssScreenRect?this._cachedCssScreenRect.top:0);} -if(contentAreaResized) -this._contentAreaResized();} -_loadImage(element,srcset){if(element.getAttribute('srcset')===srcset) -return;element.setAttribute('srcset',srcset);if(!srcset) -element.classList.toggle('hidden',true);} -_onImageLoaded(element,success){element.classList.toggle('hidden',!success);} -setNonEmulatedAvailableSize(element){if(this._model.type()!==Emulation.DeviceModeModel.Type.None) -return;var zoomFactor=UI.zoomManager.zoomFactor();var rect=element.getBoundingClientRect();var availableSize=new UI.Size(Math.max(rect.width*zoomFactor,1),Math.max(rect.height*zoomFactor,1));this._model.setAvailableSize(availableSize,availableSize);} -_contentAreaResized(){var zoomFactor=UI.zoomManager.zoomFactor();var rect=this._contentArea.getBoundingClientRect();var availableSize=new UI.Size(Math.max(rect.width*zoomFactor,1),Math.max(rect.height*zoomFactor,1));var preferredSize=new UI.Size(Math.max((rect.width-2*this._handleWidth)*zoomFactor,1),Math.max((rect.height-this._handleHeight)*zoomFactor,1));this._model.setAvailableSize(availableSize,preferredSize);} -_measureHandles(){var hidden=this._rightResizerElement.classList.contains('hidden');this._rightResizerElement.classList.toggle('hidden',false);this._bottomResizerElement.classList.toggle('hidden',false);this._handleWidth=this._rightResizerElement.offsetWidth;this._handleHeight=this._bottomResizerElement.offsetHeight;this._rightResizerElement.classList.toggle('hidden',hidden);this._bottomResizerElement.classList.toggle('hidden',hidden);} -_zoomChanged(){delete this._handleWidth;delete this._handleHeight;if(this.isShowing()){this._measureHandles();this._contentAreaResized();}} -onResize(){if(this.isShowing()) -this._contentAreaResized();} -wasShown(){this._measureHandles();this._toolbar.restore();} -willHide(){this._model.emulate(Emulation.DeviceModeModel.Type.None,null,null);} -async captureScreenshot(){SDK.OverlayModel.muteHighlight();var screenshot=await this._model.captureScreenshot(false);SDK.OverlayModel.unmuteHighlight();if(screenshot===null) -return;var pageImage=new Image();pageImage.src='data:image/png;base64,'+screenshot;pageImage.onload=async()=>{var scale=pageImage.naturalWidth/this._model.screenRect().width;var outlineRect=this._model.outlineRect().scale(scale);var screenRect=this._model.screenRect().scale(scale);var visiblePageRect=this._model.visiblePageRect().scale(scale);var contentLeft=screenRect.left+visiblePageRect.left-outlineRect.left;var contentTop=screenRect.top+visiblePageRect.top-outlineRect.top;var canvas=createElement('canvas');canvas.width=Math.floor(outlineRect.width);canvas.height=Math.floor(outlineRect.height);var ctx=canvas.getContext('2d');ctx.imageSmoothingEnabled=false;if(this._model.outlineImage()) -await this._paintImage(ctx,this._model.outlineImage(),outlineRect.relativeTo(outlineRect));if(this._model.screenImage()) -await this._paintImage(ctx,this._model.screenImage(),screenRect.relativeTo(outlineRect));ctx.drawImage(pageImage,Math.floor(contentLeft),Math.floor(contentTop));this._saveScreenshot(canvas);};} -async captureFullSizeScreenshot(){SDK.OverlayModel.muteHighlight();var screenshot=await this._model.captureScreenshot(true);SDK.OverlayModel.unmuteHighlight();if(screenshot===null) -return;return this._saveScreenshotBase64(screenshot);} -async captureAreaScreenshot(clip){SDK.OverlayModel.muteHighlight();var screenshot=await this._model.captureScreenshot(false,clip);SDK.OverlayModel.unmuteHighlight();if(screenshot===null) -return;return this._saveScreenshotBase64(screenshot);} -_saveScreenshotBase64(screenshot){var pageImage=new Image();pageImage.src='data:image/png;base64,'+screenshot;pageImage.onload=()=>{var canvas=createElement('canvas');canvas.width=pageImage.naturalWidth;canvas.height=pageImage.naturalHeight;var ctx=canvas.getContext('2d');ctx.imageSmoothingEnabled=false;ctx.drawImage(pageImage,0,0);this._saveScreenshot(canvas);};} -_paintImage(ctx,src,rect){return new Promise(fulfill=>{var image=new Image();image.crossOrigin='Anonymous';image.srcset=src;image.onerror=fulfill;image.onload=()=>{ctx.drawImage(image,rect.left,rect.top,rect.width,rect.height);fulfill();};});} -_saveScreenshot(canvas){var url=this._model.inspectedURL();var fileName=url?url.trimURL().removeURLFragment():'';if(this._model.type()===Emulation.DeviceModeModel.Type.Device) -fileName+=Common.UIString('(%s)',this._model.device().title);var link=createElement('a');link.download=fileName+'.png';canvas.toBlob(blob=>{link.href=URL.createObjectURL(blob);link.click();});}};Emulation.DeviceModeView.Ruler=class extends UI.VBox{constructor(horizontal,applyCallback){super();this.element.classList.add('device-mode-ruler');this._contentElement=this.element.createChild('div','device-mode-ruler-content').createChild('div','device-mode-ruler-inner');this._horizontal=horizontal;this._scale=1;this._count=0;this._throttler=new Common.Throttler(0);this._applyCallback=applyCallback;} -render(scale){this._scale=scale;this._throttler.schedule(this._update.bind(this));} -onResize(){this._throttler.schedule(this._update.bind(this));} -_update(){var zoomFactor=UI.zoomManager.zoomFactor();var size=this._horizontal?this._contentElement.offsetWidth:this._contentElement.offsetHeight;if(this._scale!==this._renderedScale||zoomFactor!==this._renderedZoomFactor){this._contentElement.removeChildren();this._count=0;this._renderedScale=this._scale;this._renderedZoomFactor=zoomFactor;} -var dipSize=size*zoomFactor/this._scale;var count=Math.ceil(dipSize/5);var step=1;if(this._scale<0.8) -step=2;if(this._scale<0.6) -step=4;if(this._scale<0.4) -step=8;if(this._scale<0.2) -step=16;if(this._scale<0.1) -step=32;for(var i=count;i<this._count;i++){if(!(i%step)) -this._contentElement.lastChild.remove();} -for(var i=this._count;i<count;i++){if(i%step) -continue;var marker=this._contentElement.createChild('div','device-mode-ruler-marker');if(i){if(this._horizontal) -marker.style.left=(5*i)*this._scale/zoomFactor+'px';else -marker.style.top=(5*i)*this._scale/zoomFactor+'px';if(!(i%20)){var text=marker.createChild('div','device-mode-ruler-text');text.textContent=i*5;text.addEventListener('click',this._onMarkerClick.bind(this,i*5),false);}} -if(!(i%10)) -marker.classList.add('device-mode-ruler-marker-large');else if(!(i%5)) -marker.classList.add('device-mode-ruler-marker-medium');} -this._count=count;return Promise.resolve();} -_onMarkerClick(size){this._applyCallback.call(null,size);}};;Emulation.DeviceModeWrapper=class extends UI.VBox{constructor(inspectedPagePlaceholder){super();Emulation.DeviceModeView._wrapperInstance=this;this._inspectedPagePlaceholder=inspectedPagePlaceholder;this._deviceModeView=null;this._toggleDeviceModeAction=UI.actionRegistry.action('emulation.toggle-device-mode');var model=self.singleton(Emulation.DeviceModeModel);this._showDeviceModeSetting=model.enabledSetting();this._showDeviceModeSetting.setRequiresUserAction(!!Runtime.queryParam('hasOtherClients'));this._showDeviceModeSetting.addChangeListener(this._update.bind(this,false));SDK.targetManager.addModelListener(SDK.OverlayModel,SDK.OverlayModel.Events.ScreenshotRequested,this._screenshotRequestedFromOverlay,this);this._update(true);} -_toggleDeviceMode(){this._showDeviceModeSetting.set(!this._showDeviceModeSetting.get());} -_captureScreenshot(fullSize,clip){if(!this._deviceModeView) -this._deviceModeView=new Emulation.DeviceModeView();this._deviceModeView.setNonEmulatedAvailableSize(this._inspectedPagePlaceholder.element);if(fullSize) -this._deviceModeView.captureFullSizeScreenshot();else if(clip) -this._deviceModeView.captureAreaScreenshot(clip);else -this._deviceModeView.captureScreenshot();return true;} -_screenshotRequestedFromOverlay(event){var clip=(event.data);this._captureScreenshot(false,clip);} -_update(force){this._toggleDeviceModeAction.setToggled(this._showDeviceModeSetting.get());if(!force){var showing=this._deviceModeView&&this._deviceModeView.isShowing();if(this._showDeviceModeSetting.get()===showing) -return;} -if(this._showDeviceModeSetting.get()){if(!this._deviceModeView) -this._deviceModeView=new Emulation.DeviceModeView();this._deviceModeView.show(this.element);this._inspectedPagePlaceholder.clearMinimumSize();this._inspectedPagePlaceholder.show(this._deviceModeView.element);}else{if(this._deviceModeView) -this._deviceModeView.detach();this._inspectedPagePlaceholder.restoreMinimumSize();this._inspectedPagePlaceholder.show(this.element);}}};Emulation.DeviceModeView._wrapperInstance;Emulation.DeviceModeWrapper.ActionDelegate=class{handleAction(context,actionId){if(Emulation.DeviceModeView._wrapperInstance){switch(actionId){case'emulation.capture-screenshot':return Emulation.DeviceModeView._wrapperInstance._captureScreenshot();case'emulation.capture-node-screenshot':{var node=UI.context.flavor(SDK.DOMNode);if(!node) -return true;async function captureClip(){var object=await node.resolveToObject();var result=await object.callFunctionPromise(function(){var rect=this.getBoundingClientRect();var docRect=this.ownerDocument.documentElement.getBoundingClientRect();return JSON.stringify({x:rect.left-docRect.left,y:rect.top-docRect.top,width:rect.width,height:rect.height,scale:1});});var clip=(JSON.parse(result.object.value));Emulation.DeviceModeView._wrapperInstance._captureScreenshot(false,clip);} -captureClip();return true;} -case'emulation.capture-full-height-screenshot':return Emulation.DeviceModeView._wrapperInstance._captureScreenshot(true);case'emulation.toggle-device-mode':Emulation.DeviceModeView._wrapperInstance._toggleDeviceMode();return true;}} -return false;}};;self['ProductRegistry']=self['ProductRegistry']||{};ProductRegistry.BadgePool=class{constructor(forceShow){this._showTitles=false;this._badgeElements=new Map();if(!forceShow){this._setting=Common.settings.moduleSetting('product_registry.badges-visible');this._setting.addChangeListener(this._settingUpdated.bind(this));}} -setShowTitles(value){this._showTitles=value;} -badgeForFrame(frame){return this._badgeForFrameOrUrl(this._resolveUrl.bind(this,frame));} -badgeForURL(parsedUrl){return this._badgeForFrameOrUrl(()=>Promise.resolve(parsedUrl));} -reset(){this._badgeElements.clear();} -_badgeForFrameOrUrl(urlResolver){var element=createElementWithClass('span','hidden');var root=UI.createShadowRootWithCoreStyles(element,'product_registry/badge.css');var badgeElement=root.createChild('span');badgeElement.classList.toggle('hide-badge-title',!this._showTitles);badgeElement.addEventListener('mousedown',event=>event.consume());badgeElement.addEventListener('click',event=>{this._showPopup(badgeElement);event.consume();},false);this._badgeElements.set(badgeElement,urlResolver);this._renderBadge(badgeElement);return element;} -async _resolveUrl(frame){var registry=await ProductRegistry.instance();var parsedUrl=new Common.ParsedURL(frame.url);var entry=registry.entryForUrl(parsedUrl);if(!entry){frame.findCreationCallFrame(callFrame=>{if(!callFrame.url) -return false;parsedUrl=new Common.ParsedURL(callFrame.url);return!!registry.entryForUrl(parsedUrl);});} -return parsedUrl;} -async _renderBadge(badgeElement){if(badgeElement.children.length||!this._isVisible(badgeElement)){this._updateBadgeElementVisibility(badgeElement);return;} -var parsedUrl=await this._badgeElements.get(badgeElement)();var registry=await ProductRegistry.instance();var entryName=parsedUrl&®istry.nameForUrl(parsedUrl);if(!entryName) -return;var tokens=entryName.replace(/[a-z]*/g,'').split(' ');var label;if(tokens.length>1) -label=tokens[0][0]+tokens[1][0];else -label=entryName;var iconElement=badgeElement.createChild('span','product-registry-badge monospace');iconElement.setAttribute('data-initial',label.substring(0,2).toUpperCase());iconElement.title=entryName;iconElement.style.backgroundColor=ProductRegistry.BadgePool.colorForEntryName(entryName);badgeElement.createChild('span','product-registry-badge-title').textContent=entryName;this._updateBadgeElementVisibility(badgeElement);} -_settingUpdated(){for(var badgeElement of this._badgeElements.keys()) -this._renderBadge(badgeElement);} -_isVisible(badgeElement){return!this._setting||this._setting.get();} -_updateBadgeElementVisibility(badgeElement){badgeElement.parentNodeOrShadowHost().parentNodeOrShadowHost().classList.toggle('hidden',!this._isVisible(badgeElement));} -async _showPopup(badgeElement){if(!this._badgeElements.has(badgeElement)) -return;var registry=await ProductRegistry.instance();var parsedUrl=await this._badgeElements.get(badgeElement)();var entryName=registry.nameForUrl(parsedUrl);var element=createElement('div');var root=UI.createShadowRootWithCoreStyles(element,'product_registry/popup.css');var popupElement=root.createChild('div','product-registry-popup');var domainElement=popupElement.createChild('div','product-registry-domain');domainElement.textContent=parsedUrl.domain();var entryNameElement=popupElement.createChild('div','product-registry-name');entryNameElement.textContent=entryName;var reportLink='https://docs.google.com/forms/d/e/1FAIpQLSchz2FdcQ-rRllzl8BbhWaTRRY-12BpPjW6Hr9e1-BpCA083w/viewform'+'?entry_1425918171='+encodeURIComponent((parsedUrl.domain()+parsedUrl.path).substr(0,100));popupElement.appendChild(UI.createExternalLink(reportLink,'Report mismatch','product-registry-link'));var dialog=new UI.Dialog();dialog.setContentAnchorBox(badgeElement.boxInWindow());dialog.contentElement.appendChild(element);dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferTop);dialog.addCloseButton();dialog.show((badgeElement.ownerDocument));} -static colorForEntryName(entryName){if(!ProductRegistry.BadgePool._colorGenerator){ProductRegistry.BadgePool._colorGenerator=new Common.Color.Generator({min:30,max:330},{min:50,max:80,count:3},80);} -return ProductRegistry.BadgePool._colorGenerator.colorForID(entryName);}};;ProductRegistry.instance=function(){var extension=self.runtime.extension(ProductRegistry.Registry);if(extension) -return extension.instance();return Promise.resolve(self.singleton(ProductRegistry.RegistryStub));};ProductRegistry.Registry=function(){};ProductRegistry.Registry.prototype={nameForUrl:function(parsedUrl){},entryForUrl:function(parsedUrl){},typeForUrl:function(parsedUrl){}};ProductRegistry.RegistryStub=class{nameForUrl(parsedUrl){return null;} -entryForUrl(parsedUrl){return null;} -typeForUrl(parsedUrl){return null;}};ProductRegistry.Registry.ProductEntry;;self['ConsoleCounters']=self['ConsoleCounters']||{};ConsoleCounters.WarningErrorCounter=class{constructor(){ConsoleCounters.WarningErrorCounter._instanceForTest=this;this._counter=createElement('div');this._counter.addEventListener('click',Common.console.show.bind(Common.console),false);this._toolbarItem=new UI.ToolbarItem(this._counter);var shadowRoot=UI.createShadowRootWithCoreStyles(this._counter,'console_counters/errorWarningCounter.css');this._errors=this._createItem(shadowRoot,'smallicon-error');this._warnings=this._createItem(shadowRoot,'smallicon-warning');this._titles=[];this._errorCount=-1;this._warningCount=-1;this._throttler=new Common.Throttler(100);ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.ConsoleCleared,this._update,this);ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.MessageAdded,this._update,this);ConsoleModel.consoleModel.addEventListener(ConsoleModel.ConsoleModel.Events.MessageUpdated,this._update,this);this._update();} -_updatedForTest(){} -_createItem(shadowRoot,iconType){var item=createElementWithClass('span','counter-item');var icon=item.createChild('label','','dt-icon-label');icon.type=iconType;var text=icon.createChild('span');shadowRoot.appendChild(item);return{item:item,text:text};} -_updateItem(item,count,first,title){item.item.classList.toggle('hidden',!count);item.item.classList.toggle('counter-item-first',first);item.text.textContent=count;if(count) -this._titles.push(title);} -_update(){this._updatingForTest=true;this._throttler.schedule(this._updateThrottled.bind(this));} -_updateThrottled(){var errors=ConsoleModel.consoleModel.errors();var warnings=ConsoleModel.consoleModel.warnings();if(errors===this._errorCount&&warnings===this._warningCount) -return Promise.resolve();this._errorCount=errors;this._warningCount=warnings;this._titles=[];this._toolbarItem.setVisible(!!(errors||warnings));this._updateItem(this._errors,errors,false,Common.UIString(errors===1?'%d error':'%d errors',errors));this._updateItem(this._warnings,warnings,!errors,Common.UIString(warnings===1?'%d warning':'%d warnings',warnings));this._counter.title=this._titles.join(', ');UI.inspectorView.toolbarItemResized();this._updatingForTest=false;this._updatedForTest();return Promise.resolve();} -item(){return this._toolbarItem;}};;self['Main']=self['Main']||{};Main.RenderingOptionsView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('main/renderingOptions.css');this._appendCheckbox(Common.UIString('Paint flashing'),Common.UIString('Highlights areas of the page (green) that need to be repainted'),Common.moduleSetting('showPaintRects'));this._appendCheckbox(Common.UIString('Layer borders'),Common.UIString('Shows layer borders (orange/olive) and tiles (cyan)'),Common.moduleSetting('showDebugBorders'));this._appendCheckbox(Common.UIString('FPS meter'),Common.UIString('Plots frames per second, frame rate distribution, and GPU memory'),Common.moduleSetting('showFPSCounter'));this._appendCheckbox(Common.UIString('Scrolling performance issues'),Common.UIString('Highlights elements (teal) that can slow down scrolling, including touch & wheel event handlers and other main-thread scrolling situations.'),Common.moduleSetting('showScrollBottleneckRects'));this.contentElement.createChild('div').classList.add('panel-section-separator');var mediaSetting=Common.moduleSetting('emulatedCSSMedia');var mediaSelect=UI.SettingsUI.createControlForSetting(mediaSetting);if(mediaSelect){var mediaRow=this.contentElement.createChild('span','media-row');mediaRow.createChild('label').textContent=Common.UIString('Emulate CSS media');mediaRow.createChild('p').textContent=Common.UIString('Forces media type for testing print and screen styles');mediaRow.appendChild(mediaSelect);}} -_appendCheckbox(label,subtitle,setting){var checkboxLabel=UI.CheckboxLabel.create(label,false,subtitle);UI.SettingsUI.bindCheckbox(checkboxLabel.checkboxElement,setting);this.contentElement.appendChild(checkboxLabel);}};;Main.SimpleApp=class{presentUI(document){var rootView=new UI.RootView();UI.inspectorView.show(rootView.element);rootView.attachToDocument(document);rootView.focus();}};Main.SimpleAppProvider=class{createApp(){return new Main.SimpleApp();}};;Main.GCActionDelegate=class{handleAction(context,actionId){for(var heapProfilerModel of SDK.targetManager.models(SDK.HeapProfilerModel)) -heapProfilerModel.collectGarbage();return true;}};;Main.RequestAppBannerActionDelegate=class{handleAction(context,actionId){var target=SDK.targetManager.mainTarget();if(target&&target.hasBrowserCapability()){target.pageAgent().requestAppBanner();Common.console.show();} -return true;}};;Main.ExecutionContextSelector=class{constructor(targetManager,context){targetManager.observeTargets(this,SDK.Target.Capability.JS);context.addFlavorChangeListener(SDK.ExecutionContext,this._executionContextChanged,this);context.addFlavorChangeListener(SDK.Target,this._targetChanged,this);targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextCreated,this._onExecutionContextCreated,this);targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextDestroyed,this._onExecutionContextDestroyed,this);targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextOrderChanged,this._onExecutionContextOrderChanged,this);this._targetManager=targetManager;this._context=context;} -targetAdded(target){setImmediate(deferred.bind(this));function deferred(){if(!this._context.flavor(SDK.Target)) -this._context.setFlavor(SDK.Target,target);}} -targetRemoved(target){var currentExecutionContext=this._context.flavor(SDK.ExecutionContext);if(currentExecutionContext&¤tExecutionContext.target()===target) -this._currentExecutionContextGone();var targets=this._targetManager.targets(SDK.Target.Capability.JS);if(this._context.flavor(SDK.Target)===target&&targets.length) -this._context.setFlavor(SDK.Target,targets[0]);} -_executionContextChanged(event){var newContext=(event.data);if(newContext){this._context.setFlavor(SDK.Target,newContext.target());if(!this._ignoreContextChanged) -this._lastSelectedContextId=this._contextPersistentId(newContext);}} -_contextPersistentId(executionContext){return executionContext.isDefault?executionContext.target().name()+':'+executionContext.frameId:'';} -_targetChanged(event){var newTarget=(event.data);var currentContext=this._context.flavor(SDK.ExecutionContext);if(!newTarget||(currentContext&¤tContext.target()===newTarget)) -return;var runtimeModel=newTarget.model(SDK.RuntimeModel);var executionContexts=runtimeModel?runtimeModel.executionContexts():[];if(!executionContexts.length) -return;var newContext=null;for(var i=0;i<executionContexts.length&&!newContext;++i){if(this._shouldSwitchToContext(executionContexts[i])) -newContext=executionContexts[i];} -for(var i=0;i<executionContexts.length&&!newContext;++i){if(this._isDefaultContext(executionContexts[i])) -newContext=executionContexts[i];} -this._ignoreContextChanged=true;this._context.setFlavor(SDK.ExecutionContext,newContext||executionContexts[0]);this._ignoreContextChanged=false;} -_shouldSwitchToContext(executionContext){if(this._lastSelectedContextId&&this._lastSelectedContextId===this._contextPersistentId(executionContext)) -return true;if(!this._lastSelectedContextId&&this._isDefaultContext(executionContext)) -return true;return false;} -_isDefaultContext(executionContext){if(!executionContext.isDefault||!executionContext.frameId) -return false;if(executionContext.target().parentTarget()) -return false;var resourceTreeModel=executionContext.target().model(SDK.ResourceTreeModel);var frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);if(frame&&frame.isMainFrame()) -return true;return false;} -_onExecutionContextCreated(event){this._switchContextIfNecessary((event.data));} -_onExecutionContextDestroyed(event){var executionContext=(event.data);if(this._context.flavor(SDK.ExecutionContext)===executionContext) -this._currentExecutionContextGone();} -_onExecutionContextOrderChanged(event){var runtimeModel=(event.data);var executionContexts=runtimeModel.executionContexts();for(var i=0;i<executionContexts.length;i++){if(this._switchContextIfNecessary(executionContexts[i])) -break;}} -_switchContextIfNecessary(executionContext){if(!this._context.flavor(SDK.ExecutionContext)||this._shouldSwitchToContext(executionContext)){this._ignoreContextChanged=true;this._context.setFlavor(SDK.ExecutionContext,executionContext);this._ignoreContextChanged=false;return true;} -return false;} -_currentExecutionContextGone(){var runtimeModels=this._targetManager.models(SDK.RuntimeModel);var newContext=null;for(var i=0;i<runtimeModels.length&&!newContext;++i){var executionContexts=runtimeModels[i].executionContexts();for(var executionContext of executionContexts){if(this._isDefaultContext(executionContext)){newContext=executionContext;break;}}} -if(!newContext){for(var i=0;i<runtimeModels.length&&!newContext;++i){var executionContexts=runtimeModels[i].executionContexts();if(executionContexts.length){newContext=executionContexts[0];break;}}} -this._ignoreContextChanged=true;this._context.setFlavor(SDK.ExecutionContext,newContext);this._ignoreContextChanged=false;}};;Main.Main=class{constructor(){Main.Main._instanceForTest=this;runOnWindowLoad(this._loaded.bind(this));} -static _reloadPage(hard){SDK.ResourceTreeModel.reloadAllPages(hard);} -static time(label){if(Host.isUnderTest()) -return;console.time(label);} -static timeEnd(label){if(Host.isUnderTest()) -return;console.timeEnd(label);} -_loaded(){console.timeStamp('Main._loaded');Runtime.setPlatform(Host.platform());InspectorFrontendHost.getPreferences(this._gotPreferences.bind(this));} -_gotPreferences(prefs){console.timeStamp('Main._gotPreferences');if(Host.isUnderTest(prefs)) -self.runtime.useTestBase();this._createSettings(prefs);this._createAppUI();} -_createSettings(prefs){this._initializeExperiments(prefs);var storagePrefix='';if(Host.isCustomDevtoolsFrontend()) -storagePrefix='__custom__';else if(!Runtime.queryParam('can_dock')&&!!Runtime.queryParam('debugFrontend')&&!Host.isUnderTest(prefs)) -storagePrefix='__bundled__';var clearLocalStorage=window.localStorage?window.localStorage.clear.bind(window.localStorage):undefined;var localStorage=new Common.SettingsStorage(window.localStorage||{},undefined,undefined,clearLocalStorage,storagePrefix);var globalStorage=new Common.SettingsStorage(prefs,InspectorFrontendHost.setPreference,InspectorFrontendHost.removePreference,InspectorFrontendHost.clearPreferences,storagePrefix);Common.settings=new Common.Settings(globalStorage,localStorage);if(!Host.isUnderTest(prefs)) -new Common.VersionController().updateVersion();} -_initializeExperiments(prefs){Runtime.experiments.register('accessibilityInspection','Accessibility Inspection');Runtime.experiments.register('applyCustomStylesheet','Allow custom UI themes');Runtime.experiments.register('autoAttachToCrossProcessSubframes','Auto-attach to cross-process subframes',true);Runtime.experiments.register('blackboxJSFramesOnTimeline','Blackbox JavaScript frames on Timeline',true);Runtime.experiments.register('changesDrawer','Changes drawer',true);Runtime.experiments.register('colorContrastRatio','Color contrast ratio line in color picker',true);Runtime.experiments.register('continueToLocationMarkers','Continue to location markers',true);Runtime.experiments.register('emptySourceMapAutoStepping','Empty sourcemap auto-stepping');Runtime.experiments.register('inputEventsOnTimelineOverview','Input events on Timeline overview',true);Runtime.experiments.register('logManagement','Log management',true);Runtime.experiments.register('liveSASS','Live SASS');Runtime.experiments.register('networkGroupingRequests','Network request groups support',true);Runtime.experiments.register('networkPersistence','Override requests with workspace project');Runtime.experiments.register('objectPreviews','Object previews',true);Runtime.experiments.register('performanceMonitor','Performance Monitor',true);Runtime.experiments.register('persistence2','Persistence 2.0');Runtime.experiments.register('sourceDiff','Source diff');Runtime.experiments.register('terminalInDrawer','Terminal in drawer',true);Runtime.experiments.register('timelineColorByProduct','Timeline: color by product',true);Runtime.experiments.register('timelineEventInitiators','Timeline: event initiators');Runtime.experiments.register('timelineFlowEvents','Timeline: flow events',true);Runtime.experiments.register('timelineInvalidationTracking','Timeline: invalidation tracking',true);Runtime.experiments.register('timelineKeepHistory','Timeline: keep recording history');Runtime.experiments.register('timelineMultipleMainViews','Timeline: multiple main views');Runtime.experiments.register('timelinePaintTimingMarkers','Timeline: paint timing markers',true);Runtime.experiments.register('timelinePerFrameTrack','Timeline: per-frame tracks',true);Runtime.experiments.register('timelineShowAllEvents','Timeline: show all events',true);Runtime.experiments.register('timelineShowAllProcesses','Timeline: show all processes',true);Runtime.experiments.register('timelineTracingJSProfile','Timeline: tracing based JS profiler',true);Runtime.experiments.register('timelineV8RuntimeCallStats','Timeline: V8 Runtime Call Stats on Timeline',true);Runtime.experiments.cleanUpStaleExperiments();if(Host.isUnderTest(prefs)){var testPath=Runtime.queryParam('test')||JSON.parse(prefs['testPath']||'""');if(testPath.indexOf('accessibility/')!==-1) -Runtime.experiments.enableForTest('accessibilityInspection');if(testPath.indexOf('changes/')!==-1) -Runtime.experiments.enableForTest('changesDrawer');if(testPath.indexOf('console-sidebar/')!==-1) -Runtime.experiments.enableForTest('logManagement');if(testPath.indexOf('sass/')!==-1) -Runtime.experiments.enableForTest('liveSASS');} -Runtime.experiments.setDefaultExperiments(['continueToLocationMarkers','autoAttachToCrossProcessSubframes','objectPreviews','persistence2','networkGroupingRequests','timelineColorByProduct','accessibilityInspection','networkPersistence','logManagement','performanceMonitor']);} -_createAppUI(){Main.Main.time('Main._createAppUI');UI.viewManager=new UI.ViewManager();Persistence.isolatedFileSystemManager=new Persistence.IsolatedFileSystemManager();var themeSetting=Common.settings.createSetting('uiTheme','default');UI.initializeUIUtils(document,themeSetting);themeSetting.addChangeListener(Components.reload.bind(Components));UI.installComponentRootStyles((document.body));this._addMainEventListeners(document);var canDock=!!Runtime.queryParam('can_dock');UI.zoomManager=new UI.ZoomManager(window,InspectorFrontendHost);UI.inspectorView=UI.InspectorView.instance();UI.ContextMenu.initialize();UI.ContextMenu.installHandler(document);UI.Tooltip.installHandler(document);Components.dockController=new Components.DockController(canDock);ConsoleModel.consoleModel=new ConsoleModel.ConsoleModel();SDK.multitargetNetworkManager=new SDK.MultitargetNetworkManager();NetworkLog.networkLog=new NetworkLog.NetworkLog();SDK.domDebuggerManager=new SDK.DOMDebuggerManager();SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._onSuspendStateChanged.bind(this));UI.shortcutsScreen=new UI.ShortcutsScreen();UI.shortcutsScreen.section(Common.UIString('Elements Panel'));UI.shortcutsScreen.section(Common.UIString('Styles Pane'));UI.shortcutsScreen.section(Common.UIString('Debugger'));UI.shortcutsScreen.section(Common.UIString('Console'));Workspace.fileManager=new Workspace.FileManager();Workspace.workspace=new Workspace.Workspace();Persistence.fileSystemMapping=new Persistence.FileSystemMapping(Persistence.isolatedFileSystemManager);Bindings.networkProjectManager=new Bindings.NetworkProjectManager(SDK.targetManager,Workspace.workspace);Bindings.resourceMapping=new Bindings.ResourceMapping(SDK.targetManager,Workspace.workspace);Bindings.presentationConsoleMessageHelper=new Bindings.PresentationConsoleMessageHelper(Workspace.workspace);Bindings.cssWorkspaceBinding=new Bindings.CSSWorkspaceBinding(SDK.targetManager,Workspace.workspace);Bindings.debuggerWorkspaceBinding=new Bindings.DebuggerWorkspaceBinding(SDK.targetManager,Workspace.workspace);Bindings.breakpointManager=new Bindings.BreakpointManager(null,Workspace.workspace,SDK.targetManager,Bindings.debuggerWorkspaceBinding);Extensions.extensionServer=new Extensions.ExtensionServer();new Persistence.FileSystemWorkspaceBinding(Persistence.isolatedFileSystemManager,Workspace.workspace);Persistence.persistence=new Persistence.Persistence(Workspace.workspace,Bindings.breakpointManager,Persistence.fileSystemMapping);Persistence.networkPersistenceManager=new Persistence.NetworkPersistenceManager(Workspace.workspace);new Main.ExecutionContextSelector(SDK.targetManager,UI.context);Bindings.blackboxManager=new Bindings.BlackboxManager(Bindings.debuggerWorkspaceBinding);new Main.Main.PauseListener();new Main.Main.InspectedNodeRevealer();new Main.NetworkPanelIndicator();new Main.SourcesPanelIndicator();new Main.BackendSettingsSync();UI.actionRegistry=new UI.ActionRegistry();UI.shortcutRegistry=new UI.ShortcutRegistry(UI.actionRegistry,document);UI.ShortcutsScreen.registerShortcuts();this._registerForwardedShortcuts();this._registerMessageSinkListener();self.runtime.extension(Common.AppProvider).instance().then(this._showAppUI.bind(this));Main.Main.timeEnd('Main._createAppUI');} -_showAppUI(appProvider){Main.Main.time('Main._showAppUI');var app=(appProvider).createApp();Components.dockController.initialize();app.presentUI(document);var toggleSearchNodeAction=UI.actionRegistry.action('elements.toggle-element-search');if(toggleSearchNodeAction){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.EnterInspectElementMode,toggleSearchNodeAction.execute.bind(toggleSearchNodeAction),this);} -InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.RevealSourceLine,this._revealSourceLine,this);UI.inspectorView.createToolbars();InspectorFrontendHost.loadCompleted();InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ReloadInspectedPage,this._reloadInspectedPage,this);var extensions=self.runtime.extensions(Common.QueryParamHandler);for(var extension of extensions){var value=Runtime.queryParam(extension.descriptor()['name']);if(value!==null) -extension.instance().then(handleQueryParam.bind(null,value));} -function handleQueryParam(value,handler){handler.handleQueryParam(value);} -setTimeout(this._initializeTarget.bind(this),0);Main.Main.timeEnd('Main._showAppUI');} -_initializeTarget(){Main.Main.time('Main._initializeTarget');SDK.targetManager.connectToMainTarget(webSocketConnectionLost);InspectorFrontendHost.readyForTest();setTimeout(this._lateInitialization.bind(this),100);Main.Main.timeEnd('Main._initializeTarget');function webSocketConnectionLost(){if(!Main._disconnectedScreenWithReasonWasShown) -Main.RemoteDebuggingTerminatedScreen.show('WebSocket disconnected');}} -_lateInitialization(){console.timeStamp('Main._lateInitialization');this._registerShortcuts();Extensions.extensionServer.initializeExtensions();if(!Host.isUnderTest()) -Help.showReleaseNoteIfNeeded();} -_registerForwardedShortcuts(){var forwardedActions=['main.toggle-dock','debugger.toggle-breakpoints-active','debugger.toggle-pause','commandMenu.show','console.show'];var actionKeys=UI.shortcutRegistry.keysForActions(forwardedActions).map(UI.KeyboardShortcut.keyCodeAndModifiersFromKey);InspectorFrontendHost.setWhitelistedShortcuts(JSON.stringify(actionKeys));} -_registerMessageSinkListener(){Common.console.addEventListener(Common.Console.Events.MessageAdded,messageAdded);function messageAdded(event){var message=(event.data);if(message.show) -Common.console.show();}} -_revealSourceLine(event){var url=(event.data['url']);var lineNumber=(event.data['lineNumber']);var columnNumber=(event.data['columnNumber']);var uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);if(uiSourceCode){Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber,columnNumber));return;} -function listener(event){var uiSourceCode=(event.data);if(uiSourceCode.url()===url){Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber,columnNumber));Workspace.workspace.removeEventListener(Workspace.Workspace.Events.UISourceCodeAdded,listener);}} -Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,listener);} -_registerShortcuts(){var shortcut=UI.KeyboardShortcut;var section=UI.shortcutsScreen.section(Common.UIString('All Panels'));var keys=[shortcut.makeDescriptor('[',shortcut.Modifiers.CtrlOrMeta),shortcut.makeDescriptor(']',shortcut.Modifiers.CtrlOrMeta)];section.addRelatedKeys(keys,Common.UIString('Go to the panel to the left/right'));var toggleConsoleLabel=Common.UIString('Show console');section.addKey(shortcut.makeDescriptor(shortcut.Keys.Tilde,shortcut.Modifiers.Ctrl),toggleConsoleLabel);section.addKey(shortcut.makeDescriptor(shortcut.Keys.Esc),Common.UIString('Toggle drawer'));if(Components.dockController.canDock()){section.addKey(shortcut.makeDescriptor('M',shortcut.Modifiers.CtrlOrMeta|shortcut.Modifiers.Shift),Common.UIString('Toggle device mode'));section.addKey(shortcut.makeDescriptor('D',shortcut.Modifiers.CtrlOrMeta|shortcut.Modifiers.Shift),Common.UIString('Toggle dock side'));} -section.addKey(shortcut.makeDescriptor('f',shortcut.Modifiers.CtrlOrMeta),Common.UIString('Search'));var advancedSearchShortcutModifier=Host.isMac()?UI.KeyboardShortcut.Modifiers.Meta|UI.KeyboardShortcut.Modifiers.Alt:UI.KeyboardShortcut.Modifiers.Ctrl|UI.KeyboardShortcut.Modifiers.Shift;var advancedSearchShortcut=shortcut.makeDescriptor('f',advancedSearchShortcutModifier);section.addKey(advancedSearchShortcut,Common.UIString('Search across all sources'));var inspectElementModeShortcuts=UI.shortcutRegistry.shortcutDescriptorsForAction('elements.toggle-element-search');if(inspectElementModeShortcuts.length) -section.addKey(inspectElementModeShortcuts[0],Common.UIString('Select node to inspect'));var openResourceShortcut=UI.KeyboardShortcut.makeDescriptor('p',UI.KeyboardShortcut.Modifiers.CtrlOrMeta);section.addKey(openResourceShortcut,Common.UIString('Go to source'));if(Host.isMac()){keys=[shortcut.makeDescriptor('g',shortcut.Modifiers.Meta),shortcut.makeDescriptor('g',shortcut.Modifiers.Meta|shortcut.Modifiers.Shift)];section.addRelatedKeys(keys,Common.UIString('Find next/previous'));}} -_postDocumentKeyDown(event){if(event.handled) -return;if(!UI.Dialog.hasInstance()&&UI.inspectorView.currentPanelDeprecated()){UI.inspectorView.currentPanelDeprecated().handleShortcut(event);if(event.handled){event.consume(true);return;}} -UI.shortcutRegistry.handleShortcut(event);} -_redispatchClipboardEvent(event){var eventCopy=new CustomEvent('clipboard-'+event.type,{bubbles:true});eventCopy['original']=event;var document=event.target&&event.target.ownerDocument;var target=document?document.deepActiveElement():null;if(target) -target.dispatchEvent(eventCopy);if(eventCopy.handled) -event.preventDefault();} -_contextMenuEventFired(event){if(event.handled||event.target.classList.contains('popup-glasspane')) -event.preventDefault();} -_addMainEventListeners(document){document.addEventListener('keydown',this._postDocumentKeyDown.bind(this),false);document.addEventListener('beforecopy',this._redispatchClipboardEvent.bind(this),true);document.addEventListener('copy',this._redispatchClipboardEvent.bind(this),false);document.addEventListener('cut',this._redispatchClipboardEvent.bind(this),false);document.addEventListener('paste',this._redispatchClipboardEvent.bind(this),false);document.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),true);} -_reloadInspectedPage(event){var hard=(event.data);Main.Main._reloadPage(hard);} -_onSuspendStateChanged(){var suspended=SDK.targetManager.allTargetsSuspended();UI.inspectorView.onSuspendStateChanged(suspended);}};Main.Main.InspectorModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerInspectorDispatcher(this);target.inspectorAgent().enable();} -detached(reason){Main._disconnectedScreenWithReasonWasShown=true;Main.RemoteDebuggingTerminatedScreen.show(reason);} -targetCrashed(){var debuggerModel=this.target().model(SDK.DebuggerModel);if(debuggerModel) -Main.TargetCrashedScreen.show(debuggerModel);}};SDK.SDKModel.register(Main.Main.InspectorModel,SDK.Target.Capability.Inspector,true);Main.Main.ReloadActionDelegate=class{handleAction(context,actionId){switch(actionId){case'main.reload':Main.Main._reloadPage(false);return true;case'main.hard-reload':Main.Main._reloadPage(true);return true;case'main.debug-reload':Components.reload();return true;} -return false;}};Main.Main.ZoomActionDelegate=class{handleAction(context,actionId){if(InspectorFrontendHost.isHostedMode()) -return false;switch(actionId){case'main.zoom-in':InspectorFrontendHost.zoomIn();return true;case'main.zoom-out':InspectorFrontendHost.zoomOut();return true;case'main.zoom-reset':InspectorFrontendHost.resetZoom();return true;} -return false;}};Main.Main.SearchActionDelegate=class{handleAction(context,actionId){var searchableView=UI.SearchableView.fromElement(document.deepActiveElement())||UI.inspectorView.currentPanelDeprecated().searchableView();if(!searchableView) -return false;switch(actionId){case'main.search-in-panel.find':return searchableView.handleFindShortcut();case'main.search-in-panel.cancel':return searchableView.handleCancelSearchShortcut();case'main.search-in-panel.find-next':return searchableView.handleFindNextShortcut();case'main.search-in-panel.find-previous':return searchableView.handleFindPreviousShortcut();} -return false;}};Main.Main.MainMenuItem=class{constructor(){this._item=new UI.ToolbarMenuButton(this._handleContextMenu.bind(this),true);this._item.setTitle(Common.UIString('Customize and control DevTools'));} -item(){return this._item;} -_handleContextMenu(contextMenu){if(Components.dockController.canDock()){var dockItemElement=createElementWithClass('div','flex-centered flex-auto');var titleElement=dockItemElement.createChild('span','flex-auto');titleElement.textContent=Common.UIString('Dock side');var toggleDockSideShorcuts=UI.shortcutRegistry.shortcutDescriptorsForAction('main.toggle-dock');titleElement.title=Common.UIString('Placement of DevTools relative to the page. (%s to restore last position)',toggleDockSideShorcuts[0].name);dockItemElement.appendChild(titleElement);var dockItemToolbar=new UI.Toolbar('',dockItemElement);dockItemToolbar.makeBlueOnHover();var undock=new UI.ToolbarToggle(Common.UIString('Undock into separate window'),'largeicon-undock');var bottom=new UI.ToolbarToggle(Common.UIString('Dock to bottom'),'largeicon-dock-to-bottom');var right=new UI.ToolbarToggle(Common.UIString('Dock to right'),'largeicon-dock-to-right');var left=new UI.ToolbarToggle(Common.UIString('Dock to left'),'largeicon-dock-to-left');undock.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());bottom.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());right.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());left.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());undock.addEventListener(UI.ToolbarButton.Events.MouseUp,setDockSide.bind(null,Components.DockController.State.Undocked));bottom.addEventListener(UI.ToolbarButton.Events.MouseUp,setDockSide.bind(null,Components.DockController.State.DockedToBottom));right.addEventListener(UI.ToolbarButton.Events.MouseUp,setDockSide.bind(null,Components.DockController.State.DockedToRight));left.addEventListener(UI.ToolbarButton.Events.MouseUp,setDockSide.bind(null,Components.DockController.State.DockedToLeft));undock.setToggled(Components.dockController.dockSide()===Components.DockController.State.Undocked);bottom.setToggled(Components.dockController.dockSide()===Components.DockController.State.DockedToBottom);right.setToggled(Components.dockController.dockSide()===Components.DockController.State.DockedToRight);left.setToggled(Components.dockController.dockSide()===Components.DockController.State.DockedToLeft);dockItemToolbar.appendToolbarItem(undock);dockItemToolbar.appendToolbarItem(left);dockItemToolbar.appendToolbarItem(bottom);dockItemToolbar.appendToolbarItem(right);contextMenu.headerSection().appendCustomItem(dockItemElement);} -function setDockSide(side){Components.dockController.setDockSide(side);contextMenu.discard();} -contextMenu.defaultSection().appendAction('main.toggle-drawer',UI.inspectorView.drawerVisible()?Common.UIString('Hide console drawer'):Common.UIString('Show console drawer'));contextMenu.appendItemsAtLocation('mainMenu');var moreTools=contextMenu.defaultSection().appendSubMenuItem(Common.UIString('More tools'));var extensions=self.runtime.extensions('view',undefined,true);for(var extension of extensions){var descriptor=extension.descriptor();if(descriptor['persistence']!=='closeable') -continue;if(descriptor['location']!=='drawer-view'&&descriptor['location']!=='panel') -continue;moreTools.defaultSection().appendItem(extension.title(),UI.viewManager.showView.bind(UI.viewManager,descriptor['id']));} -var helpSubMenu=contextMenu.footerSection().appendSubMenuItem(Common.UIString('Help'));helpSubMenu.defaultSection().appendAction('settings.documentation');helpSubMenu.defaultSection().appendItem('Release Notes',()=>InspectorFrontendHost.openInNewTab(Help.latestReleaseNote().link));}};Main.Main.NodeIndicator=class{constructor(){var element=createElement('div');var shadowRoot=UI.createShadowRootWithCoreStyles(element,'main/nodeIcon.css');this._element=shadowRoot.createChild('div','node-icon');element.addEventListener('click',()=>InspectorFrontendHost.openNodeFrontend(),false);this._button=new UI.ToolbarItem(element);this._button.setTitle(Common.UIString('Open dedicated DevTools for Node.js'));SDK.targetManager.addEventListener(SDK.TargetManager.Events.AvailableNodeTargetsChanged,this._update,this);this._button.setVisible(false);this._update();} -_update(){this._element.classList.toggle('inactive',!SDK.targetManager.availableNodeTargetsCount());if(SDK.targetManager.availableNodeTargetsCount()) -this._button.setVisible(true);} -item(){return this._button;}};Main.NetworkPanelIndicator=class{constructor(){if(!UI.inspectorView.hasPanel('network')) -return;var manager=SDK.multitargetNetworkManager;manager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,updateVisibility);manager.addEventListener(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged,updateVisibility);manager.addEventListener(SDK.MultitargetNetworkManager.Events.InterceptorsChanged,updateVisibility);updateVisibility();function updateVisibility(){var icon=null;if(manager.isThrottling()){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('Network throttling is enabled');}else if(SDK.multitargetNetworkManager.isIntercepting()){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('Requests may be rewritten');}else if(manager.isBlocking()){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('Requests may be blocked');} -UI.inspectorView.setPanelIcon('network',icon);}}};Main.SourcesPanelIndicator=class{constructor(){Common.moduleSetting('javaScriptDisabled').addChangeListener(javaScriptDisabledChanged);javaScriptDisabledChanged();function javaScriptDisabledChanged(){var icon=null;var javaScriptDisabled=Common.moduleSetting('javaScriptDisabled').get();if(javaScriptDisabled){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('JavaScript is disabled');} -UI.inspectorView.setPanelIcon('sources',icon);}}};Main.Main.PauseListener=class{constructor(){SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerPaused,this._debuggerPaused,this);} -_debuggerPaused(event){SDK.targetManager.removeModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerPaused,this._debuggerPaused,this);var debuggerModel=(event.data);var debuggerPausedDetails=debuggerModel.debuggerPausedDetails();UI.context.setFlavor(SDK.Target,debuggerModel.target());Common.Revealer.reveal(debuggerPausedDetails);}};Main.Main.InspectedNodeRevealer=class{constructor(){SDK.targetManager.addModelListener(SDK.OverlayModel,SDK.OverlayModel.Events.InspectNodeRequested,this._inspectNode,this);} -_inspectNode(event){var deferredNode=(event.data);Common.Revealer.reveal(deferredNode);}};Main.sendOverProtocol=function(method,params){return new Promise((resolve,reject)=>{Protocol.InspectorBackend.sendRawMessageForTesting(method,params,(err,...results)=>{if(err) -return reject(err);return resolve(results);});});};Main.RemoteDebuggingTerminatedScreen=class extends UI.VBox{constructor(reason){super(true);this.registerRequiredCSS('main/remoteDebuggingTerminatedScreen.css');var message=this.contentElement.createChild('div','message');message.createChild('span').textContent=Common.UIString('Debugging connection was closed. Reason: ');message.createChild('span','reason').textContent=reason;this.contentElement.createChild('div','message').textContent=Common.UIString('Reconnect when ready by reopening DevTools.');var button=UI.createTextButton(Common.UIString('Reconnect DevTools'),()=>window.location.reload());this.contentElement.createChild('div','button').appendChild(button);} -static show(reason){var dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.addCloseButton();dialog.setDimmed(true);new Main.RemoteDebuggingTerminatedScreen(reason).show(dialog.contentElement);dialog.show();}};Main.TargetCrashedScreen=class extends UI.VBox{constructor(hideCallback){super(true);this.registerRequiredCSS('main/targetCrashedScreen.css');this.contentElement.createChild('div','message').textContent=Common.UIString('DevTools was disconnected from the page.');this.contentElement.createChild('div','message').textContent=Common.UIString('Once page is reloaded, DevTools will automatically reconnect.');this._hideCallback=hideCallback;} -static show(debuggerModel){var dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.addCloseButton();dialog.setDimmed(true);var hideBound=dialog.hide.bind(dialog);debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,hideBound);new Main.TargetCrashedScreen(onHide).show(dialog.contentElement);dialog.show();function onHide(){debuggerModel.removeEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,hideBound);}} -willHide(){this._hideCallback.call(null);}};Main.BackendSettingsSync=class{constructor(){this._autoAttachSetting=Common.settings.moduleSetting('autoAttachToCreatedPages');this._autoAttachSetting.addChangeListener(this._update,this);this._adBlockEnabledSetting=Common.settings.moduleSetting('network.adBlockingEnabled');this._adBlockEnabledSetting.addChangeListener(this._update,this);SDK.targetManager.observeTargets(this,SDK.Target.Capability.Browser);} -_updateTarget(target){target.pageAgent().setAutoAttachToCreatedPages(this._autoAttachSetting.get());target.pageAgent().setAdBlockingEnabled(this._adBlockEnabledSetting.get());} -_update(){SDK.targetManager.targets(SDK.Target.Capability.Browser).forEach(this._updateTarget,this);} -targetAdded(target){this._updateTarget(target);} -targetRemoved(target){}};Main.ShowMetricsRulersSettingUI=class{settingElement(){return UI.SettingsUI.createSettingCheckbox(Common.UIString('Show rulers'),Common.moduleSetting('showMetricsRulers'));}};new Main.Main();;applicationDescriptor={"has_html":true,"modules":[{"name":"text_editor"},{"name":"network_priorities"},{"type":"autostart","name":"protocol"},{"type":"autostart","name":"help"},{"name":"cm"},{"name":"heap_snapshot_model"},{"type":"remote","name":"accessibility","condition":"!v8only"},{"type":"remote","name":"cm_modes"},{"name":"layer_viewer","condition":"!v8only"},{"name":"sources"},{"name":"cookie_table"},{"type":"remote","name":"emulated_devices","condition":"!v8only"},{"type":"remote","name":"product_registry_impl","condition":"!v8only"},{"name":"diff"},{"type":"autostart","name":"bindings"},{"type":"remote","name":"audits","condition":"!v8only"},{"name":"snippets"},{"name":"layers","condition":"!v8only"},{"name":"har_importer","condition":"!v8only"},{"name":"console"},{"name":"network","condition":"!v8only"},{"name":"workspace_diff"},{"type":"remote","name":"screencast","condition":"remoteFrontend"},{"name":"perf_ui"},{"type":"autostart","name":"product_registry"},{"type":"remote","name":"terminal"},{"type":"autostart","name":"platform"},{"name":"animation","condition":"!v8only"},{"name":"source_frame"},{"type":"autostart","name":"main"},{"name":"resources","condition":"!v8only"},{"type":"autostart","name":"common"},{"name":"inline_editor"},{"type":"autostart","name":"console_counters"},{"type":"autostart","name":"network_log"},{"name":"elements","condition":"!v8only"},{"type":"autostart","name":"workspace"},{"name":"audits2","condition":"!v8only"},{"name":"timeline","condition":"!v8only"},{"name":"quick_open"},{"name":"data_grid"},{"type":"autostart","name":"emulation"},{"name":"coverage"},{"type":"autostart","name":"services"},{"type":"autostart","name":"ui"},{"name":"event_listeners"},{"type":"autostart","name":"dom_extension"},{"type":"autostart","name":"mobile_throttling"},{"type":"autostart","name":"sdk"},{"name":"formatter"},{"name":"sass","condition":"!v8only"},{"name":"settings"},{"type":"autostart","name":"console_model"},{"type":"autostart","name":"host"},{"name":"devices"},{"name":"profiler"},{"name":"color_picker"},{"type":"autostart","name":"extensions"},{"type":"autostart","name":"persistence"},{"type":"autostart","name":"components"},{"name":"object_ui"},{"name":"timeline_model","condition":"!v8only"},{"name":"security","condition":"!v8only"},{"name":"changes"},{"type":"autostart","name":"text_utils"}]};Runtime.cachedResources["ui/checkboxTextLabel.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n padding: 0;\n margin: 0;\n display: inline-flex;\n flex-shrink: 0;\n align-items: center !important;\n}\n\ninput {\n height: 12px;\n width: 12px;\n flex-shrink: 0;\n}\n\ninput:focus {\n outline: auto 5px -webkit-focus-ring-color;\n}\n\ninput.dt-checkbox-themed {\n -webkit-appearance: none;\n margin: 0 5px auto 2px;\n border: 1px solid rgb(45, 45, 45);\n border-radius: 3px;\n background-color: rgb(102, 102, 102);\n position: relative;\n top: 1px;\n}\n\ninput.dt-checkbox-themed:after {\n content: '';\n line-height: 10px;\n position: absolute;\n cursor: pointer;\n width: 12px;\n height: 12px;\n background: none;\n}\n\ninput.dt-checkbox-themed:checked:after {\n background-color: #333;\n}\n\ninput.dt-checkbox-themed:after {\n -webkit-mask-image: url(Images/checkboxCheckmark.png);\n -webkit-mask-size: 11px 11px;\n -webkit-mask-position: 0 0;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\ninput.dt-checkbox-themed:after {\n -webkit-mask-image: url(Images/checkboxCheckmark_2x.png);\n}\n\n} /* media */\n\n.dt-checkbox-text {\n margin-left: 3px;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.dt-checkbox-subtitle {\n color: gray;\n}\n\n/*# sourceURL=ui/checkboxTextLabel.css */";Runtime.cachedResources["ui/closeButton.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.close-button {\n width: 14px;\n height: 14px;\n cursor: default;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.hover-icon, .active-icon {\n display: none;\n}\n\n.close-button:hover .default-icon, .close-button:active .default-icon {\n display: none;\n}\n\n.close-button:hover .hover-icon {\n display: block;\n}\n\n.close-button:active .hover-icon {\n display: none !important;\n}\n\n.close-button:active .active-icon {\n display: block;\n}\n\n/*# sourceURL=ui/closeButton.css */";Runtime.cachedResources["ui/confirmDialog.css"]="/*\n * Copyright (c) 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n padding: 20px;\n}\n\n.message, .button {\n font-size: larger;\n white-space: pre;\n margin: 5px;\n}\n\n.button {\n text-align: center;\n margin-top: 10px;\n}\n\n.button button {\n min-width: 80px;\n}\n\n.reason {\n color: #8b0000;\n}\n\n/*# sourceURL=ui/confirmDialog.css */";Runtime.cachedResources["ui/dialog.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2), 0 2px 4px rgba(0, 0, 0, 0.2), 0 2px 6px rgba(0, 0, 0, 0.1);\n background: white;\n justify-content: flex-start;\n align-items: stretch;\n display: flex;\n}\n\n.dialog-close-button {\n position: absolute;\n right: 9px;\n top: 9px;\n z-index: 1;\n}\n/*# sourceURL=ui/dialog.css */";Runtime.cachedResources["ui/dropTarget.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n display: flex;\n background-color: rgba(255,255,255,0.8);\n z-index: 1000;\n}\n\n.drop-target-message {\n flex: auto;\n font-size: 30px;\n color: #999;\n display: flex;\n justify-content: center;\n align-items: center;\n margin: 20px;\n border: 4px dashed #ddd;\n pointer-events: none;\n}\n\n/*# sourceURL=ui/dropTarget.css */";Runtime.cachedResources["ui/emptyWidget.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.empty-view {\n color: hsla(0, 0%, 65%, 1);\n padding: 30px;\n display: flex;\n align-items: center;\n flex-direction: column;\n min-width: 70px;\n}\n\n.empty-view-scroller {\n justify-content: center;\n overflow: auto;\n}\n\n.empty-view p {\n white-space: initial;\n line-height: 18px;\n max-width: 300px;\n}\n\n/*# sourceURL=ui/emptyWidget.css */";Runtime.cachedResources["ui/filter.css"]="/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.filter-bar {\n background-color: #f3f3f3;\n flex: none;\n flex-wrap: wrap;\n align-items: center;\n border-bottom: 1px solid #dadada;\n}\n\n.filter-text-filter {\n display: inline-flex;\n margin-left: 1px;\n margin-right: 2px;\n min-width: 40px;\n max-width: 200px;\n height: 24px;\n align-items: center;\n}\n\n.filter-text-filter label {\n margin: auto 0;\n}\n\n.filter-bitset-filter {\n padding: 2px;\n display: inline-flex;\n overflow: hidden;\n height: 24px;\n position: relative;\n}\n\n.filter-bitset-filter li {\n display: inline-block;\n flex: none;\n margin: auto 2px;\n padding: 3px;\n background: transparent;\n text-shadow: rgba(255, 255, 255, 0.5) 0 1px 0;\n border-radius: 6px;\n overflow: hidden;\n}\n\n.filter-bitset-filter-divider {\n background-color: #ccc;\n height: 16px;\n width: 1px;\n margin: auto 2px;\n display: inline-block;\n}\n\n.filter-bitset-filter li.selected,\n.filter-bitset-filter li:hover,\n.filter-bitset-filter li:active {\n color: white;\n text-shadow: rgba(0, 0, 0, 0.4) 0 1px 0;\n}\n\n.filter-bitset-filter li:hover {\n background: rgba(0, 0, 0, 0.2);\n}\n\n.filter-bitset-filter li.selected {\n background: rgba(0, 0, 0, 0.3);\n}\n\n.filter-bitset-filter li:active {\n background: rgba(0, 0, 0, 0.5);\n}\n\n.filter-combobox-filter {\n margin-left: 5px;\n margin-right: 2px;\n flex: 0 0 auto;\n display: inline-block;\n}\n\n.filter-checkbox-filter {\n padding-left: 4px;\n padding-right: 2px;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n display: inline-flex;\n vertical-align: middle;\n height: 24px;\n position: relative;\n}\n\n.filter-checkbox-filter > label {\n display: flex;\n margin: auto 0;\n}\n\n.filter-checkbox-filter .checkbox-filter-checkbox {\n width: 10px;\n height: 10px;\n margin: auto 3px;\n padding: 0;\n border-radius: 2px;\n border: solid 1px;\n display: inline-block;\n overflow: visible;\n opacity: 0.8;\n flex-shrink: 0;\n}\n\n.filter-input-field {\n border: 1px solid rgb(163, 163, 163);\n border-radius: 2px;\n padding: 1px 3px 0;\n margin: 0 0 0 3px;\n width: 163px;\n height: 20px;\n line-height: 17px;\n display: inline-block;\n background: #FFF;\n overflow: hidden;\n white-space: nowrap;\n cursor: auto;\n}\n\n/*# sourceURL=ui/filter.css */";Runtime.cachedResources["ui/glassPane.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n position: absolute !important;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n overflow: hidden;\n contain: strict;\n background-color: transparent;\n}\n\n:host-context(.dimmed-pane) {\n background-color: rgba(255, 255, 255, 0.5);\n}\n\n:host-context(.no-pointer-events) {\n pointer-events: none;\n}\n\n.widget {\n display: flex;\n background-color: transparent;\n pointer-events: auto;\n flex: none;\n}\n\n.no-pointer-events {\n pointer-events: none;\n}\n\n.arrow-top {\n margin-top: -19px;\n margin-left: -9px;\n}\n\n.arrow-bottom {\n margin-left: -9px;\n}\n\n.arrow-left {\n margin-left: -19px;\n margin-top: -9px;\n}\n\n.arrow-right {\n margin-top: -9px;\n}\n\n.arrow-none {\n display: none;\n}\n\n:host-context(.-theme-with-dark-background) .arrow {\n -webkit-filter: invert(80%);\n}\n\n/*# sourceURL=ui/glassPane.css */";Runtime.cachedResources["ui/infobar.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.infobar {\n color: rgb(34, 34, 34);\n display: flex;\n flex: auto;\n border-bottom: 1px solid rgb(171, 171, 171);\n flex-direction: column;\n align-items: stretch;\n position: relative;\n}\n\n.infobar-warning {\n background-color: rgb(253, 242, 192);\n}\n\n.infobar-info {\n background-color: rgb(255, 255, 255);\n}\n\n.infobar-main-row {\n display: flex;\n flex-direction: row;\n flex: auto;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n justify-content: space-between;\n margin-right: 20px;\n min-height: 25px;\n align-items: center;\n padding-left: 4px;\n}\n\n.infobar-main-row > * {\n flex: none;\n padding: 0 3px;\n}\n\n.infobar-main-title {\n flex: auto;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.infobar-details-rows {\n padding: 5px 5px 0 5px;\n}\n\n.infobar-details-row {\n display: flex;\n flex-direction: column;\n line-height: 18px;\n padding-bottom: 6px;\n}\n\n.close-button {\n position: absolute;\n top: 5px;\n right: 6px;\n}\n\n.infobar-toggle {\n color: hsl(214, 92%, 50%);\n cursor: pointer;\n}\n\n.infobar-toggle:hover {\n color: hsl(214, 92%, 30%);\n}\n\n.info-icon {\n -webkit-mask-image: url(Images/ic_info_black_18dp.svg);\n background-color: hsl(214, 92%, 50%);\n}\n\n.warning-icon {\n -webkit-mask-image: url(Images/ic_warning_black_18dp.svg);\n background-color: hsl(44, 92%, 50%);\n}\n\n.icon {\n -webkit-mask-size: 18px 18px;\n width: 18px;\n height: 19px;\n}\n\n/*# sourceURL=ui/infobar.css */";Runtime.cachedResources["ui/inlineButton.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n display: inline-block;\n border: 1px solid #ddd;\n position: relative;\n top: 7px;\n margin: 2px;\n background-color: #f3f3f3;\n}\n\n:host > * {\n position: relative;\n left: -2px;\n width: 28px;\n height: 26px;\n}\n/*# sourceURL=ui/inlineButton.css */";Runtime.cachedResources["ui/inspectorCommon.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n* {\n /* This is required for correct sizing of flex items because we rely\n * on an old version of the flexbox spec.\n * Longer-term we should remove this, see crbug.com/473625 */\n min-width: 0;\n min-height: 0;\n}\n\n:host-context(.platform-mac) .monospace,\n:host-context(.platform-mac) .source-code,\n.platform-mac .monospace,\n.platform-mac .source-code {\n font-size: 11px !important;\n font-family: Menlo, monospace;\n}\n\n:host-context(.platform-windows) .monospace,\n:host-context(.platform-windows) .source-code,\n.platform-windows .monospace,\n.platform-windows .source-code {\n font-size: 12px !important;\n font-family: Consolas, Lucida Console, Courier New, monospace;\n}\n\n:host-context(.platform-linux) .monospace,\n:host-context(.platform-linux) .source-code,\n.platform-linux .monospace,\n.platform-linux .source-code {\n font-size: 11px !important;\n font-family: dejavu sans mono, monospace;\n}\n\n.source-code {\n font-family: monospace;\n font-size: 11px !important;\n white-space: pre-wrap;\n}\n\n* {\n box-sizing: border-box;\n}\n\n:focus {\n outline-width: 0;\n}\n\nimg {\n -webkit-user-drag: none;\n}\n\niframe,\na img {\n border: none;\n}\n\n.fill {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n}\n\niframe.fill {\n width: 100%;\n height: 100%;\n}\n\n.widget {\n position: relative;\n flex: auto;\n contain: layout style;\n}\n\n.hbox {\n display: flex;\n flex-direction: row !important;\n position: relative;\n}\n\n.vbox {\n display: flex;\n flex-direction: column !important;\n position: relative;\n}\n\n.view-container > .toolbar {\n border-bottom: 1px solid #eee;\n}\n\n.flex-auto {\n flex: auto;\n}\n\n.flex-auto-important {\n flex: auto !important;\n}\n\n.flex-none {\n flex: none;\n}\n\n.flex-centered {\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.overflow-auto {\n overflow: auto;\n}\n\niframe.widget {\n position: absolute;\n width: 100%;\n height: 100%;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n}\n\n.hidden {\n display: none !important;\n}\n\n.monospace {\n font-size: 10px !important;\n font-family: monospace;\n}\n\n.highlighted-search-result {\n border-radius: 1px;\n padding: 1px;\n margin: -1px;\n background-color: rgba(255, 255, 0, 0.8);\n}\n\n.-theme-with-dark-background .highlighted-search-result,\n:host-context(.-theme-with-dark-background) .highlighted-search-result {\n background-color: hsl(133, 100%, 30%);\n color: #333;\n}\n\n.link {\n cursor: pointer;\n text-decoration: underline;\n color: rgb(17, 85, 204);\n}\n\nbutton,\ninput,\nselect {\n font-family: inherit;\n font-size: inherit;\n color: inherit;\n}\n\ninput {\n background-color: white;\n}\n\n:host-context(.-theme-with-dark-background) input[type=\"checkbox\"]::not(.-theme-preserve) {\n -webkit-filter: invert(80%);\n}\n\n.harmony-input:not([type]),\n.harmony-input[type=number],\n.harmony-input[type=text] {\n padding: 3px 6px;\n border: 1px solid rgba(0, 0, 0, 0.2);\n border-radius: 2px;\n height: 24px;\n}\n\n.harmony-input:not([type]):not(.error-input):not(:invalid):focus,\n.harmony-input[type=number]:not(.error-input):not(:invalid):focus,\n.harmony-input[type=text]:not(.error-input):not(:invalid):focus {\n box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.4);\n border-color: transparent;\n}\n\n.highlighted-search-result.current-search-result {\n border-radius: 1px;\n padding: 1px;\n margin: -1px;\n background-color: rgba(255, 127, 0, 0.8);\n}\n\n.dimmed {\n opacity: 0.6;\n}\n\n.editing {\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2),\n 0 2px 4px rgba(0, 0, 0, 0.2),\n 0 2px 6px rgba(0, 0, 0, 0.1);\n background-color: white;\n text-overflow: clip !important;\n padding-left: 2px;\n margin-left: -2px;\n padding-right: 2px;\n margin-right: -2px;\n margin-bottom: -1px;\n padding-bottom: 1px;\n opacity: 1.0 !important;\n}\n\n.editing,\n.editing * {\n color: #222 !important;\n text-decoration: none !important;\n}\n\n.harmony-input:not([type]).error-input,\n.harmony-input[type=number].error-input,\n.harmony-input[type=text].error-input,\n.harmony-input:not([type]):invalid,\n.harmony-input[type=number]:invalid,\n.harmony-input[type=text]:invalid {\n border-color: #C53929;\n}\n\n.harmony-input:not([type]).error-input:focus,\n.harmony-input[type=number].error-input:focus,\n.harmony-input[type=text].error-input:focus,\n.harmony-input:not([type]):invalid:focus,\n.harmony-input[type=number]:invalid:focus,\n.harmony-input[type=text]:invalid:focus {\n border-color: transparent;\n box-shadow: 0 0 0 2px rgba(197, 57, 41, 0.4);\n}\n\n.chrome-select {\n -webkit-appearance: none;\n -webkit-user-select: none;\n border: 1px solid rgba(0, 0, 0, 0.2);\n border-radius: 2px;\n color: #333;\n font: inherit;\n margin: 0;\n outline: none;\n padding-right: 20px;\n padding-left: 6px;\n background-image: -webkit-image-set(url(Images/chromeSelect.png) 1x, url(Images/chromeSelect_2x.png) 2x);\n background-color: hsl(0, 0%, 98%);\n background-position: right center;\n background-repeat: no-repeat;\n min-height: 24px;\n min-width: 80px;\n background-size: 15px;\n}\n\n.chrome-select:enabled:active,\n.chrome-select:enabled:focus,\n.chrome-select:enabled:hover {\n background-color: hsl(0, 0%, 96%);\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);\n}\n\n.chrome-select:enabled:active {\n background-color: #f2f2f2;\n}\n\n.chrome-select:enabled:focus {\n border-color: transparent;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1), 0 0 0 2px rgba(66, 133, 244, 0.4);\n}\n\n.chrome-select:disabled {\n opacity: 0.38;\n}\n\n.chrome-select optgroup,\n.chrome-select option {\n background-color: #EEEEEE;\n color: #222;\n}\n\n:not(.platform-mac).-theme-with-dark-background ::-webkit-scrollbar,\n:host-context(:not(.platform-mac).-theme-with-dark-background) ::-webkit-scrollbar {\n width: 14px;\n}\n\n:not(.platform-mac).-theme-with-dark-background ::-webkit-scrollbar-track,\n:host-context(:not(.platform-mac).-theme-with-dark-background) ::-webkit-scrollbar-track {\n -webkit-box-shadow: inset 0 0 1px rgba(255,255,255,0.3);\n}\n\n:not(.platform-mac).-theme-with-dark-background ::-webkit-scrollbar-thumb,\n:host-context(:not(.platform-mac).-theme-with-dark-background) ::-webkit-scrollbar-thumb {\n border-radius: 2px;\n background-color: #333;\n -webkit-box-shadow: inset 0 0 1px rgba(255,255,255,0.5);\n}\n\n.gray-info-message {\n text-align: center;\n font-style: italic;\n padding: 6px;\n color: #888;\n white-space: nowrap;\n}\n\nlabel[is=dt-icon-label] {\n flex: none;\n}\n\n.full-widget-dimmed-banner a {\n color: inherit;\n}\n\n.full-widget-dimmed-banner {\n color: #777;\n background-color: white;\n display: flex;\n justify-content: center;\n align-items: center;\n text-align: center;\n padding: 20px;\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n font-size: 13px;\n overflow: auto;\n z-index: 500;\n}\n\n[is=ui-icon] {\n display: inline-block;\n flex-shrink: 0;\n}\n\n.-theme-with-dark-background [is=ui-icon].icon-invert,\n:host-context(.-theme-with-dark-background) [is=ui-icon].icon-invert {\n filter: invert(80%) hue-rotate(180deg);\n}\n\n[is=ui-icon].icon-mask {\n background-color: rgb(110, 110, 110);\n -webkit-mask-position: var(--spritesheet-position);\n}\n\n[is=ui-icon]:not(.icon-mask) {\n background-position: var(--spritesheet-position);\n}\n\n.spritesheet-smallicons:not(.icon-mask) {\n background-image: -webkit-image-set(url(Images/smallIcons.png) 1x, url(Images/smallIcons_2x.png) 2x);\n}\n\n.spritesheet-smallicons.icon-mask {\n -webkit-mask-image: -webkit-image-set(url(Images/smallIcons.png) 1x, url(Images/smallIcons_2x.png) 2x);\n}\n\n.spritesheet-largeicons:not(.icon-mask) {\n background-image: -webkit-image-set(url(Images/largeIcons.png) 1x, url(Images/largeIcons_2x.png) 2x);\n}\n\n.spritesheet-largeicons.icon-mask {\n -webkit-mask-image: -webkit-image-set(url(Images/largeIcons.png) 1x, url(Images/largeIcons_2x.png) 2x);\n}\n\n.spritesheet-mediumicons:not(.icon-mask) {\n background-image: -webkit-image-set(url(Images/mediumIcons.png) 1x, url(Images/mediumIcons_2x.png) 2x);\n}\n\n.spritesheet-mediumicons.icon-mask {\n -webkit-mask-image: -webkit-image-set(url(Images/mediumIcons.png) 1x, url(Images/mediumIcons_2x.png) 2x);\n}\n\n.spritesheet-arrowicons {\n background-image: url(Images/popoverArrows.png);\n}\n\n.force-white-icons [is=ui-icon].spritesheet-smallicons, [is=ui-icon].force-white-icons.spritesheet-smallicons {\n -webkit-mask-image: -webkit-image-set(url(Images/smallIcons.png) 1x, url(Images/smallIcons_2x.png) 2x);\n -webkit-mask-position: var(--spritesheet-position);\n background: white !important;\n}\n\n.force-white-icons [is=ui-icon].spritesheet-largeicons, [is=ui-icon].force-white-icons.spritesheet-largeicons {\n -webkit-mask-image: -webkit-image-set(url(Images/largeIcons.png) 1x, url(Images/largeIcons_2x.png) 2x);\n -webkit-mask-position: var(--spritesheet-position);\n background: white !important;\n}\n\n.force-white-icons [is=ui-icon].spritesheet-mediumicons, [is=ui-icon].force-white-icons.spritesheet-mediumicons {\n -webkit-mask-image: -webkit-image-set(url(Images/mediumIcons.png) 1x, url(Images/mediumIcons_2x.png) 2x);\n -webkit-mask-position: var(--spritesheet-position);\n background: white !important;\n}\n\n/*# sourceURL=ui/inspectorCommon.css */";Runtime.cachedResources["ui/inspectorStyle.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nhtml {\n height: 100%;\n overflow: hidden;\n}\n\nbody {\n height: 100%;\n width: 100%;\n position: relative;\n overflow: hidden;\n margin: 0;\n cursor: default;\n font-family: '.SFNSDisplay-Regular', 'Helvetica Neue', 'Lucida Grande', sans-serif;\n font-size: 12px;\n tab-size: 4;\n -webkit-user-select: none;\n color: #222;\n}\n\n.platform-linux {\n color: rgb(48, 57, 66);\n font-family: Roboto, Ubuntu, Arial, sans-serif;\n}\n\n.platform-mac {\n color: rgb(48, 57, 66);\n font-family: '.SFNSDisplay-Regular', 'Helvetica Neue', 'Lucida Grande', sans-serif;\n}\n\n.platform-windows {\n font-family: 'Segoe UI', Tahoma, sans-serif;\n}\n\n.panel {\n display: flex;\n overflow: hidden;\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 0;\n background-color: white;\n}\n\n.panel-sidebar {\n overflow-x: hidden;\n background-color: #f3f3f3;\n}\n\niframe.extension {\n flex: auto;\n width: 100%;\n height: 100%;\n}\n\niframe.panel.extension {\n display: block;\n height: 100%;\n}\n\n/*# sourceURL=ui/inspectorStyle.css */";Runtime.cachedResources["ui/inspectorSyntaxHighlight.css"]="/*\n * Copyright (C) 2009 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n.cm-js-keyword {color: hsl(310, 86%, 36%);}\n.cm-js-number {color: hsl(248, 100%, 41%);}\n.cm-js-comment {color: hsl(120, 100%, 23%) !important; font-style: italic;}\n.cm-js-string {color: hsl(1, 80%, 43%) !important;}\n.cm-js-string-2 {color: hsl(1, 99%, 39%) !important;}\n.cm-js-atom {color: hsl(310, 86%, 36%);}\n.cm-js-def {color: hsl(240, 73%, 38%);}\n.cm-js-operator {color: hsl(27, 100%, 30%);}\n.cm-js-meta {color: hsl(27, 100%, 30%);}\n.cm-js-variable-2 {color: hsl(240, 73%, 38%);}\n\n.cm-css-keyword { color: rgb(7, 144, 154);}\n.cm-css-number {color: rgb(50, 0, 255);}\n.cm-css-comment {color: rgb(0, 116, 0) !important;}\n.cm-css-def {color: rgb(200, 0, 0);}\n.cm-css-meta {color: rgb(200, 0, 0);}\n.cm-css-atom {color: rgb(7, 144, 154);}\n.cm-css-string {color: rgb(7, 144, 154) !important;}\n.cm-css-string-2 {color: rgb(7, 144, 154) !important;}\n.cm-css-link {color: rgb(7, 144, 154) !important;}\n.cm-css-variable {color: rgb(200, 0, 0);}\n.cm-css-variable-2 {color: rgb(0, 0, 128);}\n.cm-css-property, .webkit-css-property {color: rgb(200, 0, 0);}\n\n.cm-xml-meta {color: rgb(192, 192, 192);}\n.cm-xml-comment {color: rgb(35, 110, 37) !important;}\n.cm-xml-string {color: rgb(26, 26, 166) !important;}\n.cm-xml-tag {color: rgb(136, 18, 128);}\n.cm-xml-attribute {color: rgb(153, 69, 0);}\n.cm-xml-link {color: #00e !important;}\n\n.webkit-html-comment {\n /* Keep this in sync with view-source.css (.webkit-html-comment) */\n color: rgb(35, 110, 37);\n}\n\n.webkit-html-tag {\n color: rgb(168, 148, 166);\n}\n\n.webkit-html-tag-name, .webkit-html-close-tag-name {\n /* Keep this in sync with view-source.css (.webkit-html-tag) */\n color: rgb(136, 18, 128);\n}\n\n.webkit-html-pseudo-element {\n /* This one is non-standard. */\n color: brown;\n}\n\n.webkit-html-js-node,\n.webkit-html-css-node {\n white-space: pre-wrap;\n}\n\n.webkit-html-text-node {\n unicode-bidi: -webkit-isolate;\n}\n\n.webkit-html-entity-value {\n /* This one is non-standard. */\n background-color: rgba(0, 0, 0, 0.15);\n unicode-bidi: -webkit-isolate;\n}\n\n.webkit-html-doctype {\n /* Keep this in sync with view-source.css (.webkit-html-doctype) */\n color: rgb(192, 192, 192);\n}\n\n.webkit-html-attribute-name {\n /* Keep this in sync with view-source.css (.webkit-html-attribute-name) */\n color: rgb(153, 69, 0);\n unicode-bidi: -webkit-isolate;\n}\n\n.webkit-html-attribute-value {\n /* Keep this in sync with view-source.css (.webkit-html-attribute-value) */\n color: rgb(26, 26, 166);\n unicode-bidi: -webkit-isolate;\n}\n\n.devtools-link {\n color: rgb(17, 85, 204);\n text-decoration: underline;\n}\n\n.devtools-link [is=ui-icon] {\n vertical-align: middle;\n}\n\n.devtools-link:not(.devtools-link-prevent-click) {\n cursor: pointer;\n}\n\n.-theme-with-dark-background .devtools-link,\n:host-context(.-theme-with-dark-background) .devtools-link {\n color: hsl(0, 0%, 67%);\n}\n\n.webkit-html-end-of-file {\n /* Keep this in sync with view-source.css (.webkit-html-end-of-file) */\n color: rgb(255, 0, 0);\n font-weight: bold;\n}\n\n/*# sourceURL=ui/inspectorSyntaxHighlight.css */";Runtime.cachedResources["ui/inspectorSyntaxHighlightDark.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.cm-js-atom{color:rgb(161, 247, 181);}\n.cm-js-attribute{color:rgb(97, 148, 198);}\n.cm-js-builtin{color:rgb(159, 180, 214);}\n.cm-js-comment{color:rgb(116, 116, 116) !important;}\n.cm-js-def{color:rgb(93, 176, 215);}\n.cm-js-keyword{color:rgb(154, 127, 213);}\n.cm-js-link{color:rgb(159, 180, 214);}\n.cm-js-meta{color:rgb(221, 251, 85);}\n.cm-js-number{color:rgb(161, 247, 181);}\n.cm-js-operator{color:rgb(210, 192, 87);}\n.cm-js-property{color:rgb(210, 192, 87);}\n.cm-js-string{color:rgb(242, 139, 84) !important;}\n.cm-js-string-2{color:rgb(242, 139, 84) !important;}\n.cm-js-tag{color:rgb(93, 176, 215);}\n.cm-js-variable{color:rgb(217, 217, 217);}\n.cm-js-variable-2{color:rgb(217, 217, 217);}\n.cm-atom{color:rgb(161, 247, 181);}\n.cm-comment{color:rgb(116, 116, 116) !important;}\n.cm-variable{color:rgb(217, 217, 217);}\n.cm-string{color:rgb(242, 139, 84) !important;}\n.cm-keyword{color:rgb(154, 127, 213);}\n.cm-number{color:rgb(161, 247, 181);}\n.cm-operator{color:rgb(210, 192, 87);}\n.cm-css-atom{color:rgb(217, 217, 217);}\n.cm-css-builtin{color:rgb(255, 163, 79);}\n.cm-css-def{color:rgb(255, 163, 79);}\n.cm-css-comment{color:rgb(116, 116, 116) !important;}\n.cm-css-meta{color:rgb(132, 240, 255);}\n.cm-css-number{color:rgb(217, 217, 217);}\n.cm-css-operator{color:rgb(217, 217, 217);}\n.cm-css-property{color:rgb(132, 240, 255);}\n.cm-css-qualifier{color:rgb(255, 163, 79);}\n.cm-css-string{color:rgb(231, 194, 111) !important;}\n.cm-css-string-2{color:rgb(217, 217, 217) !important;}\n.cm-css-tag{color:rgb(255, 163, 79);}\n.cm-css-variable{color:rgb(255, 163, 79);}\n.cm-css-variable-2{color:rgb(255, 163, 79);}\n.cm-xml-comment{color:rgb(137, 137, 137) !important;}\n.cm-xml-error{color:rgb(198, 95, 95);}\n.cm-xml-string{color:rgb(242, 151, 102) !important;}\n.cm-xml-tag{color:rgb(93, 176, 215);}\n.cm-xml-attribute{color:rgb(155, 187, 220);}\n.cm-xml-link{color:rgb(231, 194, 111);}\n\n.webkit-html-attribute-name{color:rgb(155, 187, 220);}\n.webkit-html-attribute-value{color:rgb(242, 151, 102);}\n.webkit-html-comment{color:rgb(137, 137, 137) !important;}\n.devtools-link{color:rgb(231, 194, 111);}\n.webkit-html-tag{color:rgb(93, 176, 215);}\n.webkit-html-tag-name{color:rgb(93, 176, 215);}\n.webkit-html-close-tag-name{color:rgb(93, 176, 215);}\n.webkit-html-text-node{color:rgb(207, 208, 208);}\n.webkit-html-css-node{color:rgb(207, 208, 208);}\n.webkit-html-js-node{color:rgb(207, 208, 208);}\n.webkit-html-pseudo-element{color:rgb(93, 175, 215);}\n.webkit-css-selector{color:rgb(255, 163, 79);}\n.webkit-css-at-rule{color:rgb(188, 164, 197);}\n.webkit-css-color{color:rgb(255, 163, 79);}\n.webkit-css-comment{color:rgb(116, 116, 116);}\n.webkit-css-important{color:rgb(255, 26, 26);}\n.webkit-css-keyword{color:rgb(255, 163, 79);}\n.webkit-css-number{color:rgb(217, 217, 217);}\n.webkit-css-property{color: rgb(53, 212, 199);}\n.webkit-css-string{color:rgb(231, 194, 111) !important;}\n.webkit-css-url{color:rgb(231, 194, 111);}\n\n/*# sourceURL=ui/inspectorSyntaxHighlightDark.css */";Runtime.cachedResources["ui/inspectorViewTabbedPane.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tabbed-pane-header-tab,\n.tabbed-pane-header-tab.selected {\n height: 26px;\n margin: 0;\n background: #f3f3f3;\n border: none;\n border-left: 2px solid transparent;\n border-right: 2px solid transparent;\n}\n\n.tabbed-pane-header-tab.selected {\n border-width: 0 2px 0 2px;\n}\n\n.tabbed-pane-header-contents {\n margin-left: 0;\n}\n\n.tabbed-pane-left-toolbar {\n margin-right: 0 !important;\n}\n\n/*# sourceURL=ui/inspectorViewTabbedPane.css */";Runtime.cachedResources["ui/listWidget.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.list {\n flex: auto 0 1;\n overflow-y: auto;\n border: 1px solid rgb(231, 231, 231);\n flex-direction: column;\n}\n\n.list-separator {\n background: rgb(231, 231, 231);\n height: 1px;\n}\n\n.list-item {\n flex: none;\n min-height: 30px;\n display: flex;\n align-items: center;\n position: relative;\n}\n\n.list-item:hover {\n background: hsl(0, 0%, 96%);\n}\n\n.controls-container {\n display: flex;\n flex-direction: row;\n justify-content: flex-end;\n align-items: stretch;\n pointer-events: none;\n}\n\n.controls-gradient {\n flex: 0 1 50px;\n}\n\n.list-item:hover .controls-gradient {\n background-image: linear-gradient(90deg, transparent, hsl(0, 0%, 96%));\n}\n\n.controls-buttons {\n flex: none;\n display: flex;\n flex-direction: row;\n align-items: center;\n pointer-events: auto;\n visibility: hidden;\n}\n\n.list-item:hover .controls-buttons {\n background-color: hsl(0, 0%, 96%);\n visibility: visible;\n}\n\n.editor-container {\n display: flex;\n flex-direction: column;\n align-items: stretch;\n flex: none;\n background: hsl(0, 0%, 96%);\n overflow: hidden;\n}\n\n.editor-content {\n flex: auto;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n}\n\n.editor-buttons {\n flex: none;\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: flex-start;\n padding: 5px;\n}\n\n.editor-buttons > button {\n flex: none;\n margin-right: 10px;\n}\n\n.editor-content input {\n margin-right: 10px;\n}\n\n.editor-content input.error-input {\n background-color: white;\n}\n\n/*# sourceURL=ui/listWidget.css */";Runtime.cachedResources["ui/panelEnablerView.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.panel-enabler-view {\n background-color: white;\n font-size: 13px;\n text-align: center;\n overflow-x: hidden;\n overflow-y: overlay;\n flex: auto;\n display: flex;\n}\n\n.panel-enabler-view h1 {\n color: rgb(110, 116, 128);\n font-size: 16px;\n line-height: 20px;\n font-weight: normal;\n margin-top: 0;\n}\n\n.panel-enabler-view img {\n height: 100%;\n min-height: 200px;\n max-width: 100%;\n top: 0;\n bottom: 0;\n padding: 20px 0 20px 20px;\n margin: auto;\n vertical-align: middle;\n}\n\n.panel-enabler-view img.hidden {\n display: initial !important;\n width: 0;\n}\n\n.panel-enabler-view .flexible-space {\n -webkit-flex: 1;\n}\n\n.panel-enabler-view form {\n display: inline-block;\n vertical-align: middle;\n width: 330px;\n margin: 0;\n padding: 15px;\n white-space: normal;\n}\n\n.panel-enabler-view label {\n position: relative;\n display: block;\n text-align: left;\n word-break: break-word;\n margin: 0 0 5px 20px;\n}\n\n.panel-enabler-view label:only-of-type {\n display: none;\n}\n\n/*# sourceURL=ui/panelEnablerView.css */";Runtime.cachedResources["ui/popover.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n display: flex;\n background: white;\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2), 0 2px 4px rgba(0, 0, 0, 0.2), 0 2px 6px rgba(0, 0, 0, 0.1);\n border-radius: 2px;\n overflow: auto;\n -webkit-user-select: text;\n line-height: 11px;\n}\n\n.widget.has-padding {\n padding: 6px;\n}\n\n/*# sourceURL=ui/popover.css */";Runtime.cachedResources["ui/progressIndicator.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.progress-indicator-shadow-stop-button {\n background-color: rgb(216, 0, 0) !important;\n border: 0;\n width: 10px;\n height: 12px;\n border-radius: 2px;\n}\n\n.progress-indicator-shadow-container {\n display: flex;\n flex: 1 0 auto;\n align-items: center;\n}\n\n.progress-indicator-shadow-container .title {\n text-overflow: ellipsis;\n overflow: hidden;\n max-width: 150px;\n margin-right: 2px;\n color: #777;\n}\n\n.progress-indicator-shadow-container progress {\n flex: auto;\n margin: 0 2px;\n width: 100px\n}\n\n/*# sourceURL=ui/progressIndicator.css */";Runtime.cachedResources["ui/radioButton.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n::content .dt-radio-button {\n height: 17px;\n width: 17px;\n min-width: 17px;\n border: 1px solid rgb(165, 165, 165);\n background-image: linear-gradient(to bottom, rgb(252, 252, 252), rgb(223, 223, 223));\n border-radius: 8px;\n -webkit-appearance: none;\n vertical-align: middle;\n margin: 0 5px 5px 0;\n}\n\n::content .dt-radio-button:active:not(:disabled) {\n background-image: linear-gradient(to bottom, rgb(194, 194, 194), rgb(239, 239, 239));\n}\n\n::content .dt-radio-button:checked {\n background: url(Images/radioDot.png) center no-repeat,\n linear-gradient(to bottom, rgb(252, 252, 252), rgb(223, 223, 223));\n}\n\n::content .dt-radio-button:checked:active {\n background: url(Images/radioDot.png) center no-repeat,\n linear-gradient(to bottom, rgb(194, 194, 194), rgb(239, 239, 239));\n}\n\n/*# sourceURL=ui/radioButton.css */";Runtime.cachedResources["ui/reportView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n background-color: #f9f9f9;\n}\n\n.report-content-box {\n background-color: white;\n white-space: nowrap;\n overflow: auto;\n}\n\n.report-header {\n border-bottom: 1px solid rgb(230, 230, 230);\n padding: 12px 24px;\n}\n\n.report-header .toolbar {\n margin-bottom: -8px;\n}\n\n.report-header .toolbar {\n margin-top: 5px;\n margin-left: -8px;\n}\n\n.report-title {\n font-size: 15px;\n}\n\n.report-url, .report-subtitle {\n font-size: 12px;\n margin-top: 10px;\n}\n\n.report-section {\n display: flex;\n padding: 12px;\n border-bottom: 1px solid rgb(230, 230, 230);\n flex-direction: column;\n}\n\n.report-section-header {\n margin-left: 18px;\n display: flex;\n flex-direction: row;\n align-items: center;\n}\n\n.report-section-title {\n flex: auto;\n text-overflow: ellipsis;\n overflow: hidden;\n font-weight: bold;\n color: #555;\n}\n\n.report-field {\n margin-top: 8px;\n display: flex;\n line-height: 28px;\n}\n\n.report-row {\n margin: 10px 0 2px 18px;\n}\n\n.report-field-name {\n color: #888;\n flex: 0 0 128px;\n text-align: right;\n padding: 0 6px;\n white-space: pre;\n}\n\n.report-field-value {\n flex: auto;\n padding: 0 6px;\n white-space: pre;\n}\n\n.report-field-value-subtitle {\n color: #888;\n line-height: 14px;\n}\n\n/*# sourceURL=ui/reportView.css */";Runtime.cachedResources["ui/rootView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.root-view {\n background-color: white;\n overflow: hidden;\n position: absolute !important;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n}\n\n/*# sourceURL=ui/rootView.css */";Runtime.cachedResources["ui/searchableView.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.search-bar {\n flex: 0 0 29px;\n background-color: #eee;\n border-top: 1px solid #ccc;\n display: flex;\n overflow: hidden;\n z-index: 0;\n}\n\n.search-bar.replaceable {\n flex: 0 0 55px;\n}\n\n.search-replace {\n -webkit-appearance: none;\n border: 0;\n padding: 0 3px;\n margin: 0;\n flex: 1;\n}\n\n.search-replace:focus {\n outline: none;\n}\n\n.toolbar-replace-checkbox {\n margin-top: 4px;\n margin-right: 2px;\n display: block;\n}\n\n.toolbar-search {\n display: flex;\n width: 100%;\n}\n\n.toolbar-search > div {\n margin: 0px 2px;\n flex-shrink: 0;\n}\n\n.toolbar-search-inputs {\n flex-grow: 1;\n min-width: 150px;\n}\n\n.toolbar-search-navigation-controls {\n align-self: stretch;\n}\n\n.toolbar-search-navigation {\n display: inline-block;\n width: 20px;\n height: 20px;\n background-repeat: no-repeat;\n background-position: 4px 7px;\n border-left: 1px solid rgb(170, 170, 170);\n opacity: 0.3;\n}\n\n.toolbar-search-navigation.enabled {\n opacity: 1.0;\n}\n\n.toolbar-search button.search-action-button {\n font-weight: 400;\n height: 22px;\n width: 87px;\n}\n\n.toolbar-search-control {\n display: -webkit-flex;\n position: relative;\n background-color: white;\n}\n\n.toolbar-search-buttons {\n flex-basis: 182px;\n}\n\n.toolbar-replace-control,\n#search-input-field {\n margin-top: 1px;\n line-height: 17px;\n}\n\n.toolbar-search-control, .toolbar-replace-control {\n border: 1px solid rgb(163, 163, 163);\n height: 22px;\n border-radius: 2px;\n width: 100%;\n margin-top: 2px;\n margin-bottom: 2px;\n}\n\n.toolbar-search-navigation.enabled:active {\n background-position: 4px 7px, 0 0;\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-prev {\n background-image: url(Images/searchPrev.png);\n border-left: 1px solid rgb(163, 163, 163);\n}\n\n:host-context(.-theme-with-dark-background) .toolbar-search-navigation {\n -webkit-filter: invert(90%);\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-prev.enabled:active {\n background-image: url(Images/searchPrev.png), #f2f2f2;\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-next {\n background-image: url(Images/searchNext.png);\n border-left: 1px solid rgb(230, 230, 230);\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-next.enabled:active {\n background-image: url(Images/searchNext.png), #f2f2f2;\n}\n\n.search-results-matches {\n display: inline-block;\n text-align: right;\n padding: 0 4px;\n color: rgb(165, 165, 165);\n align-self: center;\n}\n\n/*# sourceURL=ui/searchableView.css */";Runtime.cachedResources["ui/viewContainers.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.sidebar-hidden-override {\n display: none !important;\n}\n\n.expandable-view-title {\n display: flex;\n align-items: center;\n background-color: #f3f3f3;\n height: 22px;\n padding: 0 5px;\n border-top: 1px solid #dadada;\n white-space: nowrap;\n overflow: hidden;\n position: relative;\n border-bottom: 1px solid transparent;\n}\n\n.expandable-view-title.expanded,\n.expandable-view-title:last-child {\n border-bottom: 1px solid #ddd;\n}\n\n.expandable-view-title .toolbar {\n margin-top: -3px;\n}\n\n.expandable-view-title:not(.expanded) .toolbar {\n display: none;\n}\n\n.title-expand-icon {\n margin-right: 2px;\n margin-bottom: -2px;\n}\n\n.expandable-view-title > .toolbar {\n position: absolute;\n right: 0;\n top: 0;\n}\n\n.sidebar-pane-container .toolbar {\n border-bottom: 1px solid #eee;\n}\n\n.sidebar-pane-container .toolbar > * {\n pointer-events: auto;\n}\n\n/*# sourceURL=ui/viewContainers.css */";Runtime.cachedResources["ui/slider.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.dt-range-input {\n -webkit-appearance: none;\n margin: 0;\n padding: 0;\n height: 10px;\n width: 88px;\n outline: none;\n background: none;\n}\n\n.dt-range-input::-webkit-slider-thumb, -theme-preserve {\n -webkit-appearance: none;\n margin: 0;\n padding: 0;\n border: 0;\n width: 12px;\n height: 12px;\n margin-top: -5px;\n border-radius: 50%;\n background-color: #4285F4;\n}\n\n.dt-range-input::-webkit-slider-runnable-track {\n -webkit-appearance: none;\n margin: 0;\n padding: 0;\n width: 100%;\n height: 2px;\n background-color: rgba(0, 0, 0, 0.26);\n}\n\n.dt-range-input:focus::-webkit-slider-thumb, -theme-preserve {\n box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.4);\n}\n\n.dt-range-input:disabled::-webkit-slider-thumb {\n background-color: #bdbdbd;\n}\n\n/*# sourceURL=ui/slider.css */";Runtime.cachedResources["ui/smallBubble.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\ndiv {\n display: inline-block;\n height: 14px;\n vertical-align: middle;\n white-space: nowrap;\n padding: 1px 4px;\n text-align: left;\n font-size: 11px;\n line-height: normal;\n font-weight: bold;\n text-shadow: none;\n color: white;\n margin-top: -1px;\n border-radius: 7px;\n}\n\ndiv.verbose {\n background-color: rgb(0, 0, 255);\n}\n\ndiv.info {\n background-color: rgb(128, 151, 189);\n}\n\ndiv.warning {\n background-color: rgb(232, 164, 0);\n}\n\ndiv.error {\n background-color: rgb(216, 35, 35);\n}\n\n/*# sourceURL=ui/smallBubble.css */";Runtime.cachedResources["ui/softContextMenu.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.soft-context-menu {\n border: 1px solid rgba(196, 196, 196, 0.9);\n border-top: 1px solid rgba(196, 196, 196, 0.5);\n /* NOTE: Keep padding in sync with padding adjustment in SoftContextMenu.js */\n padding: 4px 0 4px 0;\n border-radius: 4px;\n background-color: rgb(240, 240, 240);\n box-shadow: 0 5px 10px rgba(0, 0, 0, 0.25);\n overflow-y: auto;\n min-width: 160px !important;\n}\n\n.soft-context-menu-item {\n display: flex;\n width: 100%;\n line-height: 14px;\n font-size: 12px;\n border-top: 1px solid transparent;\n border-bottom: 1px solid transparent;\n padding: 2px 7px 2px 8px;\n margin: 0 13px 0 0;\n white-space: nowrap;\n}\n\n.soft-context-menu-disabled {\n color: #999;\n pointer-events: none;\n}\n\n.soft-context-menu-separator {\n height: 10px;\n margin: 0 1px;\n}\n\n.soft-context-menu-separator > .separator-line {\n margin: 0;\n height: 5px;\n border-bottom: 1px solid rgb(222, 222, 222);\n pointer-events: none;\n}\n\n.soft-context-menu-item-mouse-over,\n.-theme-selection-color {\n border-top: 1px solid rgb(56, 121, 217);\n border-bottom: 1px solid rgb(56, 121, 217);\n background-color: rgb(56, 121, 217);\n color: white;\n}\n\n:host-context(.platform-mac) .soft-context-menu-item-mouse-over,\n.-theme-selection-color {\n border-top: 1px solid transparent;\n border-bottom: 1px solid transparent;\n background-image: linear-gradient(to right, hsl(214, 81%, 60%), hsl(214, 100%, 56%));\n}\n\n:host-context(.platform-mac) .separator-line {\n border-width: 2px;\n}\n\n.soft-context-menu-item-submenu-arrow {\n color: #222;\n pointer-events: none;\n font-size: 11px;\n flex: 1 1 auto;\n text-align: right;\n}\n\n.soft-context-menu-item-mouse-over .soft-context-menu-item-checkmark {\n color: white;\n}\n\n.soft-context-menu-custom-item {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n flex: auto;\n}\n\n.soft-context-menu-shortcut {\n color: gray;\n pointer-events: none;\n flex: 1 1 auto;\n text-align: right;\n padding-left: 10px;\n}\n\n.soft-context-menu-item-mouse-over .soft-context-menu-shortcut {\n color: inherit;\n}\n\n.checkmark {\n opacity: 0.7;\n pointer-events: none;\n margin: auto 5px auto 0px;\n}\n\n.soft-context-menu-item-mouse-over .checkmark {\n opacity: 1;\n}\n/*# sourceURL=ui/softContextMenu.css */";Runtime.cachedResources["ui/softDropDown.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.item.disabled {\n opacity: 0.5;\n}\n\n.item-list {\n background-color: white;\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05),\n 0 2px 4px rgba(0, 0, 0, 0.2),\n 0 2px 6px rgba(0, 0, 0, 0.1);\n overflow-x: hidden;\n overflow-y: auto;\n width: 100%;\n}\n\n.item.highlighted {\n color: white;\n background-color: rgb(56, 121, 217);\n}\n\n/*# sourceURL=ui/softDropDown.css */";Runtime.cachedResources["ui/softDropDownButton.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n:host {\n height: 26px;\n text-align: left;\n position: relative;\n border: none;\n background: none;\n}\n\n:host([disabled]) {\n opacity: .5;\n}\n\n:host .title {\n padding-right: 5px;\n width: 120px;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n:host([data-keyboard-focus=\"true\"]:focus)::before {\n content: \"\";\n position: absolute;\n top: 2px;\n left: 2px;\n right: 2px;\n bottom: 2px;\n border-radius: 2px;\n background: rgba(0, 0, 0, 0.08);\n}\n\n:host(.warning) {\n background: #ffd7d7 !important;\n}\n\n/*# sourceURL=ui/softDropDownButton.css */";Runtime.cachedResources["ui/splitWidget.css"]="/*\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC.\n * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n:host {\n overflow: hidden;\n}\n\n.shadow-split-widget {\n display: flex;\n overflow: hidden;\n}\n\n.shadow-split-widget-contents {\n display: flex;\n position: relative;\n flex-direction: column;\n contain: layout size style;\n}\n\n.shadow-split-widget-sidebar {\n flex: none;\n}\n\n.shadow-split-widget-main, .shadow-split-widget-sidebar.maximized {\n flex: auto;\n}\n\n.shadow-split-widget.hbox > .shadow-split-widget-resizer {\n position: absolute;\n top: 0;\n bottom: 0;\n width: 6px;\n z-index: 500;\n}\n\n.shadow-split-widget.vbox > .shadow-split-widget-resizer {\n position: absolute;\n left: 0;\n right: 0;\n height: 6px;\n z-index: 500;\n}\n\n.shadow-split-widget.hbox.shadow-split-widget-first-is-sidebar {\n flex-direction: row-reverse !important;\n}\n\n.shadow-split-widget.vbox.shadow-split-widget-first-is-sidebar {\n flex-direction: column-reverse !important;\n}\n\n.shadow-split-widget-resizer-border {\n pointer-events: none;\n}\n\n.shadow-split-widget.vbox > .shadow-split-widget-sidebar.no-default-splitter {\n border: 0 !important;\n}\n\n.shadow-split-widget.vbox > .shadow-split-widget-sidebar:not(.maximized) {\n border: 0;\n border-top: 1px solid rgb(64%, 64%, 64%);\n}\n\n.shadow-split-widget.vbox.shadow-split-widget-first-is-sidebar > .shadow-split-widget-sidebar:not(.maximized) {\n border: 0;\n border-bottom: 1px solid rgb(64%, 64%, 64%);\n}\n\n.shadow-split-widget.hbox > .shadow-split-widget-sidebar:not(.maximized) {\n border: 0;\n border-left: 1px solid rgb(64%, 64%, 64%);\n}\n\n.shadow-split-widget.hbox.shadow-split-widget-first-is-sidebar > .shadow-split-widget-sidebar:not(.maximized) {\n border: 0;\n border-right: 1px solid rgb(64%, 64%, 64%);\n}\n\n/*# sourceURL=ui/splitWidget.css */";Runtime.cachedResources["ui/toolbar.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n flex: none;\n padding: 0 2px;\n}\n\n.toolbar-shadow {\n position: relative;\n white-space: nowrap;\n height: 26px;\n overflow: hidden;\n z-index: 12;\n display: flex;\n flex: none;\n align-items: center;\n}\n\n.toolbar-shadow.wrappable {\n flex-wrap: wrap;\n overflow: visible;\n}\n\n.toolbar-shadow.wrappable-reverse {\n flex-direction: row-reverse;\n}\n\n.toolbar-shadow.toolbar-grow-vertical {\n height: initial;\n}\n\n.toolbar-shadow.vertical {\n flex-direction: column;\n height: auto;\n align-items: flex-start;\n}\n\n.toolbar-item {\n position: relative;\n display: flex;\n background-color: transparent;\n flex: none;\n align-items: center;\n justify-content: center;\n padding: 0;\n height: 26px;\n border: none;\n color: #5a5a5a;\n}\n\n.toolbar-dropdown-arrow {\n background-color: #6D6D6D;\n pointer-events: none;\n flex: none;\n}\n\n/* Toolbar item */\n\n.toolbar-button {\n white-space: nowrap;\n overflow: hidden;\n min-width: 28px;\n background: transparent;\n border-radius: 0;\n}\n\n.toolbar-text {\n margin: 0 5px;\n flex: none;\n color: #5a5a5a;\n}\n\n.toolbar-text:empty {\n margin: 0;\n}\n\n.toolbar-has-dropdown {\n justify-content: space-between;\n padding: 0 3px 0 5px;\n}\n\n.toolbar-has-dropdown .toolbar-text {\n margin: 0 4px 0 0;\n text-overflow: ellipsis;\n flex: auto;\n overflow: hidden;\n text-align: right;\n}\n\n.toolbar-button.dark-text .toolbar-dropdown-arrow {\n background-color: #333;\n}\n\n.toolbar-has-glyph .toolbar-text {\n margin-left: -4px;\n}\n\n.toolbar-button:not(.toolbar-has-glyph):not(.toolbar-has-dropdown):not(.largeicon-menu) {\n font-weight: bold;\n}\n\n.toolbar-render-as-links * {\n font-weight: initial;\n color: rgb(17, 85, 204);\n text-decoration: underline;\n cursor: pointer;\n}\n\n:not(.toolbar-render-as-links) .toolbar-button:not(.toolbar-has-glyph):not(.toolbar-has-dropdown):not(.largeicon-menu):hover {\n background-color: #f3f3f3;\n}\n\n.toolbar-glyph {\n background-color: #5a5a5a;\n flex: none;\n}\n\n/* Button */\n\n.toolbar-button:disabled {\n opacity: 0.5;\n}\n\n.toolbar-button.dark-text .toolbar-text{\n color: #333 !important;\n}\n\n:not(.toolbar-render-as-links) .toolbar-button:enabled:hover:not(:active) .toolbar-glyph {\n background-color: #333;\n}\n\n:not(.toolbar-render-as-links) .toolbar-button:enabled:hover:not(:active) .toolbar-text {\n color: #333;\n}\n\n.toolbar-button.toolbar-state-on .toolbar-glyph,\n.toolbar-blue-on-hover .toolbar-button:not(.toolbar-state-on):enabled:hover:not(:active),\n.-theme-selection-color {\n background-color: hsl(218, 81%, 59%);\n}\n\n.toolbar-button.toolbar-state-on .toolbar-text,\n.-theme-selection-color {\n color: hsl(218, 81%, 59%);\n}\n\n.toolbar-blue-on-hover .toolbar-button:not(.toolbar-state-on):enabled:hover .toolbar-glyph {\n background-color: white;\n}\n\n.toolbar-blue-on-hover .toolbar-button:not(.toolbar-state-on):enabled:hover .toolbar-text {\n color: white;\n}\n\n.toolbar-button.toolbar-state-on:enabled:hover:not(:active) .toolbar-glyph,\n.toolbar-blue-on-hover .toolbar-button:not(.toolbar-state-on):enabled:active:hover,\n.-theme-selection-color {\n background-color: hsl(218, 96%, 54%);\n}\n\n.toolbar-button.toolbar-state-on:enabled:hover:not(:active) .toolbar-text,\n.-theme-selection-color {\n color: hsl(218, 96%, 54%);\n}\n\n.toolbar-toggled-gray .toolbar-button.toolbar-state-on {\n background-color: #f3f3f3 !important;\n}\n\n.toolbar-button.toolbar-state-on.toolbar-toggle-with-red-color .toolbar-glyph,\n.toolbar-button.toolbar-state-off.toolbar-default-with-red-color .toolbar-glyph {\n background-color: rgb(216, 0, 0) !important;\n}\n\n:host-context(.-theme-with-dark-background) .toolbar-button.toolbar-state-on.toolbar-toggle-with-red-color .toolbar-glyph,\n:host-context(.-theme-with-dark-background) .toolbar-button.toolbar-state-off.toolbar-default-with-red-color .toolbar-glyph {\n background-color: hsl(0, 100%, 65%) !important;\n}\n\n\n/* Checkbox */\n\n.toolbar-item.checkbox {\n padding: 0 5px 0 2px;\n}\n\n.toolbar-item.checkbox:hover {\n color: #333;\n}\n\n/* Select */\n\n.toolbar-select-container {\n display: inline-flex;\n flex-shrink: 0;\n margin-right: 6px;\n}\n\nselect.toolbar-item {\n min-width: 38px;\n -webkit-appearance: none;\n border: 0;\n border-radius: 0;\n padding: 0 13px 0 5px;\n margin-right: -10px;\n position: relative;\n height: 22px;\n margin-top: 2px;\n margin-bottom: 2px;\n}\n\nselect.toolbar-item[data-keyboard-focus=\"true\"]:focus {\n background: rgba(0, 0, 0, 0.08);\n border-radius: 2px;\n}\n\nselect.toolbar-item[data-keyboard-focus=\"true\"]:focus > * {\n background: white;\n}\n\n/* Input */\n\n.toolbar-input {\n width: 120px;\n height: 19px;\n padding: 4px 3px 3px 3px;\n margin: 1px 3px;\n background-color: white;\n border: solid 1px #d8d8d8;\n border-radius: 2px;\n min-width: 35px;\n}\n\n.toolbar-input.focused,\n.toolbar-input:hover {\n border: solid 1px rgb(202, 202, 202);\n}\n\n.toolbar-input > input {\n border: none;\n flex-grow: 1;\n}\n\n.toolbar-input-clear-button {\n opacity: 0.7;\n flex-basis: 13px;\n flex-shrink: 0;\n height: 16px;\n}\n\n.toolbar-input-clear-button:hover {\n opacity: 1;\n}\n\n.toolbar-input-empty .toolbar-input-clear-button {\n display: none;\n}\n\n.toolbar-prompt-proxy {\n flex: 1;\n}\n\n.toolbar-input-prompt {\n flex: 1;\n overflow: hidden;\n white-space: nowrap;\n cursor: auto;\n}\n\n/* Separator */\n\n.toolbar-divider {\n background-color: #ccc;\n width: 1px;\n margin: 5px 4px;\n height: 16px;\n}\n\n.toolbar-spacer {\n flex: auto;\n}\n\n/* Long click */\n\n.long-click-glyph {\n position: absolute;\n background-color: #5a5a5a;\n top: 0;\n left: 0;\n}\n\n.toolbar-button.emulate-active {\n background-color: rgb(163, 163, 163);\n}\n\n.toolbar-button[data-keyboard-focus=\"true\"]:focus::after {\n position: absolute;\n top: 2px;\n bottom: 2px;\n left: 2px;\n right: 2px;\n background-color: rgba(0, 0, 0, 0.08);\n border-radius: 2px;\n content: \"\";\n}\n\n.toolbar-shadow.floating {\n flex-direction: column;\n height: auto;\n background-color: white;\n border: 1px solid #ccc;\n margin-top: -1px;\n width: 28px;\n left: -2px;\n}\n\n/*# sourceURL=ui/toolbar.css */";Runtime.cachedResources["ui/suggestBox.css"]="/*\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n:host {\n display: flex;\n flex: auto;\n}\n\n.suggest-box {\n flex: auto;\n background-color: #FFFFFF;\n pointer-events: auto;\n margin-left: -3px;\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05),\n 0 2px 4px rgba(0, 0, 0, 0.2),\n 0 2px 6px rgba(0, 0, 0, 0.1);\n overflow-x: hidden;\n}\n\n.suggest-box-content-item {\n padding: 1px 0 1px 1px;\n margin: 0;\n border: 1px solid transparent;\n white-space: nowrap;\n display: flex;\n}\n\n.suggest-box-content-item.secondary {\n background-color: #f9f9f9;\n}\n\n.suggestion-title {\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.suggestion-subtitle {\n flex: auto;\n text-align: right;\n color: #999;\n margin-right: 3px;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.suggestion-icon {\n user-select: none;\n align-self: center;\n flex-shrink: 0;\n}\n\n.suggest-box-content-item .query {\n font-weight: bold;\n}\n\n.suggest-box-content-item .spacer {\n display: inline-block;\n width: 20px;\n}\n\n.suggest-box-content-item.selected {\n background-color: rgb(56, 121, 217);\n}\n\n.suggest-box-content-item.selected > span {\n color: #fff;\n}\n\n.default-selection-is-dimmed .suggest-box-content-item.selected {\n background-color: #E0E0E0;\n}\n\n.default-selection-is-dimmed .suggest-box-content-item.selected > span {\n color: inherit;\n}\n\n.user-has-interacted .suggest-box-content-item.selected {\n background-color: rgb(56, 121, 217);\n}\n\n.user-has-interacted .suggest-box-content-item.selected > span {\n color: #FFF;\n}\n\n.suggest-box-content-item:hover:not(.selected) {\n background-color: rgba(56, 121, 217, 0.1);\n}\n\n/*# sourceURL=ui/suggestBox.css */";Runtime.cachedResources["ui/tabbedPane.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC.\n * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.tabbed-pane {\n flex: auto;\n overflow: hidden;\n}\n\n.tabbed-pane-content {\n position: relative;\n overflow: auto;\n flex: auto;\n display: flex;\n flex-direction: column;\n}\n\n.tabbed-pane-content.has-no-tabs {\n background-color: lightgray;\n}\n\n.tabbed-pane-placeholder {\n font-size: 14px;\n text-align: center;\n margin-top: 20px;\n text-shadow: rgba(255, 255, 255, 0.75) 0 1px 0;\n line-height: 28px;\n overflow: hidden;\n}\n\n.tabbed-pane-placeholder-row {\n display: flex;\n white-space: nowrap;\n}\n\n.tabbed-pane-placeholder-key {\n flex: 1;\n text-align: right;\n padding-right: 14px;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.tabbed-pane-placeholder-value {\n flex: 1;\n text-align: left;\n padding-left: 14px;\n}\n\n.tabbed-pane-header {\n display: flex;\n flex: 0 0 27px;\n border-bottom: 1px solid #ccc;\n overflow: visible;\n width: 100%;\n background-color: #f3f3f3;\n}\n\n.tabbed-pane-header-contents {\n flex: auto;\n pointer-events: none;\n margin-left: 5px;\n position: relative;\n}\n\n.tabbed-pane-header-contents > * {\n pointer-events: initial;\n}\n\n.tabbed-pane-header-tab-icon {\n min-width: 14px;\n display: flex;\n align-items: center;\n margin-right: 2px;\n}\n\n.tabbed-pane-header-tab {\n float: left;\n margin-top: 2px;\n padding: 2px 4px 2px 4px;\n height: 24px;\n border: 1px solid transparent;\n border-bottom: none;\n line-height: 15px;\n white-space: nowrap;\n cursor: default;\n display: flex;\n align-items: center;\n color: #5a5a5a;\n}\n\n.tabbed-pane-header-tab:hover,\n.tabbed-pane-header-tab.selected:hover,\n.tabbed-pane-shadow .tabbed-pane-header-tab[data-keyboard-focus=\"true\"]:focus {\n color: #333;\n background-color: #e5e5e5;\n}\n\n.tabbed-pane-header-tab-title {\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.tabbed-pane-header-tab.measuring {\n visibility: hidden;\n}\n\n.tabbed-pane-header-tab.selected {\n border: 1px solid #ccc;\n border-bottom: none;\n color: #333;\n}\n\n.tabbed-pane-header-tab.selected {\n background-color: white;\n border-top-color: #ccc;\n}\n\n.tabbed-pane-header-tab.dragging {\n position: relative;\n box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.37);\n background-color: #e5e5e5;\n}\n\n.tabbed-pane-header-tab .tabbed-pane-close-button {\n margin: 0 -3px 0 4px;\n visibility: hidden;\n}\n\n.tabbed-pane-header-tab:hover .tabbed-pane-close-button,\n.tabbed-pane-header-tab.selected .tabbed-pane-close-button {\n visibility: visible;\n}\n\n.tabbed-pane-header-tabs-drop-down-container {\n float: left;\n opacity: 0.8;\n cursor: pointer;\n display: flex;\n align-items: center;\n height: 100%;\n}\n\n.tabbed-pane-header-tabs-drop-down-container > .chevron-icon {\n background-color: hsla(0,0%,20%,1);\n display: block;\n}\n\n.tabbed-pane-header-tabs-drop-down-container:hover {\n background-color: rgb(229, 229, 229);\n}\n\n.tabbed-pane-header-tabs-drop-down-container.measuring {\n visibility: hidden;\n}\n\n.tabbed-pane-header-tabs-drop-down-container:hover {\n opacity: 1.0;\n}\n\n.tabbed-pane-header-tabs-drop-down-container:active {\n opacity: 0.8;\n}\n\n/* Web page style */\n\n.tabbed-pane-shadow.vertical-tab-layout {\n flex-direction: row !important;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header {\n background-color: transparent;\n border: none transparent !important;\n width: auto;\n flex: 0 0 auto;\n flex-direction: column;\n padding-top: 10px;\n overflow: hidden;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-content {\n padding: 10px 10px 10px 0;\n overflow-x: hidden;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-contents {\n margin: 0;\n flex: none;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tabs {\n display: flex;\n flex-direction: column;\n width: 120px;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab {\n background-color: transparent;\n border: none transparent;\n font-weight: normal;\n text-shadow: none;\n color: #777;\n height: 26px;\n padding-left: 10px;\n border-left: 6px solid transparent;\n margin: 0;\n display: flex;\n align-items: center;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab:not(.selected) {\n cursor: pointer !important;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab.selected {\n color: inherit;\n border: none transparent;\n border-left: 6px solid #666;\n}\n\n.tabbed-pane-tab-slider,\n.-theme-selection-color {\n height: 2px;\n position: absolute;\n bottom: -1px;\n background-color: #3E82F7;\n left: 0;\n z-index: 50;\n transform-origin: 0 100%;\n transition: transform 150ms cubic-bezier(0, 0, 0.2, 1);\n visibility: hidden;\n border-top: 1px solid hsl(218, 82%, 78%);\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\n .tabbed-pane-tab-slider {\n border-top: none;\n }\n}\n\n.tabbed-pane-tab-slider.enabled {\n visibility: visible;\n}\n\n.tabbed-pane-header-tab.disabled {\n opacity: 0.5;\n pointer-events: none;\n}\n\n.tabbed-pane-header.tabbed-pane-no-header-background {\n background-color: transparent;\n}\n\n.tabbed-pane-no-tab-borders .tabbed-pane-header-tab {\n border: none !important;\n padding: 2px 0.8em;\n}\n\n.tabbed-pane-no-tab-borders .tabbed-pane-header-contents {\n margin-left: 0;\n}\n\n.tabbed-pane-left-toolbar {\n margin-right: -4px;\n flex: none;\n}\n\n.tabbed-pane-right-toolbar {\n margin-left: -4px;\n flex: none;\n}\n\n/*# sourceURL=ui/tabbedPane.css */";Runtime.cachedResources["ui/textButton.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n margin: 2px;\n height: 24px;\n font-size: 12px;\n border: 1px solid rgba(0, 0, 0, 0.2);\n border-radius: 2px;\n padding: 0px 12px;\n font-weight: 500;\n color: #333;\n background-color: #fff;\n flex: none;\n white-space: nowrap;\n}\n\n:host(:not(:disabled):focus),\n:host(:not(:disabled):hover),\n:host(:not(:disabled):active) {\n background-color: #fafafa;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);\n cursor: pointer;\n}\n\n:host(:not(:disabled):active) {\n background-color: #f2f2f2;\n}\n\n:host(:not(:disabled):focus) {\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1), 0 0 0 2px rgba(66, 133, 244, 0.4);\n}\n\n:host(:disabled) {\n opacity: 0.38;\n}\n\n:host(.primary-button), -theme-preserve {\n background-color: #4285F4;\n border: none;\n color: #fff;\n}\n\n:host(.primary-button:not(:disabled):focus),\n:host(.primary-button:not(:disabled):hover), -theme-preserve {\n background-color: #3B78E7;\n}\n\n:host(.primary-button:not(:disabled):active), -theme-preserve {\n background-color: #3367D6;\n}\n\n:host-context(.-theme-with-dark-background):host(:not(.primary-button):not(:disabled):focus),\n:host-context(.-theme-with-dark-background):host(:not(.primary-button):not(:disabled):hover),\n:host-context(.-theme-with-dark-background):host(:not(.primary-button):not(:disabled):active) {\n background-color: #313131;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);\n}\n\n:host-context(.-theme-with-dark-background):host(:not(.primary-button):not(:disabled):focus) {\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1), 0 0 0 2px rgba(94, 151, 246, 0.6);\n}\n\n:host-context(.-theme-with-dark-background):host(:not(.primary-button):not(:disabled):active) {\n background-color: #3e3e3e;\n}\n\n/*# sourceURL=ui/textButton.css */";Runtime.cachedResources["ui/textPrompt.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.text-prompt-root {\n display: flex;\n align-items: center;\n}\n\n.text-prompt-editing {\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2),\n 0 2px 4px rgba(0, 0, 0, 0.2),\n 0 2px 6px rgba(0, 0, 0, 0.1);\n background-color: white;\n text-overflow: clip !important;\n padding-left: 2px;\n margin-left: -2px;\n padding-right: 2px;\n margin-right: -2px;\n margin-bottom: -1px;\n padding-bottom: 1px;\n opacity: 1.0 !important;\n}\n\n.text-prompt-editing,\n.text-prompt-editing ::content * {\n color: #222 !important;\n text-decoration: none !important;\n white-space: pre;\n}\n\n::content .auto-complete-text {\n color: rgb(128, 128, 128) !important;\n}\n\n::content .text-prompt[data-placeholder]:empty::before {\n content: attr(data-placeholder);\n color: rgb(128, 128, 128);\n}\n\n::content .text-prompt:not([data-placeholder]):empty::after {\n content: '\\00A0';\n width: 0;\n display: block;\n}\n\n.text-prompt-editing ::content br {\n display: none;\n}\n\n/*# sourceURL=ui/textPrompt.css */";Runtime.cachedResources["ui/tooltip.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tooltip {\n background: hsl(0, 0%, 95%);\n border-radius: 2px;\n color: hsl(0, 0%, 20%);\n padding: 5px 8px;\n line-height: 14px;\n display: flex;\n align-items: center;\n -webkit-filter: drop-shadow(0 1px 2px hsla(0, 0%, 0%, 0.3));\n border: 1px solid hsla(0, 0%, 0%, 0.1);\n background-clip: padding-box;\n box-sizing: border-box;\n position: absolute;\n visibility: hidden;\n transition: visibility 0s 100ms, opacity 150ms cubic-bezier(0, 0, .2, 1);\n z-index: 20001;\n top: 0;\n left: 0;\n opacity: 0;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.tooltip-breakword {\n word-break: break-word;\n}\n\n.tooltip.shown {\n visibility: visible;\n transition-delay: 600ms;\n opacity: 1;\n}\n\n.tooltip.shown.instant {\n transition-delay: 0s;\n}\n\n.tooltip-shortcut {\n color: hsl(0, 0%, 45%);\n display: inline-block;\n margin-left: 8px;\n flex: 0 0 auto;\n}\n\n/*# sourceURL=ui/tooltip.css */";Runtime.cachedResources["ui/treeoutline.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n flex: 1 1;\n padding: 2px 0 0 0;\n}\n\n.tree-outline-disclosure:not(.tree-outline-disclosure-hide-overflow) {\n min-width: 100%;\n display: inline-block;\n}\n\n.tree-outline {\n padding: 0 0 4px 4px;\n margin: 0;\n z-index: 0;\n position: relative;\n}\n\n.tree-outline li.hovered:not(.selected) .selection {\n display: block;\n left: 3px;\n right: 3px;\n background-color: rgba(56, 121, 217, 0.1);\n border-radius: 5px;\n}\n\n.tree-outline li .selection {\n display: none;\n z-index: -1;\n margin-left: -10000px;\n}\n\n.tree-outline li.selected .selection {\n display: block;\n background-color: #ddd;\n}\n\n.tree-outline li.in-clipboard .highlight {\n outline: 1px dotted darkgrey;\n}\n\n.tree-outline li.elements-drag-over .selection {\n display: block;\n margin-top: -2px;\n border-top: 2px solid rgb(56, 121, 217);\n}\n\nol.tree-outline li.selected:focus .selection {\n background-color: rgb(56, 121, 217);\n}\n\nol.tree-outline li.parent.selected:focus::before {\n background-color: white;\n}\n\nol.tree-outline,\n.tree-outline ol {\n list-style-type: none;\n}\n\n.tree-outline-no-padding {\n padding: 0;\n}\n\n.tree-outline ol {\n padding-left: 12px;\n}\n\n.tree-outline li {\n text-overflow: ellipsis;\n white-space: nowrap;\n position: relative;\n display: flex;\n align-items: center;\n min-height: 16px;\n}\n\nol.tree-outline li.selected:focus {\n color: white;\n}\n\nol.tree-outline li.selected:focus * {\n color: inherit;\n}\n\n.tree-outline li .icons-container {\n align-self: center;\n display: flex;\n align-items: center;\n}\n\n.tree-outline li .leading-icons {\n margin-right: 4px;\n}\n\n.tree-outline li .trailing-icons {\n margin-left: 4px;\n}\n\n.tree-outline li::before {\n -webkit-user-select: none;\n -webkit-mask-image: url(Images/treeoutlineTriangles.png);\n -webkit-mask-size: 32px 24px;\n content: \"aa\";\n color: transparent;\n text-shadow: none;\n margin-right: -2px;\n height: 12px;\n}\n\n.tree-outline li:not(.parent)::before {\n background-color: transparent;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\n.tree-outline li::before {\n -webkit-mask-image: url(Images/treeoutlineTriangles_2x.png);\n}\n} /* media */\n\n.tree-outline li::before {\n -webkit-mask-position: 0 0;\n background-color: rgb(110, 110, 110);\n}\n\n.tree-outline li.parent.expanded::before {\n -webkit-mask-position: -16px 0;\n}\n\n.tree-outline ol.children {\n display: none;\n}\n\n.tree-outline ol.children.expanded {\n display: block;\n}\n\n.tree-outline.tree-outline-dense li {\n margin-top: 1px;\n min-height: 12px;\n}\n\n.tree-outline.tree-outline-dense li.parent {\n margin-top: 0;\n}\n\n.tree-outline.tree-outline-dense li.parent::before {\n top: 0;\n}\n\n.tree-outline.tree-outline-dense ol {\n padding-left: 10px;\n}\n\n/*# sourceURL=ui/treeoutline.css */";Runtime.cachedResources["help/releaseNote.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n}\n\n.hbox {\n overflow-y: auto;\n overflow-x: hidden;\n}\n\n.release-note-top-section {\n color: white;\n height: 36px;\n line-height: 36px;\n padding: 0 15px;\n font-size: 16px;\n flex: none;\n background-color: #3367d6;\n box-shadow: 0 2px 4px rgba(0,0,0,.28);\n}\n\n.release-note-container {\n display: flex;\n flex-direction: column;\n}\n\n.release-note-container ul {\n display: flex;\n padding: 10px 16px;\n flex-direction: column;\n flex: none;\n margin: 4px 12px 0 2px;\n max-width: 600px;\n}\n\n.release-note-container li {\n display: flex;\n flex-direction:column;\n flex: none;\n line-height: 24px;\n font-size: 14px;\n}\n\n\n.release-note-container li:hover {\n color: #039be5;\n}\n\n.release-note-title,\n.release-note-subtitle {\n color: inherit;\n text-decoration: none;\n}\n\n.release-note-subtitle {\n font-size: 13px;\n line-height: 13px;\n padding-bottom: 8px;\n}\n\n.release-note-container li:not(:hover) .release-note-subtitle {\n color: #999;\n}\n\n.release-note-action-container > button {\n margin: 10px 0 20px 20px;\n color: #757575;\n}\n\n.release-note-action-container {\n flex: none;\n}\n\n.release-note-image {\n flex-shrink: 2;\n}\n\nimg {\n margin: 20px;\n width: 260px;\n height: 200px;\n flex: none;\n box-shadow: 0 2px 4px rgba(0, 0, 0, .3);\n}\n\nimg:hover {\n box-shadow: 0 2px 4px rgba(0, 0, 0, .5);\n}\n\n/*# sourceURL=help/releaseNote.css */";Runtime.cachedResources["components/domBreakpointsSidebarPane.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.breakpoint-list {\n padding-bottom: 3px;\n}\n\n.breakpoint-list .dom-breakpoint > div {\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.breakpoint-entry {\n display: flex;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n padding: 2px 0;\n}\n\n.breakpoint-list .breakpoint-entry:hover {\n background-color: #eee;\n}\n\n.breakpoint-hit {\n background-color: rgb(255, 255, 194);\n}\n\n:host-context(.-theme-with-dark-background) .breakpoint-hit {\n background-color: hsl(46, 98%, 22%);\n color: #ccc;\n}\n\n/*# sourceURL=components/domBreakpointsSidebarPane.css */";Runtime.cachedResources["components/domUtils.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n display: inline;\n}\n\n.node-link {\n cursor: pointer;\n display: inline;\n pointer-events: auto;\n}\n\n.stack-preview-async-description {\n padding: 3px 0 1px;\n font-style: italic;\n}\n\n.stack-preview-container .webkit-html-blackbox-link {\n opacity: 0.6;\n}\n\n.stack-preview-container > tr {\n height: 16px;\n line-height: 16px;\n}\n\n.stack-preview-container td {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.stack-preview-container .function-name {\n max-width: 80em;\n}\n\n.node-label-name {\n color: rgb(136, 18, 128);\n}\n\n.node-label-id {\n color: rgb(26, 26, 166);\n}\n\n.node-label-class, .node-label-pseudo {\n color: rgb(153, 69, 0);\n}\n\n/*# sourceURL=components/domUtils.css */";Runtime.cachedResources["components/imagePreview.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.image-preview-container {\n background: transparent;\n text-align: center;\n border-spacing: 0;\n}\n\n.image-preview-container img {\n margin: 2px auto;\n max-width: 100px;\n max-height: 100px;\n background-image: url(Images/checker.png);\n -webkit-user-select: text;\n -webkit-user-drag: auto;\n}\n\n.image-container {\n padding: 0;\n}\n\n/*# sourceURL=components/imagePreview.css */";Runtime.cachedResources["persistence/editFileSystemView.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.file-system-header {\n display: flex;\n flex-direction: row;\n align-items: center;\n flex: auto;\n margin: 10px 0;\n}\n\n.file-system-header-text {\n flex: auto;\n}\n\n.add-button {\n margin-left: 10px;\n align-self: flex-start;\n}\n\n.file-system-list {\n flex: auto;\n}\n\n.file-system-list-empty {\n flex: auto;\n height: 30px;\n display: flex;\n align-items: center;\n justify-content: center;\n text-align: center;\n}\n\n.file-system-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n flex: auto 1 1;\n}\n\n.list-item .file-system-value {\n white-space: nowrap;\n text-overflow: ellipsis;\n -webkit-user-select: none;\n overflow: hidden;\n}\n\n.file-system-value {\n flex: 1 1 0px;\n}\n\n.file-system-separator {\n flex: 0 0 1px;\n background-color: rgb(231, 231, 231);\n height: 30px;\n margin: 0 4px;\n}\n\n.file-system-separator-invisible {\n visibility: hidden;\n height: 100% !important;\n}\n\n.file-system-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 6px 5px;\n align-items: center;\n}\n\n.file-system-edit-row input {\n width: 100%;\n text-align: inherit;\n}\n\n/*# sourceURL=persistence/editFileSystemView.css */";Runtime.cachedResources["persistence/workspaceSettingsTab.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\nheader {\n padding: 0 0 6px;\n border-bottom: 1px solid #EEEEEE;\n}\n\nheader > h3 {\n font-size: 18px;\n font-weight: normal;\n margin: 0;\n padding-bottom: 3px;\n}\n\n.help-content {\n overflow-y: auto;\n overflow-x: hidden;\n margin: 8px 8px 8px 0;\n padding: 0 4px;\n flex: auto;\n}\n\n.help-container {\n width: 100%;\n -webkit-user-select: auto;\n -webkit-column-width: 288px;\n}\n\n\n.settings-tab.help-container {\n -webkit-column-width: 308px;\n}\n\n.settings-tab label {\n padding-right: 4px;\n display: inline-flex;\n}\n\n.help-container-wrapper {\n position: absolute;\n top: 31px;\n left: 0px;\n right: 0;\n bottom: 0;\n overflow: auto;\n padding-top: 9px;\n}\n\n.settings-tab.help-content {\n margin: 0;\n padding: 0;\n}\n\n.settings-tab p {\n margin: 12px 0;\n}\n\np.folder-exclude-pattern {\n display: flex;\n align-items: center;\n}\n\np.folder-exclude-pattern > input {\n flex: auto;\n}\n\n.settings-tab .file-system-container {\n border-top: 1px solid #aaa;\n padding: 19px 0 10px;\n margin: 20px 0;\n}\n\n.settings-tab .file-system-header {\n display: flex;\n flex-direction: row;\n align-items: center;\n}\n\n.settings-tab .file-system-name {\n font-weight: bold;\n flex: none;\n margin-right: 10px;\n font-size: 15px;\n overflow: hidden;\n text-overflow: ellipsis;\n max-width: 70%;\n}\n\n.settings-tab .file-system-path {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n flex: auto;\n}\n\n.settings-info-message {\n background-color: #eee;\n padding: 10px;\n margin: 20px 0;\n}\n\n.settings-tab.help-content.help-container {\n -webkit-column-width: initial;\n overflow: hidden;\n padding-right: 10px;\n}\n\n/*# sourceURL=persistence/workspaceSettingsTab.css */";Runtime.cachedResources["mobile_throttling/throttlingSettingsTab.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow:hidden;\n}\n\n.header {\n padding: 0 0 6px;\n border-bottom: 1px solid #EEEEEE;\n font-size: 18px;\n font-weight: normal;\n flex: none;\n}\n\n.add-conditions-button {\n flex: none;\n margin: 10px 2px;\n min-width: 140px;\n align-self: flex-start;\n}\n\n.conditions-list {\n max-width: 500px;\n min-width: 340px;\n flex: auto;\n}\n\n.conditions-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n position: relative;\n flex: auto 1 1;\n}\n\n.conditions-list-text {\n white-space: nowrap;\n text-overflow: ellipsis;\n flex: 0 0 70px;\n -webkit-user-select: none;\n color: #222;\n text-align: end;\n position: relative;\n}\n\n.conditions-list-title {\n text-align: start;\n flex: auto;\n display: flex;\n align-items: flex-start;\n}\n\n.conditions-list-title-text {\n overflow: hidden;\n flex: auto;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n\n.conditions-list-separator {\n flex: 0 0 1px;\n background-color: rgb(231, 231, 231);\n height: 30px;\n margin: 0 4px;\n}\n\n.conditions-list-separator-invisible {\n visibility: hidden;\n height: 100% !important;\n}\n\n.conditions-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 6px 5px;\n}\n\n.conditions-edit-row input {\n width: 100%;\n text-align: inherit;\n}\n\n.conditions-edit-optional {\n position: absolute;\n bottom: -20px;\n right: 0;\n color: rgb(128, 128, 128);\n}\n\n/*# sourceURL=mobile_throttling/throttlingSettingsTab.css */";Runtime.cachedResources["emulation/devicesSettingsTab.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.devices-settings-tab .settings-tab.help-content {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n height: 100%;\n margin: 0;\n}\n\n.devices-settings-tab .devices-title {\n font-size: 120%;\n color: #222;\n flex: none;\n}\n\n.devices-settings-tab .devices-button-row {\n flex: none;\n display: flex;\n}\n\n.devices-settings-tab .devices-button-row button {\n margin-right: 10px;\n min-width: 120px;\n flex: none;\n}\n\n.devices-settings-tab .devices-list {\n width: 350px;\n margin-top: 10px;\n}\n\n.devices-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n flex: auto 1 1;\n cursor: pointer;\n}\n\n.devices-list-checkbox {\n height: 12px;\n width: 12px;\n margin: 3px 5px 2px 2px;\n flex: none;\n pointer-events: none;\n}\n\n.devices-list-title {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n flex: auto;\n -webkit-user-select: none;\n color: #222;\n}\n\n.devices-edit-fields {\n flex: auto;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n margin-bottom: 5px;\n}\n\n.devices-edit-fields input {\n flex: auto;\n margin: 8px 5px 0 5px;\n}\n\n.devices-edit-fields .device-edit-fixed {\n flex: 0 0 140px;\n}\n\n.devices-edit-fields select {\n margin: 8px 5px 0 5px;\n}\n\n/*# sourceURL=emulation/devicesSettingsTab.css */";Runtime.cachedResources["emulation/deviceModeToolbar.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.device-mode-size-input {\n width: 41px;\n max-height: 18px;\n margin: 0 2px;\n text-align: center;\n}\n\n.device-mode-size-input:focus::-webkit-input-placeholder {\n color: transparent;\n}\n\n.device-mode-size-input:disabled {\n background: transparent;\n -webkit-user-select: none;\n opacity: 0.6;\n}\n\n.device-mode-x {\n margin: 0 1px;\n font-size: 16px;\n}\n\n.device-mode-empty-toolbar-element {\n width: 0;\n}\n\n/*# sourceURL=emulation/deviceModeToolbar.css */";Runtime.cachedResources["emulation/deviceModeView.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow: hidden;\n align-items: stretch;\n flex: auto;\n background-color: hsl(0, 0%, 98%);\n}\n\n.device-mode-toolbar {\n flex: none;\n background-color: hsl(0, 0%, 98%);\n border-bottom: 1px solid #ccc;\n display: flex;\n flex-direction: row;\n align-items: stretch;\n}\n\n.device-mode-toolbar .toolbar {\n overflow: hidden;\n flex: 0 100000 auto;\n padding: 0 5px;\n}\n\n.device-mode-toolbar .toolbar.device-mode-toolbar-fixed-size {\n flex: 0 1 auto;\n}\n\n.device-mode-toolbar-spacer {\n flex: 1 1 0;\n display: flex;\n flex-direction: row;\n overflow: hidden;\n}\n\n.device-mode-content-clip {\n overflow: hidden;\n flex: auto;\n}\n\n.device-mode-media-container {\n flex: none;\n overflow: hidden;\n box-shadow: inset 0 -1px #ccc;\n}\n\n.device-mode-content-clip:not(.device-mode-outline-visible) .device-mode-media-container {\n margin-bottom: 20px;\n}\n\n.device-mode-presets-container {\n flex: 0 0 20px;\n display: flex;\n}\n\n.device-mode-presets-container-inner {\n flex: auto;\n justify-content: center;\n position: relative;\n background-color: hsl(0, 0%, 90%);\n border: 2px solid hsl(0, 0%, 98%);\n border-bottom: 2px solid hsl(0, 0%, 98%);\n }\n\n.device-mode-presets-container:hover {\n transition: opacity 0.1s;\n transition-delay: 50ms;\n opacity: 1;\n}\n\n.device-mode-preset-bar-outer {\n pointer-events: none;\n display: flex;\n justify-content: center;\n}\n\n.device-mode-preset-bar {\n border-left: 2px solid hsl(0, 0%, 98%);\n border-right: 2px solid hsl(0, 0%, 98%);\n pointer-events: auto;\n text-align: center;\n flex: none;\n cursor: pointer;\n color: #5A5A5A;\n display: flex;\n align-items: center;\n justify-content: center;\n white-space: nowrap;\n margin-bottom: 1px;\n}\n\n.device-mode-preset-bar:hover {\n transition: background-color 0.1s;\n transition-delay: 50ms;\n background-color: #d6d6d6;\n}\n\n.device-mode-preset-bar > span {\n visibility: hidden;\n}\n\n.device-mode-preset-bar:hover > span {\n transition: visibility 0.1s;\n transition-delay: 50ms;\n visibility: visible;\n}\n\n.device-mode-content-area {\n flex: auto;\n position: relative;\n margin: 0;\n}\n\n.device-mode-screen-area {\n position: absolute;\n left: 0;\n right: 0;\n width: 0;\n height: 0;\n background-color: #171717;\n}\n\n.device-mode-content-clip:not(.device-mode-outline-visible) .device-mode-screen-area {\n box-shadow: hsl(240, 3%, 84%) 0 0 0 0.5px, hsla(0, 0%, 80%, 0.4) 0 0 20px;\n}\n\n.device-mode-screen-image {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n\n.device-mode-resizer {\n position: absolute;\n display: flex;\n align-items: center;\n justify-content: center;\n overflow: hidden;\n transition: background-color 0.1s ease, opacity 0.1s ease;\n}\n\n.device-mode-resizer:hover {\n background-color: hsla(0, 0%, 0%, 0.1);\n opacity: 1;\n}\n\n.device-mode-resizer > div {\n pointer-events: none;\n}\n\n.device-mode-right-resizer {\n top: 0;\n bottom: -1px;\n right: -20px;\n width: 20px;\n}\n\n.device-mode-left-resizer {\n top: 0;\n bottom: -1px;\n left: -20px;\n width: 20px;\n opacity: 0;\n}\n\n.device-mode-bottom-resizer {\n left: 0;\n right: -1px;\n bottom: -20px;\n height: 20px;\n}\n\n.device-mode-bottom-right-resizer {\n left: 0;\n top: 0;\n right: -20px;\n bottom: -20px;\n background-color: hsla(0, 0%, 0%, 0.02);\n}\n\n.device-mode-bottom-left-resizer {\n left: -20px;\n top: 0;\n right: 0;\n bottom: -20px;\n opacity: 0;\n}\n\n.device-mode-right-resizer > div {\n content: url(Images/resizeHorizontal.png);\n width: 6px;\n height: 26px;\n}\n\n.device-mode-left-resizer > div {\n content: url(Images/resizeHorizontal.png);\n width: 6px;\n height: 26px;\n}\n\n.device-mode-bottom-resizer > div {\n content: url(Images/resizeVertical.png);\n margin-bottom: -2px;\n width: 26px;\n height: 6px;\n}\n\n.device-mode-bottom-right-resizer > div {\n position: absolute;\n bottom: 3px;\n right: 3px;\n width: 13px;\n height: 13px;\n content: url(Images/resizeDiagonal.png);\n}\n\n.device-mode-bottom-left-resizer > div {\n position: absolute;\n bottom: 3px;\n left: 3px;\n width: 13px;\n height: 13px;\n content: url(Images/resizeDiagonal.png);\n transform: rotate(90deg);\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\n .device-mode-right-resizer > div {\n content: url(Images/resizeHorizontal_2x.png);\n }\n\n .device-mode-left-resizer > div {\n content: url(Images/resizeHorizontal_2x.png);\n }\n\n .device-mode-bottom-resizer > div {\n content: url(Images/resizeVertical_2x.png);\n }\n\n .device-mode-bottom-right-resizer > div {\n content: url(Images/resizeDiagonal_2x.png);\n }\n\n .device-mode-bottom-left-resizer > div {\n content: url(Images/resizeDiagonal_2x.png);\n }\n} /* media */\n\n.device-mode-page-area {\n position: absolute;\n left: 0;\n right: 0;\n width: 0;\n height: 0;\n display: flex;\n background-color: #fcfcfc;\n}\n\n.device-mode-ruler {\n position: absolute;\n overflow: visible;\n}\n\n.device-mode-ruler-top {\n height: 20px;\n right: 0;\n}\n\n.device-mode-ruler-left {\n width: 20px;\n bottom: 0;\n}\n\n.device-mode-ruler-content {\n pointer-events: none;\n position: absolute;\n left: -20px;\n top: -20px;\n}\n\n.device-mode-ruler-top .device-mode-ruler-content {\n border-top: 1px solid transparent;\n right: 0;\n bottom: 20px;\n background-color: hsla(0, 0%, 98%, 0.9);\n}\n\n.device-mode-content-clip.device-mode-outline-visible .device-mode-ruler-top .device-mode-ruler-content {\n border-top: 1px solid hsl(0, 0%, 50%);\n}\n\n.device-mode-ruler-left .device-mode-ruler-content {\n border-left: 1px solid transparent;\n border-top: 1px solid transparent;\n right: 20px;\n bottom: 0;\n}\n\n.device-mode-content-clip.device-mode-outline-visible .device-mode-ruler-left .device-mode-ruler-content {\n border-left: 1px solid hsl(0, 0%, 50%);\n border-top: 1px solid hsl(0, 0%, 50%);\n}\n\n.device-mode-ruler-inner {\n position: absolute;\n}\n\n.device-mode-ruler-top .device-mode-ruler-inner {\n top: 0;\n bottom: 0;\n left: 20px;\n right: 0;\n border-bottom: 1px solid hsl(0, 0%, 50%);\n}\n\n.device-mode-ruler-left .device-mode-ruler-inner {\n left: 0;\n right: 0;\n top: 19px;\n bottom: 0;\n border-right: 1px solid hsl(0, 0%, 50%);\n background-color: hsla(0, 0%, 98%, 0.9);\n}\n\n.device-mode-ruler-marker {\n position: absolute;\n}\n\n.device-mode-ruler-top .device-mode-ruler-marker {\n width: 0;\n height: 5px;\n bottom: 0;\n border-right: 1px solid hsl(0, 0%, 50%);\n margin-right: -1px;\n}\n\n.device-mode-ruler-top .device-mode-ruler-marker.device-mode-ruler-marker-medium {\n height: 10px;\n}\n\n.device-mode-ruler-top .device-mode-ruler-marker.device-mode-ruler-marker-large {\n height: 15px;\n}\n\n.device-mode-ruler-left .device-mode-ruler-marker {\n height: 0;\n width: 5px;\n right: 0;\n border-bottom: 1px solid hsl(0, 0%, 50%);\n margin-bottom: -1px;\n}\n\n.device-mode-ruler-left .device-mode-ruler-marker.device-mode-ruler-marker-medium {\n width: 10px;\n}\n\n.device-mode-ruler-left .device-mode-ruler-marker.device-mode-ruler-marker-large {\n width: 15px;\n}\n\n.device-mode-ruler-text {\n color: hsl(0, 0%, 50%);\n position: relative;\n pointer-events: auto;\n}\n\n.device-mode-ruler-text:hover {\n color: hsl(0, 0%, 10%);\n}\n\n.device-mode-ruler-top .device-mode-ruler-text {\n left: 2px;\n top: -2px;\n}\n\n.device-mode-ruler-left .device-mode-ruler-text {\n left: -4px;\n top: -15px;\n transform: rotate(270deg);\n}\n\n/*# sourceURL=emulation/deviceModeView.css */";Runtime.cachedResources["emulation/inspectedPagePlaceholder.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n background-color: white;\n}\n\n/*# sourceURL=emulation/inspectedPagePlaceholder.css */";Runtime.cachedResources["emulation/mediaQueryInspector.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n/* Media query bars */\n\n.media-inspector-view {\n height: 50px;\n}\n\n.media-inspector-marker-container {\n height: 14px;\n margin: 2px 0;\n position: relative;\n}\n\n.media-inspector-bar {\n display: flex;\n flex-direction: row;\n align-items: stretch;\n pointer-events: none;\n position: absolute;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n}\n\n.media-inspector-marker {\n flex: none;\n pointer-events: auto;\n margin: 1px 0;\n white-space: nowrap;\n z-index: auto;\n position: relative;\n}\n\n.media-inspector-marker-spacer {\n flex: auto;\n}\n\n.media-inspector-marker:hover {\n margin: -1px 0;\n opacity: 1;\n}\n\n.media-inspector-marker-max-width {\n background-color: hsl(207, 90%, 77%);\n border-right: 2px solid hsl(207, 90%, 61%);\n border-left: 2px solid hsl(207, 90%, 61%);\n}\n\n.media-inspector-marker-inactive .media-inspector-marker-max-width:not(:hover) {\n background-color: hsl(199, 94%, 94%);\n}\n\n.media-inspector-marker-min-max-width {\n background-color: hsl(88, 50%, 76%);\n border-left: 2px solid #689F38;\n border-right: 2px solid hsl(92, 48%, 42%);\n}\n\n.media-inspector-marker-inactive .media-inspector-marker-min-max-width:not(:hover) {\n background-color: hsl(125, 39%, 94%);\n}\n\n.media-inspector-marker-min-max-width:hover {\n z-index: 1;\n}\n\n.media-inspector-marker-min-width {\n background-color: hsl(36, 100%, 75%);\n flex: auto;\n}\n\n.media-inspector-marker-inactive .media-inspector-marker-min-width:not(:hover) {\n background-color: hsl(37, 100%, 94%);\n}\n\n.media-inspector-marker-min-width-right {\n border-left: 2px solid hsl(30, 100%, 48%);\n}\n\n.media-inspector-marker-min-width-left {\n border-right: 2px solid hsl(30, 100%, 48%);\n}\n\n/* Media query labels */\n\n.media-inspector-marker:not(:hover) .media-inspector-marker-label-container {\n display: none;\n}\n\n.media-inspector-marker-label-container {\n position: absolute;\n z-index: 1;\n}\n\n.media-inspector-marker-label-container-left {\n left: -2px;\n}\n\n.media-inspector-marker-label-container-right {\n right: -2px;\n}\n\n.media-inspector-marker-label {\n color: #222;\n position: absolute;\n top: 1px;\n bottom: 0;\n font-size: 12px;\n pointer-events: none;\n}\n\n.media-inspector-label-right {\n right: 4px;\n}\n\n.media-inspector-label-left {\n left: 4px;\n}\n\n/*# sourceURL=emulation/mediaQueryInspector.css */";Runtime.cachedResources["emulation/sensors.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.sensors-view {\n padding: 12px;\n display: block;\n}\n\n.sensors-view label {\n margin-bottom: 10px;\n}\n\n.sensors-view input {\n width: 100%;\n max-width: 100px;\n margin: -5px 10px 0px 0px;\n text-align: end;\n}\n\n.sensors-view input[readonly] {\n background-color: rgb(235, 235, 228);\n}\n\n.sensors-view fieldset {\n border: none;\n padding: 10px 0px;\n margin-left: 0;\n flex: 0 0 auto;\n margin: 0;\n}\n\n.sensors-view fieldset[disabled] {\n opacity: 0.5;\n}\n\n.sensors-view .field-error-message {\n display: none;\n}\n\n.sensors-view input:focus::-webkit-input-placeholder {\n color: transparent !important;\n}\n\n.sensors-view .chrome-select {\n width: 200px;\n}\n\n.sensors-group-title {\n width: 80px;\n line-height: 24px;\n}\n\n.sensors-group {\n display: flex;\n flex-wrap: wrap;\n margin-bottom: 10px;\n}\n\n.geo-fields {\n flex: 2 0 200px;\n}\n\n.latlong-group {\n display: flex;\n margin-bottom: 10px;\n}\n\n.latlong-title {\n width: 70px;\n}\n\n/* Device Orientation */\n\n.orientation-content {\n display: flex;\n flex-wrap: wrap;\n}\n\n.orientation-fields {\n margin-right: 10px;\n}\n\n.orientation-stage {\n -webkit-perspective: 700px;\n -webkit-perspective-origin: 50% 50%;\n width: 160px;\n height: 150px;\n background: linear-gradient(#E1F5FE 0%, #E1F5FE 64%, #b0Ebf3 64%, #DEF6F9 100%);\n transition: 0.2s ease opacity, 0.2s ease -webkit-filter;\n overflow: hidden;\n margin-bottom: 10px;\n}\n\n.orientation-stage.disabled {\n -webkit-filter: grayscale();\n opacity: 0.5;\n cursor: default !important;\n}\n\n.orientation-element,\n.orientation-element::before,\n.orientation-element::after\n{\n position: absolute;\n box-sizing: border-box;\n transform-style: preserve-3d;\n background: no-repeat;\n background-size: cover;\n backface-visibility: hidden;\n}\n\n.orientation-box {\n width: 66px;\n height: 122px;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n margin: auto;\n transform: rotate3d(1, 0, 0, 90deg);\n}\n\n.orientation-box.is-animating, .is-animating .orientation-layer {\n transition: transform 300ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;\n}\n\n.orientation-layer {\n width: 100%;\n height: 100%;\n transform-style: preserve-3d;\n}\n\n.orientation-front,\n.orientation-back\n{\n width: 66px;\n height: 122px;\n border-radius: 8px;\n}\n\n.orientation-front {\n background-image: url(Images/accelerometer-front.png);\n}\n\n.orientation-back {\n transform: rotateY(180deg) translateZ(12px);\n background-image: url(Images/accelerometer-back.png);\n}\n\n\n.orientation-left,\n.orientation-right {\n width: 12px;\n height: 106px;\n top: 8px;\n background-position: center center;\n}\n\n.orientation-left {\n left: -12px;\n transform-origin: right center;\n transform: rotateY(-90deg);\n background-image: url(Images/accelerometer-left.png);\n}\n\n\n.orientation-right {\n right: -12px;\n transform-origin: left center;\n transform: rotateY(90deg);\n background-image: url(Images/accelerometer-right.png);\n}\n\n.orientation-left::before,\n.orientation-left::after,\n.orientation-right::before,\n.orientation-right::after\n{\n content: '';\n width: 12px;\n height: 6px;\n}\n\n.orientation-left::before,\n.orientation-left::after\n{\n background-image: url(Images/accelerometer-left.png);\n}\n\n.orientation-right::before,\n.orientation-right::after\n{\n background-image: url(Images/accelerometer-right.png);\n}\n\n.orientation-left::before,\n.orientation-right::before {\n top: -6px;\n transform-origin: center bottom;\n transform: rotateX(26deg);\n background-position: center top;\n}\n\n.orientation-left::after,\n.orientation-right::after {\n bottom: -6px;\n transform-origin: center top;\n transform: rotateX(-25deg);\n background-position: center bottom;\n}\n\n.orientation-top,\n.orientation-bottom {\n width: 50px;\n height: 12px;\n left: 8px;\n background-position: center center;\n}\n\n.orientation-top {\n top: -12px;\n transform-origin: center bottom;\n transform: rotateX(90deg);\n background-image: url(Images/accelerometer-top.png);\n}\n\n\n.orientation-bottom {\n bottom: -12px;\n transform-origin: center top;\n transform: rotateX(-90deg);\n background-image: url(Images/accelerometer-bottom.png);\n}\n\n\n.orientation-top::before,\n.orientation-top::after,\n.orientation-bottom::before,\n.orientation-bottom::after\n{\n content: '';\n width: 8px;\n height: 12px;\n}\n\n.orientation-top::before,\n.orientation-top::after\n{\n background-image: url(Images/accelerometer-top.png);\n}\n\n.orientation-bottom::before,\n.orientation-bottom::after\n{\n background-image: url(Images/accelerometer-bottom.png);\n}\n\n.orientation-top::before,\n.orientation-bottom::before {\n left: -6px;\n transform-origin: right center;\n transform: rotateY(-26deg);\n background-position: left center;\n}\n\n.orientation-top::after,\n.orientation-bottom::after {\n right: -6px;\n transform-origin: left center;\n transform: rotateY(26deg);\n background-position: right center;\n}\n\n.orientation-axis-input-container {\n margin-bottom: 10px;\n}\n\n.orientation-axis-input-container input {\n max-width: 100px;\n}\n\n.orientation-reset-button {\n min-width: 80px;\n}\n\nfieldset.device-orientation-override-section {\n margin: 0;\n display: flex;\n}\n\n.touch-label {\n margin-top: 10px;\n}\n\n.touch-label select {\n margin-left: 10px;\n}\n\n.panel-section-separator {\n height: 2px;\n margin-bottom: 12px;\n background: #f1f1f1;\n}\n\n.reload-warning {\n align-self: center;\n margin-left: 10px;\n}\n\n/*# sourceURL=emulation/sensors.css */";Runtime.cachedResources["product_registry/badge.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.product-registry-badge {\n background-color: rgba(0, 0, 0, 0.2);\n border-radius: 2px;\n padding: 1px 2px;\n white-space: pre;\n cursor: pointer;\n}\n\n.product-registry-badge::before {\n content: attr(data-initial);\n color: #222;\n}\n\n.hide-badge-title .product-registry-badge-title {\n display: none;\n}\n\n.product-registry-badge-title {\n padding-left: 4px;\n}\n/*# sourceURL=product_registry/badge.css */";Runtime.cachedResources["product_registry/popup.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.product-registry-popup {\n background-color: white;\n padding: 15px 45px 15px 15px;\n border-radius: 4px;\n white-space: nowrap;\n box-shadow: 0px 1px 2px 0px gray;\n}\n\n.product-registry-domain {\n font-weight: bold;\n}\n\n.product-registry-name {\n padding: 10px 0;\n}\n\n.product-registry-link {\n display: block;\n}\n\ndiv[is=dt-close-button] {\n position: absolute;\n top: 5px;\n right: 5px;\n}\n\n/*# sourceURL=product_registry/popup.css */";Runtime.cachedResources["console_counters/errorWarningCounter.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n cursor: pointer;\n padding: 0 2px;\n min-width: 26px;\n}\n\n:host:hover {\n color: #333;\n}\n\n.counter-item {\n margin-left: 6px;\n}\n\n.counter-item label {\n cursor: inherit;\n}\n\n.counter-item.counter-item-first {\n margin-left: 0;\n}\n\n/*# sourceURL=console_counters/errorWarningCounter.css */";Runtime.cachedResources["main/nodeIcon.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.node-icon {\n width: 28px;\n height: 26px;\n background-image: url(Images/nodeIcon.png);\n background-size: 17px 17px;\n background-repeat: no-repeat;\n background-position: center;\n opacity: 0.8;\n}\n\n.node-icon:hover {\n opacity: 1.0;\n}\n\n.node-icon.inactive {\n filter: grayscale(100%);\n}\n\n/*# sourceURL=main/nodeIcon.css */";Runtime.cachedResources["main/remoteDebuggingTerminatedScreen.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n padding: 20px;\n}\n\n.message, .button {\n font-size: larger;\n white-space: pre;\n margin: 5px;\n}\n\n.button {\n text-align: center;\n margin-top: 10px;\n}\n\n.reason {\n color: #8b0000;\n}\n\n/*# sourceURL=main/remoteDebuggingTerminatedScreen.css */";Runtime.cachedResources["main/renderingOptions.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n padding: 12px;\n }\n\nlabel {\n margin: 0px 0px 10px 0px;\n flex: none;\n}\n\n.media-row {\n margin-left: 22px;\n flex: none;\n}\n\n.media-row p {\n margin-top: 0;\n color: gray;\n}\n\n.panel-section-separator {\n height: 1px;\n margin-bottom: 10px;\n background: #f0f0f0;\n flex: none;\n}\n\n/*# sourceURL=main/renderingOptions.css */";Runtime.cachedResources["main/targetCrashedScreen.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n padding: 25px;\n}\n\n.message {\n font-size: larger;\n white-space: pre;\n margin: 5px;\n}\n\n/*# sourceURL=main/targetCrashedScreen.css */";Runtime.startApplication('inspector'); \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/layer_viewer/layer_viewer_module.js b/src/cobalt/debug/content/devtools/layer_viewer/layer_viewer_module.js deleted file mode 100644 index b2dae0f..0000000 --- a/src/cobalt/debug/content/devtools/layer_viewer/layer_viewer_module.js +++ /dev/null
@@ -1,310 +0,0 @@ -LayerViewer.LayerDetailsView=class extends UI.Widget{constructor(layerViewHost){super(true);this.registerRequiredCSS('layer_viewer/layerDetailsView.css');this._layerViewHost=layerViewHost;this._layerViewHost.registerView(this);this._emptyWidget=new UI.EmptyWidget(Common.UIString('Select a layer to see its details'));this._buildContent();} -hoverObject(selection){} -selectObject(selection){this._selection=selection;if(this.isShowing()) -this.update();} -setLayerTree(layerTree){} -wasShown(){super.wasShown();this.update();} -_onScrollRectClicked(index,event){if(event.which!==1) -return;this._layerViewHost.selectObject(new LayerViewer.LayerView.ScrollRectSelection(this._selection.layer(),index));} -_onPaintProfilerButtonClicked(){if(this._selection.type()===LayerViewer.LayerView.Selection.Type.Snapshot||this._selection.layer()) -this.dispatchEventToListeners(LayerViewer.LayerDetailsView.Events.PaintProfilerRequested,this._selection);} -_createScrollRectElement(scrollRect,index){if(index) -this._scrollRectsCell.createTextChild(', ');var element=this._scrollRectsCell.createChild('span','scroll-rect');if(this._selection.scrollRectIndex===index) -element.classList.add('active');element.textContent=Common.UIString('%s %d × %d (at %d, %d)',LayerViewer.LayerDetailsView._slowScrollRectNames.get(scrollRect.type),scrollRect.rect.x,scrollRect.rect.y,scrollRect.rect.width,scrollRect.rect.height);element.addEventListener('click',this._onScrollRectClicked.bind(this,index),false);} -_formatStickyAncestorLayer(title,layer){if(!layer) -return'';var node=layer.nodeForSelfOrAncestor();var name=node?Components.DOMPresentationUtils.simpleSelector(node):Common.UIString('<unnamed>');return Common.UIString('%s: %s (%s)',title,name,layer.id());} -_createStickyAncestorChild(title,layer){if(!layer) -return;this._stickyPositionConstraintCell.createTextChild(', ');var child=this._stickyPositionConstraintCell.createChild('span');child.textContent=this._formatStickyAncestorLayer(title,layer);} -_populateStickyPositionConstraintCell(constraint){this._stickyPositionConstraintCell.removeChildren();if(!constraint) -return;var stickyBoxRect=constraint.stickyBoxRect();var stickyBoxRectElement=this._stickyPositionConstraintCell.createChild('span');stickyBoxRectElement.textContent=Common.UIString('Sticky Box %d × %d (at %d, %d)',stickyBoxRect.width,stickyBoxRect.height,stickyBoxRect.x,stickyBoxRect.y);this._stickyPositionConstraintCell.createTextChild(', ');var containingBlockRect=constraint.containingBlockRect();var containingBlockRectElement=this._stickyPositionConstraintCell.createChild('span');containingBlockRectElement.textContent=Common.UIString('Containing Block %d × %d (at %d, %d)',containingBlockRect.width,containingBlockRect.height,containingBlockRect.x,containingBlockRect.y);this._createStickyAncestorChild(Common.UIString('Nearest Layer Shifting Sticky Box'),constraint.nearestLayerShiftingStickyBox());this._createStickyAncestorChild(Common.UIString('Nearest Layer Shifting Containing Block'),constraint.nearestLayerShiftingContainingBlock());} -update(){var layer=this._selection&&this._selection.layer();if(!layer){this._tableElement.remove();this._paintProfilerButton.remove();this._emptyWidget.show(this.contentElement);return;} -this._emptyWidget.detach();this.contentElement.appendChild(this._tableElement);this.contentElement.appendChild(this._paintProfilerButton);this._sizeCell.textContent=Common.UIString('%d × %d (at %d,%d)',layer.width(),layer.height(),layer.offsetX(),layer.offsetY());this._paintCountCell.parentElement.classList.toggle('hidden',!layer.paintCount());this._paintCountCell.textContent=layer.paintCount();this._memoryEstimateCell.textContent=Number.bytesToString(layer.gpuMemoryUsage());layer.requestCompositingReasons().then(this._updateCompositingReasons.bind(this));this._scrollRectsCell.removeChildren();layer.scrollRects().forEach(this._createScrollRectElement.bind(this));this._populateStickyPositionConstraintCell(layer.stickyPositionConstraint());var snapshot=this._selection.type()===LayerViewer.LayerView.Selection.Type.Snapshot?(this._selection).snapshot():null;this._paintProfilerButton.classList.toggle('hidden',!snapshot);} -_buildContent(){this._tableElement=this.contentElement.createChild('table');this._tbodyElement=this._tableElement.createChild('tbody');this._sizeCell=this._createRow(Common.UIString('Size'));this._compositingReasonsCell=this._createRow(Common.UIString('Compositing Reasons'));this._memoryEstimateCell=this._createRow(Common.UIString('Memory estimate'));this._paintCountCell=this._createRow(Common.UIString('Paint count'));this._scrollRectsCell=this._createRow(Common.UIString('Slow scroll regions'));this._stickyPositionConstraintCell=this._createRow(Common.UIString('Sticky position constraint'));this._paintProfilerButton=this.contentElement.createChild('a','hidden link');this._paintProfilerButton.textContent=Common.UIString('Paint Profiler');this._paintProfilerButton.addEventListener('click',this._onPaintProfilerButtonClicked.bind(this));} -_createRow(title){var tr=this._tbodyElement.createChild('tr');var titleCell=tr.createChild('td');titleCell.textContent=title;return tr.createChild('td');} -_updateCompositingReasons(compositingReasons){if(!compositingReasons||!compositingReasons.length){this._compositingReasonsCell.textContent='n/a';return;} -this._compositingReasonsCell.removeChildren();var list=this._compositingReasonsCell.createChild('ul');for(var i=0;i<compositingReasons.length;++i){var text=LayerViewer.LayerDetailsView.CompositingReasonDetail[compositingReasons[i]]||compositingReasons[i];if(/\s.*[^.]$/.test(text)) -text+='.';list.createChild('li').textContent=text;}}};LayerViewer.LayerDetailsView.Events={PaintProfilerRequested:Symbol('PaintProfilerRequested')};LayerViewer.LayerDetailsView.CompositingReasonDetail={'transform3D':Common.UIString('Composition due to association with an element with a CSS 3D transform.'),'video':Common.UIString('Composition due to association with a <video> element.'),'canvas':Common.UIString('Composition due to the element being a <canvas> element.'),'plugin':Common.UIString('Composition due to association with a plugin.'),'iFrame':Common.UIString('Composition due to association with an <iframe> element.'),'backfaceVisibilityHidden':Common.UIString('Composition due to association with an element with a "backface-visibility: hidden" style.'),'animation':Common.UIString('Composition due to association with an animated element.'),'filters':Common.UIString('Composition due to association with an element with CSS filters applied.'),'scrollDependentPosition':Common.UIString('Composition due to association with an element with a "position: fixed" or "position: sticky" style.'),'overflowScrollingTouch':Common.UIString('Composition due to association with an element with a "overflow-scrolling: touch" style.'),'blending':Common.UIString('Composition due to association with an element that has blend mode other than "normal".'),'assumedOverlap':Common.UIString('Composition due to association with an element that may overlap other composited elements.'),'overlap':Common.UIString('Composition due to association with an element overlapping other composited elements.'),'negativeZIndexChildren':Common.UIString('Composition due to association with an element with descendants that have a negative z-index.'),'transformWithCompositedDescendants':Common.UIString('Composition due to association with an element with composited descendants.'),'opacityWithCompositedDescendants':Common.UIString('Composition due to association with an element with opacity applied and composited descendants.'),'maskWithCompositedDescendants':Common.UIString('Composition due to association with a masked element and composited descendants.'),'reflectionWithCompositedDescendants':Common.UIString('Composition due to association with an element with a reflection and composited descendants.'),'filterWithCompositedDescendants':Common.UIString('Composition due to association with an element with CSS filters applied and composited descendants.'),'blendingWithCompositedDescendants':Common.UIString('Composition due to association with an element with CSS blending applied and composited descendants.'),'clipsCompositingDescendants':Common.UIString('Composition due to association with an element clipping compositing descendants.'),'perspective':Common.UIString('Composition due to association with an element with perspective applied.'),'preserve3D':Common.UIString('Composition due to association with an element with a "transform-style: preserve-3d" style.'),'root':Common.UIString('Root layer.'),'layerForClip':Common.UIString('Layer for clip.'),'layerForScrollbar':Common.UIString('Layer for scrollbar.'),'layerForScrollingContainer':Common.UIString('Layer for scrolling container.'),'layerForForeground':Common.UIString('Layer for foreground.'),'layerForBackground':Common.UIString('Layer for background.'),'layerForMask':Common.UIString('Layer for mask.'),'layerForVideoOverlay':Common.UIString('Layer for video overlay.'),};LayerViewer.LayerDetailsView._slowScrollRectNames=new Map([[SDK.Layer.ScrollRectType.NonFastScrollable,Common.UIString('Non fast scrollable')],[SDK.Layer.ScrollRectType.TouchEventHandler,Common.UIString('Touch event handler')],[SDK.Layer.ScrollRectType.WheelEventHandler,Common.UIString('Wheel event handler')],[SDK.Layer.ScrollRectType.RepaintsOnScroll,Common.UIString('Repaints on scroll')]]);;LayerViewer.LayerTreeOutline=class extends Common.Object{constructor(layerViewHost){super();this._layerViewHost=layerViewHost;this._layerViewHost.registerView(this);this._treeOutline=new UI.TreeOutlineInShadow();this._treeOutline.element.classList.add('layer-tree','overflow-auto');this._treeOutline.element.addEventListener('mousemove',this._onMouseMove.bind(this),false);this._treeOutline.element.addEventListener('mouseout',this._onMouseMove.bind(this),false);this._treeOutline.element.addEventListener('contextmenu',this._onContextMenu.bind(this),true);this._lastHoveredNode=null;this.element=this._treeOutline.element;this._layerViewHost.showInternalLayersSetting().addChangeListener(this._update,this);} -focus(){this._treeOutline.focus();} -selectObject(selection){this.hoverObject(null);var layer=selection&&selection.layer();var node=layer&&layer[LayerViewer.LayerTreeElement._symbol];if(node) -node.revealAndSelect(true);else if(this._treeOutline.selectedTreeElement) -this._treeOutline.selectedTreeElement.deselect();} -hoverObject(selection){var layer=selection&&selection.layer();var node=layer&&layer[LayerViewer.LayerTreeElement._symbol];if(node===this._lastHoveredNode) -return;if(this._lastHoveredNode) -this._lastHoveredNode.setHovered(false);if(node) -node.setHovered(true);this._lastHoveredNode=node;} -setLayerTree(layerTree){this._layerTree=layerTree;this._update();} -_update(){var showInternalLayers=this._layerViewHost.showInternalLayersSetting().get();var seenLayers=new Map();var root=null;if(this._layerTree){if(!showInternalLayers) -root=this._layerTree.contentRoot();if(!root) -root=this._layerTree.root();} -function updateLayer(layer){if(!layer.drawsContent()&&!showInternalLayers) -return;if(seenLayers.get(layer)) -console.assert(false,'Duplicate layer: '+layer.id());seenLayers.set(layer,true);var node=layer[LayerViewer.LayerTreeElement._symbol];var parentLayer=layer.parent();while(parentLayer&&parentLayer!==root&&!parentLayer.drawsContent()&&!showInternalLayers) -parentLayer=parentLayer.parent();var parent=layer===root?this._treeOutline.rootElement():parentLayer[LayerViewer.LayerTreeElement._symbol];if(!parent){console.assert(false,'Parent is not in the tree');return;} -if(!node){node=new LayerViewer.LayerTreeElement(this,layer);parent.appendChild(node);if(!layer.drawsContent()) -node.expand();}else{if(node.parent!==parent){var oldSelection=this._treeOutline.selectedTreeElement;if(node.parent) -node.parent.removeChild(node);parent.appendChild(node);if(oldSelection!==this._treeOutline.selectedTreeElement) -oldSelection.select();} -node._update();}} -if(root) -this._layerTree.forEachLayer(updateLayer.bind(this),root);var rootElement=this._treeOutline.rootElement();for(var node=rootElement.firstChild();node&&!node.root;){if(seenLayers.get(node._layer)){node=node.traverseNextTreeElement(false);}else{var nextNode=node.nextSibling||node.parent;node.parent.removeChild(node);if(node===this._lastHoveredNode) -this._lastHoveredNode=null;node=nextNode;}} -if(!this._treeOutline.selectedTreeElement){var elementToSelect=this._layerTree.contentRoot()||this._layerTree.root();if(elementToSelect) -elementToSelect[LayerViewer.LayerTreeElement._symbol].revealAndSelect(true);}} -_onMouseMove(event){var node=this._treeOutline.treeElementFromEvent(event);if(node===this._lastHoveredNode) -return;this._layerViewHost.hoverObject(this._selectionForNode(node));} -_selectedNodeChanged(node){this._layerViewHost.selectObject(this._selectionForNode(node));} -_onContextMenu(event){var selection=this._selectionForNode(this._treeOutline.treeElementFromEvent(event));var contextMenu=new UI.ContextMenu(event);this._layerViewHost.showContextMenu(contextMenu,selection);} -_selectionForNode(node){return node&&node._layer?new LayerViewer.LayerView.LayerSelection(node._layer):null;}};LayerViewer.LayerTreeElement=class extends UI.TreeElement{constructor(tree,layer){super();this._treeOutline=tree;this._layer=layer;this._layer[LayerViewer.LayerTreeElement._symbol]=this;this._update();} -_update(){var node=this._layer.nodeForSelfOrAncestor();var title=createDocumentFragment();title.createTextChild(node?Components.DOMPresentationUtils.simpleSelector(node):'#'+this._layer.id());var details=title.createChild('span','dimmed');details.textContent=Common.UIString(' (%d × %d)',this._layer.width(),this._layer.height());this.title=title;} -onselect(){this._treeOutline._selectedNodeChanged(this);return false;} -setHovered(hovered){this.listItemElement.classList.toggle('hovered',hovered);}};LayerViewer.LayerTreeElement._symbol=Symbol('layer');;LayerViewer.LayerView=function(){};LayerViewer.LayerView.prototype={hoverObject(selection){},selectObject(selection){},setLayerTree(layerTree){}};LayerViewer.LayerView.Selection=class{constructor(type,layer){this._type=type;this._layer=layer;} -static isEqual(a,b){return a&&b?a._isEqual(b):a===b;} -type(){return this._type;} -layer(){return this._layer;} -_isEqual(other){return false;}};LayerViewer.LayerView.Selection.Type={Layer:Symbol('Layer'),ScrollRect:Symbol('ScrollRect'),Snapshot:Symbol('Snapshot')};LayerViewer.LayerView.LayerSelection=class extends LayerViewer.LayerView.Selection{constructor(layer){console.assert(layer,'LayerSelection with empty layer');super(LayerViewer.LayerView.Selection.Type.Layer,layer);} -_isEqual(other){return other._type===LayerViewer.LayerView.Selection.Type.Layer&&other.layer().id()===this.layer().id();}};LayerViewer.LayerView.ScrollRectSelection=class extends LayerViewer.LayerView.Selection{constructor(layer,scrollRectIndex){super(LayerViewer.LayerView.Selection.Type.ScrollRect,layer);this.scrollRectIndex=scrollRectIndex;} -_isEqual(other){return other._type===LayerViewer.LayerView.Selection.Type.ScrollRect&&this.layer().id()===other.layer().id()&&this.scrollRectIndex===other.scrollRectIndex;}};LayerViewer.LayerView.SnapshotSelection=class extends LayerViewer.LayerView.Selection{constructor(layer,snapshot){super(LayerViewer.LayerView.Selection.Type.Snapshot,layer);this._snapshot=snapshot;} -_isEqual(other){return other._type===LayerViewer.LayerView.Selection.Type.Snapshot&&this.layer().id()===other.layer().id()&&this._snapshot===other._snapshot;} -snapshot(){return this._snapshot;}};LayerViewer.LayerViewHost=class{constructor(){this._views=[];this._selectedObject=null;this._hoveredObject=null;this._showInternalLayersSetting=Common.settings.createSetting('layersShowInternalLayers',false);} -registerView(layerView){this._views.push(layerView);} -setLayerTree(layerTree){this._target=layerTree.target();var selectedLayer=this._selectedObject&&this._selectedObject.layer();if(selectedLayer&&(!layerTree||!layerTree.layerById(selectedLayer.id()))) -this.selectObject(null);var hoveredLayer=this._hoveredObject&&this._hoveredObject.layer();if(hoveredLayer&&(!layerTree||!layerTree.layerById(hoveredLayer.id()))) -this.hoverObject(null);for(var view of this._views) -view.setLayerTree(layerTree);} -hoverObject(selection){if(LayerViewer.LayerView.Selection.isEqual(this._hoveredObject,selection)) -return;this._hoveredObject=selection;var layer=selection&&selection.layer();this._toggleNodeHighlight(layer?layer.nodeForSelfOrAncestor():null);for(var view of this._views) -view.hoverObject(selection);} -selectObject(selection){if(LayerViewer.LayerView.Selection.isEqual(this._selectedObject,selection)) -return;this._selectedObject=selection;for(var view of this._views) -view.selectObject(selection);} -selection(){return this._selectedObject;} -showContextMenu(contextMenu,selection){contextMenu.defaultSection().appendCheckboxItem(Common.UIString('Show internal layers'),this._toggleShowInternalLayers.bind(this),this._showInternalLayersSetting.get());var node=selection&&selection.layer()&&selection.layer().nodeForSelfOrAncestor();if(node) -contextMenu.appendApplicableItems(node);contextMenu.show();} -showInternalLayersSetting(){return this._showInternalLayersSetting;} -_toggleShowInternalLayers(){this._showInternalLayersSetting.set(!this._showInternalLayersSetting.get());} -_toggleNodeHighlight(node){if(node){node.highlightForTwoSeconds();return;} -SDK.OverlayModel.hideDOMNodeHighlight();}};;LayerViewer.Layers3DView=class extends UI.VBox{constructor(layerViewHost){super(true);this.registerRequiredCSS('layer_viewer/layers3DView.css');this.contentElement.classList.add('layers-3d-view');this._failBanner=new UI.VBox();this._failBanner.element.classList.add('full-widget-dimmed-banner');this._failBanner.element.createTextChild(Common.UIString('Layer information is not yet available.'));this._layerViewHost=layerViewHost;this._layerViewHost.registerView(this);this._transformController=new LayerViewer.TransformController(this.contentElement);this._transformController.addEventListener(LayerViewer.TransformController.Events.TransformChanged,this._update,this);this._initToolbar();this._canvasElement=this.contentElement.createChild('canvas');this._canvasElement.tabIndex=0;this._canvasElement.addEventListener('dblclick',this._onDoubleClick.bind(this),false);this._canvasElement.addEventListener('mousedown',this._onMouseDown.bind(this),false);this._canvasElement.addEventListener('mouseup',this._onMouseUp.bind(this),false);this._canvasElement.addEventListener('mouseleave',this._onMouseMove.bind(this),false);this._canvasElement.addEventListener('mousemove',this._onMouseMove.bind(this),false);this._canvasElement.addEventListener('contextmenu',this._onContextMenu.bind(this),false);this._lastSelection={};this._layerTree=null;this._textureManager=new LayerViewer.LayerTextureManager(this._update.bind(this));this._chromeTextures=[];this._rects=[];this._layerViewHost.showInternalLayersSetting().addChangeListener(this._update,this);} -setLayerTree(layerTree){this._layerTree=layerTree;this._layerTexture=null;delete this._oldTextureScale;if(this._showPaints()) -this._textureManager.setLayerTree(layerTree);this._update();} -showImageForLayer(layer,imageURL){if(!imageURL){this._layerTexture=null;this._update();return;} -UI.loadImage(imageURL).then(image=>{var texture=image&&LayerViewer.LayerTextureManager._createTextureForImage(this._gl,image);this._layerTexture=texture?{layer:layer,texture:texture}:null;this._update();});} -onResize(){this._resizeCanvas();this._update();} -willHide(){this._textureManager.suspend();} -wasShown(){this._textureManager.resume();if(!this._needsUpdate) -return;this._resizeCanvas();this._update();} -updateLayerSnapshot(layer){this._textureManager.layerNeedsUpdate(layer);} -_setOutline(type,selection){this._lastSelection[type]=selection;this._update();} -hoverObject(selection){this._setOutline(LayerViewer.Layers3DView.OutlineType.Hovered,selection);} -selectObject(selection){this._setOutline(LayerViewer.Layers3DView.OutlineType.Hovered,null);this._setOutline(LayerViewer.Layers3DView.OutlineType.Selected,selection);} -snapshotForSelection(selection){if(selection.type()===LayerViewer.LayerView.Selection.Type.Snapshot){var snapshotWithRect=(selection).snapshot();snapshotWithRect.snapshot.addReference();return(Promise.resolve(snapshotWithRect));} -if(selection.layer()){var promise=selection.layer().snapshots()[0];if(promise) -return promise;} -return(Promise.resolve(null));} -_initGL(canvas){var gl=canvas.getContext('webgl');if(!gl) -return null;gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);gl.enable(gl.BLEND);gl.clearColor(0.0,0.0,0.0,0.0);gl.enable(gl.DEPTH_TEST);return gl;} -_createShader(type,script){var shader=this._gl.createShader(type);this._gl.shaderSource(shader,script);this._gl.compileShader(shader);this._gl.attachShader(this._shaderProgram,shader);} -_initShaders(){this._shaderProgram=this._gl.createProgram();this._createShader(this._gl.FRAGMENT_SHADER,LayerViewer.Layers3DView.FragmentShader);this._createShader(this._gl.VERTEX_SHADER,LayerViewer.Layers3DView.VertexShader);this._gl.linkProgram(this._shaderProgram);this._gl.useProgram(this._shaderProgram);this._shaderProgram.vertexPositionAttribute=this._gl.getAttribLocation(this._shaderProgram,'aVertexPosition');this._gl.enableVertexAttribArray(this._shaderProgram.vertexPositionAttribute);this._shaderProgram.vertexColorAttribute=this._gl.getAttribLocation(this._shaderProgram,'aVertexColor');this._gl.enableVertexAttribArray(this._shaderProgram.vertexColorAttribute);this._shaderProgram.textureCoordAttribute=this._gl.getAttribLocation(this._shaderProgram,'aTextureCoord');this._gl.enableVertexAttribArray(this._shaderProgram.textureCoordAttribute);this._shaderProgram.pMatrixUniform=this._gl.getUniformLocation(this._shaderProgram,'uPMatrix');this._shaderProgram.samplerUniform=this._gl.getUniformLocation(this._shaderProgram,'uSampler');} -_resizeCanvas(){this._canvasElement.width=this._canvasElement.offsetWidth*window.devicePixelRatio;this._canvasElement.height=this._canvasElement.offsetHeight*window.devicePixelRatio;} -_updateTransformAndConstraints(){var paddingFraction=0.1;var viewport=this._layerTree.viewportSize();var baseWidth=viewport?viewport.width:this._dimensionsForAutoscale.width;var baseHeight=viewport?viewport.height:this._dimensionsForAutoscale.height;var canvasWidth=this._canvasElement.width;var canvasHeight=this._canvasElement.height;var paddingX=canvasWidth*paddingFraction;var paddingY=canvasHeight*paddingFraction;var scaleX=(canvasWidth-2*paddingX)/baseWidth;var scaleY=(canvasHeight-2*paddingY)/baseHeight;var viewScale=Math.min(scaleX,scaleY);var minScaleConstraint=Math.min(baseWidth/this._dimensionsForAutoscale.width,baseHeight/this._dimensionsForAutoscale.width)/2;this._transformController.setScaleConstraints(minScaleConstraint,10/viewScale);var scale=this._transformController.scale();var rotateX=this._transformController.rotateX();var rotateY=this._transformController.rotateY();this._scale=scale*viewScale;var textureScale=Number.constrain(this._scale,0.1,1);if(textureScale!==this._oldTextureScale){this._oldTextureScale=textureScale;this._textureManager.setScale(textureScale);this.dispatchEventToListeners(LayerViewer.Layers3DView.Events.ScaleChanged,textureScale);} -var scaleAndRotationMatrix=new WebKitCSSMatrix().scale(scale,scale,scale).translate(canvasWidth/2,canvasHeight/2,0).rotate(rotateX,rotateY,0).scale(viewScale,viewScale,viewScale).translate(-baseWidth/2,-baseHeight/2,0);var bounds;for(var i=0;i<this._rects.length;++i) -bounds=UI.Geometry.boundsForTransformedPoints(scaleAndRotationMatrix,this._rects[i].vertices,bounds);this._transformController.clampOffsets((paddingX-bounds.maxX)/window.devicePixelRatio,(canvasWidth-paddingX-bounds.minX)/window.devicePixelRatio,(paddingY-bounds.maxY)/window.devicePixelRatio,(canvasHeight-paddingY-bounds.minY)/window.devicePixelRatio);var offsetX=this._transformController.offsetX()*window.devicePixelRatio;var offsetY=this._transformController.offsetY()*window.devicePixelRatio;this._projectionMatrix=new WebKitCSSMatrix().translate(offsetX,offsetY,0).multiply(scaleAndRotationMatrix);var glProjectionMatrix=new WebKitCSSMatrix().scale(1,-1,-1).translate(-1,-1,0).scale(2/this._canvasElement.width,2/this._canvasElement.height,1/1000000).multiply(this._projectionMatrix);this._gl.uniformMatrix4fv(this._shaderProgram.pMatrixUniform,false,this._arrayFromMatrix(glProjectionMatrix));} -_arrayFromMatrix(m){return new Float32Array([m.m11,m.m12,m.m13,m.m14,m.m21,m.m22,m.m23,m.m24,m.m31,m.m32,m.m33,m.m34,m.m41,m.m42,m.m43,m.m44]);} -_initWhiteTexture(){this._whiteTexture=this._gl.createTexture();this._gl.bindTexture(this._gl.TEXTURE_2D,this._whiteTexture);var whitePixel=new Uint8Array([255,255,255,255]);this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,1,1,0,this._gl.RGBA,this._gl.UNSIGNED_BYTE,whitePixel);} -_initChromeTextures(){function loadChromeTexture(index,url){UI.loadImage(url).then(image=>{this._chromeTextures[index]=image&&LayerViewer.LayerTextureManager._createTextureForImage(this._gl,image)||undefined;});} -loadChromeTexture.call(this,LayerViewer.Layers3DView.ChromeTexture.Left,'Images/chromeLeft.png');loadChromeTexture.call(this,LayerViewer.Layers3DView.ChromeTexture.Middle,'Images/chromeMiddle.png');loadChromeTexture.call(this,LayerViewer.Layers3DView.ChromeTexture.Right,'Images/chromeRight.png');} -_initGLIfNecessary(){if(this._gl) -return this._gl;this._gl=this._initGL(this._canvasElement);if(!this._gl) -return null;this._initShaders();this._initWhiteTexture();this._initChromeTextures();this._textureManager.setContext(this._gl);return this._gl;} -_calculateDepthsAndVisibility(){this._depthByLayerId={};var depth=0;var showInternalLayers=this._layerViewHost.showInternalLayersSetting().get();var root=showInternalLayers?this._layerTree.root():(this._layerTree.contentRoot()||this._layerTree.root());var queue=[root];this._depthByLayerId[root.id()]=0;this._visibleLayers=new Set();while(queue.length>0){var layer=queue.shift();if(showInternalLayers||layer.drawsContent()) -this._visibleLayers.add(layer);var children=layer.children();for(var i=0;i<children.length;++i){this._depthByLayerId[children[i].id()]=++depth;queue.push(children[i]);}} -this._maxDepth=depth;} -_depthForLayer(layer){return this._depthByLayerId[layer.id()]*LayerViewer.Layers3DView.LayerSpacing;} -_calculateScrollRectDepth(layer,index){return this._depthForLayer(layer)+index*LayerViewer.Layers3DView.ScrollRectSpacing+1;} -_updateDimensionsForAutoscale(layer){this._dimensionsForAutoscale.width=Math.max(layer.width(),this._dimensionsForAutoscale.width);this._dimensionsForAutoscale.height=Math.max(layer.height(),this._dimensionsForAutoscale.height);} -_calculateLayerRect(layer){if(!this._visibleLayers.has(layer)) -return;var selection=new LayerViewer.LayerView.LayerSelection(layer);var rect=new LayerViewer.Layers3DView.Rectangle(selection);rect.setVertices(layer.quad(),this._depthForLayer(layer));this._appendRect(rect);this._updateDimensionsForAutoscale(layer);} -_appendRect(rect){var selection=rect.relatedObject;var isSelected=LayerViewer.LayerView.Selection.isEqual(this._lastSelection[LayerViewer.Layers3DView.OutlineType.Selected],selection);var isHovered=LayerViewer.LayerView.Selection.isEqual(this._lastSelection[LayerViewer.Layers3DView.OutlineType.Hovered],selection);if(isSelected){rect.borderColor=LayerViewer.Layers3DView.SelectedBorderColor;}else if(isHovered){rect.borderColor=LayerViewer.Layers3DView.HoveredBorderColor;var fillColor=rect.fillColor||[255,255,255,1];var maskColor=LayerViewer.Layers3DView.HoveredImageMaskColor;rect.fillColor=[fillColor[0]*maskColor[0]/255,fillColor[1]*maskColor[1]/255,fillColor[2]*maskColor[2]/255,fillColor[3]*maskColor[3]];}else{rect.borderColor=LayerViewer.Layers3DView.BorderColor;} -rect.lineWidth=isSelected?LayerViewer.Layers3DView.SelectedBorderWidth:LayerViewer.Layers3DView.BorderWidth;this._rects.push(rect);} -_calculateLayerScrollRects(layer){var scrollRects=layer.scrollRects();for(var i=0;i<scrollRects.length;++i){var selection=new LayerViewer.LayerView.ScrollRectSelection(layer,i);var rect=new LayerViewer.Layers3DView.Rectangle(selection);rect.calculateVerticesFromRect(layer,scrollRects[i].rect,this._calculateScrollRectDepth(layer,i));rect.fillColor=LayerViewer.Layers3DView.ScrollRectBackgroundColor;this._appendRect(rect);}} -_calculateLayerTileRects(layer){var tiles=this._textureManager.tilesForLayer(layer);for(var i=0;i<tiles.length;++i){var tile=tiles[i];if(!tile.texture) -continue;var selection=new LayerViewer.LayerView.SnapshotSelection(layer,{rect:tile.rect,snapshot:tile.snapshot});var rect=new LayerViewer.Layers3DView.Rectangle(selection);rect.calculateVerticesFromRect(layer,tile.rect,this._depthForLayer(layer)+1);rect.texture=tile.texture;this._appendRect(rect);}} -_calculateRects(){this._rects=[];this._dimensionsForAutoscale={width:0,height:0};this._layerTree.forEachLayer(this._calculateLayerRect.bind(this));if(this._showSlowScrollRectsSetting.get()) -this._layerTree.forEachLayer(this._calculateLayerScrollRects.bind(this));if(this._layerTexture&&this._visibleLayers.has(this._layerTexture.layer)){var layer=this._layerTexture.layer;var selection=new LayerViewer.LayerView.LayerSelection(layer);var rect=new LayerViewer.Layers3DView.Rectangle(selection);rect.setVertices(layer.quad(),this._depthForLayer(layer));rect.texture=this._layerTexture.texture;this._appendRect(rect);}else if(this._showPaints()){this._layerTree.forEachLayer(this._calculateLayerTileRects.bind(this));}} -_makeColorsArray(color){var colors=[];var normalizedColor=[color[0]/255,color[1]/255,color[2]/255,color[3]];for(var i=0;i<4;i++) -colors=colors.concat(normalizedColor);return colors;} -_setVertexAttribute(attribute,array,length){var gl=this._gl;var buffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(array),gl.STATIC_DRAW);gl.vertexAttribPointer(attribute,length,gl.FLOAT,false,0,0);} -_drawRectangle(vertices,mode,color,texture){var gl=this._gl;var white=[255,255,255,1];color=color||white;this._setVertexAttribute(this._shaderProgram.vertexPositionAttribute,vertices,3);this._setVertexAttribute(this._shaderProgram.textureCoordAttribute,[0,1,1,1,1,0,0,0],2);this._setVertexAttribute(this._shaderProgram.vertexColorAttribute,this._makeColorsArray(color),color.length);if(texture){gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,texture);gl.uniform1i(this._shaderProgram.samplerUniform,0);}else{gl.bindTexture(gl.TEXTURE_2D,this._whiteTexture);} -var numberOfVertices=vertices.length/3;gl.drawArrays(mode,0,numberOfVertices);} -_drawTexture(vertices,texture,color){this._drawRectangle(vertices,this._gl.TRIANGLE_FAN,color,texture);} -_drawViewportAndChrome(){var viewport=this._layerTree.viewportSize();if(!viewport) -return;var drawChrome=!Common.moduleSetting('frameViewerHideChromeWindow').get()&&this._chromeTextures.length>=3&&this._chromeTextures.indexOf(undefined)<0;var z=(this._maxDepth+1)*LayerViewer.Layers3DView.LayerSpacing;var borderWidth=Math.ceil(LayerViewer.Layers3DView.ViewportBorderWidth*this._scale);var vertices=[viewport.width,0,z,viewport.width,viewport.height,z,0,viewport.height,z,0,0,z];this._gl.lineWidth(borderWidth);this._drawRectangle(vertices,drawChrome?this._gl.LINE_STRIP:this._gl.LINE_LOOP,LayerViewer.Layers3DView.ViewportBorderColor);if(!drawChrome) -return;var borderAdjustment=LayerViewer.Layers3DView.ViewportBorderWidth/2;var viewportWidth=this._layerTree.viewportSize().width+2*borderAdjustment;var chromeHeight=this._chromeTextures[0].image.naturalHeight;var middleFragmentWidth=viewportWidth-this._chromeTextures[0].image.naturalWidth-this._chromeTextures[2].image.naturalWidth;var x=-borderAdjustment;var y=-chromeHeight;for(var i=0;i<this._chromeTextures.length;++i){var width=i===LayerViewer.Layers3DView.ChromeTexture.Middle?middleFragmentWidth:this._chromeTextures[i].image.naturalWidth;if(width<0||x+width>viewportWidth) -break;vertices=[x,y,z,x+width,y,z,x+width,y+chromeHeight,z,x,y+chromeHeight,z];this._drawTexture(vertices,(this._chromeTextures[i]));x+=width;}} -_drawViewRect(rect){var vertices=rect.vertices;if(rect.texture) -this._drawTexture(vertices,rect.texture,rect.fillColor||undefined);else if(rect.fillColor) -this._drawRectangle(vertices,this._gl.TRIANGLE_FAN,rect.fillColor);this._gl.lineWidth(rect.lineWidth);if(rect.borderColor) -this._drawRectangle(vertices,this._gl.LINE_LOOP,rect.borderColor);} -_update(){if(!this.isShowing()){this._needsUpdate=true;return;} -if(!this._layerTree||!this._layerTree.root()){this._failBanner.show(this.contentElement);return;} -var gl=this._initGLIfNecessary();if(!gl){this._failBanner.element.removeChildren();this._failBanner.element.appendChild(this._webglDisabledBanner());this._failBanner.show(this.contentElement);return;} -this._failBanner.detach();this._gl.viewportWidth=this._canvasElement.width;this._gl.viewportHeight=this._canvasElement.height;this._calculateDepthsAndVisibility();this._calculateRects();this._updateTransformAndConstraints();gl.viewport(0,0,gl.viewportWidth,gl.viewportHeight);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);this._rects.forEach(this._drawViewRect.bind(this));this._drawViewportAndChrome();} -_webglDisabledBanner(){var fragment=this.contentElement.ownerDocument.createDocumentFragment();fragment.createChild('div').textContent=Common.UIString('Can\'t display layers,');fragment.createChild('div').textContent=Common.UIString('WebGL support is disabled in your browser.');fragment.appendChild(UI.formatLocalized('Check %s for possible reasons.',[UI.createExternalLink('about:gpu')]));return fragment;} -_selectionFromEventPoint(event){if(!this._layerTree) -return null;var closestIntersectionPoint=Infinity;var closestObject=null;var projectionMatrix=new WebKitCSSMatrix().scale(1,-1,-1).translate(-1,-1,0).multiply(this._projectionMatrix);var x0=(event.clientX-this._canvasElement.totalOffsetLeft())*window.devicePixelRatio;var y0=-(event.clientY-this._canvasElement.totalOffsetTop())*window.devicePixelRatio;function checkIntersection(rect){if(!rect.relatedObject) -return;var t=rect.intersectWithLine(projectionMatrix,x0,y0);if(t<closestIntersectionPoint){closestIntersectionPoint=t;closestObject=rect.relatedObject;}} -this._rects.forEach(checkIntersection);return closestObject;} -_createVisibilitySetting(caption,name,value,toolbar){var setting=Common.settings.createSetting(name,value);setting.setTitle(Common.UIString(caption));setting.addChangeListener(this._update,this);toolbar.appendToolbarItem(new UI.ToolbarSettingCheckbox(setting));return setting;} -_initToolbar(){this._panelToolbar=this._transformController.toolbar();this.contentElement.appendChild(this._panelToolbar.element);this._showSlowScrollRectsSetting=this._createVisibilitySetting('Slow scroll rects','frameViewerShowSlowScrollRects',true,this._panelToolbar);this._showPaintsSetting=this._createVisibilitySetting('Paints','frameViewerShowPaints',true,this._panelToolbar);this._showPaintsSetting.addChangeListener(this._updatePaints,this);Common.moduleSetting('frameViewerHideChromeWindow').addChangeListener(this._update,this);} -_onContextMenu(event){var contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Reset View'),this._transformController.resetAndNotify.bind(this._transformController),false);var selection=this._selectionFromEventPoint(event);if(selection&&selection.type()===LayerViewer.LayerView.Selection.Type.Snapshot){contextMenu.defaultSection().appendItem(Common.UIString('Show Paint Profiler'),this.dispatchEventToListeners.bind(this,LayerViewer.Layers3DView.Events.PaintProfilerRequested,selection),false);} -this._layerViewHost.showContextMenu(contextMenu,selection);} -_onMouseMove(event){if(event.which) -return;this._layerViewHost.hoverObject(this._selectionFromEventPoint(event));} -_onMouseDown(event){this._mouseDownX=event.clientX;this._mouseDownY=event.clientY;} -_onMouseUp(event){const maxDistanceInPixels=6;if(this._mouseDownX&&Math.abs(event.clientX-this._mouseDownX)<maxDistanceInPixels&&Math.abs(event.clientY-this._mouseDownY)<maxDistanceInPixels) -this._layerViewHost.selectObject(this._selectionFromEventPoint(event));delete this._mouseDownX;delete this._mouseDownY;} -_onDoubleClick(event){var selection=this._selectionFromEventPoint(event);if(selection&&(selection.type()===LayerViewer.LayerView.Selection.Type.Snapshot||selection.layer())) -this.dispatchEventToListeners(LayerViewer.Layers3DView.Events.PaintProfilerRequested,selection);event.stopPropagation();} -_updatePaints(){if(this._showPaints()){this._textureManager.setLayerTree(this._layerTree);this._textureManager.forceUpdate();}else{this._textureManager.reset();} -this._update();} -_showPaints(){return this._showPaintsSetting.get();}};LayerViewer.Layers3DView.LayerStyle;LayerViewer.Layers3DView.OutlineType={Hovered:'hovered',Selected:'selected'};LayerViewer.Layers3DView.Events={PaintProfilerRequested:Symbol('PaintProfilerRequested'),ScaleChanged:Symbol('ScaleChanged')};LayerViewer.Layers3DView.ChromeTexture={Left:0,Middle:1,Right:2};LayerViewer.Layers3DView.ScrollRectTitles={RepaintsOnScroll:Common.UIString('repaints on scroll'),TouchEventHandler:Common.UIString('touch event listener'),WheelEventHandler:Common.UIString('mousewheel event listener')};LayerViewer.Layers3DView.FragmentShader=''+'precision mediump float;\n'+'varying vec4 vColor;\n'+'varying vec2 vTextureCoord;\n'+'uniform sampler2D uSampler;\n'+'void main(void)\n'+'{\n'+' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)) * vColor;\n'+'}';LayerViewer.Layers3DView.VertexShader=''+'attribute vec3 aVertexPosition;\n'+'attribute vec2 aTextureCoord;\n'+'attribute vec4 aVertexColor;\n'+'uniform mat4 uPMatrix;\n'+'varying vec2 vTextureCoord;\n'+'varying vec4 vColor;\n'+'void main(void)\n'+'{\n'+'gl_Position = uPMatrix * vec4(aVertexPosition, 1.0);\n'+'vColor = aVertexColor;\n'+'vTextureCoord = aTextureCoord;\n'+'}';LayerViewer.Layers3DView.HoveredBorderColor=[0,0,255,1];LayerViewer.Layers3DView.SelectedBorderColor=[0,255,0,1];LayerViewer.Layers3DView.BorderColor=[0,0,0,1];LayerViewer.Layers3DView.ViewportBorderColor=[160,160,160,1];LayerViewer.Layers3DView.ScrollRectBackgroundColor=[178,100,100,0.6];LayerViewer.Layers3DView.HoveredImageMaskColor=[200,200,255,1];LayerViewer.Layers3DView.BorderWidth=1;LayerViewer.Layers3DView.SelectedBorderWidth=2;LayerViewer.Layers3DView.ViewportBorderWidth=3;LayerViewer.Layers3DView.LayerSpacing=20;LayerViewer.Layers3DView.ScrollRectSpacing=4;LayerViewer.LayerTextureManager=class{constructor(textureUpdatedCallback){this._textureUpdatedCallback=textureUpdatedCallback;this._throttler=new Common.Throttler(0);this._scale=0;this._active=false;this.reset();} -static _createTextureForImage(gl,image){var texture=gl.createTexture();texture.image=image;gl.bindTexture(gl.TEXTURE_2D,texture);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,1);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,texture.image);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.bindTexture(gl.TEXTURE_2D,null);return texture;} -reset(){if(this._tilesByLayer) -this.setLayerTree(null);this._tilesByLayer=new Map();this._queue=[];} -setContext(glContext){this._gl=glContext;if(this._scale) -this._updateTextures();} -suspend(){this._active=false;} -resume(){this._active=true;if(this._queue.length) -this._update();} -setLayerTree(layerTree){var newLayers=new Set();var oldLayers=Array.from(this._tilesByLayer.keys());if(layerTree){layerTree.forEachLayer(layer=>{if(!layer.drawsContent()) -return;newLayers.add(layer);if(!this._tilesByLayer.has(layer)){this._tilesByLayer.set(layer,[]);this.layerNeedsUpdate(layer);}});} -if(!oldLayers.length) -this.forceUpdate();for(var layer of oldLayers){if(newLayers.has(layer)) -continue;this._tilesByLayer.get(layer).forEach(tile=>tile.dispose());this._tilesByLayer.delete(layer);}} -_setSnapshotsForLayer(layer,snapshots){var oldSnapshotsToTiles=new Map((this._tilesByLayer.get(layer)||[]).map(tile=>[tile.snapshot,tile]));var newTiles=[];var reusedTiles=[];for(var snapshot of snapshots){var oldTile=oldSnapshotsToTiles.get(snapshot);if(oldTile){reusedTiles.push(oldTile);oldSnapshotsToTiles.delete(oldTile);}else{newTiles.push(new LayerViewer.LayerTextureManager.Tile(snapshot));}} -this._tilesByLayer.set(layer,reusedTiles.concat(newTiles));for(var tile of oldSnapshotsToTiles.values()) -tile.dispose();if(!this._gl||!this._scale) -return Promise.resolve();return Promise.all(newTiles.map(tile=>tile.update(this._gl,this._scale))).then(this._textureUpdatedCallback);} -setScale(scale){if(this._scale&&this._scale>=scale) -return;this._scale=scale;this._updateTextures();} -tilesForLayer(layer){return this._tilesByLayer.get(layer)||[];} -layerNeedsUpdate(layer){if(this._queue.indexOf(layer)<0) -this._queue.push(layer);if(this._active) -this._throttler.schedule(this._update.bind(this));} -forceUpdate(){this._queue.forEach(layer=>this._updateLayer(layer));this._queue=[];this._update();} -_update(){var layer=this._queue.shift();if(!layer) -return Promise.resolve();if(this._queue.length) -this._throttler.schedule(this._update.bind(this));return this._updateLayer(layer);} -_updateLayer(layer){return Promise.all(layer.snapshots()).then(snapshots=>this._setSnapshotsForLayer(layer,snapshots.filter(snapshot=>!!snapshot)));} -_updateTextures(){if(!this._gl) -return;if(!this._scale) -return;for(var tiles of this._tilesByLayer.values()){for(var tile of tiles){var promise=tile.updateScale(this._gl,this._scale);if(promise) -promise.then(this._textureUpdatedCallback);}}}};LayerViewer.Layers3DView.Rectangle=class{constructor(relatedObject){this.relatedObject=relatedObject;this.lineWidth=1;this.borderColor=null;this.fillColor=null;this.texture=null;} -setVertices(quad,z){this.vertices=[quad[0],quad[1],z,quad[2],quad[3],z,quad[4],quad[5],z,quad[6],quad[7],z];} -_calculatePointOnQuad(quad,ratioX,ratioY){var x0=quad[0];var y0=quad[1];var x1=quad[2];var y1=quad[3];var x2=quad[4];var y2=quad[5];var x3=quad[6];var y3=quad[7];var firstSidePointX=x0+ratioX*(x1-x0);var firstSidePointY=y0+ratioX*(y1-y0);var thirdSidePointX=x3+ratioX*(x2-x3);var thirdSidePointY=y3+ratioX*(y2-y3);var x=firstSidePointX+ratioY*(thirdSidePointX-firstSidePointX);var y=firstSidePointY+ratioY*(thirdSidePointY-firstSidePointY);return[x,y];} -calculateVerticesFromRect(layer,rect,z){var quad=layer.quad();var rx1=rect.x/layer.width();var rx2=(rect.x+rect.width)/layer.width();var ry1=rect.y/layer.height();var ry2=(rect.y+rect.height)/layer.height();var rectQuad=this._calculatePointOnQuad(quad,rx1,ry1).concat(this._calculatePointOnQuad(quad,rx2,ry1)).concat(this._calculatePointOnQuad(quad,rx2,ry2)).concat(this._calculatePointOnQuad(quad,rx1,ry2));this.setVertices(rectQuad,z);} -intersectWithLine(matrix,x0,y0){var i;var points=[];for(i=0;i<4;++i){points[i]=UI.Geometry.multiplyVectorByMatrixAndNormalize(new UI.Geometry.Vector(this.vertices[i*3],this.vertices[i*3+1],this.vertices[i*3+2]),matrix);} -var normal=UI.Geometry.crossProduct(UI.Geometry.subtract(points[1],points[0]),UI.Geometry.subtract(points[2],points[1]));var A=normal.x;var B=normal.y;var C=normal.z;var D=-(A*points[0].x+B*points[0].y+C*points[0].z);var t=-(D+A*x0+B*y0)/C;var pt=new UI.Geometry.Vector(x0,y0,t);var tVects=points.map(UI.Geometry.subtract.bind(null,pt));for(i=0;i<tVects.length;++i){var product=UI.Geometry.scalarProduct(normal,UI.Geometry.crossProduct(tVects[i],tVects[(i+1)%tVects.length]));if(product<0) -return undefined;} -return t;}};LayerViewer.LayerTextureManager.Tile=class{constructor(snapshotWithRect){this.snapshot=snapshotWithRect.snapshot;this.rect=snapshotWithRect.rect;this.scale=0;this.texture=null;} -dispose(){this.snapshot.release();if(this.texture){this._gl.deleteTexture(this.texture);this.texture=null;}} -updateScale(glContext,scale){if(this.texture&&this.scale>=scale) -return null;return this.update(glContext,scale);} -async update(glContext,scale){this._gl=glContext;this.scale=scale;var imageURL=await this.snapshot.replay(scale);var image=imageURL&&await UI.loadImage(imageURL);this.texture=image&&LayerViewer.LayerTextureManager._createTextureForImage(glContext,image);}};;LayerViewer.PaintProfilerView=class extends UI.HBox{constructor(showImageCallback){super(true);this.registerRequiredCSS('layer_viewer/paintProfiler.css');this.contentElement.classList.add('paint-profiler-overview');this._canvasContainer=this.contentElement.createChild('div','paint-profiler-canvas-container');this._progressBanner=this.contentElement.createChild('div','full-widget-dimmed-banner hidden');this._progressBanner.textContent=Common.UIString('Profiling\u2026');this._pieChart=new PerfUI.PieChart(55,this._formatPieChartTime.bind(this),true);this._pieChart.element.classList.add('paint-profiler-pie-chart');this.contentElement.appendChild(this._pieChart.element);this._showImageCallback=showImageCallback;this._canvas=this._canvasContainer.createChild('canvas','fill');this._context=this._canvas.getContext('2d');this._selectionWindow=new PerfUI.OverviewGrid.Window(this._canvasContainer);this._selectionWindow.addEventListener(PerfUI.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);this._innerBarWidth=4*window.devicePixelRatio;this._minBarHeight=window.devicePixelRatio;this._barPaddingWidth=2*window.devicePixelRatio;this._outerBarWidth=this._innerBarWidth+this._barPaddingWidth;this._pendingScale=1;this._scale=this._pendingScale;this._reset();} -static categories(){if(LayerViewer.PaintProfilerView._categories) -return LayerViewer.PaintProfilerView._categories;LayerViewer.PaintProfilerView._categories={shapes:new LayerViewer.PaintProfilerCategory('shapes',Common.UIString('Shapes'),'rgb(255, 161, 129)'),bitmap:new LayerViewer.PaintProfilerCategory('bitmap',Common.UIString('Bitmap'),'rgb(136, 196, 255)'),text:new LayerViewer.PaintProfilerCategory('text',Common.UIString('Text'),'rgb(180, 255, 137)'),misc:new LayerViewer.PaintProfilerCategory('misc',Common.UIString('Misc'),'rgb(206, 160, 255)')};return LayerViewer.PaintProfilerView._categories;} -static _initLogItemCategories(){if(LayerViewer.PaintProfilerView._logItemCategoriesMap) -return LayerViewer.PaintProfilerView._logItemCategoriesMap;var categories=LayerViewer.PaintProfilerView.categories();var logItemCategories={};logItemCategories['Clear']=categories['misc'];logItemCategories['DrawPaint']=categories['misc'];logItemCategories['DrawData']=categories['misc'];logItemCategories['SetMatrix']=categories['misc'];logItemCategories['PushCull']=categories['misc'];logItemCategories['PopCull']=categories['misc'];logItemCategories['Translate']=categories['misc'];logItemCategories['Scale']=categories['misc'];logItemCategories['Concat']=categories['misc'];logItemCategories['Restore']=categories['misc'];logItemCategories['SaveLayer']=categories['misc'];logItemCategories['Save']=categories['misc'];logItemCategories['BeginCommentGroup']=categories['misc'];logItemCategories['AddComment']=categories['misc'];logItemCategories['EndCommentGroup']=categories['misc'];logItemCategories['ClipRect']=categories['misc'];logItemCategories['ClipRRect']=categories['misc'];logItemCategories['ClipPath']=categories['misc'];logItemCategories['ClipRegion']=categories['misc'];logItemCategories['DrawPoints']=categories['shapes'];logItemCategories['DrawRect']=categories['shapes'];logItemCategories['DrawOval']=categories['shapes'];logItemCategories['DrawRRect']=categories['shapes'];logItemCategories['DrawPath']=categories['shapes'];logItemCategories['DrawVertices']=categories['shapes'];logItemCategories['DrawDRRect']=categories['shapes'];logItemCategories['DrawBitmap']=categories['bitmap'];logItemCategories['DrawBitmapRectToRect']=categories['bitmap'];logItemCategories['DrawBitmapMatrix']=categories['bitmap'];logItemCategories['DrawBitmapNine']=categories['bitmap'];logItemCategories['DrawSprite']=categories['bitmap'];logItemCategories['DrawPicture']=categories['bitmap'];logItemCategories['DrawText']=categories['text'];logItemCategories['DrawPosText']=categories['text'];logItemCategories['DrawPosTextH']=categories['text'];logItemCategories['DrawTextOnPath']=categories['text'];LayerViewer.PaintProfilerView._logItemCategoriesMap=logItemCategories;return logItemCategories;} -static _categoryForLogItem(logItem){var method=logItem.method.toTitleCase();var logItemCategories=LayerViewer.PaintProfilerView._initLogItemCategories();var result=logItemCategories[method];if(!result){result=LayerViewer.PaintProfilerView.categories()['misc'];logItemCategories[method]=result;} -return result;} -onResize(){this._update();} -async setSnapshotAndLog(snapshot,log,clipRect){this._reset();this._snapshot=snapshot;if(this._snapshot) -this._snapshot.addReference();this._log=log;this._logCategories=this._log.map(LayerViewer.PaintProfilerView._categoryForLogItem);if(!this._snapshot){this._update();this._pieChart.setTotal(0);this._selectionWindow.setEnabled(false);return;} -this._selectionWindow.setEnabled(true);this._progressBanner.classList.remove('hidden');this._updateImage();var profiles=await snapshot.profile(clipRect);this._progressBanner.classList.add('hidden');this._profiles=profiles;this._update();this._updatePieChart();} -setScale(scale){var needsUpdate=scale>this._scale;var predictiveGrowthFactor=2;this._pendingScale=Math.min(1,scale*predictiveGrowthFactor);if(needsUpdate&&this._snapshot) -this._updateImage();} -_update(){this._canvas.width=this._canvasContainer.clientWidth*window.devicePixelRatio;this._canvas.height=this._canvasContainer.clientHeight*window.devicePixelRatio;this._samplesPerBar=0;if(!this._profiles||!this._profiles.length) -return;var maxBars=Math.floor((this._canvas.width-2*this._barPaddingWidth)/this._outerBarWidth);var sampleCount=this._log.length;this._samplesPerBar=Math.ceil(sampleCount/maxBars);var maxBarTime=0;var barTimes=[];var barHeightByCategory=[];var heightByCategory={};for(var i=0,lastBarIndex=0,lastBarTime=0;i<sampleCount;){var categoryName=(this._logCategories[i]&&this._logCategories[i].name)||'misc';var sampleIndex=this._log[i].commandIndex;for(var row=0;row<this._profiles.length;row++){var sample=this._profiles[row][sampleIndex];lastBarTime+=sample;heightByCategory[categoryName]=(heightByCategory[categoryName]||0)+sample;} -++i;if(i-lastBarIndex===this._samplesPerBar||i===sampleCount){var factor=this._profiles.length*(i-lastBarIndex);lastBarTime/=factor;for(categoryName in heightByCategory) -heightByCategory[categoryName]/=factor;barTimes.push(lastBarTime);barHeightByCategory.push(heightByCategory);if(lastBarTime>maxBarTime) -maxBarTime=lastBarTime;lastBarTime=0;heightByCategory={};lastBarIndex=i;}} -const paddingHeight=4*window.devicePixelRatio;var scale=(this._canvas.height-paddingHeight-this._minBarHeight)/maxBarTime;for(var i=0;i<barTimes.length;++i){for(var categoryName in barHeightByCategory[i]) -barHeightByCategory[i][categoryName]*=(barTimes[i]*scale+this._minBarHeight)/barTimes[i];this._renderBar(i,barHeightByCategory[i]);}} -_renderBar(index,heightByCategory){var categories=LayerViewer.PaintProfilerView.categories();var currentHeight=0;var x=this._barPaddingWidth+index*this._outerBarWidth;for(var categoryName in categories){if(!heightByCategory[categoryName]) -continue;currentHeight+=heightByCategory[categoryName];var y=this._canvas.height-currentHeight;this._context.fillStyle=categories[categoryName].color;this._context.fillRect(x,y,this._innerBarWidth,heightByCategory[categoryName]);}} -_onWindowChanged(){this.dispatchEventToListeners(LayerViewer.PaintProfilerView.Events.WindowChanged);this._updatePieChart();if(this._updateImageTimer) -return;this._updateImageTimer=setTimeout(this._updateImage.bind(this),100);} -_updatePieChart(){var window=this.selectionWindow();if(!this._profiles||!this._profiles.length||!window) -return;var totalTime=0;var timeByCategory={};for(var i=window.left;i<window.right;++i){var logEntry=this._log[i];var category=LayerViewer.PaintProfilerView._categoryForLogItem(logEntry);timeByCategory[category.color]=timeByCategory[category.color]||0;for(var j=0;j<this._profiles.length;++j){var time=this._profiles[j][logEntry.commandIndex];totalTime+=time;timeByCategory[category.color]+=time;}} -this._pieChart.setTotal(totalTime/this._profiles.length);for(var color in timeByCategory) -this._pieChart.addSlice(timeByCategory[color]/this._profiles.length,color);} -_formatPieChartTime(value){return Number.millisToString(value*1000,true);} -selectionWindow(){if(!this._log) -return null;var screenLeft=this._selectionWindow.windowLeft*this._canvas.width;var screenRight=this._selectionWindow.windowRight*this._canvas.width;var barLeft=Math.floor(screenLeft/this._outerBarWidth);var barRight=Math.floor((screenRight+this._innerBarWidth-this._barPaddingWidth/2)/this._outerBarWidth);var stepLeft=Number.constrain(barLeft*this._samplesPerBar,0,this._log.length-1);var stepRight=Number.constrain(barRight*this._samplesPerBar,0,this._log.length);return{left:stepLeft,right:stepRight};} -_updateImage(){delete this._updateImageTimer;var left;var right;var window=this.selectionWindow();if(this._profiles&&this._profiles.length&&window){left=this._log[window.left].commandIndex;right=this._log[window.right-1].commandIndex;} -var scale=this._pendingScale;this._snapshot.replay(scale,left,right).then(image=>{if(!image) -return;this._scale=scale;this._showImageCallback(image);});} -_reset(){if(this._snapshot) -this._snapshot.release();this._snapshot=null;this._profiles=null;this._selectionWindow.reset();this._selectionWindow.setEnabled(false);}};LayerViewer.PaintProfilerView.Events={WindowChanged:Symbol('WindowChanged')};LayerViewer.PaintProfilerCommandLogView=class extends UI.ThrottledWidget{constructor(){super();this.setMinimumSize(100,25);this.element.classList.add('overflow-auto');this._treeOutline=new UI.TreeOutlineInShadow();this.element.appendChild(this._treeOutline.element);this._log=[];} -setCommandLog(log){this._log=log;this._treeItemCache=new Map();this.updateWindow({left:0,right:this._log.length});} -_appendLogItem(logItem){var treeElement=this._treeItemCache.get(logItem);if(!treeElement){treeElement=new LayerViewer.LogTreeElement(this,logItem);this._treeItemCache.set(logItem,treeElement);}else if(treeElement.parent){return;} -this._treeOutline.appendChild(treeElement);} -updateWindow(selectionWindow){this._selectionWindow=selectionWindow;this.update();} -doUpdate(){if(!this._selectionWindow||!this._log.length){this._treeOutline.removeChildren();return Promise.resolve();} -var root=this._treeOutline.rootElement();for(;;){var child=root.firstChild();if(!child||child._logItem.commandIndex>=this._selectionWindow.left) -break;root.removeChildAtIndex(0);} -for(;;){var child=root.lastChild();if(!child||child._logItem.commandIndex<this._selectionWindow.right) -break;root.removeChildAtIndex(root.children().length-1);} -for(var i=this._selectionWindow.left,right=this._selectionWindow.right;i<right;++i) -this._appendLogItem(this._log[i]);return Promise.resolve();}};LayerViewer.LogTreeElement=class extends UI.TreeElement{constructor(ownerView,logItem){super('',!!logItem.params);this._logItem=logItem;this._ownerView=ownerView;this._filled=false;} -onattach(){this._update();} -onpopulate(){for(var param in this._logItem.params) -LayerViewer.LogPropertyTreeElement._appendLogPropertyItem(this,param,this._logItem.params[param]);} -_paramToString(param,name){if(typeof param!=='object') -return typeof param==='string'&¶m.length>100?name:JSON.stringify(param);var str='';var keyCount=0;for(var key in param){if(++keyCount>4||typeof param[key]==='object'||(typeof param[key]==='string'&¶m[key].length>100)) -return name;if(str) -str+=', ';str+=param[key];} -return str;} -_paramsToString(params){var str='';for(var key in params){if(str) -str+=', ';str+=this._paramToString(params[key],key);} -return str;} -_update(){var title=createDocumentFragment();title.createTextChild(this._logItem.method+'('+this._paramsToString(this._logItem.params)+')');this.title=title;}};LayerViewer.LogPropertyTreeElement=class extends UI.TreeElement{constructor(property){super();this._property=property;} -static _appendLogPropertyItem(element,name,value){var treeElement=new LayerViewer.LogPropertyTreeElement({name:name,value:value});element.appendChild(treeElement);if(value&&typeof value==='object'){for(var property in value) -LayerViewer.LogPropertyTreeElement._appendLogPropertyItem(treeElement,property,value[property]);}} -onattach(){var title=createDocumentFragment();var nameElement=title.createChild('span','name');nameElement.textContent=this._property.name;var separatorElement=title.createChild('span','separator');separatorElement.textContent=': ';if(this._property.value===null||typeof this._property.value!=='object'){var valueElement=title.createChild('span','value');valueElement.textContent=JSON.stringify(this._property.value);valueElement.classList.add('cm-js-'+(this._property.value===null?'null':typeof this._property.value));} -this.title=title;}};LayerViewer.PaintProfilerCategory=class{constructor(name,title,color){this.name=name;this.title=title;this.color=color;}};;LayerViewer.TransformController=class extends Common.Object{constructor(element,disableRotate){super();this._shortcuts={};this.element=element;if(this.element.tabIndex<0) -this.element.tabIndex=0;this._registerShortcuts();UI.installDragHandle(element,this._onDragStart.bind(this),this._onDrag.bind(this),this._onDragEnd.bind(this),'move',null);element.addEventListener('keydown',this._onKeyDown.bind(this),false);element.addEventListener('keyup',this._onKeyUp.bind(this),false);element.addEventListener('mousewheel',this._onMouseWheel.bind(this),false);this._minScale=0;this._maxScale=Infinity;this._controlPanelToolbar=new UI.Toolbar('transform-control-panel');this._modeButtons={};if(!disableRotate){var panModeButton=new UI.ToolbarToggle(Common.UIString('Pan mode (X)'),'largeicon-pan');panModeButton.addEventListener(UI.ToolbarButton.Events.Click,this._setMode.bind(this,LayerViewer.TransformController.Modes.Pan));this._modeButtons[LayerViewer.TransformController.Modes.Pan]=panModeButton;this._controlPanelToolbar.appendToolbarItem(panModeButton);var rotateModeButton=new UI.ToolbarToggle(Common.UIString('Rotate mode (V)'),'largeicon-rotate');rotateModeButton.addEventListener(UI.ToolbarButton.Events.Click,this._setMode.bind(this,LayerViewer.TransformController.Modes.Rotate));this._modeButtons[LayerViewer.TransformController.Modes.Rotate]=rotateModeButton;this._controlPanelToolbar.appendToolbarItem(rotateModeButton);} -this._setMode(LayerViewer.TransformController.Modes.Pan);var resetButton=new UI.ToolbarButton(Common.UIString('Reset transform (0)'),'largeicon-center');resetButton.addEventListener(UI.ToolbarButton.Events.Click,this.resetAndNotify.bind(this,undefined));this._controlPanelToolbar.appendToolbarItem(resetButton);this._reset();} -toolbar(){return this._controlPanelToolbar;} -_onKeyDown(event){if(event.keyCode===UI.KeyboardShortcut.Keys.Shift.code){this._toggleMode();return;} -var shortcutKey=UI.KeyboardShortcut.makeKeyFromEventIgnoringModifiers(event);var handler=this._shortcuts[shortcutKey];if(handler&&handler(event)) -event.consume();} -_onKeyUp(event){if(event.keyCode===UI.KeyboardShortcut.Keys.Shift.code) -this._toggleMode();} -_addShortcuts(keys,handler){for(var i=0;i<keys.length;++i) -this._shortcuts[keys[i].key]=handler;} -_registerShortcuts(){this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.ResetView,this.resetAndNotify.bind(this));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.PanMode,this._setMode.bind(this,LayerViewer.TransformController.Modes.Pan));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.RotateMode,this._setMode.bind(this,LayerViewer.TransformController.Modes.Rotate));var zoomFactor=1.1;this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.ZoomIn,this._onKeyboardZoom.bind(this,zoomFactor));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.ZoomOut,this._onKeyboardZoom.bind(this,1/zoomFactor));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.Up,this._onKeyboardPanOrRotate.bind(this,0,-1));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.Down,this._onKeyboardPanOrRotate.bind(this,0,1));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.Left,this._onKeyboardPanOrRotate.bind(this,-1,0));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.Right,this._onKeyboardPanOrRotate.bind(this,1,0));} -_postChangeEvent(){this.dispatchEventToListeners(LayerViewer.TransformController.Events.TransformChanged);} -_reset(){this._scale=1;this._offsetX=0;this._offsetY=0;this._rotateX=0;this._rotateY=0;} -_toggleMode(){this._setMode(this._mode===LayerViewer.TransformController.Modes.Pan?LayerViewer.TransformController.Modes.Rotate:LayerViewer.TransformController.Modes.Pan);} -_setMode(mode){if(this._mode===mode) -return;this._mode=mode;this._updateModeButtons();this.element.focus();} -_updateModeButtons(){for(var mode in this._modeButtons) -this._modeButtons[mode].setToggled(mode===this._mode);} -resetAndNotify(event){this._reset();this._postChangeEvent();if(event) -event.preventDefault();this.element.focus();} -setScaleConstraints(minScale,maxScale){this._minScale=minScale;this._maxScale=maxScale;this._scale=Number.constrain(this._scale,minScale,maxScale);} -clampOffsets(minX,maxX,minY,maxY){this._offsetX=Number.constrain(this._offsetX,minX,maxX);this._offsetY=Number.constrain(this._offsetY,minY,maxY);} -scale(){return this._scale;} -offsetX(){return this._offsetX;} -offsetY(){return this._offsetY;} -rotateX(){return this._rotateX;} -rotateY(){return this._rotateY;} -_onScale(scaleFactor,x,y){scaleFactor=Number.constrain(this._scale*scaleFactor,this._minScale,this._maxScale)/this._scale;this._scale*=scaleFactor;this._offsetX-=(x-this._offsetX)*(scaleFactor-1);this._offsetY-=(y-this._offsetY)*(scaleFactor-1);this._postChangeEvent();} -_onPan(offsetX,offsetY){this._offsetX+=offsetX;this._offsetY+=offsetY;this._postChangeEvent();} -_onRotate(rotateX,rotateY){this._rotateX=rotateX;this._rotateY=rotateY;this._postChangeEvent();} -_onKeyboardZoom(zoomFactor){this._onScale(zoomFactor,this.element.clientWidth/2,this.element.clientHeight/2);} -_onKeyboardPanOrRotate(xMultiplier,yMultiplier){var panStepInPixels=6;var rotateStepInDegrees=5;if(this._mode===LayerViewer.TransformController.Modes.Rotate){this._onRotate(this._rotateX+yMultiplier*rotateStepInDegrees,this._rotateY+xMultiplier*rotateStepInDegrees);}else{this._onPan(xMultiplier*panStepInPixels,yMultiplier*panStepInPixels);}} -_onMouseWheel(event){var zoomFactor=1.1;var mouseWheelZoomSpeed=1/120;var scaleFactor=Math.pow(zoomFactor,event.wheelDeltaY*mouseWheelZoomSpeed);this._onScale(scaleFactor,event.clientX-this.element.totalOffsetLeft(),event.clientY-this.element.totalOffsetTop());} -_onDrag(event){if(this._mode===LayerViewer.TransformController.Modes.Rotate){this._onRotate(this._oldRotateX+(this._originY-event.clientY)/this.element.clientHeight*180,this._oldRotateY-(this._originX-event.clientX)/this.element.clientWidth*180);}else{this._onPan(event.clientX-this._originX,event.clientY-this._originY);this._originX=event.clientX;this._originY=event.clientY;}} -_onDragStart(event){this.element.focus();this._originX=event.clientX;this._originY=event.clientY;this._oldRotateX=this._rotateX;this._oldRotateY=this._rotateY;return true;} -_onDragEnd(){delete this._originX;delete this._originY;delete this._oldRotateX;delete this._oldRotateY;}};LayerViewer.TransformController.Events={TransformChanged:Symbol('TransformChanged')};LayerViewer.TransformController.Modes={Pan:'Pan',Rotate:'Rotate',};;Runtime.cachedResources["layer_viewer/layers3DView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.layers-3d-view {\n overflow: hidden;\n -webkit-user-select: none;\n}\n\ncanvas {\n flex: 1 1;\n}\n\n/*# sourceURL=layer_viewer/layers3DView.css */";Runtime.cachedResources["layer_viewer/paintProfiler.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.paint-profiler-overview {\n background-color: #eee;\n}\n\n.paint-profiler-canvas-container {\n flex: auto;\n position: relative;\n}\n\n.paint-profiler-pie-chart {\n width: 60px !important;\n height: 60px !important;\n padding: 2px;\n overflow: hidden;\n font-size: 10px;\n}\n\n.paint-profiler-canvas-container canvas {\n z-index: 200;\n background-color: white;\n opacity: 0.95;\n height: 100%;\n width: 100%;\n}\n\n.paint-profiler-canvas-container .overview-grid-dividers-background,\n.paint-profiler-canvas-container .overview-grid-window {\n bottom: 0;\n height: auto;\n}\n\n.paint-profiler-canvas-container .overview-grid-window-resizer {\n z-index: 2000;\n}\n\n/*# sourceURL=layer_viewer/paintProfiler.css */";Runtime.cachedResources["layer_viewer/layerDetailsView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\ntable td {\n padding-left: 8px;\n}\n\ntable td:first-child {\n font-weight: bold;\n}\n\n.scroll-rect.active {\n background-color: rgba(100, 100, 100, 0.2);\n}\n\nul {\n list-style: none;\n -webkit-padding-start: 0;\n -webkit-margin-before: 0;\n -webkit-margin-after: 0;\n}\n\na {\n padding: 8px;\n display: block;\n}\n\n/*# sourceURL=layer_viewer/layerDetailsView.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/layers/layers_module.js b/src/cobalt/debug/content/devtools/layers/layers_module.js deleted file mode 100644 index 235535a..0000000 --- a/src/cobalt/debug/content/devtools/layers/layers_module.js +++ /dev/null
@@ -1,101 +0,0 @@ -Layers.LayerPaintProfilerView=class extends UI.SplitWidget{constructor(showImageCallback){super(true,false);this._logTreeView=new LayerViewer.PaintProfilerCommandLogView();this.setSidebarWidget(this._logTreeView);this._paintProfilerView=new LayerViewer.PaintProfilerView(showImageCallback);this.setMainWidget(this._paintProfilerView);this._paintProfilerView.addEventListener(LayerViewer.PaintProfilerView.Events.WindowChanged,this._onWindowChanged,this);} -reset(){this._paintProfilerView.setSnapshotAndLog(null,[],null);} -profile(snapshot){snapshot.commandLog().then(log=>setSnapshotAndLog.call(this,snapshot,log));function setSnapshotAndLog(snapshot,log){this._logTreeView.setCommandLog(log||[]);this._paintProfilerView.setSnapshotAndLog(snapshot,log||[],null);if(snapshot) -snapshot.release();}} -setScale(scale){this._paintProfilerView.setScale(scale);} -_onWindowChanged(){this._logTreeView.updateWindow(this._paintProfilerView.selectionWindow());}};;Layers.LayerTreeModel=class extends SDK.SDKModel{constructor(target){super(target);this._layerTreeAgent=target.layerTreeAgent();target.registerLayerTreeDispatcher(new Layers.LayerTreeDispatcher(this));this._paintProfilerModel=(target.model(SDK.PaintProfilerModel));var resourceTreeModel=target.model(SDK.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this);} -this._layerTree=null;} -disable(){if(!this._enabled) -return;this._enabled=false;this._layerTreeAgent.disable();} -enable(){if(this._enabled) -return;this._enabled=true;this._forceEnable();} -_forceEnable(){this._lastPaintRectByLayerId={};if(!this._layerTree) -this._layerTree=new Layers.AgentLayerTree(this);this._layerTreeAgent.enable();} -layerTree(){return this._layerTree;} -async _layerTreeChanged(layers){if(!this._enabled) -return;var layerTree=(this._layerTree);await layerTree.setLayers(layers);for(var layerId in this._lastPaintRectByLayerId){var lastPaintRect=this._lastPaintRectByLayerId[layerId];var layer=layerTree.layerById(layerId);if(layer) -layer._lastPaintRect=lastPaintRect;} -this._lastPaintRectByLayerId={};this.dispatchEventToListeners(Layers.LayerTreeModel.Events.LayerTreeChanged);} -_layerPainted(layerId,clipRect){if(!this._enabled) -return;var layerTree=(this._layerTree);var layer=layerTree.layerById(layerId);if(!layer){this._lastPaintRectByLayerId[layerId]=clipRect;return;} -layer._didPaint(clipRect);this.dispatchEventToListeners(Layers.LayerTreeModel.Events.LayerPainted,layer);} -_onMainFrameNavigated(){this._layerTree=null;if(this._enabled) -this._forceEnable();}};SDK.SDKModel.register(Layers.LayerTreeModel,SDK.Target.Capability.DOM,false);Layers.LayerTreeModel.Events={LayerTreeChanged:Symbol('LayerTreeChanged'),LayerPainted:Symbol('LayerPainted'),};Layers.AgentLayerTree=class extends SDK.LayerTreeBase{constructor(layerTreeModel){super(layerTreeModel.target());this._layerTreeModel=layerTreeModel;} -async setLayers(payload){if(!payload){this._innerSetLayers(payload);return;} -var idsToResolve=new Set();for(var i=0;i<payload.length;++i){var backendNodeId=payload[i].backendNodeId;if(!backendNodeId||this.backendNodeIdToNode().has(backendNodeId)) -continue;idsToResolve.add(backendNodeId);} -await this.resolveBackendNodeIds(idsToResolve);this._innerSetLayers(payload);} -_innerSetLayers(layers){this.setRoot(null);this.setContentRoot(null);if(!layers) -return;var root;var oldLayersById=this._layersById;this._layersById={};for(var i=0;i<layers.length;++i){var layerId=layers[i].layerId;var layer=oldLayersById[layerId];if(layer) -layer._reset(layers[i]);else -layer=new Layers.AgentLayer(this._layerTreeModel,layers[i]);this._layersById[layerId]=layer;var backendNodeId=layers[i].backendNodeId;if(backendNodeId) -layer._setNode(this.backendNodeIdToNode().get(backendNodeId));if(!this.contentRoot()&&layer.drawsContent()) -this.setContentRoot(layer);var parentId=layer.parentId();if(parentId){var parent=this._layersById[parentId];if(!parent) -console.assert(parent,'missing parent '+parentId+' for layer '+layerId);parent.addChild(layer);}else{if(root) -console.assert(false,'Multiple root layers');root=layer;}} -if(root){this.setRoot(root);root._calculateQuad(new WebKitCSSMatrix());}}};Layers.AgentLayer=class{constructor(layerTreeModel,layerPayload){this._layerTreeModel=layerTreeModel;this._reset(layerPayload);} -id(){return this._layerPayload.layerId;} -parentId(){return this._layerPayload.parentLayerId;} -parent(){return this._parent;} -isRoot(){return!this.parentId();} -children(){return this._children;} -addChild(child){if(child._parent) -console.assert(false,'Child already has a parent');this._children.push(child);child._parent=this;} -_setNode(node){this._node=node;} -node(){return this._node;} -nodeForSelfOrAncestor(){for(var layer=this;layer;layer=layer._parent){if(layer._node) -return layer._node;} -return null;} -offsetX(){return this._layerPayload.offsetX;} -offsetY(){return this._layerPayload.offsetY;} -width(){return this._layerPayload.width;} -height(){return this._layerPayload.height;} -transform(){return this._layerPayload.transform;} -quad(){return this._quad;} -anchorPoint(){return[this._layerPayload.anchorX||0,this._layerPayload.anchorY||0,this._layerPayload.anchorZ||0,];} -invisible(){return this._layerPayload.invisible;} -paintCount(){return this._paintCount||this._layerPayload.paintCount;} -lastPaintRect(){return this._lastPaintRect;} -scrollRects(){return this._scrollRects;} -stickyPositionConstraint(){return this._stickyPositionConstraint;} -async requestCompositingReasons(){var reasons=await this._layerTreeModel._layerTreeAgent.compositingReasons(this.id());return reasons||[];} -drawsContent(){return this._layerPayload.drawsContent;} -gpuMemoryUsage(){var bytesPerPixel=4;return this.drawsContent()?this.width()*this.height()*bytesPerPixel:0;} -snapshots(){var promise=this._layerTreeModel._paintProfilerModel.makeSnapshot(this.id()).then(snapshot=>{if(!snapshot) -return null;return{rect:{x:0,y:0,width:this.width(),height:this.height()},snapshot:snapshot};});return[promise];} -_didPaint(rect){this._lastPaintRect=rect;this._paintCount=this.paintCount()+1;this._image=null;} -_reset(layerPayload){this._node=null;this._children=[];this._parent=null;this._paintCount=0;this._layerPayload=layerPayload;this._image=null;this._scrollRects=this._layerPayload.scrollRects||[];this._stickyPositionConstraint=this._layerPayload.stickyPositionConstraint?new SDK.Layer.StickyPositionConstraint(this._layerTreeModel.layerTree(),this._layerPayload.stickyPositionConstraint):null;} -_matrixFromArray(a){function toFixed9(x){return x.toFixed(9);} -return new WebKitCSSMatrix('matrix3d('+a.map(toFixed9).join(',')+')');} -_calculateTransformToViewport(parentTransform){var offsetMatrix=new WebKitCSSMatrix().translate(this._layerPayload.offsetX,this._layerPayload.offsetY);var matrix=offsetMatrix;if(this._layerPayload.transform){var transformMatrix=this._matrixFromArray(this._layerPayload.transform);var anchorVector=new UI.Geometry.Vector(this._layerPayload.width*this.anchorPoint()[0],this._layerPayload.height*this.anchorPoint()[1],this.anchorPoint()[2]);var anchorPoint=UI.Geometry.multiplyVectorByMatrixAndNormalize(anchorVector,matrix);var anchorMatrix=new WebKitCSSMatrix().translate(-anchorPoint.x,-anchorPoint.y,-anchorPoint.z);matrix=anchorMatrix.inverse().multiply(transformMatrix.multiply(anchorMatrix.multiply(matrix)));} -matrix=parentTransform.multiply(matrix);return matrix;} -_createVertexArrayForRect(width,height){return[0,0,0,width,0,0,width,height,0,0,height,0];} -_calculateQuad(parentTransform){var matrix=this._calculateTransformToViewport(parentTransform);this._quad=[];var vertices=this._createVertexArrayForRect(this._layerPayload.width,this._layerPayload.height);for(var i=0;i<4;++i){var point=UI.Geometry.multiplyVectorByMatrixAndNormalize(new UI.Geometry.Vector(vertices[i*3],vertices[i*3+1],vertices[i*3+2]),matrix);this._quad.push(point.x,point.y);} -function calculateQuadForLayer(layer){layer._calculateQuad(matrix);} -this._children.forEach(calculateQuadForLayer);}};Layers.LayerTreeDispatcher=class{constructor(layerTreeModel){this._layerTreeModel=layerTreeModel;} -layerTreeDidChange(layers){this._layerTreeModel._layerTreeChanged(layers||null);} -layerPainted(layerId,clipRect){this._layerTreeModel._layerPainted(layerId,clipRect);}};;Layers.LayersPanel=class extends UI.PanelWithSidebar{constructor(){super('layers',225);this._model=null;SDK.targetManager.observeTargets(this);this._layerViewHost=new LayerViewer.LayerViewHost();this._layerTreeOutline=new LayerViewer.LayerTreeOutline(this._layerViewHost);this.panelSidebarElement().appendChild(this._layerTreeOutline.element);this.setDefaultFocusedElement(this._layerTreeOutline.element);this._rightSplitWidget=new UI.SplitWidget(false,true,'layerDetailsSplitViewState');this.splitWidget().setMainWidget(this._rightSplitWidget);this._layers3DView=new LayerViewer.Layers3DView(this._layerViewHost);this._rightSplitWidget.setMainWidget(this._layers3DView);this._layers3DView.addEventListener(LayerViewer.Layers3DView.Events.PaintProfilerRequested,this._onPaintProfileRequested,this);this._layers3DView.addEventListener(LayerViewer.Layers3DView.Events.ScaleChanged,this._onScaleChanged,this);this._tabbedPane=new UI.TabbedPane();this._rightSplitWidget.setSidebarWidget(this._tabbedPane);this._layerDetailsView=new LayerViewer.LayerDetailsView(this._layerViewHost);this._layerDetailsView.addEventListener(LayerViewer.LayerDetailsView.Events.PaintProfilerRequested,this._onPaintProfileRequested,this);this._tabbedPane.appendTab(Layers.LayersPanel.DetailsViewTabs.Details,Common.UIString('Details'),this._layerDetailsView);this._paintProfilerView=new Layers.LayerPaintProfilerView(this._showImage.bind(this));this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabClosed,this._onTabClosed,this);this._updateThrottler=new Common.Throttler(100);} -focus(){this._layerTreeOutline.focus();} -wasShown(){super.wasShown();if(this._model) -this._model.enable();} -willHide(){if(this._model) -this._model.disable();super.willHide();} -targetAdded(target){if(this._model) -return;this._model=target.model(Layers.LayerTreeModel);if(!this._model) -return;this._model.addEventListener(Layers.LayerTreeModel.Events.LayerTreeChanged,this._onLayerTreeUpdated,this);this._model.addEventListener(Layers.LayerTreeModel.Events.LayerPainted,this._onLayerPainted,this);if(this.isShowing()) -this._model.enable();} -targetRemoved(target){if(!this._model||this._model.target()!==target) -return;this._model.removeEventListener(Layers.LayerTreeModel.Events.LayerTreeChanged,this._onLayerTreeUpdated,this);this._model.removeEventListener(Layers.LayerTreeModel.Events.LayerPainted,this._onLayerPainted,this);this._model.disable();this._model=null;} -_onLayerTreeUpdated(){this._updateThrottler.schedule(this._update.bind(this));} -_update(){if(this._model) -this._layerViewHost.setLayerTree(this._model.layerTree());return Promise.resolve();} -_onLayerPainted(event){if(!this._model) -return;var layer=(event.data);if(this._layerViewHost.selection()&&this._layerViewHost.selection().layer()===layer) -this._layerDetailsView.update();this._layers3DView.updateLayerSnapshot(layer);} -_onPaintProfileRequested(event){var selection=(event.data);this._layers3DView.snapshotForSelection(selection).then(snapshotWithRect=>{if(!snapshotWithRect) -return;this._layerBeingProfiled=selection.layer();if(!this._tabbedPane.hasTab(Layers.LayersPanel.DetailsViewTabs.Profiler)){this._tabbedPane.appendTab(Layers.LayersPanel.DetailsViewTabs.Profiler,Common.UIString('Profiler'),this._paintProfilerView,undefined,true,true);} -this._tabbedPane.selectTab(Layers.LayersPanel.DetailsViewTabs.Profiler);this._paintProfilerView.profile(snapshotWithRect.snapshot);});} -_onTabClosed(event){if(event.data.tabId!==Layers.LayersPanel.DetailsViewTabs.Profiler||!this._layerBeingProfiled) -return;this._paintProfilerView.reset();this._layers3DView.showImageForLayer(this._layerBeingProfiled,undefined);this._layerBeingProfiled=null;} -_showImage(imageURL){this._layers3DView.showImageForLayer(this._layerBeingProfiled,imageURL);} -_onScaleChanged(event){this._paintProfilerView.setScale((event.data));}};Layers.LayersPanel.DetailsViewTabs={Details:'details',Profiler:'profiler'};; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/network/network_module.js b/src/cobalt/debug/content/devtools/network/network_module.js deleted file mode 100644 index 0ac7608..0000000 --- a/src/cobalt/debug/content/devtools/network/network_module.js +++ /dev/null
@@ -1,890 +0,0 @@ -Network.BlockedURLsPane=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('network/blockedURLsPane.css');Network.BlockedURLsPane._instance=this;this._manager=SDK.multitargetNetworkManager;this._manager.addEventListener(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged,this._update,this);this._toolbar=new UI.Toolbar('',this.contentElement);this._enabledCheckbox=new UI.ToolbarCheckbox(Common.UIString('Enable request blocking'),undefined,this._toggleEnabled.bind(this));this._toolbar.appendToolbarItem(this._enabledCheckbox);this._toolbar.appendSeparator();var addButton=new UI.ToolbarButton(Common.UIString('Add pattern'),'largeicon-add');addButton.addEventListener(UI.ToolbarButton.Events.Click,this._addButtonClicked,this);this._toolbar.appendToolbarItem(addButton);var clearButton=new UI.ToolbarButton(Common.UIString('Remove all patterns'),'largeicon-clear');clearButton.addEventListener(UI.ToolbarButton.Events.Click,this._removeAll,this);this._toolbar.appendToolbarItem(clearButton);this._list=new UI.ListWidget(this);this._list.element.classList.add('blocked-urls');this._list.registerRequiredCSS('network/blockedURLsPane.css');this._list.setEmptyPlaceholder(this._createEmptyPlaceholder());this._list.show(this.contentElement);this._editor=null;this._blockedCountForUrl=new Map();SDK.targetManager.addModelListener(SDK.NetworkManager,SDK.NetworkManager.Events.RequestFinished,this._onRequestFinished,this);this._updateThrottler=new Common.Throttler(200);this._update();} -_createEmptyPlaceholder(){var element=this.contentElement.createChild('div','no-blocked-urls');element.createChild('span').textContent=Common.UIString('Requests are not blocked. ');var addLink=element.createChild('span','link');addLink.textContent=Common.UIString('Add pattern.');addLink.href='';addLink.addEventListener('click',this._addButtonClicked.bind(this),false);return element;} -static reset(){if(Network.BlockedURLsPane._instance) -Network.BlockedURLsPane._instance.reset();} -_addButtonClicked(){this._manager.setBlockingEnabled(true);this._list.addNewItem(0,{url:'',enabled:true});} -renderItem(pattern,editable){var count=this._blockedRequestsCount(pattern.url);var element=createElementWithClass('div','blocked-url');var checkbox=element.createChild('input','blocked-url-checkbox');checkbox.type='checkbox';checkbox.checked=pattern.enabled;checkbox.disabled=!this._manager.blockingEnabled();element.createChild('div','blocked-url-label').textContent=pattern.url;element.createChild('div','blocked-url-count').textContent=Common.UIString('%d blocked',count);element.addEventListener('click',event=>this._togglePattern(pattern,event),false);checkbox.addEventListener('click',event=>this._togglePattern(pattern,event),false);return element;} -_togglePattern(pattern,event){event.consume(true);var patterns=this._manager.blockedPatterns();patterns.splice(patterns.indexOf(pattern),1,{enabled:!pattern.enabled,url:pattern.url});this._manager.setBlockedPatterns(patterns);} -_toggleEnabled(){this._manager.setBlockingEnabled(!this._manager.blockingEnabled());this._update();} -removeItemRequested(pattern,index){var patterns=this._manager.blockedPatterns();patterns.splice(index,1);this._manager.setBlockedPatterns(patterns);} -beginEdit(pattern){this._editor=this._createEditor();this._editor.control('url').value=pattern.url;return this._editor;} -commitEdit(item,editor,isNew){var url=editor.control('url').value;var patterns=this._manager.blockedPatterns();if(isNew) -patterns.push({enabled:true,url:url});else -patterns.splice(patterns.indexOf(item),1,{enabled:true,url:url});this._manager.setBlockedPatterns(patterns);} -_createEditor(){if(this._editor) -return this._editor;var editor=new UI.ListWidget.Editor();var content=editor.contentElement();var titles=content.createChild('div','blocked-url-edit-row');titles.createChild('div').textContent=Common.UIString('Text pattern to block matching requests; use * for wildcard');var fields=content.createChild('div','blocked-url-edit-row');var urlInput=editor.createInput('url','text','',(item,index,input)=>!!input.value&&!this._manager.blockedPatterns().find(pattern=>pattern.url===input.value));fields.createChild('div','blocked-url-edit-value').appendChild(urlInput);return editor;} -_removeAll(){this._manager.setBlockedPatterns([]);} -_update(){var enabled=this._manager.blockingEnabled();this._list.element.classList.toggle('blocking-disabled',!enabled&&!!this._manager.blockedPatterns().length);this._enabledCheckbox.setChecked(enabled);this._list.clear();for(var pattern of this._manager.blockedPatterns()) -this._list.appendItem(pattern,true);return Promise.resolve();} -_blockedRequestsCount(url){if(!url) -return 0;var result=0;for(var blockedUrl of this._blockedCountForUrl.keys()){if(this._matches(url,blockedUrl)) -result+=this._blockedCountForUrl.get(blockedUrl);} -return result;} -_matches(pattern,url){var pos=0;var parts=pattern.split('*');for(var index=0;index<parts.length;index++){var part=parts[index];if(!part.length) -continue;pos=url.indexOf(part,pos);if(pos===-1) -return false;pos+=part.length;} -return true;} -reset(){this._blockedCountForUrl.clear();this._updateThrottler.schedule(this._update.bind(this));} -_onRequestFinished(event){var request=(event.data);if(request.wasBlocked()){var count=this._blockedCountForUrl.get(request.url())||0;this._blockedCountForUrl.set(request.url(),count+1);this._updateThrottler.schedule(this._update.bind(this));}}};Network.BlockedURLsPane._instance=null;;Network.EventSourceMessagesView=class extends UI.VBox{constructor(request){super();this.registerRequiredCSS('network/eventSourceMessagesView.css');this.element.classList.add('event-source-messages-view');this._request=request;var columns=([{id:'id',title:Common.UIString('Id'),sortable:true,weight:8},{id:'type',title:Common.UIString('Type'),sortable:true,weight:8},{id:'data',title:Common.UIString('Data'),sortable:false,weight:88},{id:'time',title:Common.UIString('Time'),sortable:true,weight:8}]);this._dataGrid=new DataGrid.SortableDataGrid(columns);this._dataGrid.setStriped(true);this._dataGrid.setStickToBottom(true);this._dataGrid.markColumnAsSortedBy('time',DataGrid.DataGrid.Order.Ascending);this._sortItems();this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortItems,this);this._dataGrid.setName('EventSourceMessagesView');this._dataGrid.asWidget().show(this.element);} -wasShown(){this._dataGrid.rootNode().removeChildren();var messages=this._request.eventSourceMessages();for(var i=0;i<messages.length;++i) -this._dataGrid.insertChild(new Network.EventSourceMessageNode(messages[i]));this._request.addEventListener(SDK.NetworkRequest.Events.EventSourceMessageAdded,this._messageAdded,this);} -willHide(){this._request.removeEventListener(SDK.NetworkRequest.Events.EventSourceMessageAdded,this._messageAdded,this);} -_messageAdded(event){var message=(event.data);this._dataGrid.insertChild(new Network.EventSourceMessageNode(message));} -_sortItems(){var sortColumnId=this._dataGrid.sortColumnId();if(!sortColumnId) -return;var comparator=Network.EventSourceMessageNode.Comparators[sortColumnId];if(!comparator) -return;this._dataGrid.sortNodes(comparator,!this._dataGrid.isSortOrderAscending());}};Network.EventSourceMessageNode=class extends DataGrid.SortableDataGridNode{constructor(message){var time=new Date(message.time*1000);var timeText=('0'+time.getHours()).substr(-2)+':'+('0'+time.getMinutes()).substr(-2)+':'+ -('0'+time.getSeconds()).substr(-2)+'.'+('00'+time.getMilliseconds()).substr(-3);var timeNode=createElement('div');timeNode.createTextChild(timeText);timeNode.title=time.toLocaleString();super({id:message.eventId,type:message.eventName,data:message.data,time:timeNode});this._message=message;}};Network.EventSourceMessageNodeComparator=function(field,a,b){var aValue=a._message[field];var bValue=b._message[field];return aValue<bValue?-1:aValue>bValue?1:0;};Network.EventSourceMessageNode.Comparators={'id':Network.EventSourceMessageNodeComparator.bind(null,'eventId'),'type':Network.EventSourceMessageNodeComparator.bind(null,'eventName'),'time':Network.EventSourceMessageNodeComparator.bind(null,'time')};;Network.HARWriter=class{static async write(stream,requests,progress){var compositeProgress=new Common.CompositeProgress(progress);var content=await Network.HARWriter._harStringForRequests(requests,compositeProgress);if(progress.isCanceled()) -return Promise.resolve();return Network.HARWriter._writeToStream(stream,compositeProgress,content);} -static async _harStringForRequests(requests,compositeProgress){var progress=compositeProgress.createSubProgress();progress.setTitle(Common.UIString('Collecting content\u2026'));progress.setTotalWork(requests.length);var harLog=(new NetworkLog.HARLog(requests)).build();var promises=[];for(var i=0;i<requests.length;i++){var promise=requests[i].contentData();promises.push(promise.then(contentLoaded.bind(null,harLog.entries[i])));} -await Promise.all(promises);progress.done();if(progress.isCanceled()) -return'';return JSON.stringify({log:harLog},null,Network.HARWriter._jsonIndent);function contentLoaded(entry,contentData){progress.worked();if(contentData.content!==null) -entry.response.content.text=contentData.content;if(contentData.encoded) -entry.response.content.encoding='base64';}} -static async _writeToStream(stream,compositeProgress,fileContent){var progress=compositeProgress.createSubProgress();progress.setTitle(Common.UIString('Writing file\u2026'));progress.setTotalWork(fileContent.length);for(var i=0;i<fileContent.length&&!progress.isCanceled();i+=Network.HARWriter._chunkSize){var chunk=fileContent.substr(i,Network.HARWriter._chunkSize);await stream.write(chunk);progress.worked(chunk.length);} -progress.done();}};Network.HARWriter._jsonIndent=2;Network.HARWriter._chunkSize=100000;;Network.NetworkConfigView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('network/networkConfigView.css');this.contentElement.classList.add('network-config');this._createCacheSection();this.contentElement.createChild('div').classList.add('panel-section-separator');this._createNetworkThrottlingSection();this.contentElement.createChild('div').classList.add('panel-section-separator');this._createUserAgentSection();} -static createUserAgentSelectAndInput(){var userAgentSetting=Common.settings.createSetting('customUserAgent','');var userAgentSelectElement=createElement('select');const customOverride={title:Common.UIString('Custom...'),value:'custom'};userAgentSelectElement.appendChild(new Option(customOverride.title,customOverride.value));var groups=Network.NetworkConfigView._userAgentGroups;for(var userAgentDescriptor of groups){var groupElement=userAgentSelectElement.createChild('optgroup');groupElement.label=userAgentDescriptor.title;for(var userAgentVersion of userAgentDescriptor.values){var userAgentValue=SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(userAgentVersion.value);groupElement.appendChild(new Option(userAgentVersion.title,userAgentValue));}} -userAgentSelectElement.selectedIndex=0;var otherUserAgentElement=UI.createInput('','text');otherUserAgentElement.value=userAgentSetting.get();otherUserAgentElement.title=userAgentSetting.get();otherUserAgentElement.placeholder=Common.UIString('Enter a custom user agent');otherUserAgentElement.required=true;settingChanged();userAgentSelectElement.addEventListener('change',userAgentSelected,false);otherUserAgentElement.addEventListener('input',applyOtherUserAgent,false);function userAgentSelected(){var value=userAgentSelectElement.options[userAgentSelectElement.selectedIndex].value;if(value!==customOverride.value){userAgentSetting.set(value);otherUserAgentElement.value=value;otherUserAgentElement.title=value;}else{otherUserAgentElement.select();}} -function settingChanged(){var value=userAgentSetting.get();var options=userAgentSelectElement.options;var selectionRestored=false;for(var i=0;i<options.length;++i){if(options[i].value===value){userAgentSelectElement.selectedIndex=i;selectionRestored=true;break;}} -if(!selectionRestored) -userAgentSelectElement.selectedIndex=0;} -function applyOtherUserAgent(){if(userAgentSetting.get()!==otherUserAgentElement.value){userAgentSetting.set(otherUserAgentElement.value);otherUserAgentElement.title=otherUserAgentElement.value;settingChanged();}} -return{select:userAgentSelectElement,input:otherUserAgentElement};} -_createSection(title,className){var section=this.contentElement.createChild('section','network-config-group');if(className) -section.classList.add(className);section.createChild('div','network-config-title').textContent=title;return section.createChild('div','network-config-fields');} -_createCacheSection(){var section=this._createSection(Common.UIString('Caching'),'network-config-disable-cache');section.appendChild(UI.SettingsUI.createSettingCheckbox(Common.UIString('Disable cache'),Common.moduleSetting('cacheDisabled'),true));} -_createNetworkThrottlingSection(){var section=this._createSection(Common.UIString('Network throttling'),'network-config-throttling');var networkThrottlingSelect=(section.createChild('select','chrome-select'));MobileThrottling.throttlingManager().decorateSelectWithNetworkThrottling(networkThrottlingSelect);} -_createUserAgentSection(){var section=this._createSection(Common.UIString('User agent'),'network-config-ua');var checkboxLabel=UI.CheckboxLabel.create(Common.UIString('Select automatically'),true);section.appendChild(checkboxLabel);var autoCheckbox=checkboxLabel.checkboxElement;var customUserAgentSetting=Common.settings.createSetting('customUserAgent','');customUserAgentSetting.addChangeListener(()=>{if(autoCheckbox.checked) -return;SDK.multitargetNetworkManager.setCustomUserAgentOverride(customUserAgentSetting.get());});var customUserAgentSelectBox=section.createChild('div','network-config-ua-custom');autoCheckbox.addEventListener('change',userAgentSelectBoxChanged);var customSelectAndInput=Network.NetworkConfigView.createUserAgentSelectAndInput();customSelectAndInput.select.classList.add('chrome-select');customUserAgentSelectBox.appendChild(customSelectAndInput.select);customUserAgentSelectBox.appendChild(customSelectAndInput.input);userAgentSelectBoxChanged();function userAgentSelectBoxChanged(){var useCustomUA=!autoCheckbox.checked;customUserAgentSelectBox.classList.toggle('checked',useCustomUA);customSelectAndInput.select.disabled=!useCustomUA;customSelectAndInput.input.disabled=!useCustomUA;var customUA=useCustomUA?customUserAgentSetting.get():'';SDK.multitargetNetworkManager.setCustomUserAgentOverride(customUA);}}};Network.NetworkConfigView._userAgentGroups=[{title:'Android',values:[{title:'Android (4.0.2) Browser \u2014 Galaxy Nexus',value:'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'},{title:'Android (2.3) Browser \u2014 Nexus S',value:'Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'}]},{title:'BlackBerry',values:[{title:'BlackBerry \u2014 BB10',value:'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.1+ (KHTML, like Gecko) Version/10.0.0.1337 Mobile Safari/537.1+'},{title:'BlackBerry \u2014 PlayBook 2.1',value:'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML, like Gecko) Version/7.2.1.0 Safari/536.2+'},{title:'BlackBerry \u2014 9900',value:'Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en-US) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.0.0.187 Mobile Safari/534.11+'}]},{title:'Chrome',values:[{title:'Chrome \u2014 Android Mobile',value:'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36'},{title:'Chrome \u2014 Android Tablet',value:'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'},{title:'Chrome \u2014 iPhone',value:'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/%s Mobile/13B143 Safari/601.1.46'},{title:'Chrome \u2014 iPad',value:'Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/%s Mobile/13B143 Safari/601.1.46'},{title:'Chrome \u2014 Mac',value:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'},{title:'Chrome \u2014 Windows',value:'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'}]},{title:'Edge',values:[{title:'Edge \u2014 Windows',value:'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240'},{title:'Edge \u2014 Mobile',value:'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166'},{title:'Edge \u2014 XBox',value:'Mozilla/5.0 (Windows NT 10.0; Win64; x64; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/13.10586'}]},{title:'Firefox',values:[{title:'Firefox \u2014 Android Mobile',value:'Mozilla/5.0 (Android 4.4; Mobile; rv:46.0) Gecko/46.0 Firefox/46.0'},{title:'Firefox \u2014 Android Tablet',value:'Mozilla/5.0 (Android 4.4; Tablet; rv:46.0) Gecko/46.0 Firefox/46.0'},{title:'Firefox \u2014 iPhone',value:'Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4'},{title:'Firefox \u2014 iPad',value:'Mozilla/5.0 (iPad; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4'},{title:'Firefox \u2014 Mac',value:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0'},{title:'Firefox \u2014 Windows',value:'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0'}]},{title:'Googlebot',values:[{title:'Googlebot',value:'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'},{title:'Googlebot Smartphone',value:'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'}]},{title:'Internet Explorer',values:[{title:'Internet Explorer 11',value:'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'},{title:'Internet Explorer 10',value:'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)'},{title:'Internet Explorer 9',value:'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'},{title:'Internet Explorer 8',value:'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'},{title:'Internet Explorer 7',value:'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)'}]},{title:'Opera',values:[{title:'Opera \u2014 Mac',value:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36 OPR/37.0.2178.31'},{title:'Opera \u2014 Windows',value:'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36 OPR/37.0.2178.31'},{title:'Opera (Presto) \u2014 Mac',value:'Opera/9.80 (Macintosh; Intel Mac OS X 10.9.1) Presto/2.12.388 Version/12.16'},{title:'Opera (Presto) \u2014 Windows',value:'Opera/9.80 (Windows NT 6.1) Presto/2.12.388 Version/12.16'},{title:'Opera Mobile \u2014 Android Mobile',value:'Opera/12.02 (Android 4.1; Linux; Opera Mobi/ADR-1111101157; U; en-US) Presto/2.9.201 Version/12.02'},{title:'Opera Mini \u2014 iOS',value:'Opera/9.80 (iPhone; Opera Mini/8.0.0/34.2336; U; en) Presto/2.8.119 Version/11.10'}]},{title:'Safari',values:[{title:'Safari \u2014 iPad iOS 9',value:'Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B137 Safari/601.1'},{title:'Safari \u2014 iPhone iOS 9',value:'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B137 Safari/601.1'},{title:'Safari \u2014 Mac',value:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A'}]},{title:'UC Browser',values:[{title:'UC Browser \u2014 Android Mobile',value:'Mozilla/5.0 (Linux; U; Android 4.4.4; en-US; XT1022 Build/KXC21.5-40) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/10.7.0.636 U3/0.8.0 Mobile Safari/534.30'},{title:'UC Browser \u2014 iOS',value:'UCWEB/2.0 (iPad; U; CPU OS 7_1 like Mac OS X; en; iPad3,6) U2/1.0.0 UCBrowser/9.3.1.344'},{title:'UC Browser \u2014 Windows Phone',value:'NokiaX2-02/2.0 (11.79) Profile/MIDP-2.1 Configuration/CLDC-1.1 Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2;.NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2) UCBrowser8.4.0.159/70/352'}]}];;Network.NetworkNode=class extends DataGrid.SortableDataGridNode{constructor(parentView){super({});this._parentView=parentView;this._isHovered=false;this._isProduct=false;this._showingInitiatorChain=false;this._requestOrFirstKnownChildRequest=null;} -static _themedBackgroundColors(){if(Network.NetworkNode._themedBackgroundColorsCache) -return Network.NetworkNode._themedBackgroundColorsCache;var themedColors={};for(var name in Network.NetworkNode._backgroundColors){var color=Common.Color.fromRGBA(Network.NetworkNode._backgroundColors[name]);themedColors[name]=UI.themeSupport.patchColor(color,UI.ThemeSupport.ColorUsage.Background);} -Network.NetworkNode._themedBackgroundColorsCache=(themedColors);return Network.NetworkNode._themedBackgroundColorsCache;} -displayName(){return'';} -isFromFrame(){return false;} -createCell(columnId){var cell=this.createTD(columnId);this.renderCell(cell,columnId);return cell;} -renderCell(cell,columnId){} -backgroundColor(){var bgColors=Network.NetworkNode._themedBackgroundColors();if(this.selected) -return(bgColors.Selected.asString(Common.Color.Format.HEX));var color=this.isStriped()?bgColors.Stripe:bgColors.Default;if(this.isNavigationRequest()) -color=color.blendWith(bgColors.Navigation);if(this.hovered()) -color=color.blendWith(bgColors.Hovered);if(this.isOnInitiatorPath()) -color=color.blendWith(bgColors.InitiatorPath);if(this.isOnInitiatedPath()) -color=color.blendWith(bgColors.InitiatedPath);return(color.asString(Common.Color.Format.HEX));} -_updateBackgroundColor(){var element=this.existingElement();if(!element) -return;element.style.backgroundColor=this.backgroundColor();this._parentView.stylesChanged();} -setStriped(isStriped){super.setStriped(isStriped);this._updateBackgroundColor();} -parentView(){return this._parentView;} -hovered(){return this._isHovered;} -showingInitiatorChain(){return this._showingInitiatorChain;} -nodeSelfHeight(){return this._parentView.rowHeight();} -setHovered(hovered,showInitiatorChain){if(this._isHovered===hovered&&this._showingInitiatorChain===showInitiatorChain) -return;if(this._isHovered!==hovered){this._isHovered=hovered;if(this.attached()) -this.element().classList.toggle('hover',hovered);} -if(this._showingInitiatorChain!==showInitiatorChain){this._showingInitiatorChain=showInitiatorChain;this.showingInitiatorChainChanged();} -this._parentView.stylesChanged();this._updateBackgroundColor();} -showingInitiatorChainChanged(){} -isOnInitiatorPath(){return false;} -isOnInitiatedPath(){return false;} -request(){return null;} -isNavigationRequest(){return false;} -clearFlatNodes(){super.clearFlatNodes();this._requestOrFirstKnownChildRequest=null;} -requestOrFirstKnownChildRequest(){if(this._requestOrFirstKnownChildRequest) -return this._requestOrFirstKnownChildRequest;var request=this.request();if(request||!this.hasChildren()){this._requestOrFirstKnownChildRequest=request;return this._requestOrFirstKnownChildRequest;} -var firstChildRequest=null;var flatChildren=this.flatChildren();for(var i=0;i<flatChildren.length;i++){request=flatChildren[i].request();if(!firstChildRequest||(request&&request.issueTime()<firstChildRequest.issueTime())) -firstChildRequest=request;} -this._requestOrFirstKnownChildRequest=firstChildRequest;return this._requestOrFirstKnownChildRequest;}};Network.NetworkNode._backgroundColors={Default:[255,255,255,1.0],Stripe:[245,245,245,1.0],Navigation:[221,238,255,1.0],Hovered:[235,242,252,0.7],InitiatorPath:[58,217,58,0.4],InitiatedPath:[217,58,58,0.4],Selected:[63,81,181,.6],FromFrame:[224,247,250,.4],IsProduct:[255,252,225,.6],};Network.NetworkNode._SupportedBackgroundColors;Network.NetworkNode._themedBackgroundColorsCache;Network.NetworkNode._ProductEntryInfo;Network.NetworkRequestNode=class extends Network.NetworkNode{constructor(parentView,request){super(parentView);this._nameCell=null;this._nameBadgeElement=null;this._initiatorCell=null;this._request=request;this._isNavigationRequest=false;this.selectable=true;this._isOnInitiatorPath=false;this._isOnInitiatedPath=false;this._isFromFrame=false;if(!Runtime.experiments.isEnabled('networkGroupingRequests')) -return;var frame=SDK.ResourceTreeModel.frameForRequest(request);this._isFromFrame=frame?!frame.isMainFrame():false;} -static NameComparator(a,b){var aName=a.displayName().toLowerCase();var bName=b.displayName().toLowerCase();if(aName===bName){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(aRequest&&bRequest) -return aRequest.indentityCompare(bRequest);return aRequest?-1:1;} -return aName<bName?-1:1;} -static RemoteAddressComparator(a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;var aRemoteAddress=aRequest.remoteAddress();var bRemoteAddress=bRequest.remoteAddress();if(aRemoteAddress>bRemoteAddress) -return 1;if(bRemoteAddress>aRemoteAddress) -return-1;return aRequest.indentityCompare(bRequest);} -static ProductComparator(productRegistry,a,b){var aRequest=a.request();var bRequest=b.request();if(!aRequest||!bRequest) -return!aRequest?-1:1;var aName=productRegistry.nameForUrl(aRequest.parsedURL)||'';var bName=productRegistry.nameForUrl(bRequest.parsedURL)||'';return aName.localeCompare(bName)||aRequest.indentityCompare(bRequest);} -static SizeComparator(a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;if(bRequest.cached()&&!aRequest.cached()) -return 1;if(aRequest.cached()&&!bRequest.cached()) -return-1;return(aRequest.transferSize-bRequest.transferSize)||aRequest.indentityCompare(bRequest);} -static TypeComparator(a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;var aSimpleType=a.displayType();var bSimpleType=b.displayType();if(aSimpleType>bSimpleType) -return 1;if(bSimpleType>aSimpleType) -return-1;return aRequest.indentityCompare(bRequest);} -static InitiatorComparator(a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;var aInitiator=NetworkLog.networkLog.initiatorInfoForRequest(aRequest);var bInitiator=NetworkLog.networkLog.initiatorInfoForRequest(bRequest);if(aInitiator.type<bInitiator.type) -return-1;if(aInitiator.type>bInitiator.type) -return 1;if(typeof aInitiator.__source==='undefined') -aInitiator.__source=Bindings.displayNameForURL(aInitiator.url);if(typeof bInitiator.__source==='undefined') -bInitiator.__source=Bindings.displayNameForURL(bInitiator.url);if(aInitiator.__source<bInitiator.__source) -return-1;if(aInitiator.__source>bInitiator.__source) -return 1;if(aInitiator.lineNumber<bInitiator.lineNumber) -return-1;if(aInitiator.lineNumber>bInitiator.lineNumber) -return 1;if(aInitiator.columnNumber<bInitiator.columnNumber) -return-1;if(aInitiator.columnNumber>bInitiator.columnNumber) -return 1;return aRequest.indentityCompare(bRequest);} -static RequestCookiesCountComparator(a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;var aScore=aRequest.requestCookies?aRequest.requestCookies.length:0;var bScore=bRequest.requestCookies?bRequest.requestCookies.length:0;return(aScore-bScore)||aRequest.indentityCompare(bRequest);} -static ResponseCookiesCountComparator(a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;var aScore=aRequest.responseCookies?aRequest.responseCookies.length:0;var bScore=bRequest.responseCookies?bRequest.responseCookies.length:0;return(aScore-bScore)||aRequest.indentityCompare(bRequest);} -static InitialPriorityComparator(a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;var priorityMap=NetworkPriorities.prioritySymbolToNumericMap();var aPriority=aRequest.initialPriority();var aScore=aPriority?priorityMap.get(aPriority):0;aScore=aScore||0;var bPriority=aRequest.initialPriority();var bScore=bPriority?priorityMap.get(bPriority):0;bScore=bScore||0;return aScore-bScore||aRequest.indentityCompare(bRequest);} -static RequestPropertyComparator(propertyName,a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;var aValue=aRequest[propertyName];var bValue=bRequest[propertyName];if(aValue===bValue) -return aRequest.indentityCompare(bRequest);return aValue>bValue?1:-1;} -static ResponseHeaderStringComparator(propertyName,a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;var aValue=String(aRequest.responseHeaderValue(propertyName)||'');var bValue=String(bRequest.responseHeaderValue(propertyName)||'');return aValue.localeCompare(bValue)||aRequest.indentityCompare(bRequest);} -static ResponseHeaderNumberComparator(propertyName,a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;var aValue=(aRequest.responseHeaderValue(propertyName)!==undefined)?parseFloat(aRequest.responseHeaderValue(propertyName)):-Infinity;var bValue=(bRequest.responseHeaderValue(propertyName)!==undefined)?parseFloat(bRequest.responseHeaderValue(propertyName)):-Infinity;if(aValue===bValue) -return aRequest.indentityCompare(bRequest);return aValue>bValue?1:-1;} -static ResponseHeaderDateComparator(propertyName,a,b){var aRequest=a.requestOrFirstKnownChildRequest();var bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest) -return!aRequest?-1:1;var aHeader=aRequest.responseHeaderValue(propertyName);var bHeader=bRequest.responseHeaderValue(propertyName);var aValue=aHeader?new Date(aHeader).getTime():-Infinity;var bValue=bHeader?new Date(bHeader).getTime():-Infinity;if(aValue===bValue) -return aRequest.indentityCompare(bRequest);return aValue>bValue?1:-1;} -showingInitiatorChainChanged(){var showInitiatorChain=this.showingInitiatorChain();var initiatorGraph=NetworkLog.networkLog.initiatorGraphForRequest(this._request);for(var request of initiatorGraph.initiators){if(request===this._request) -continue;var node=this.parentView().nodeForRequest(request);if(!node) -continue;node._setIsOnInitiatorPath(showInitiatorChain);} -for(var request of initiatorGraph.initiated){if(request===this._request) -continue;var node=this.parentView().nodeForRequest(request);if(!node) -continue;node._setIsOnInitiatedPath(showInitiatorChain);}} -_setIsOnInitiatorPath(isOnInitiatorPath){if(this._isOnInitiatorPath===isOnInitiatorPath||!this.attached()) -return;this._isOnInitiatorPath=isOnInitiatorPath;this._updateBackgroundColor();} -isOnInitiatorPath(){return this._isOnInitiatorPath;} -_setIsOnInitiatedPath(isOnInitiatedPath){if(this._isOnInitiatedPath===isOnInitiatedPath||!this.attached()) -return;this._isOnInitiatedPath=isOnInitiatedPath;this._updateBackgroundColor();} -isOnInitiatedPath(){return this._isOnInitiatedPath;} -isFromFrame(){return this._isFromFrame;} -displayType(){var mimeType=this._request.mimeType||this._request.requestContentType()||'';var resourceType=this._request.resourceType();var simpleType=resourceType.name();if(resourceType===Common.resourceTypes.Other||resourceType===Common.resourceTypes.Image) -simpleType=mimeType.replace(/^(application|image)\//,'');return simpleType;} -displayName(){return this._request.name();} -request(){return this._request;} -isNavigationRequest(){var pageLoad=NetworkLog.PageLoad.forRequest(this._request);return pageLoad?pageLoad.mainRequest===this._request:false;} -nodeSelfHeight(){return this.parentView().rowHeight();} -createCells(element){this._nameCell=null;this._initiatorCell=null;element.classList.toggle('network-error-row',this._isFailed());element.classList.toggle('network-navigation-row',this._isNavigationRequest);super.createCells(element);this._updateBackgroundColor();if(!Runtime.experiments.isEnabled('networkGroupingRequests')) -return;ProductRegistry.instance().then(productRegistry=>{if(productRegistry.entryForUrl(this._request.parsedURL)){this._isProduct=true;this._updateBackgroundColor();}});} -_setTextAndTitle(element,text){element.createTextChild(text);element.title=text;} -renderCell(cell,columnId){switch(columnId){case'name':this._renderNameCell(cell);break;case'method':this._setTextAndTitle(cell,this._request.requestMethod);break;case'status':this._renderStatusCell(cell);break;case'protocol':this._setTextAndTitle(cell,this._request.protocol);break;case'scheme':this._setTextAndTitle(cell,this._request.scheme);break;case'domain':this._setTextAndTitle(cell,this._request.domain);break;case'remoteaddress':this._setTextAndTitle(cell,this._request.remoteAddress());break;case'cookies':this._setTextAndTitle(cell,this._arrayLength(this._request.requestCookies));break;case'setcookies':this._setTextAndTitle(cell,this._arrayLength(this._request.responseCookies));break;case'priority':var priority=this._request.initialPriority();this._setTextAndTitle(cell,priority?NetworkPriorities.uiLabelForPriority(priority):'');break;case'connectionid':this._setTextAndTitle(cell,this._request.connectionId);break;case'type':this._setTextAndTitle(cell,this.displayType());break;case'initiator':this._renderInitiatorCell(cell);break;case'size':this._renderSizeCell(cell);break;case'time':this._renderTimeCell(cell);break;case'timeline':this._setTextAndTitle(cell,'');break;default:this._setTextAndTitle(cell,this._request.responseHeaderValue(columnId)||'');break;}} -_arrayLength(array){return array?''+array.length:'';} -select(supressSelectedEvent){super.select(supressSelectedEvent);this.parentView().dispatchEventToListeners(Network.NetworkLogView.Events.RequestSelected,this._request);} -highlightMatchedSubstring(regexp){if(!regexp) -return[];this.element();var domChanges=[];var matchInfo=this._nameCell.textContent.match(regexp);if(matchInfo) -UI.highlightSearchResult(this._nameCell,matchInfo.index,matchInfo[0].length,domChanges);return domChanges;} -_openInNewTab(){InspectorFrontendHost.openInNewTab(this._request.url());} -_isFailed(){return(this._request.failed&&!this._request.statusCode)||(this._request.statusCode>=400);} -_renderNameCell(cell){var leftPadding=this.leftPadding?this.leftPadding+'px':'';cell.style.setProperty('padding-left',leftPadding);this._nameCell=cell;cell.addEventListener('dblclick',this._openInNewTab.bind(this),false);var iconElement;if(this._request.resourceType()===Common.resourceTypes.Image){var previewImage=createElementWithClass('img','image-network-icon-preview');this._request.populateImageSource(previewImage);iconElement=createElementWithClass('div','icon');iconElement.appendChild(previewImage);}else{iconElement=createElementWithClass('img','icon');} -iconElement.classList.add(this._request.resourceType().name());cell.appendChild(iconElement);if(!this._nameBadgeElement){this._nameBadgeElement=this.parentView().badgePool.badgeForURL(this._request.parsedURL);this._nameBadgeElement.classList.add('network-badge');} -cell.appendChild(this._nameBadgeElement);var name=this._request.name().trimMiddle(100);var networkManager=SDK.NetworkManager.forRequest(this._request);cell.createTextChild(networkManager?networkManager.target().decorateLabel(name):name);this._appendSubtitle(cell,this._request.path());cell.title=this._request.url();} -_renderStatusCell(cell){cell.classList.toggle('network-dim-cell',!this._isFailed()&&(this._request.cached()||!this._request.statusCode));if(this._request.failed&&!this._request.canceled&&!this._request.wasBlocked()){var failText=Common.UIString('(failed)');if(this._request.localizedFailDescription){cell.createTextChild(failText);this._appendSubtitle(cell,this._request.localizedFailDescription);cell.title=failText+' '+this._request.localizedFailDescription;}else{this._setTextAndTitle(cell,failText);}}else if(this._request.statusCode){cell.createTextChild(''+this._request.statusCode);this._appendSubtitle(cell,this._request.statusText);cell.title=this._request.statusCode+' '+this._request.statusText;}else if(this._request.parsedURL.isDataURL()){this._setTextAndTitle(cell,Common.UIString('(data)'));}else if(this._request.canceled){this._setTextAndTitle(cell,Common.UIString('(canceled)'));}else if(this._request.wasBlocked()){var reason=Common.UIString('other');switch(this._request.blockedReason()){case Protocol.Network.BlockedReason.Csp:reason=Common.UIString('csp');break;case Protocol.Network.BlockedReason.MixedContent:reason=Common.UIString('mixed-content');break;case Protocol.Network.BlockedReason.Origin:reason=Common.UIString('origin');break;case Protocol.Network.BlockedReason.Inspector:reason=Common.UIString('devtools');break;case Protocol.Network.BlockedReason.Other:reason=Common.UIString('other');break;} -this._setTextAndTitle(cell,Common.UIString('(blocked:%s)',reason));}else if(this._request.finished){this._setTextAndTitle(cell,Common.UIString('Finished'));}else{this._setTextAndTitle(cell,Common.UIString('(pending)'));}} -_renderInitiatorCell(cell){this._initiatorCell=cell;var request=this._request;var initiator=NetworkLog.networkLog.initiatorInfoForRequest(request);var timing=request.timing;if(timing&&timing.pushStart) -cell.appendChild(createTextNode(Common.UIString('Push / ')));switch(initiator.type){case SDK.NetworkRequest.InitiatorType.Parser:cell.title=initiator.url+':'+(initiator.lineNumber+1);var uiSourceCode=Workspace.workspace.uiSourceCodeForURL(initiator.url);cell.appendChild(Components.Linkifier.linkifyURL(initiator.url,{text:uiSourceCode?uiSourceCode.displayName():undefined,lineNumber:initiator.lineNumber,columnNumber:initiator.columnNumber}));this._appendSubtitle(cell,Common.UIString('Parser'));break;case SDK.NetworkRequest.InitiatorType.Redirect:cell.title=initiator.url;var redirectSource=(request.redirectSource());console.assert(redirectSource);if(this.parentView().nodeForRequest(redirectSource)){cell.appendChild(Components.Linkifier.linkifyRevealable(redirectSource,Bindings.displayNameForURL(redirectSource.url())));}else{cell.appendChild(Components.Linkifier.linkifyURL(redirectSource.url()));} -this._appendSubtitle(cell,Common.UIString('Redirect'));break;case SDK.NetworkRequest.InitiatorType.Script:var networkManager=SDK.NetworkManager.forRequest(request);this._linkifiedInitiatorAnchor=this.parentView().linkifier.linkifyScriptLocation(networkManager?networkManager.target():null,initiator.scriptId,initiator.url,initiator.lineNumber,initiator.columnNumber);this._linkifiedInitiatorAnchor.title='';cell.appendChild(this._linkifiedInitiatorAnchor);this._appendSubtitle(cell,Common.UIString('Script'));cell.classList.add('network-script-initiated');cell.request=request;break;case SDK.NetworkRequest.InitiatorType.Preload:cell.title=Common.UIString('Preload');cell.classList.add('network-dim-cell');cell.appendChild(createTextNode(Common.UIString('Preload')));break;default:cell.title=Common.UIString('Other');cell.classList.add('network-dim-cell');cell.appendChild(createTextNode(Common.UIString('Other')));}} -_renderSizeCell(cell){if(this._request.fetchedViaServiceWorker){this._setTextAndTitle(cell,Common.UIString('(from ServiceWorker)'));cell.classList.add('network-dim-cell');}else if(this._request.cached()){if(this._request.cachedInMemory()) -this._setTextAndTitle(cell,Common.UIString('(from memory cache)'));else -this._setTextAndTitle(cell,Common.UIString('(from disk cache)'));cell.classList.add('network-dim-cell');}else{var resourceSize=Number.bytesToString(this._request.resourceSize);var transferSize=Number.bytesToString(this._request.transferSize);this._setTextAndTitle(cell,transferSize);this._appendSubtitle(cell,resourceSize);}} -_renderTimeCell(cell){if(this._request.duration>0){this._setTextAndTitle(cell,Number.secondsToString(this._request.duration));this._appendSubtitle(cell,Number.secondsToString(this._request.latency));}else{cell.classList.add('network-dim-cell');this._setTextAndTitle(cell,Common.UIString('Pending'));}} -_appendSubtitle(cellElement,subtitleText){var subtitleElement=createElement('div');subtitleElement.className='network-cell-subtitle';subtitleElement.textContent=subtitleText;cellElement.appendChild(subtitleElement);}};Network.NetworkGroupNode=class extends Network.NetworkNode{renderCell(cell,columnId){if(columnId==='name'){var leftPadding=this.leftPadding?this.leftPadding+'px':'';cell.style.setProperty('padding-left',leftPadding);cell.classList.add('disclosure');}} -select(supressSelectedEvent){if(this.expanded){this.collapse();return;} -this.expand();}};;Network.NetworkItemView=class extends UI.TabbedPane{constructor(request,calculator){super();this.renderWithNoHeaderBackground();this.element.classList.add('network-item-view');this._resourceViewTabSetting=Common.settings.createSetting('resourceViewTab','preview');var headersView=new Network.RequestHeadersView(request);this.appendTab('headers',Common.UIString('Headers'),headersView);this.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);if(request.resourceType()===Common.resourceTypes.WebSocket){var frameView=new Network.ResourceWebSocketFrameView(request);this.appendTab('webSocketFrames',Common.UIString('Frames'),frameView);}else if(request.mimeType==='text/event-stream'){this.appendTab('eventSource',Common.UIString('EventStream'),new Network.EventSourceMessagesView(request));}else{var responseView=new Network.RequestResponseView(request);var previewView=new Network.RequestPreviewView(request);this.appendTab('preview',Common.UIString('Preview'),previewView);this.appendTab('response',Common.UIString('Response'),responseView);} -if(request.requestCookies||request.responseCookies){this._cookiesView=new Network.RequestCookiesView(request);this.appendTab('cookies',Common.UIString('Cookies'),this._cookiesView);} -this.appendTab('timing',Common.UIString('Timing'),new Network.RequestTimingView(request,calculator));this._request=request;} -wasShown(){super.wasShown();this._selectTab();} -_selectTab(tabId){if(!tabId) -tabId=this._resourceViewTabSetting.get();if(!this.selectTab(tabId)) -this.selectTab('headers');} -_tabSelected(event){if(!event.data.isUserGesture) -return;this._resourceViewTabSetting.set(event.data.tabId);} -request(){return this._request;}};;Network.NetworkTimeBoundary=class{constructor(minimum,maximum){this.minimum=minimum;this.maximum=maximum;} -equals(other){return(this.minimum===other.minimum)&&(this.maximum===other.maximum);}};Network.NetworkTimeCalculator=class extends Common.Object{constructor(startAtZero){super();this.startAtZero=startAtZero;this._minimumBoundary=-1;this._maximumBoundary=-1;this._boundryChangedEventThrottler=new Common.Throttler(0);this._window=null;} -setWindow(window){this._window=window;this._boundaryChanged();} -setInitialUserFriendlyBoundaries(){this._minimumBoundary=0;this._maximumBoundary=1;} -computePosition(time){return(time-this.minimumBoundary())/this.boundarySpan()*this._workingArea;} -formatValue(value,precision){return Number.secondsToString(value,!!precision);} -minimumBoundary(){return this._window?this._window.minimum:this._minimumBoundary;} -zeroTime(){return this._minimumBoundary;} -maximumBoundary(){return this._window?this._window.maximum:this._maximumBoundary;} -boundary(){return new Network.NetworkTimeBoundary(this.minimumBoundary(),this.maximumBoundary());} -boundarySpan(){return this.maximumBoundary()-this.minimumBoundary();} -reset(){this._minimumBoundary=-1;this._maximumBoundary=-1;this._boundaryChanged();} -_value(item){return 0;} -setDisplayWidth(clientWidth){this._workingArea=clientWidth;} -computeBarGraphPercentages(request){if(request.startTime!==-1) -var start=((request.startTime-this.minimumBoundary())/this.boundarySpan())*100;else -var start=0;if(request.responseReceivedTime!==-1) -var middle=((request.responseReceivedTime-this.minimumBoundary())/this.boundarySpan())*100;else -var middle=(this.startAtZero?start:100);if(request.endTime!==-1) -var end=((request.endTime-this.minimumBoundary())/this.boundarySpan())*100;else -var end=(this.startAtZero?middle:100);if(this.startAtZero){end-=start;middle-=start;start=0;} -return{start:start,middle:middle,end:end};} -computePercentageFromEventTime(eventTime){if(eventTime!==-1&&!this.startAtZero) -return((eventTime-this.minimumBoundary())/this.boundarySpan())*100;return 0;} -percentageToTime(percentage){return percentage*this.boundarySpan()/100+this.minimumBoundary();} -_boundaryChanged(){this._boundryChangedEventThrottler.schedule(dispatchEvent.bind(this));function dispatchEvent(){this.dispatchEventToListeners(Network.NetworkTimeCalculator.Events.BoundariesChanged);return Promise.resolve();}} -updateBoundariesForEventTime(eventTime){if(eventTime===-1||this.startAtZero) -return;if(this._maximumBoundary===undefined||eventTime>this._maximumBoundary){this._maximumBoundary=eventTime;this._boundaryChanged();}} -computeBarGraphLabels(request){var rightLabel='';if(request.responseReceivedTime!==-1&&request.endTime!==-1) -rightLabel=Number.secondsToString(request.endTime-request.responseReceivedTime);var hasLatency=request.latency>0;if(hasLatency) -var leftLabel=Number.secondsToString(request.latency);else -var leftLabel=rightLabel;if(request.timing) -return{left:leftLabel,right:rightLabel};if(hasLatency&&rightLabel){var total=Number.secondsToString(request.duration);var tooltip=Network.NetworkTimeCalculator._latencyDownloadTotalFormat.format(leftLabel,rightLabel,total);}else if(hasLatency){var tooltip=Network.NetworkTimeCalculator._latencyFormat.format(leftLabel);}else if(rightLabel){var tooltip=Network.NetworkTimeCalculator._downloadFormat.format(rightLabel);} -if(request.fetchedViaServiceWorker) -tooltip=Network.NetworkTimeCalculator._fromServiceWorkerFormat.format(tooltip);else if(request.cached()) -tooltip=Network.NetworkTimeCalculator._fromCacheFormat.format(tooltip);return{left:leftLabel,right:rightLabel,tooltip:tooltip};} -updateBoundaries(request){var lowerBound=this._lowerBound(request);var upperBound=this._upperBound(request);var changed=false;if(lowerBound!==-1||this.startAtZero) -changed=this._extendBoundariesToIncludeTimestamp(this.startAtZero?0:lowerBound);if(upperBound!==-1) -changed=this._extendBoundariesToIncludeTimestamp(upperBound)||changed;if(changed) -this._boundaryChanged();} -_extendBoundariesToIncludeTimestamp(timestamp){var previousMinimumBoundary=this._minimumBoundary;var previousMaximumBoundary=this._maximumBoundary;const minOffset=Network.NetworkTimeCalculator._minimumSpread;if(this._minimumBoundary===-1||this._maximumBoundary===-1){this._minimumBoundary=timestamp;this._maximumBoundary=timestamp+minOffset;}else{this._minimumBoundary=Math.min(timestamp,this._minimumBoundary);this._maximumBoundary=Math.max(timestamp,this._minimumBoundary+minOffset,this._maximumBoundary);} -return previousMinimumBoundary!==this._minimumBoundary||previousMaximumBoundary!==this._maximumBoundary;} -_lowerBound(request){return 0;} -_upperBound(request){return 0;}};Network.NetworkTimeCalculator._minimumSpread=0.1;Network.NetworkTimeCalculator.Events={BoundariesChanged:Symbol('BoundariesChanged')};Network.NetworkTimeCalculator._latencyDownloadTotalFormat=new Common.UIStringFormat('%s latency, %s download (%s total)');Network.NetworkTimeCalculator._latencyFormat=new Common.UIStringFormat('%s latency');Network.NetworkTimeCalculator._downloadFormat=new Common.UIStringFormat('%s download');Network.NetworkTimeCalculator._fromServiceWorkerFormat=new Common.UIStringFormat('%s (from ServiceWorker)');Network.NetworkTimeCalculator._fromCacheFormat=new Common.UIStringFormat('%s (from cache)');Network.NetworkTransferTimeCalculator=class extends Network.NetworkTimeCalculator{constructor(){super(false);} -formatValue(value,precision){return Number.secondsToString(value-this.zeroTime(),!!precision);} -_lowerBound(request){return request.issueTime();} -_upperBound(request){return request.endTime;}};Network.NetworkTransferDurationCalculator=class extends Network.NetworkTimeCalculator{constructor(){super(true);} -formatValue(value,precision){return Number.secondsToString(value,!!precision);} -_upperBound(request){return request.duration;}};;Network.NetworkLogView=class extends UI.VBox{constructor(filterBar,progressBarContainer,networkLogLargeRowsSetting){super();this.setMinimumSize(50,64);this.registerRequiredCSS('network/networkLogView.css');this.element.id='network-container';this._networkHideDataURLSetting=Common.settings.createSetting('networkHideDataURL',false);this._networkResourceTypeFiltersSetting=Common.settings.createSetting('networkResourceTypeFilters',{});this._rawRowHeight=0;this._progressBarContainer=progressBarContainer;this._networkLogLargeRowsSetting=networkLogLargeRowsSetting;this._networkLogLargeRowsSetting.addChangeListener(updateRowHeight.bind(this),this);function updateRowHeight(){this._rawRowHeight=!!this._networkLogLargeRowsSetting.get()?41:21;this._rowHeight=this._computeRowHeight();} -this._rawRowHeight=0;this._rowHeight=0;updateRowHeight.call(this);this._timeCalculator=new Network.NetworkTransferTimeCalculator();this._durationCalculator=new Network.NetworkTransferDurationCalculator();this._calculator=this._timeCalculator;this._columns=new Network.NetworkLogViewColumns(this,this._timeCalculator,this._durationCalculator,networkLogLargeRowsSetting);this._columns.show(this.element);this._staleRequests=new Set();this._mainRequestLoadTime=-1;this._mainRequestDOMContentLoadedTime=-1;this._matchedRequestCount=0;this._highlightedSubstringChanges=[];this._filters=[];this._timeFilter=null;this._hoveredNode=null;this._recordingHint=null;this._refreshRequestId=null;this._searchRegex=null;this._highlightedNode=null;this._currentMatchedRequestNode=null;this._currentMatchedRequestIndex=-1;this.linkifier=new Components.Linkifier();this.badgePool=new ProductRegistry.BadgePool();this._recording=false;this._needsRefresh=false;this._headerHeight=0;this._groupLookups=new Map();this._groupLookups.set('Frame',new Network.NetworkFrameGrouper(this));this._activeGroupLookup=null;this._textFilterUI=new UI.TextFilterUI();this._textFilterUI.addEventListener(UI.FilterUI.Events.FilterChanged,this._filterChanged,this);filterBar.addFilter(this._textFilterUI);this._dataURLFilterUI=new UI.CheckboxFilterUI('hide-data-url',Common.UIString('Hide data URLs'),true,this._networkHideDataURLSetting);this._dataURLFilterUI.addEventListener(UI.FilterUI.Events.FilterChanged,this._filterChanged.bind(this),this);filterBar.addFilter(this._dataURLFilterUI);var filterItems=Object.values(Common.resourceCategories).map(category=>({name:category.title,label:category.shortTitle,title:category.title}));this._resourceCategoryFilterUI=new UI.NamedBitSetFilterUI(filterItems,this._networkResourceTypeFiltersSetting);this._resourceCategoryFilterUI.addEventListener(UI.FilterUI.Events.FilterChanged,this._filterChanged.bind(this),this);filterBar.addFilter(this._resourceCategoryFilterUI);this._filterParser=new TextUtils.FilterParser(Network.NetworkLogView._searchKeys);this._suggestionBuilder=new UI.FilterSuggestionBuilder(Network.NetworkLogView._searchKeys,Network.NetworkLogView._sortSearchValues);this._resetSuggestionBuilder();this._dataGrid=this._columns.dataGrid();this._setupDataGrid();this._columns.sortByCurrentColumn();this._summaryBarElement=this.element.createChild('div','network-summary-bar');new UI.DropTarget(this.element,[UI.DropTarget.Type.File],Common.UIString('Drop HAR files here'),this._handleDrop.bind(this));Common.moduleSetting('networkColorCodeResourceTypes').addChangeListener(this._invalidateAllItems.bind(this,false),this);SDK.targetManager.observeModels(SDK.NetworkManager,this);NetworkLog.networkLog.addEventListener(NetworkLog.NetworkLog.Events.RequestAdded,this._onRequestUpdated,this);NetworkLog.networkLog.addEventListener(NetworkLog.NetworkLog.Events.RequestUpdated,this._onRequestUpdated,this);NetworkLog.networkLog.addEventListener(NetworkLog.NetworkLog.Events.Reset,this._reset,this);this._updateGroupByFrame();Common.moduleSetting('network.group-by-frame').addChangeListener(()=>this._updateGroupByFrame());} -_updateGroupByFrame(){var value=Common.moduleSetting('network.group-by-frame').get();this._setGrouping(value?'Frame':null);} -static _sortSearchValues(key,values){if(key===Network.NetworkLogView.FilterType.Priority){var symbolToNumeric=NetworkPriorities.prioritySymbolToNumericMap();values.sort((a,b)=>{var aPriority=(NetworkPriorities.uiLabelToPriority(a));var bPriority=(NetworkPriorities.uiLabelToPriority(b));return symbolToNumeric.get(aPriority)-symbolToNumeric.get(bPriority);});}else{values.sort();}} -static _negativeFilter(filter,request){return!filter(request);} -static _requestPathFilter(regex,request){if(!regex) -return false;return regex.test(request.path()+'/'+request.name());} -static _subdomains(domain){var result=[domain];var indexOfPeriod=domain.indexOf('.');while(indexOfPeriod!==-1){result.push('*'+domain.substring(indexOfPeriod));indexOfPeriod=domain.indexOf('.',indexOfPeriod+1);} -return result;} -static _createRequestDomainFilter(value){function escapeForRegExp(string){return string.escapeForRegExp();} -var escapedPattern=value.split('*').map(escapeForRegExp).join('.*');return Network.NetworkLogView._requestDomainFilter.bind(null,new RegExp('^'+escapedPattern+'$','i'));} -static _requestDomainFilter(regex,request){return regex.test(request.domain);} -static _runningRequestFilter(request){return!request.finished;} -static _fromCacheRequestFilter(request){return request.cached();} -static _requestResponseHeaderFilter(value,request){return request.responseHeaderValue(value)!==undefined;} -static _requestMethodFilter(value,request){return request.requestMethod===value;} -static _requestPriorityFilter(value,request){return request.initialPriority()===value;} -static _requestMimeTypeFilter(value,request){return request.mimeType===value;} -static _requestMixedContentFilter(value,request){if(value===Network.NetworkLogView.MixedContentFilterValues.Displayed) -return request.mixedContentType===Protocol.Security.MixedContentType.OptionallyBlockable;else if(value===Network.NetworkLogView.MixedContentFilterValues.Blocked) -return request.mixedContentType===Protocol.Security.MixedContentType.Blockable&&request.wasBlocked();else if(value===Network.NetworkLogView.MixedContentFilterValues.BlockOverridden) -return request.mixedContentType===Protocol.Security.MixedContentType.Blockable&&!request.wasBlocked();else if(value===Network.NetworkLogView.MixedContentFilterValues.All) -return request.mixedContentType!==Protocol.Security.MixedContentType.None;return false;} -static _requestSchemeFilter(value,request){return request.scheme===value;} -static _requestSetCookieDomainFilter(value,request){var cookies=request.responseCookies;for(var i=0,l=cookies?cookies.length:0;i<l;++i){if(cookies[i].domain()===value) -return true;} -return false;} -static _requestSetCookieNameFilter(value,request){var cookies=request.responseCookies;for(var i=0,l=cookies?cookies.length:0;i<l;++i){if(cookies[i].name()===value) -return true;} -return false;} -static _requestSetCookieValueFilter(value,request){var cookies=request.responseCookies;for(var i=0,l=cookies?cookies.length:0;i<l;++i){if(cookies[i].value()===value) -return true;} -return false;} -static _requestSizeLargerThanFilter(value,request){return request.transferSize>=value;} -static _statusCodeFilter(value,request){return(''+request.statusCode)===value;} -static HTTPRequestsFilter(request){return request.parsedURL.isValid&&(request.scheme in Network.NetworkLogView.HTTPSchemas);} -static FinishedRequestsFilter(request){return request.finished;} -static _requestTimeFilter(windowStart,windowEnd,request){if(request.issueTime()>windowEnd) -return false;if(request.endTime!==-1&&request.endTime<windowStart) -return false;return true;} -static _copyRequestHeaders(request){InspectorFrontendHost.copyText(request.requestHeadersText());} -static _copyResponseHeaders(request){InspectorFrontendHost.copyText(request.responseHeadersText);} -static async _copyResponse(request){var contentData=await request.contentData();var content=contentData.content;if(contentData.encoded){content=Common.ContentProvider.contentAsDataURL(contentData.content,request.mimeType,contentData.encoded,contentData.encoded?'utf-8':null);} -InspectorFrontendHost.copyText(content||'');} -_handleDrop(dataTransfer){var items=dataTransfer.items;if(!items.length) -return;var entry=items[0].webkitGetAsEntry();if(entry.isDirectory) -return;entry.file(this._onLoadFromFile.bind(this));} -async _onLoadFromFile(file){var outputStream=new Common.StringOutputStream();var reader=new Bindings.ChunkedFileReader(file,10000000);var success=await reader.read(outputStream);if(!success){this._harLoadFailed(reader.error().message);return;} -try{var harRoot=new HARImporter.HARRoot(JSON.parse(outputStream.data()));}catch(e){this._harLoadFailed(e);return;} -NetworkLog.networkLog.importRequests(HARImporter.Importer.requestsFromHARLog(harRoot.log));} -_harLoadFailed(message){Common.console.error('Failed to load HAR file with following error: '+message);} -_setGrouping(groupKey){if(this._activeGroupLookup) -this._activeGroupLookup.reset();var groupLookup=groupKey?this._groupLookups.get(groupKey)||null:null;this._activeGroupLookup=groupLookup;this._invalidateAllItems();} -_computeRowHeight(){return Math.floor(this._rawRowHeight*window.devicePixelRatio)/window.devicePixelRatio;} -nodeForRequest(request){return request[Network.NetworkLogView._networkNodeSymbol]||null;} -headerHeight(){return this._headerHeight;} -setRecording(recording){this._recording=recording;this._updateSummaryBar();} -modelAdded(networkManager){if(networkManager.target().parentTarget()) -return;var resourceTreeModel=networkManager.target().model(SDK.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded,this._domContentLoadedEventFired,this);}} -modelRemoved(networkManager){if(!networkManager.target().parentTarget()){var resourceTreeModel=networkManager.target().model(SDK.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded,this._domContentLoadedEventFired,this);}}} -setWindow(start,end){if(!start&&!end){this._timeFilter=null;this._timeCalculator.setWindow(null);}else{this._timeFilter=Network.NetworkLogView._requestTimeFilter.bind(null,start,end);this._timeCalculator.setWindow(new Network.NetworkTimeBoundary(start,end));} -this._filterRequests();} -clearSelection(){if(this._dataGrid.selectedNode) -this._dataGrid.selectedNode.deselect();} -_resetSuggestionBuilder(){this._suggestionBuilder.clear();this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Is,Network.NetworkLogView.IsFilterType.Running);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Is,Network.NetworkLogView.IsFilterType.FromCache);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.LargerThan,'100');this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.LargerThan,'10k');this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.LargerThan,'1M');this._textFilterUI.setSuggestionProvider(this._suggestionBuilder.completions.bind(this._suggestionBuilder));} -_filterChanged(event){this.removeAllNodeHighlights();this._parseFilterQuery(this._textFilterUI.value());this._filterRequests();} -_showRecordingHint(){this._hideRecordingHint();this._recordingHint=this.element.createChild('div','network-status-pane fill');var hintText=this._recordingHint.createChild('div','recording-hint');var reloadShortcutNode=this._recordingHint.createChild('b');reloadShortcutNode.textContent=UI.shortcutRegistry.shortcutDescriptorsForAction('main.reload')[0].name;if(this._recording){var recordingText=hintText.createChild('span');recordingText.textContent=Common.UIString('Recording network activity\u2026');hintText.createChild('br');hintText.appendChild(UI.formatLocalized('Perform a request or hit %s to record the reload.',[reloadShortcutNode]));hintText.createChild('br');hintText.appendChild(UI.formatLocalized('Note: some network activity from out-of-process iframes might be missing. '+'See http://crbug.com/750901#c4 for more details.',[]));}else{var recordNode=hintText.createChild('b');recordNode.textContent=UI.shortcutRegistry.shortcutTitleForAction('network.toggle-recording');hintText.appendChild(UI.formatLocalized('Record (%s) or reload (%s) to display network activity.',[recordNode,reloadShortcutNode]));}} -_hideRecordingHint(){if(this._recordingHint) -this._recordingHint.remove();this._recordingHint=null;} -elementsToRestoreScrollPositionsFor(){if(!this._dataGrid) -return[];return[this._dataGrid.scrollContainer];} -columnExtensionResolved(){this._invalidateAllItems(true);} -_setupDataGrid(){this._dataGrid.setRowContextMenuCallback((contextMenu,node)=>{var request=node.request();if(request) -this.handleContextMenuForRequest(contextMenu,request);});this._dataGrid.setStickToBottom(true);this._dataGrid.setName('networkLog');this._dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last);this._dataGrid.element.classList.add('network-log-grid');this._dataGrid.element.addEventListener('mousedown',this._dataGridMouseDown.bind(this),true);this._dataGrid.element.addEventListener('mousemove',this._dataGridMouseMove.bind(this),true);this._dataGrid.element.addEventListener('mouseleave',()=>this._setHoveredNode(null),true);return this._dataGrid;} -_dataGridMouseMove(event){var node=(this._dataGrid.dataGridNodeFromNode((event.target)));var highlightInitiatorChain=event.shiftKey;this._setHoveredNode(node,highlightInitiatorChain);} -hoveredNode(){return this._hoveredNode;} -_setHoveredNode(node,highlightInitiatorChain){if(this._hoveredNode) -this._hoveredNode.setHovered(false,false);this._hoveredNode=node;if(this._hoveredNode) -this._hoveredNode.setHovered(true,!!highlightInitiatorChain);} -_dataGridMouseDown(event){if(!this._dataGrid.selectedNode&&event.button) -event.consume();} -_updateSummaryBar(){this._hideRecordingHint();var transferSize=0;var selectedNodeNumber=0;var selectedTransferSize=0;var baseTime=-1;var maxTime=-1;var nodeCount=0;for(var request of NetworkLog.networkLog.requests()){var node=request[Network.NetworkLogView._networkNodeSymbol];if(!node) -continue;nodeCount++;var requestTransferSize=request.transferSize;transferSize+=requestTransferSize;if(!node[Network.NetworkLogView._isFilteredOutSymbol]){selectedNodeNumber++;selectedTransferSize+=requestTransferSize;} -var networkManager=SDK.NetworkManager.forRequest(request);if(networkManager&&request.url()===networkManager.target().inspectedURL()&&request.resourceType()===Common.resourceTypes.Document) -baseTime=request.startTime;if(request.endTime>maxTime) -maxTime=request.endTime;} -if(!nodeCount){this._showRecordingHint();return;} -var summaryBar=this._summaryBarElement;summaryBar.removeChildren();var separator='\u2002\u2758\u2002';var text='';function appendChunk(chunk){var span=summaryBar.createChild('span');span.textContent=chunk;text+=chunk;return span;} -if(selectedNodeNumber!==nodeCount){appendChunk(Common.UIString('%d / %d requests',selectedNodeNumber,nodeCount));appendChunk(separator);appendChunk(Common.UIString('%s / %s transferred',Number.bytesToString(selectedTransferSize),Number.bytesToString(transferSize)));}else{appendChunk(Common.UIString('%d requests',nodeCount));appendChunk(separator);appendChunk(Common.UIString('%s transferred',Number.bytesToString(transferSize)));} -if(baseTime!==-1&&maxTime!==-1){appendChunk(separator);appendChunk(Common.UIString('Finish: %s',Number.secondsToString(maxTime-baseTime)));if(this._mainRequestDOMContentLoadedTime!==-1&&this._mainRequestDOMContentLoadedTime>baseTime){appendChunk(separator);var domContentLoadedText=Common.UIString('DOMContentLoaded: %s',Number.secondsToString(this._mainRequestDOMContentLoadedTime-baseTime));appendChunk(domContentLoadedText).classList.add('summary-blue');} -if(this._mainRequestLoadTime!==-1){appendChunk(separator);var loadText=Common.UIString('Load: %s',Number.secondsToString(this._mainRequestLoadTime-baseTime));appendChunk(loadText).classList.add('summary-red');}} -summaryBar.title=text;} -scheduleRefresh(){if(this._needsRefresh) -return;this._needsRefresh=true;if(this.isShowing()&&!this._refreshRequestId) -this._refreshRequestId=this.element.window().requestAnimationFrame(this._refresh.bind(this));} -addFilmStripFrames(times){this._columns.addEventDividers(times,'network-frame-divider');} -selectFilmStripFrame(time){this._columns.selectFilmStripFrame(time);} -clearFilmStripFrame(){this._columns.clearFilmStripFrame();} -_refreshIfNeeded(){if(this._needsRefresh) -this._refresh();} -_invalidateAllItems(deferUpdate){this._staleRequests=new Set(NetworkLog.networkLog.requests());if(deferUpdate) -this.scheduleRefresh();else -this._refresh();} -timeCalculator(){return this._timeCalculator;} -calculator(){return this._calculator;} -setCalculator(x){if(!x||this._calculator===x) -return;if(this._calculator!==x){this._calculator=x;this._columns.setCalculator(this._calculator);} -this._calculator.reset();if(this._calculator.startAtZero) -this._columns.hideEventDividers();else -this._columns.showEventDividers();this._invalidateAllItems();} -_loadEventFired(event){if(!this._recording) -return;var time=(event.data.loadTime);if(time){this._mainRequestLoadTime=time;this._columns.addEventDividers([time],'network-red-divider');}} -_domContentLoadedEventFired(event){if(!this._recording) -return;var data=(event.data);if(data){this._mainRequestDOMContentLoadedTime=data;this._columns.addEventDividers([data],'network-blue-divider');}} -wasShown(){this._refreshIfNeeded();this._columns.wasShown();} -willHide(){this._columns.willHide();} -onResize(){this._rowHeight=this._computeRowHeight();} -flatNodesList(){return this._dataGrid.rootNode().flatChildren();} -stylesChanged(){this._columns.scheduleRefresh();} -_refresh(){this._needsRefresh=false;if(this._refreshRequestId){this.element.window().cancelAnimationFrame(this._refreshRequestId);this._refreshRequestId=null;} -this.removeAllNodeHighlights();this._timeCalculator.updateBoundariesForEventTime(this._mainRequestLoadTime);this._durationCalculator.updateBoundariesForEventTime(this._mainRequestLoadTime);this._timeCalculator.updateBoundariesForEventTime(this._mainRequestDOMContentLoadedTime);this._durationCalculator.updateBoundariesForEventTime(this._mainRequestDOMContentLoadedTime);var nodesToInsert=new Map();var nodesToRefresh=[];var staleNodes=new Set();while(this._staleRequests.size){var request=this._staleRequests.firstValue();this._staleRequests.delete(request);var node=request[Network.NetworkLogView._networkNodeSymbol];if(!node) -node=this._createNodeForRequest(request);staleNodes.add(node);} -for(var node of staleNodes){var isFilteredOut=!this._applyFilter(node);if(isFilteredOut&&node===this._hoveredNode) -this._setHoveredNode(null);if(!isFilteredOut) -nodesToRefresh.push(node);var request=node.request();this._timeCalculator.updateBoundaries(request);this._durationCalculator.updateBoundaries(request);var newParent=this._parentNodeForInsert(node);if(node[Network.NetworkLogView._isFilteredOutSymbol]===isFilteredOut&&node.parent===newParent) -continue;node[Network.NetworkLogView._isFilteredOutSymbol]=isFilteredOut;var removeFromParent=node.parent&&(isFilteredOut||node.parent!==newParent);if(removeFromParent){var parent=node.parent;parent.removeChild(node);while(parent&&!parent.hasChildren()&&parent.dataGrid&&parent.dataGrid.rootNode()!==parent){var grandparent=parent.parent;grandparent.removeChild(parent);parent=grandparent;}} -if(!newParent||isFilteredOut) -continue;if(!newParent.dataGrid&&!nodesToInsert.has(newParent)){nodesToInsert.set(newParent,this._dataGrid.rootNode());nodesToRefresh.push(newParent);} -nodesToInsert.set(node,newParent);} -for(var node of nodesToInsert.keys()){var parent=nodesToInsert.get(node);var request=node.request();if(request) -node[Network.NetworkLogView._isMatchingSearchQuerySymbol]=this._matchRequest(request);parent.appendChild(node);} -for(var node of nodesToRefresh) -node.refresh();this._highlightNthMatchedRequestForSearch(this._updateMatchCountAndFindMatchIndex(this._currentMatchedRequestNode),false);this._updateSummaryBar();if(nodesToInsert.size) -this._columns.sortByCurrentColumn();this._dataGrid.updateInstantly();this._didRefreshForTest();} -_didRefreshForTest(){} -_parentNodeForInsert(node){if(!this._activeGroupLookup) -return this._dataGrid.rootNode();var groupNode=this._activeGroupLookup.groupNodeForRequest(node.request());if(!groupNode) -return this._dataGrid.rootNode();return groupNode;} -_reset(){this.dispatchEventToListeners(Network.NetworkLogView.Events.RequestSelected,null);this._clearSearchMatchedList();this._setHoveredNode(null);this._columns.reset();this._timeFilter=null;this._calculator.reset();this._timeCalculator.setWindow(null);this.linkifier.reset();this.badgePool.reset();if(this._activeGroupLookup) -this._activeGroupLookup.reset();this._staleRequests.clear();this._resetSuggestionBuilder();this._mainRequestLoadTime=-1;this._mainRequestDOMContentLoadedTime=-1;this._dataGrid.rootNode().removeChildren();this._updateSummaryBar();this._dataGrid.setStickToBottom(true);this.scheduleRefresh();} -setTextFilterValue(filterString){this._textFilterUI.setValue(filterString);this._dataURLFilterUI.setChecked(false);this._resourceCategoryFilterUI.reset();} -_createNodeForRequest(request){var node=new Network.NetworkRequestNode(this,request);request[Network.NetworkLogView._networkNodeSymbol]=node;node[Network.NetworkLogView._isFilteredOutSymbol]=true;node[Network.NetworkLogView._isMatchingSearchQuerySymbol]=false;for(var redirect=request.redirectSource();redirect;redirect=redirect.redirectSource()) -this._refreshRequest(redirect);return node;} -_onRequestUpdated(event){var request=(event.data);this._refreshRequest(request);} -_refreshRequest(request){Network.NetworkLogView._subdomains(request.domain).forEach(this._suggestionBuilder.addItem.bind(this._suggestionBuilder,Network.NetworkLogView.FilterType.Domain));this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Method,request.requestMethod);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.MimeType,request.mimeType);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Scheme,''+request.scheme);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.StatusCode,''+request.statusCode);var priority=request.initialPriority();if(priority){this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Priority,NetworkPriorities.uiLabelForPriority(priority));} -if(request.mixedContentType!==Protocol.Security.MixedContentType.None){this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.MixedContent,Network.NetworkLogView.MixedContentFilterValues.All);} -if(request.mixedContentType===Protocol.Security.MixedContentType.OptionallyBlockable){this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.MixedContent,Network.NetworkLogView.MixedContentFilterValues.Displayed);} -if(request.mixedContentType===Protocol.Security.MixedContentType.Blockable){var suggestion=request.wasBlocked()?Network.NetworkLogView.MixedContentFilterValues.Blocked:Network.NetworkLogView.MixedContentFilterValues.BlockOverridden;this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.MixedContent,suggestion);} -var responseHeaders=request.responseHeaders;for(var i=0,l=responseHeaders.length;i<l;++i) -this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.HasResponseHeader,responseHeaders[i].name);var cookies=request.responseCookies;for(var i=0,l=cookies?cookies.length:0;i<l;++i){var cookie=cookies[i];this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.SetCookieDomain,cookie.domain());this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.SetCookieName,cookie.name());this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.SetCookieValue,cookie.value());} -this._staleRequests.add(request);this.scheduleRefresh();} -rowHeight(){return this._rowHeight;} -switchViewMode(gridMode){this._columns.switchViewMode(gridMode);} -handleContextMenuForRequest(contextMenu,request){contextMenu.appendApplicableItems(request);var copyMenu=contextMenu.clipboardSection().appendSubMenuItem(Common.UIString('Copy'));var footerSection=copyMenu.footerSection();if(request){copyMenu.defaultSection().appendItem(UI.copyLinkAddressLabel(),InspectorFrontendHost.copyText.bind(InspectorFrontendHost,request.contentURL()));if(request.requestHeadersText()){copyMenu.defaultSection().appendItem(Common.UIString('Copy request headers'),Network.NetworkLogView._copyRequestHeaders.bind(null,request));} -if(request.responseHeadersText){copyMenu.defaultSection().appendItem(Common.UIString('Copy response headers'),Network.NetworkLogView._copyResponseHeaders.bind(null,request));} -if(request.finished){copyMenu.defaultSection().appendItem(Common.UIString('Copy response'),Network.NetworkLogView._copyResponse.bind(null,request));} -if(Host.isWin()){footerSection.appendItem(Common.UIString('Copy as cURL (cmd)'),this._copyCurlCommand.bind(this,request,'win'));footerSection.appendItem(Common.UIString('Copy as cURL (bash)'),this._copyCurlCommand.bind(this,request,'unix'));footerSection.appendItem(Common.UIString('Copy All as cURL (cmd)'),this._copyAllCurlCommand.bind(this,'win'));footerSection.appendItem(Common.UIString('Copy All as cURL (bash)'),this._copyAllCurlCommand.bind(this,'unix'));}else{footerSection.appendItem(Common.UIString('Copy as cURL'),this._copyCurlCommand.bind(this,request,'unix'));footerSection.appendItem(Common.UIString('Copy All as cURL'),this._copyAllCurlCommand.bind(this,'unix'));}}else{copyMenu=contextMenu.clipboardSection().appendSubMenuItem(Common.UIString('Copy'));} -footerSection.appendItem(Common.UIString('Copy all as HAR'),this._copyAll.bind(this));contextMenu.saveSection().appendItem(Common.UIString('Save as HAR with content'),this._exportAll.bind(this));contextMenu.editSection().appendItem(Common.UIString('Clear browser cache'),this._clearBrowserCache.bind(this));contextMenu.editSection().appendItem(Common.UIString('Clear browser cookies'),this._clearBrowserCookies.bind(this));if(request){const maxBlockedURLLength=20;var manager=SDK.multitargetNetworkManager;var patterns=manager.blockedPatterns();var urlWithoutScheme=request.parsedURL.urlWithoutScheme();if(urlWithoutScheme&&!patterns.find(pattern=>pattern.url===urlWithoutScheme)){contextMenu.debugSection().appendItem(Common.UIString('Block request URL'),addBlockedURL.bind(null,urlWithoutScheme));}else if(urlWithoutScheme){const croppedURL=urlWithoutScheme.trimMiddle(maxBlockedURLLength);contextMenu.debugSection().appendItem(Common.UIString('Unblock %s',croppedURL),removeBlockedURL.bind(null,urlWithoutScheme));} -var domain=request.parsedURL.domain();if(domain&&!patterns.find(pattern=>pattern.url===domain)){contextMenu.debugSection().appendItem(Common.UIString('Block request domain'),addBlockedURL.bind(null,domain));}else if(domain){const croppedDomain=domain.trimMiddle(maxBlockedURLLength);contextMenu.debugSection().appendItem(Common.UIString('Unblock %s',croppedDomain),removeBlockedURL.bind(null,domain));} -if(SDK.NetworkManager.canReplayRequest(request)){contextMenu.debugSection().appendItem(Common.UIString('Replay XHR'),SDK.NetworkManager.replayRequest.bind(null,request));} -function addBlockedURL(url){patterns.push({enabled:true,url:url});manager.setBlockedPatterns(patterns);manager.setBlockingEnabled(true);UI.viewManager.showView('network.blocked-urls');} -function removeBlockedURL(url){patterns=patterns.filter(pattern=>pattern.url!==url);manager.setBlockedPatterns(patterns);UI.viewManager.showView('network.blocked-urls');}}} -_harRequests(){var httpRequests=NetworkLog.networkLog.requests().filter(Network.NetworkLogView.HTTPRequestsFilter);return httpRequests.filter(Network.NetworkLogView.FinishedRequestsFilter);} -_copyAll(){var harArchive={log:(new NetworkLog.HARLog(this._harRequests())).build()};InspectorFrontendHost.copyText(JSON.stringify(harArchive,null,2));} -_copyCurlCommand(request,platform){InspectorFrontendHost.copyText(this._generateCurlCommand(request,platform));} -_copyAllCurlCommand(platform){var requests=NetworkLog.networkLog.requests();var commands=[];for(var request of requests) -commands.push(this._generateCurlCommand(request,platform));if(platform==='win') -InspectorFrontendHost.copyText(commands.join(' &\r\n'));else -InspectorFrontendHost.copyText(commands.join(' ;\n'));} -async _exportAll(){var url=SDK.targetManager.mainTarget().inspectedURL();var parsedURL=url.asParsedURL();var filename=parsedURL?parsedURL.host:'network-log';var stream=new Bindings.FileOutputStream();if(!await stream.open(filename+'.har')) -return;var progressIndicator=new UI.ProgressIndicator();this._progressBarContainer.appendChild(progressIndicator.element);await Network.HARWriter.write(stream,this._harRequests(),progressIndicator);progressIndicator.done();stream.close();} -_clearBrowserCache(){if(confirm(Common.UIString('Are you sure you want to clear browser cache?'))) -SDK.multitargetNetworkManager.clearBrowserCache();} -_clearBrowserCookies(){if(confirm(Common.UIString('Are you sure you want to clear browser cookies?'))) -SDK.multitargetNetworkManager.clearBrowserCookies();} -_matchRequest(request){var re=this._searchRegex;if(!re) -return false;var text=this._networkLogLargeRowsSetting.get()?request.path()+'/'+request.name():request.name();return re.test(text);} -_clearSearchMatchedList(){this._matchedRequestCount=-1;this._currentMatchedRequestNode=null;this._removeAllHighlights();} -_removeAllHighlights(){this.removeAllNodeHighlights();for(var i=0;i<this._highlightedSubstringChanges.length;++i) -UI.revertDomChanges(this._highlightedSubstringChanges[i]);this._highlightedSubstringChanges=[];} -dataGridSorted(){this._highlightNthMatchedRequestForSearch(this._updateMatchCountAndFindMatchIndex(this._currentMatchedRequestNode),false);} -_highlightNthMatchedRequestForSearch(n,reveal){this._removeAllHighlights();var nodes=this._dataGrid.rootNode().children;var matchCount=0;var node=null;for(var i=0;i<nodes.length;++i){if(nodes[i][Network.NetworkLogView._isMatchingSearchQuerySymbol]){if(matchCount===n){node=nodes[i];break;} -matchCount++;}} -if(!node){this._currentMatchedRequestNode=null;return;} -var request=node.request();if(reveal) -Common.Revealer.reveal(request);var highlightedSubstringChanges=node.highlightMatchedSubstring(this._searchRegex);this._highlightedSubstringChanges.push(highlightedSubstringChanges);this._currentMatchedRequestNode=node;this._currentMatchedRequestIndex=n;this.dispatchEventToListeners(Network.NetworkLogView.Events.SearchIndexUpdated,n);} -performSearch(searchConfig,shouldJump,jumpBackwards){var query=searchConfig.query;var currentMatchedRequestNode=this._currentMatchedRequestNode;this._clearSearchMatchedList();this._searchRegex=createPlainTextSearchRegex(query,'i');var nodes=this._dataGrid.rootNode().children;for(var i=0;i<nodes.length;++i) -nodes[i][Network.NetworkLogView._isMatchingSearchQuerySymbol]=this._matchRequest(nodes[i].request());var newMatchedRequestIndex=this._updateMatchCountAndFindMatchIndex(currentMatchedRequestNode);if(!newMatchedRequestIndex&&jumpBackwards) -newMatchedRequestIndex=this._matchedRequestCount-1;this._highlightNthMatchedRequestForSearch(newMatchedRequestIndex,shouldJump);} -supportsCaseSensitiveSearch(){return false;} -supportsRegexSearch(){return true;} -_updateMatchCountAndFindMatchIndex(node){var nodes=this._dataGrid.rootNode().children;var matchCount=0;var matchIndex=0;for(var i=0;i<nodes.length;++i){if(!nodes[i][Network.NetworkLogView._isMatchingSearchQuerySymbol]) -continue;if(node===nodes[i]) -matchIndex=matchCount;matchCount++;} -if(this._matchedRequestCount!==matchCount){this._matchedRequestCount=matchCount;this.dispatchEventToListeners(Network.NetworkLogView.Events.SearchCountUpdated,matchCount);} -return matchIndex;} -_normalizeSearchResultIndex(index){return(index+this._matchedRequestCount)%this._matchedRequestCount;} -_applyFilter(node){var request=node.request();if(this._timeFilter&&!this._timeFilter(request)) -return false;var categoryName=request.resourceType().category().title;if(!this._resourceCategoryFilterUI.accept(categoryName)) -return false;if(this._dataURLFilterUI.checked()&&request.parsedURL.isDataURL()) -return false;if(request.statusText==='Service Worker Fallback Required') -return false;for(var i=0;i<this._filters.length;++i){if(!this._filters[i](request)) -return false;} -return true;} -_parseFilterQuery(query){var descriptors=this._filterParser.parse(query);this._filters=descriptors.map(descriptor=>{var key=descriptor.key;var text=descriptor.text||'';var regex=descriptor.regex;var filter;if(key){var defaultText=(key+':'+text).escapeForRegExp();filter=this._createSpecialFilter((key),text)||Network.NetworkLogView._requestPathFilter.bind(null,new RegExp(defaultText,'i'));}else if(descriptor.regex){filter=Network.NetworkLogView._requestPathFilter.bind(null,(regex));}else{filter=Network.NetworkLogView._requestPathFilter.bind(null,new RegExp(text.escapeForRegExp(),'i'));} -return descriptor.negative?Network.NetworkLogView._negativeFilter.bind(null,filter):filter;});} -_createSpecialFilter(type,value){switch(type){case Network.NetworkLogView.FilterType.Domain:return Network.NetworkLogView._createRequestDomainFilter(value);case Network.NetworkLogView.FilterType.HasResponseHeader:return Network.NetworkLogView._requestResponseHeaderFilter.bind(null,value);case Network.NetworkLogView.FilterType.Is:if(value.toLowerCase()===Network.NetworkLogView.IsFilterType.Running) -return Network.NetworkLogView._runningRequestFilter;if(value.toLowerCase()===Network.NetworkLogView.IsFilterType.FromCache) -return Network.NetworkLogView._fromCacheRequestFilter;break;case Network.NetworkLogView.FilterType.LargerThan:return this._createSizeFilter(value.toLowerCase());case Network.NetworkLogView.FilterType.Method:return Network.NetworkLogView._requestMethodFilter.bind(null,value);case Network.NetworkLogView.FilterType.MimeType:return Network.NetworkLogView._requestMimeTypeFilter.bind(null,value);case Network.NetworkLogView.FilterType.MixedContent:return Network.NetworkLogView._requestMixedContentFilter.bind(null,(value));case Network.NetworkLogView.FilterType.Scheme:return Network.NetworkLogView._requestSchemeFilter.bind(null,value);case Network.NetworkLogView.FilterType.SetCookieDomain:return Network.NetworkLogView._requestSetCookieDomainFilter.bind(null,value);case Network.NetworkLogView.FilterType.SetCookieName:return Network.NetworkLogView._requestSetCookieNameFilter.bind(null,value);case Network.NetworkLogView.FilterType.SetCookieValue:return Network.NetworkLogView._requestSetCookieValueFilter.bind(null,value);case Network.NetworkLogView.FilterType.Priority:return Network.NetworkLogView._requestPriorityFilter.bind(null,NetworkPriorities.uiLabelToPriority(value));case Network.NetworkLogView.FilterType.StatusCode:return Network.NetworkLogView._statusCodeFilter.bind(null,value);} -return null;} -_createSizeFilter(value){var multiplier=1;if(value.endsWith('k')){multiplier=1024;value=value.substring(0,value.length-1);}else if(value.endsWith('m')){multiplier=1024*1024;value=value.substring(0,value.length-1);} -var quantity=Number(value);if(isNaN(quantity)) -return null;return Network.NetworkLogView._requestSizeLargerThanFilter.bind(null,quantity*multiplier);} -_filterRequests(){this._removeAllHighlights();this._invalidateAllItems();} -jumpToPreviousSearchResult(){if(!this._matchedRequestCount) -return;var index=this._normalizeSearchResultIndex(this._currentMatchedRequestIndex-1);this._highlightNthMatchedRequestForSearch(index,true);} -jumpToNextSearchResult(){if(!this._matchedRequestCount) -return;var index=this._normalizeSearchResultIndex(this._currentMatchedRequestIndex+1);this._highlightNthMatchedRequestForSearch(index,true);} -searchCanceled(){this._searchRegex=null;this._clearSearchMatchedList();this.dispatchEventToListeners(Network.NetworkLogView.Events.SearchCountUpdated,0);} -revealAndHighlightRequest(request){this.removeAllNodeHighlights();var node=request[Network.NetworkLogView._networkNodeSymbol];if(node&&node.attached()){node.reveal();this._highlightNode(node);}} -removeAllNodeHighlights(){if(this._highlightedNode){this._highlightedNode.element().classList.remove('highlighted-row');this._highlightedNode=null;}} -_highlightNode(node){UI.runCSSAnimationOnce(node.element(),'highlighted-row');this._highlightedNode=node;} -_generateCurlCommand(request,platform){var command=['curl'];var ignoredHeaders={'host':1,'method':1,'path':1,'scheme':1,'version':1};function escapeStringWin(str){var encapsChars=/[\r\n]/.test(str)?'^"':'"';return encapsChars+ -str.replace(/\\/g,'\\\\').replace(/"/g,'\\"').replace(/[^a-zA-Z0-9\s_\-:=+~'\/.',?;()*`]/g,'^$&').replace(/%(?=[a-zA-Z0-9_])/g,'%^').replace(/\r\n|[\n\r]/g,'^\n\n')+ -encapsChars;} -function escapeStringPosix(str){function escapeCharacter(x){var code=x.charCodeAt(0);if(code<256){return code<16?'\\x0'+code.toString(16):'\\x'+code.toString(16);} -code=code.toString(16);return'\\u'+('0000'+code).substr(code.length,4);} -if(/[^\x20-\x7E]|\'/.test(str)){return'$\''+ -str.replace(/\\/g,'\\\\').replace(/\'/g,'\\\'').replace(/\n/g,'\\n').replace(/\r/g,'\\r').replace(/[^\x20-\x7E]/g,escapeCharacter)+'\'';}else{return'\''+str+'\'';}} -var escapeString=platform==='win'?escapeStringWin:escapeStringPosix;command.push(escapeString(request.url()).replace(/[[{}\]]/g,'\\$&'));var inferredMethod='GET';var data=[];var requestContentType=request.requestContentType();if(requestContentType&&requestContentType.startsWith('application/x-www-form-urlencoded')&&request.requestFormData){data.push('--data');data.push(escapeString(request.requestFormData));ignoredHeaders['content-length']=true;inferredMethod='POST';}else if(request.requestFormData){data.push('--data-binary');data.push(escapeString(request.requestFormData));ignoredHeaders['content-length']=true;inferredMethod='POST';} -if(request.requestMethod!==inferredMethod){command.push('-X');command.push(request.requestMethod);} -var requestHeaders=request.requestHeaders();for(var i=0;i<requestHeaders.length;i++){var header=requestHeaders[i];var name=header.name.replace(/^:/,'');if(name.toLowerCase()in ignoredHeaders) -continue;command.push('-H');command.push(escapeString(name+': '+header.value));} -command=command.concat(data);command.push('--compressed');if(request.securityState()===Protocol.Security.SecurityState.Insecure) -command.push('--insecure');return command.join(' ');}};Network.NetworkLogView._isFilteredOutSymbol=Symbol('isFilteredOut');Network.NetworkLogView._isMatchingSearchQuerySymbol=Symbol('isMatchingSearchQuery');Network.NetworkLogView._networkNodeSymbol=Symbol('NetworkNode');Network.NetworkLogView.HTTPSchemas={'http':true,'https':true,'ws':true,'wss':true};Network.NetworkLogView.Events={RequestSelected:Symbol('RequestSelected'),SearchCountUpdated:Symbol('SearchCountUpdated'),SearchIndexUpdated:Symbol('SearchIndexUpdated')};Network.NetworkLogView.FilterType={Domain:'domain',HasResponseHeader:'has-response-header',Is:'is',LargerThan:'larger-than',Method:'method',MimeType:'mime-type',MixedContent:'mixed-content',Priority:'priority',Scheme:'scheme',SetCookieDomain:'set-cookie-domain',SetCookieName:'set-cookie-name',SetCookieValue:'set-cookie-value',StatusCode:'status-code'};Network.NetworkLogView.MixedContentFilterValues={All:'all',Displayed:'displayed',Blocked:'blocked',BlockOverridden:'block-overridden'};Network.NetworkLogView.IsFilterType={Running:'running',FromCache:'from-cache'};Network.NetworkLogView._searchKeys=Object.keys(Network.NetworkLogView.FilterType).map(key=>Network.NetworkLogView.FilterType[key]);Network.NetworkLogView.Filter;Network.GroupLookupInterface=function(){};Network.GroupLookupInterface.prototype={groupNodeForRequest:function(request){},reset:function(){}};;Network.NetworkLogViewColumns=class{constructor(networkLogView,timeCalculator,durationCalculator,networkLogLargeRowsSetting){this._networkLogView=networkLogView;this._persistantSettings=Common.settings.createSetting('networkLogColumns',{});this._networkLogLargeRowsSetting=networkLogLargeRowsSetting;this._networkLogLargeRowsSetting.addChangeListener(this._updateRowsSize,this);this._eventDividers=new Map();this._eventDividersShown=false;this._gridMode=true;this._columns=[];this._waterfallRequestsAreStale=false;this._waterfallScrollerWidthIsStale=true;this._popupLinkifier=new Components.Linkifier();this._calculatorsMap=new Map();this._calculatorsMap.set(Network.NetworkLogViewColumns._calculatorTypes.Time,timeCalculator);this._calculatorsMap.set(Network.NetworkLogViewColumns._calculatorTypes.Duration,durationCalculator);this._setupDataGrid();this._setupWaterfall();} -static _convertToDataGridDescriptor(columnConfig){return({id:columnConfig.id,title:columnConfig.title,sortable:columnConfig.sortable,align:columnConfig.align,nonSelectable:columnConfig.nonSelectable,weight:columnConfig.weight});} -wasShown(){this._updateRowsSize();} -willHide(){this._popoverHelper.hidePopover();} -reset(){if(this._popoverHelper) -this._popoverHelper.hidePopover();this._eventDividers.clear();} -_setupDataGrid(){var defaultColumns=Network.NetworkLogViewColumns._defaultColumns;var defaultColumnConfig=Network.NetworkLogViewColumns._defaultColumnConfig;this._columns=([]);for(var currentConfigColumn of defaultColumns){var columnConfig=(Object.assign({},defaultColumnConfig,currentConfigColumn));columnConfig.id=columnConfig.id;if(columnConfig.subtitle) -columnConfig.titleDOMFragment=this._makeHeaderFragment(columnConfig.title,columnConfig.subtitle);this._columns.push(columnConfig);} -this._loadCustomColumnsAndSettings();this._popoverHelper=new UI.PopoverHelper(this._networkLogView.element,this._getPopoverRequest.bind(this));this._popoverHelper.setHasPadding(true);this._popoverHelper.setTimeout(300,300);this._dataGrid=new DataGrid.SortableDataGrid(this._columns.map(Network.NetworkLogViewColumns._convertToDataGridDescriptor));this._dataGrid.element.addEventListener('mousedown',event=>{if(!this._dataGrid.selectedNode&&event.button) -event.consume();},true);this._dataGridScroller=this._dataGrid.scrollContainer;this._updateColumns();this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortHandler,this);this._dataGrid.setHeaderContextMenuCallback(this._innerHeaderContextMenu.bind(this));this._activeWaterfallSortId=Network.NetworkLogViewColumns.WaterfallSortIds.StartTime;this._dataGrid.markColumnAsSortedBy(Network.NetworkLogViewColumns._initialSortColumn,DataGrid.DataGrid.Order.Ascending);this._splitWidget=new UI.SplitWidget(true,true,'networkPanelSplitViewWaterfall',200);var widget=this._dataGrid.asWidget();widget.setMinimumSize(150,0);this._splitWidget.setMainWidget(widget);} -_setupWaterfall(){this._waterfallColumn=new Network.NetworkWaterfallColumn(this._networkLogView.calculator());this._waterfallColumn.element.addEventListener('contextmenu',handleContextMenu.bind(this));this._waterfallColumn.element.addEventListener('mousewheel',this._onMouseWheel.bind(this,false),{passive:true});this._dataGridScroller.addEventListener('mousewheel',this._onMouseWheel.bind(this,true),true);this._waterfallScroller=this._waterfallColumn.contentElement.createChild('div','network-waterfall-v-scroll');this._waterfallScrollerContent=this._waterfallScroller.createChild('div','network-waterfall-v-scroll-content');this._dataGrid.addEventListener(DataGrid.DataGrid.Events.PaddingChanged,()=>{this._waterfallScrollerWidthIsStale=true;this._syncScrollers();});this._dataGrid.addEventListener(DataGrid.ViewportDataGrid.Events.ViewportCalculated,this._redrawWaterfallColumn.bind(this));this._createWaterfallHeader();this._waterfallColumn.contentElement.classList.add('network-waterfall-view');this._waterfallColumn.setMinimumSize(100,0);this._splitWidget.setSidebarWidget(this._waterfallColumn);this.switchViewMode(false);function handleContextMenu(event){var node=this._waterfallColumn.getNodeFromPoint(event.offsetX,event.offsetY);if(!node) -return;var request=node.request();if(!request) -return;var contextMenu=new UI.ContextMenu(event);this._networkLogView.handleContextMenuForRequest(contextMenu,request);contextMenu.show();}} -_onMouseWheel(shouldConsume,event){if(shouldConsume) -event.consume(true);this._activeScroller.scrollTop-=event.wheelDeltaY;this._syncScrollers();} -_syncScrollers(){if(!this._waterfallColumn.isShowing()) -return;this._waterfallScrollerContent.style.height=this._dataGridScroller.scrollHeight+'px';this._updateScrollerWidthIfNeeded();this._dataGridScroller.scrollTop=this._waterfallScroller.scrollTop;} -_updateScrollerWidthIfNeeded(){if(this._waterfallScrollerWidthIsStale){this._waterfallScrollerWidthIsStale=false;this._waterfallColumn.setRightPadding(this._waterfallScroller.offsetWidth-this._waterfallScrollerContent.offsetWidth);}} -_redrawWaterfallColumn(){if(!this._waterfallRequestsAreStale){this._updateScrollerWidthIfNeeded();this._waterfallColumn.update(this._activeScroller.scrollTop,this._eventDividersShown?this._eventDividers:undefined);return;} -this._syncScrollers();var nodes=this._networkLogView.flatNodesList();this._waterfallColumn.update(this._activeScroller.scrollTop,this._eventDividers,nodes);} -_createWaterfallHeader(){this._waterfallHeaderElement=this._waterfallColumn.contentElement.createChild('div','network-waterfall-header');this._waterfallHeaderElement.addEventListener('click',waterfallHeaderClicked.bind(this));this._waterfallHeaderElement.addEventListener('contextmenu',event=>this._innerHeaderContextMenu(new UI.ContextMenu(event)));var innerElement=this._waterfallHeaderElement.createChild('div');innerElement.textContent=Common.UIString('Waterfall');this._waterfallColumnSortIcon=UI.Icon.create('','sort-order-icon');this._waterfallHeaderElement.createChild('div','sort-order-icon-container').appendChild(this._waterfallColumnSortIcon);function waterfallHeaderClicked(){var sortOrders=DataGrid.DataGrid.Order;var sortOrder=this._dataGrid.sortOrder()===sortOrders.Ascending?sortOrders.Descending:sortOrders.Ascending;this._dataGrid.markColumnAsSortedBy('waterfall',sortOrder);this._sortHandler();}} -setCalculator(x){this._waterfallColumn.setCalculator(x);} -scheduleRefresh(){this._waterfallColumn.scheduleDraw();} -_updateRowsSize(){var largeRows=!!this._networkLogLargeRowsSetting.get();this._dataGrid.element.classList.toggle('small',!largeRows);this._dataGrid.scheduleUpdate();this._waterfallScrollerWidthIsStale=true;this._waterfallColumn.setRowHeight(largeRows?41:21);this._waterfallScroller.classList.toggle('small',!largeRows);this._waterfallHeaderElement.classList.toggle('small',!largeRows);this._waterfallColumn.setHeaderHeight(this._waterfallScroller.offsetTop);} -show(element){this._splitWidget.show(element);} -dataGrid(){return this._dataGrid;} -sortByCurrentColumn(){this._sortHandler();} -_sortHandler(){var columnId=this._dataGrid.sortColumnId();this._networkLogView.removeAllNodeHighlights();this._waterfallRequestsAreStale=true;if(columnId==='waterfall'){if(this._dataGrid.sortOrder()===DataGrid.DataGrid.Order.Ascending) -this._waterfallColumnSortIcon.setIconType('smallicon-triangle-up');else -this._waterfallColumnSortIcon.setIconType('smallicon-triangle-down');var sortFunction=Network.NetworkRequestNode.RequestPropertyComparator.bind(null,this._activeWaterfallSortId);this._dataGrid.sortNodes(sortFunction,!this._dataGrid.isSortOrderAscending());this._networkLogView.dataGridSorted();return;} -this._waterfallColumnSortIcon.setIconType('');var columnConfig=this._columns.find(columnConfig=>columnConfig.id===columnId);if(!columnConfig||!columnConfig.sortingFunction) -return;this._dataGrid.sortNodes(columnConfig.sortingFunction,!this._dataGrid.isSortOrderAscending());this._networkLogView.dataGridSorted();} -_updateColumns(){if(!this._dataGrid) -return;var visibleColumns=({});if(this._gridMode){for(var columnConfig of this._columns) -visibleColumns[columnConfig.id]=columnConfig.visible;}else{visibleColumns.name=true;} -this._dataGrid.setColumnsVisiblity(visibleColumns);} -switchViewMode(gridMode){if(this._gridMode===gridMode) -return;this._gridMode=gridMode;if(gridMode){if(this._dataGrid.selectedNode) -this._dataGrid.selectedNode.selected=false;this._splitWidget.showBoth();this._activeScroller=this._waterfallScroller;this._waterfallScroller.scrollTop=this._dataGridScroller.scrollTop;this._dataGrid.setScrollContainer(this._waterfallScroller);}else{this._networkLogView.removeAllNodeHighlights();this._splitWidget.hideSidebar();this._activeScroller=this._dataGridScroller;this._dataGrid.setScrollContainer(this._dataGridScroller);} -this._networkLogView.element.classList.toggle('brief-mode',!gridMode);this._updateColumns();} -_toggleColumnVisibility(columnConfig){this._loadCustomColumnsAndSettings();columnConfig.visible=!columnConfig.visible;this._saveColumnsSettings();this._updateColumns();} -_saveColumnsSettings(){var saveableSettings={};for(var columnConfig of this._columns) -saveableSettings[columnConfig.id]={visible:columnConfig.visible,title:columnConfig.title};this._persistantSettings.set(saveableSettings);} -_loadCustomColumnsAndSettings(){var savedSettings=this._persistantSettings.get();var columnIds=Object.keys(savedSettings);for(var columnId of columnIds){var setting=savedSettings[columnId];var columnConfig=this._columns.find(columnConfig=>columnConfig.id===columnId);if(!columnConfig) -columnConfig=this._addCustomHeader(setting.title,columnId);if(columnConfig.hideable&&typeof setting.visible==='boolean') -columnConfig.visible=!!setting.visible;if(typeof setting.title==='string') -columnConfig.title=setting.title;}} -_makeHeaderFragment(title,subtitle){var fragment=createDocumentFragment();fragment.createTextChild(title);var subtitleDiv=fragment.createChild('div','network-header-subtitle');subtitleDiv.createTextChild(subtitle);return fragment;} -_innerHeaderContextMenu(contextMenu){var columnConfigs=this._columns.filter(columnConfig=>columnConfig.hideable);var nonResponseHeaders=columnConfigs.filter(columnConfig=>!columnConfig.isResponseHeader);for(var columnConfig of nonResponseHeaders){contextMenu.headerSection().appendCheckboxItem(columnConfig.title,this._toggleColumnVisibility.bind(this,columnConfig),columnConfig.visible);} -var responseSubMenu=contextMenu.footerSection().appendSubMenuItem(Common.UIString('Response Headers'));var responseHeaders=columnConfigs.filter(columnConfig=>columnConfig.isResponseHeader);for(var columnConfig of responseHeaders){responseSubMenu.defaultSection().appendCheckboxItem(columnConfig.title,this._toggleColumnVisibility.bind(this,columnConfig),columnConfig.visible);} -responseSubMenu.footerSection().appendItem(Common.UIString('Manage Header Columns\u2026'),this._manageCustomHeaderDialog.bind(this));var waterfallSortIds=Network.NetworkLogViewColumns.WaterfallSortIds;var waterfallSubMenu=contextMenu.footerSection().appendSubMenuItem(Common.UIString('Waterfall'));waterfallSubMenu.defaultSection().appendCheckboxItem(Common.UIString('Start Time'),setWaterfallMode.bind(this,waterfallSortIds.StartTime),this._activeWaterfallSortId===waterfallSortIds.StartTime);waterfallSubMenu.defaultSection().appendCheckboxItem(Common.UIString('Response Time'),setWaterfallMode.bind(this,waterfallSortIds.ResponseTime),this._activeWaterfallSortId===waterfallSortIds.ResponseTime);waterfallSubMenu.defaultSection().appendCheckboxItem(Common.UIString('End Time'),setWaterfallMode.bind(this,waterfallSortIds.EndTime),this._activeWaterfallSortId===waterfallSortIds.EndTime);waterfallSubMenu.defaultSection().appendCheckboxItem(Common.UIString('Total Duration'),setWaterfallMode.bind(this,waterfallSortIds.Duration),this._activeWaterfallSortId===waterfallSortIds.Duration);waterfallSubMenu.defaultSection().appendCheckboxItem(Common.UIString('Latency'),setWaterfallMode.bind(this,waterfallSortIds.Latency),this._activeWaterfallSortId===waterfallSortIds.Latency);contextMenu.show();function setWaterfallMode(sortId){var calculator=this._calculatorsMap.get(Network.NetworkLogViewColumns._calculatorTypes.Time);var waterfallSortIds=Network.NetworkLogViewColumns.WaterfallSortIds;if(sortId===waterfallSortIds.Duration||sortId===waterfallSortIds.Latency) -calculator=this._calculatorsMap.get(Network.NetworkLogViewColumns._calculatorTypes.Duration);this._networkLogView.setCalculator(calculator);this._activeWaterfallSortId=sortId;this._dataGrid.markColumnAsSortedBy('waterfall',DataGrid.DataGrid.Order.Ascending);this._sortHandler();}} -_manageCustomHeaderDialog(){var customHeaders=[];for(var columnConfig of this._columns){if(columnConfig.isResponseHeader) -customHeaders.push({title:columnConfig.title,editable:columnConfig.isCustomHeader});} -var manageCustomHeaders=new Network.NetworkManageCustomHeadersView(customHeaders,headerTitle=>!!this._addCustomHeader(headerTitle),this._changeCustomHeader.bind(this),this._removeCustomHeader.bind(this));var dialog=new UI.Dialog();manageCustomHeaders.show(dialog.contentElement);dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.show(this._networkLogView.element);} -_removeCustomHeader(headerId){headerId=headerId.toLowerCase();var index=this._columns.findIndex(columnConfig=>columnConfig.id===headerId);if(index===-1) -return false;this._columns.splice(index,1);this._dataGrid.removeColumn(headerId);this._saveColumnsSettings();this._updateColumns();return true;} -_addCustomHeader(headerTitle,headerId,index){if(!headerId) -headerId=headerTitle.toLowerCase();if(index===undefined) -index=this._columns.length-1;var currentColumnConfig=this._columns.find(columnConfig=>columnConfig.id===headerId);if(currentColumnConfig) -return null;var columnConfig=(Object.assign({},Network.NetworkLogViewColumns._defaultColumnConfig,{id:headerId,title:headerTitle,isResponseHeader:true,isCustomHeader:true,visible:true,sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,headerId)}));this._columns.splice(index,0,columnConfig);if(this._dataGrid) -this._dataGrid.addColumn(Network.NetworkLogViewColumns._convertToDataGridDescriptor(columnConfig),index);this._saveColumnsSettings();this._updateColumns();return columnConfig;} -_changeCustomHeader(oldHeaderId,newHeaderTitle,newHeaderId){if(!newHeaderId) -newHeaderId=newHeaderTitle.toLowerCase();oldHeaderId=oldHeaderId.toLowerCase();var oldIndex=this._columns.findIndex(columnConfig=>columnConfig.id===oldHeaderId);var oldColumnConfig=this._columns[oldIndex];var currentColumnConfig=this._columns.find(columnConfig=>columnConfig.id===newHeaderId);if(!oldColumnConfig||(currentColumnConfig&&oldHeaderId!==newHeaderId)) -return false;this._removeCustomHeader(oldHeaderId);this._addCustomHeader(newHeaderTitle,newHeaderId,oldIndex);return true;} -_getPopoverRequest(event){if(!this._gridMode) -return null;var hoveredNode=this._networkLogView.hoveredNode();if(!hoveredNode) -return null;var anchor=event.target.enclosingNodeOrSelfWithClass('network-script-initiated');if(!anchor) -return null;var request=hoveredNode.request();var initiator=request?request.initiator():null;if(!initiator||!initiator.stack) -return null;return{box:anchor.boxInWindow(),show:popover=>{var manager=anchor.request?SDK.NetworkManager.forRequest(anchor.request):null;var content=Components.DOMPresentationUtils.buildStackTracePreviewContents(manager?manager.target():null,this._popupLinkifier,initiator.stack);popover.contentElement.appendChild(content);return Promise.resolve(true);},hide:this._popupLinkifier.reset.bind(this._popupLinkifier)};} -addEventDividers(times,className){var color='transparent';switch(className){case'network-blue-divider':color='hsla(240, 100%, 80%, 0.7)';break;case'network-red-divider':color='rgba(255, 0, 0, 0.5)';break;default:return;} -var currentTimes=this._eventDividers.get(color)||[];this._eventDividers.set(color,currentTimes.concat(times));this._networkLogView.scheduleRefresh();} -hideEventDividers(){this._eventDividersShown=true;this._redrawWaterfallColumn();} -showEventDividers(){this._eventDividersShown=false;this._redrawWaterfallColumn();} -selectFilmStripFrame(time){this._eventDividers.set(Network.NetworkLogViewColumns._filmStripDividerColor,[time]);this._redrawWaterfallColumn();} -clearFilmStripFrame(){this._eventDividers.delete(Network.NetworkLogViewColumns._filmStripDividerColor);this._redrawWaterfallColumn();}};Network.NetworkLogViewColumns._initialSortColumn='waterfall';Network.NetworkLogViewColumns.Descriptor;Network.NetworkLogViewColumns._calculatorTypes={Duration:'Duration',Time:'Time'};Network.NetworkLogViewColumns._defaultColumnConfig={subtitle:null,visible:false,weight:6,sortable:true,hideable:true,nonSelectable:true,isResponseHeader:false,alwaysVisible:false,isCustomHeader:false};Network.NetworkLogViewColumns._defaultColumns=[{id:'name',title:Common.UIString('Name'),subtitle:Common.UIString('Path'),visible:true,weight:20,hideable:false,nonSelectable:false,alwaysVisible:true,sortingFunction:Network.NetworkRequestNode.NameComparator},{id:'method',title:Common.UIString('Method'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'requestMethod')},{id:'status',title:Common.UIString('Status'),visible:true,subtitle:Common.UIString('Text'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'statusCode')},{id:'protocol',title:Common.UIString('Protocol'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'protocol')},{id:'scheme',title:Common.UIString('Scheme'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'scheme')},{id:'domain',title:Common.UIString('Domain'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'domain')},{id:'remoteaddress',title:Common.UIString('Remote Address'),weight:10,align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.RemoteAddressComparator},{id:'type',title:Common.UIString('Type'),visible:true,sortingFunction:Network.NetworkRequestNode.TypeComparator},{id:'initiator',title:Common.UIString('Initiator'),visible:true,weight:10,sortingFunction:Network.NetworkRequestNode.InitiatorComparator},{id:'cookies',title:Common.UIString('Cookies'),align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.RequestCookiesCountComparator},{id:'setcookies',title:Common.UIString('Set Cookies'),align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.ResponseCookiesCountComparator},{id:'size',title:Common.UIString('Size'),visible:true,subtitle:Common.UIString('Content'),align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.SizeComparator},{id:'time',title:Common.UIString('Time'),visible:true,subtitle:Common.UIString('Latency'),align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'duration')},{id:'priority',title:Common.UIString('Priority'),sortingFunction:Network.NetworkRequestNode.InitialPriorityComparator},{id:'connectionid',title:Common.UIString('Connection ID'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'connectionId')},{id:'cache-control',isResponseHeader:true,title:Common.UIString('Cache-Control'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'cache-control')},{id:'connection',isResponseHeader:true,title:Common.UIString('Connection'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'connection')},{id:'content-encoding',isResponseHeader:true,title:Common.UIString('Content-Encoding'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'content-encoding')},{id:'content-length',isResponseHeader:true,title:Common.UIString('Content-Length'),align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.ResponseHeaderNumberComparator.bind(null,'content-length')},{id:'etag',isResponseHeader:true,title:Common.UIString('ETag'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'etag')},{id:'keep-alive',isResponseHeader:true,title:Common.UIString('Keep-Alive'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'keep-alive')},{id:'last-modified',isResponseHeader:true,title:Common.UIString('Last-Modified'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderDateComparator.bind(null,'last-modified')},{id:'server',isResponseHeader:true,title:Common.UIString('Server'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'server')},{id:'vary',isResponseHeader:true,title:Common.UIString('Vary'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'vary')},{id:'waterfall',title:'',visible:false,hideable:false}];Network.NetworkLogViewColumns._filmStripDividerColor='#fccc49';Network.NetworkLogViewColumns.WaterfallSortIds={StartTime:'startTime',ResponseTime:'responseReceivedTime',EndTime:'endTime',Duration:'duration',Latency:'latency'};;Network.NetworkFrameGrouper=class{constructor(parentView){this._parentView=parentView;this._activeGroups=new Map();} -groupNodeForRequest(request){var frame=SDK.ResourceTreeModel.frameForRequest(request);if(!frame||frame.isMainFrame()) -return null;var groupNode=this._activeGroups.get(frame);if(groupNode) -return groupNode;groupNode=new Network.FrameGroupNode(this._parentView,frame);this._activeGroups.set(frame,groupNode);return groupNode;} -reset(){this._activeGroups.clear();}};Network.FrameGroupNode=class extends Network.NetworkGroupNode{constructor(parentView,frame){super(parentView);this._frame=frame;this._productBadge=null;} -isFromFrame(){return true;} -displayName(){return new Common.ParsedURL(this._frame.url).domain()||this._frame.name||'<iframe>';} -renderCell(cell,columnId){super.renderCell(cell,columnId);if(columnId==='name'){var name=this.displayName();if(!this._productBadge){this._productBadge=this.parentView().badgePool.badgeForFrame(this._frame);this._productBadge.classList.add('network-frame-group-badge');} -cell.appendChild(UI.Icon.create('largeicon-navigator-frame','network-frame-group-icon'));cell.appendChild(this._productBadge);cell.createTextChild(name);cell.title=name;}}};;Network.NetworkManageCustomHeadersView=class extends UI.VBox{constructor(columnData,addHeaderColumnCallback,changeHeaderColumnCallback,removeHeaderColumnCallback){super(true);this.registerRequiredCSS('network/networkManageCustomHeadersView.css');this.contentElement.classList.add('custom-headers-wrapper');this.contentElement.createChild('div','header').textContent=Common.UIString('Manage Header Columns');this._list=new UI.ListWidget(this);this._list.element.classList.add('custom-headers-list');this._list.registerRequiredCSS('network/networkManageCustomHeadersView.css');var placeholder=createElementWithClass('div','custom-headers-list-list-empty');placeholder.textContent=Common.UIString('No custom headers');this._list.setEmptyPlaceholder(placeholder);this._list.show(this.contentElement);this.contentElement.appendChild(UI.createTextButton(Common.UIString('Add custom header\u2026'),this._addButtonClicked.bind(this),'add-button'));this._columnConfigs=new Map();columnData.forEach(columnData=>this._columnConfigs.set(columnData.title.toLowerCase(),columnData));this._addHeaderColumnCallback=addHeaderColumnCallback;this._changeHeaderColumnCallback=changeHeaderColumnCallback;this._removeHeaderColumnCallback=removeHeaderColumnCallback;this.contentElement.tabIndex=0;} -wasShown(){this._headersUpdated();} -_headersUpdated(){this._list.clear();this._columnConfigs.forEach(headerData=>this._list.appendItem({header:headerData.title},headerData.editable));} -_addButtonClicked(){this._list.addNewItem(this._columnConfigs.size,{header:''});} -renderItem(item,editable){var element=createElementWithClass('div','custom-headers-list-item');var header=element.createChild('div','custom-header-name');header.textContent=item.header;header.title=item.header;return element;} -removeItemRequested(item,index){this._removeHeaderColumnCallback(item.header);this._columnConfigs.delete(item.header.toLowerCase());this._headersUpdated();} -commitEdit(item,editor,isNew){var headerId=editor.control('header').value.trim();var success;if(isNew) -success=this._addHeaderColumnCallback(headerId);else -success=this._changeHeaderColumnCallback(item.header,headerId);if(success&&!isNew) -this._columnConfigs.delete(item.header.toLowerCase());if(success) -this._columnConfigs.set(headerId.toLowerCase(),{title:headerId,editable:true});this._headersUpdated();} -beginEdit(item){var editor=this._createEditor();editor.control('header').value=item.header;return editor;} -_createEditor(){if(this._editor) -return this._editor;var editor=new UI.ListWidget.Editor();this._editor=editor;var content=editor.contentElement();var titles=content.createChild('div','custom-headers-edit-row');titles.createChild('div','custom-headers-header').textContent=Common.UIString('Header Name');var fields=content.createChild('div','custom-headers-edit-row');fields.createChild('div','custom-headers-header').appendChild(editor.createInput('header','text','x-custom-header',validateHeader.bind(this)));return editor;function validateHeader(item,index,input){var headerId=editor.control('header').value.trim().toLowerCase();if(this._columnConfigs.has(headerId)&&item.header!==headerId) -return false;return true;}}};;Network.NetworkOverview=class extends PerfUI.TimelineOverviewBase{constructor(){super();this._selectedFilmStripTime=-1;this.element.classList.add('network-overview');this._numBands=1;this._updateScheduled=false;SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.DOMContentLoaded,this._domContentLoadedEventFired,this);this.reset();} -setFilmStripModel(filmStripModel){this._filmStripModel=filmStripModel;this.scheduleUpdate();} -selectFilmStripFrame(time){this._selectedFilmStripTime=time;this.scheduleUpdate();} -clearFilmStripFrame(){this._selectedFilmStripTime=-1;this.scheduleUpdate();} -_loadEventFired(event){var time=(event.data.loadTime);if(time) -this._loadEvents.push(time*1000);this.scheduleUpdate();} -_domContentLoadedEventFired(event){var data=(event.data);if(data) -this._domContentLoadedEvents.push(data*1000);this.scheduleUpdate();} -_bandId(connectionId){if(!connectionId||connectionId==='0') -return-1;if(this._bandMap.has(connectionId)) -return(this._bandMap.get(connectionId));var result=this._nextBand++;this._bandMap.set(connectionId,result);return result;} -updateRequest(request){if(!this._requestsSet.has(request)){this._requestsSet.add(request);this._requestsList.push(request);} -this.scheduleUpdate();} -wasShown(){this.onResize();} -onResize(){var width=this.element.offsetWidth;var height=this.element.offsetHeight;this.calculator().setDisplayWidth(width);this.resetCanvas();var numBands=(((height-1)/Network.NetworkOverview._bandHeight)-1)|0;this._numBands=(numBands>0)?numBands:1;this.scheduleUpdate();} -reset(){this._filmStripModel=null;this._span=1;this._lastBoundary=null;this._nextBand=0;this._bandMap=new Map();this._requestsList=[];this._requestsSet=new Set();this._loadEvents=[];this._domContentLoadedEvents=[];this.resetCanvas();} -scheduleUpdate(){if(this._updateScheduled||!this.isShowing()) -return;this._updateScheduled=true;this.element.window().requestAnimationFrame(this.update.bind(this));} -update(){this._updateScheduled=false;var calculator=this.calculator();var newBoundary=new Network.NetworkTimeBoundary(calculator.minimumBoundary(),calculator.maximumBoundary());if(!this._lastBoundary||!newBoundary.equals(this._lastBoundary)){var span=calculator.boundarySpan();while(this._span<span) -this._span*=1.25;calculator.setBounds(calculator.minimumBoundary(),calculator.minimumBoundary()+this._span);this._lastBoundary=new Network.NetworkTimeBoundary(calculator.minimumBoundary(),calculator.maximumBoundary());} -var context=this.context();var linesByType={};var paddingTop=2;function drawLines(type,strokeStyle){var lines=linesByType[type];if(!lines) -return;var n=lines.length;context.beginPath();context.strokeStyle=strokeStyle;for(var i=0;i<n;){var y=lines[i++]*Network.NetworkOverview._bandHeight+paddingTop;var startTime=lines[i++];var endTime=lines[i++];if(endTime===Number.MAX_VALUE) -endTime=calculator.maximumBoundary();context.moveTo(calculator.computePosition(startTime),y);context.lineTo(calculator.computePosition(endTime)+1,y);} -context.stroke();} -function addLine(type,y,start,end){var lines=linesByType[type];if(!lines){lines=[];linesByType[type]=lines;} -lines.push(y,start,end);} -var requests=this._requestsList;var n=requests.length;for(var i=0;i<n;++i){var request=requests[i];var band=this._bandId(request.connectionId);var y=(band===-1)?0:(band%this._numBands+1);var timeRanges=Network.RequestTimingView.calculateRequestTimeRanges(request,this.calculator().minimumBoundary());for(var j=0;j<timeRanges.length;++j){var type=timeRanges[j].name;if(band!==-1||type===Network.RequestTimeRangeNames.Total) -addLine(type,y,timeRanges[j].start*1000,timeRanges[j].end*1000);}} -context.clearRect(0,0,this.width(),this.height());context.save();context.scale(window.devicePixelRatio,window.devicePixelRatio);context.lineWidth=2;drawLines(Network.RequestTimeRangeNames.Total,'#CCCCCC');drawLines(Network.RequestTimeRangeNames.Blocking,'#AAAAAA');drawLines(Network.RequestTimeRangeNames.Connecting,'#FF9800');drawLines(Network.RequestTimeRangeNames.ServiceWorker,'#FF9800');drawLines(Network.RequestTimeRangeNames.ServiceWorkerPreparation,'#FF9800');drawLines(Network.RequestTimeRangeNames.Push,'#8CDBff');drawLines(Network.RequestTimeRangeNames.Proxy,'#A1887F');drawLines(Network.RequestTimeRangeNames.DNS,'#009688');drawLines(Network.RequestTimeRangeNames.SSL,'#9C27B0');drawLines(Network.RequestTimeRangeNames.Sending,'#B0BEC5');drawLines(Network.RequestTimeRangeNames.Waiting,'#00C853');drawLines(Network.RequestTimeRangeNames.Receiving,'#03A9F4');var height=this.element.offsetHeight;context.lineWidth=1;context.beginPath();context.strokeStyle='#8080FF';for(var i=this._domContentLoadedEvents.length-1;i>=0;--i){var x=Math.round(calculator.computePosition(this._domContentLoadedEvents[i]))+0.5;context.moveTo(x,0);context.lineTo(x,height);} -context.stroke();context.beginPath();context.strokeStyle='#FF8080';for(var i=this._loadEvents.length-1;i>=0;--i){var x=Math.round(calculator.computePosition(this._loadEvents[i]))+0.5;context.moveTo(x,0);context.lineTo(x,height);} -context.stroke();if(this._selectedFilmStripTime!==-1){context.lineWidth=2;context.beginPath();context.strokeStyle='#FCCC49';var x=Math.round(calculator.computePosition(this._selectedFilmStripTime));context.moveTo(x,0);context.lineTo(x,height);context.stroke();} -context.restore();}};Network.NetworkOverview._bandHeight=3;Network.NetworkOverview.Window;;Network.NetworkWaterfallColumn=class extends UI.VBox{constructor(calculator){super(false);this.registerRequiredCSS('network/networkWaterfallColumn.css');this._canvas=this.contentElement.createChild('canvas');this._canvas.tabIndex=1;this.setDefaultFocusedElement(this._canvas);this._canvasPosition=this._canvas.getBoundingClientRect();this._leftPadding=5;this._fontSize=10;this._rightPadding=0;this._scrollTop=0;this._headerHeight=0;this._calculator=calculator;this._rawRowHeight=0;this._rowHeight=0;this._offsetWidth=0;this._offsetHeight=0;this._startTime=this._calculator.minimumBoundary();this._endTime=this._calculator.maximumBoundary();this._popoverHelper=new UI.PopoverHelper(this.element,this._getPopoverRequest.bind(this));this._popoverHelper.setHasPadding(true);this._popoverHelper.setTimeout(300,300);this._nodes=[];this._hoveredNode=null;this._eventDividers=new Map();this._updateRequestID;this.element.addEventListener('mousemove',this._onMouseMove.bind(this),true);this.element.addEventListener('mouseleave',event=>this._setHoveredNode(null,false),true);this._styleForTimeRangeName=Network.NetworkWaterfallColumn._buildRequestTimeRangeStyle();var resourceStyleTuple=Network.NetworkWaterfallColumn._buildResourceTypeStyle();this._styleForWaitingResourceType=resourceStyleTuple[0];this._styleForDownloadingResourceType=resourceStyleTuple[1];var baseLineColor=UI.themeSupport.patchColorText('#a5a5a5',UI.ThemeSupport.ColorUsage.Foreground);this._wiskerStyle={borderColor:baseLineColor,lineWidth:1};this._hoverDetailsStyle={fillStyle:baseLineColor,lineWidth:1,borderColor:baseLineColor};this._pathForStyle=new Map();this._textLayers=[];} -static _buildRequestTimeRangeStyle(){const types=Network.RequestTimeRangeNames;var styleMap=new Map();styleMap.set(types.Connecting,{fillStyle:'#FF9800'});styleMap.set(types.SSL,{fillStyle:'#9C27B0'});styleMap.set(types.DNS,{fillStyle:'#009688'});styleMap.set(types.Proxy,{fillStyle:'#A1887F'});styleMap.set(types.Blocking,{fillStyle:'#AAAAAA'});styleMap.set(types.Push,{fillStyle:'#8CDBff'});styleMap.set(types.Queueing,{fillStyle:'white',lineWidth:2,borderColor:'lightgrey'});styleMap.set(types.Receiving,{fillStyle:'#03A9F4',lineWidth:2,borderColor:'#03A9F4'});styleMap.set(types.Waiting,{fillStyle:'#00C853'});styleMap.set(types.ReceivingPush,{fillStyle:'#03A9F4'});styleMap.set(types.ServiceWorker,{fillStyle:'orange'});styleMap.set(types.ServiceWorkerPreparation,{fillStyle:'orange'});return styleMap;} -static _buildResourceTypeStyle(){const baseResourceTypeColors=new Map([['document','hsl(215, 100%, 80%)'],['font','hsl(8, 100%, 80%)'],['media','hsl(90, 50%, 80%)'],['image','hsl(90, 50%, 80%)'],['script','hsl(31, 100%, 80%)'],['stylesheet','hsl(272, 64%, 80%)'],['texttrack','hsl(8, 100%, 80%)'],['websocket','hsl(0, 0%, 95%)'],['xhr','hsl(53, 100%, 80%)'],['fetch','hsl(53, 100%, 80%)'],['other','hsl(0, 0%, 95%)'],]);var waitingStyleMap=new Map();var downloadingStyleMap=new Map();for(var resourceType of Object.values(Common.resourceTypes)){var color=baseResourceTypeColors.get(resourceType.name());if(!color) -color=baseResourceTypeColors.get('other');var borderColor=toBorderColor(color);waitingStyleMap.set(resourceType,{fillStyle:toWaitingColor(color),lineWidth:1,borderColor:borderColor});downloadingStyleMap.set(resourceType,{fillStyle:color,lineWidth:1,borderColor:borderColor});} -return[waitingStyleMap,downloadingStyleMap];function toBorderColor(color){var parsedColor=Common.Color.parse(color);var hsla=parsedColor.hsla();hsla[1]/=2;hsla[2]-=Math.min(hsla[2],0.2);return parsedColor.asString(null);} -function toWaitingColor(color){var parsedColor=Common.Color.parse(color);var hsla=parsedColor.hsla();hsla[2]*=1.1;return parsedColor.asString(null);}} -_resetPaths(){this._pathForStyle.clear();this._pathForStyle.set(this._wiskerStyle,new Path2D());this._styleForTimeRangeName.forEach(style=>this._pathForStyle.set(style,new Path2D()));this._styleForWaitingResourceType.forEach(style=>this._pathForStyle.set(style,new Path2D()));this._styleForDownloadingResourceType.forEach(style=>this._pathForStyle.set(style,new Path2D()));this._pathForStyle.set(this._hoverDetailsStyle,new Path2D());} -willHide(){this._popoverHelper.hidePopover();} -wasShown(){this.update();} -_onMouseMove(event){this._setHoveredNode(this.getNodeFromPoint(event.offsetX,event.offsetY),event.shiftKey);} -_getPopoverRequest(event){if(!this._hoveredNode) -return null;var request=this._hoveredNode.request();if(!request) -return null;var useTimingBars=!Common.moduleSetting('networkColorCodeResourceTypes').get()&&!this._calculator.startAtZero;if(useTimingBars){var range=Network.RequestTimingView.calculateRequestTimeRanges(request,0).find(data=>data.name===Network.RequestTimeRangeNames.Total);var start=this._timeToPosition(range.start);var end=this._timeToPosition(range.end);}else{var range=this._getSimplifiedBarRange(request,0);var start=range.start;var end=range.end;} -if(end-start<50){var halfWidth=(end-start)/2;start=start+halfWidth-25;end=end-halfWidth+25;} -if(event.clientX<this._canvasPosition.left+start||event.clientX>this._canvasPosition.left+end) -return null;var rowIndex=this._nodes.findIndex(node=>node.hovered());var barHeight=this._getBarHeight(range.name);var y=this._headerHeight+(this._rowHeight*rowIndex-this._scrollTop)+((this._rowHeight-barHeight)/2);if(event.clientY<this._canvasPosition.top+y||event.clientY>this._canvasPosition.top+y+barHeight) -return null;var anchorBox=this.element.boxInWindow();anchorBox.x+=start;anchorBox.y+=y;anchorBox.width=end-start;anchorBox.height=barHeight;return{box:anchorBox,show:popover=>{var content=Network.RequestTimingView.createTimingTable((request),this._calculator);popover.contentElement.appendChild(content);return Promise.resolve(true);}};} -_setHoveredNode(node,highlightInitiatorChain){if(this._hoveredNode) -this._hoveredNode.setHovered(false,false);this._hoveredNode=node;if(this._hoveredNode) -this._hoveredNode.setHovered(true,highlightInitiatorChain);} -setRowHeight(height){this._rawRowHeight=height;this._updateRowHeight();} -_updateRowHeight(){this._rowHeight=Math.floor(this._rawRowHeight*window.devicePixelRatio)/window.devicePixelRatio;} -setHeaderHeight(height){this._headerHeight=height;} -setRightPadding(padding){this._rightPadding=padding;this._calculateCanvasSize();} -setCalculator(calculator){this._calculator=calculator;} -getNodeFromPoint(x,y){return this._nodes[Math.floor((this._scrollTop+y-this._headerHeight)/this._rowHeight)];} -scheduleDraw(){if(this._updateRequestID) -return;this._updateRequestID=this.element.window().requestAnimationFrame(()=>this.update());} -update(scrollTop,eventDividers,nodes){if(scrollTop!==undefined&&this._scrollTop!==scrollTop){this._popoverHelper.hidePopover();this._scrollTop=scrollTop;} -if(nodes){this._nodes=nodes;this._calculateCanvasSize();} -if(eventDividers!==undefined) -this._eventDividers=eventDividers;if(this._updateRequestID){this.element.window().cancelAnimationFrame(this._updateRequestID);delete this._updateRequestID;} -this._startTime=this._calculator.minimumBoundary();this._endTime=this._calculator.maximumBoundary();this._resetCanvas();this._resetPaths();this._textLayers=[];this._draw();} -_resetCanvas(){var ratio=window.devicePixelRatio;this._canvas.width=this._offsetWidth*ratio;this._canvas.height=this._offsetHeight*ratio;this._canvas.style.width=this._offsetWidth+'px';this._canvas.style.height=this._offsetHeight+'px';} -onResize(){super.onResize();this._updateRowHeight();this._calculateCanvasSize();this.scheduleDraw();} -_calculateCanvasSize(){this._offsetWidth=this.contentElement.offsetWidth-this._rightPadding;this._offsetHeight=this.contentElement.offsetHeight;this._calculator.setDisplayWidth(this._offsetWidth);this._canvasPosition=this._canvas.getBoundingClientRect();} -_timeToPosition(time){var availableWidth=this._offsetWidth-this._leftPadding;var timeToPixel=availableWidth/(this._endTime-this._startTime);return Math.floor(this._leftPadding+(time-this._startTime)*timeToPixel);} -_didDrawForTest(){} -_draw(){var useTimingBars=!Common.moduleSetting('networkColorCodeResourceTypes').get()&&!this._calculator.startAtZero;var nodes=this._nodes;var context=this._canvas.getContext('2d');context.save();context.scale(window.devicePixelRatio,window.devicePixelRatio);context.translate(0,this._headerHeight);context.rect(0,0,this._offsetWidth,this._offsetHeight);context.clip();var firstRequestIndex=Math.floor(this._scrollTop/this._rowHeight);var lastRequestIndex=Math.min(nodes.length,firstRequestIndex+Math.ceil(this._offsetHeight/this._rowHeight));for(var i=firstRequestIndex;i<lastRequestIndex;i++){var rowOffset=this._rowHeight*i;var node=nodes[i];this._decorateRow(context,node,rowOffset-this._scrollTop);var drawNodes=[];if(node.hasChildren()&&!node.expanded) -drawNodes=(node.flatChildren());drawNodes.push(node);for(var drawNode of drawNodes){if(useTimingBars) -this._buildTimingBarLayers(drawNode,rowOffset-this._scrollTop);else -this._buildSimplifiedBarLayers(context,drawNode,rowOffset-this._scrollTop);}} -this._drawLayers(context);context.save();context.fillStyle=UI.themeSupport.patchColorText('#888',UI.ThemeSupport.ColorUsage.Foreground);for(var textData of this._textLayers) -context.fillText(textData.text,textData.x,textData.y);context.restore();this._drawEventDividers(context);context.restore();const freeZoneAtLeft=75;const freeZoneAtRight=18;var dividersData=PerfUI.TimelineGrid.calculateDividerOffsets(this._calculator);PerfUI.TimelineGrid.drawCanvasGrid(context,dividersData);PerfUI.TimelineGrid.drawCanvasHeaders(context,dividersData,time=>this._calculator.formatValue(time,dividersData.precision),this._fontSize,this._headerHeight,freeZoneAtLeft);context.clearRect(this._offsetWidth-freeZoneAtRight,0,freeZoneAtRight,this._headerHeight);this._didDrawForTest();} -_drawLayers(context){for(var entry of this._pathForStyle){var style=(entry[0]);var path=(entry[1]);context.save();context.beginPath();if(style.lineWidth){context.lineWidth=style.lineWidth;context.strokeStyle=style.borderColor;context.stroke(path);} -if(style.fillStyle){context.fillStyle=style.fillStyle;context.fill(path);} -context.restore();}} -_drawEventDividers(context){context.save();context.lineWidth=1;for(var color of this._eventDividers.keys()){context.strokeStyle=color;for(var time of this._eventDividers.get(color)){context.beginPath();var x=this._timeToPosition(time);context.moveTo(x,0);context.lineTo(x,this._offsetHeight);} -context.stroke();} -context.restore();} -_getBarHeight(type){var types=Network.RequestTimeRangeNames;switch(type){case types.Connecting:case types.SSL:case types.DNS:case types.Proxy:case types.Blocking:case types.Push:case types.Queueing:return 7;default:return 13;}} -_getSimplifiedBarRange(request,borderOffset){var drawWidth=this._offsetWidth-this._leftPadding;var percentages=this._calculator.computeBarGraphPercentages(request);return{start:this._leftPadding+Math.floor((percentages.start/100)*drawWidth)+borderOffset,mid:this._leftPadding+Math.floor((percentages.middle/100)*drawWidth)+borderOffset,end:this._leftPadding+Math.floor((percentages.end/100)*drawWidth)+borderOffset};} -_buildSimplifiedBarLayers(context,node,y){var request=node.request();if(!request) -return;const borderWidth=1;var borderOffset=borderWidth%2===0?0:0.5;var ranges=this._getSimplifiedBarRange(request,borderOffset);var height=this._getBarHeight();y+=Math.floor(this._rowHeight/2-height/2+borderWidth)-borderWidth/2;var waitingStyle=this._styleForWaitingResourceType.get(request.resourceType());var waitingPath=this._pathForStyle.get(waitingStyle);waitingPath.rect(ranges.start,y,ranges.mid-ranges.start,height-borderWidth);var barWidth=Math.max(2,ranges.end-ranges.mid);var downloadingStyle=this._styleForDownloadingResourceType.get(request.resourceType());var downloadingPath=this._pathForStyle.get(downloadingStyle);downloadingPath.rect(ranges.mid,y,barWidth,height-borderWidth);var labels=null;if(node.hovered()){labels=this._calculator.computeBarGraphLabels(request);const barDotLineLength=10;var leftLabelWidth=context.measureText(labels.left).width;var rightLabelWidth=context.measureText(labels.right).width;var hoverLinePath=this._pathForStyle.get(this._hoverDetailsStyle);if(leftLabelWidth<ranges.mid-ranges.start){var midBarX=ranges.start+(ranges.mid-ranges.start-leftLabelWidth)/2;this._textLayers.push({text:labels.left,x:midBarX,y:y+this._fontSize});}else if(barDotLineLength+leftLabelWidth+this._leftPadding<ranges.start){this._textLayers.push({text:labels.left,x:ranges.start-leftLabelWidth-barDotLineLength-1,y:y+this._fontSize});hoverLinePath.moveTo(ranges.start-barDotLineLength,y+Math.floor(height/2));hoverLinePath.arc(ranges.start,y+Math.floor(height/2),2,0,2*Math.PI);hoverLinePath.moveTo(ranges.start-barDotLineLength,y+Math.floor(height/2));hoverLinePath.lineTo(ranges.start,y+Math.floor(height/2));} -var endX=ranges.mid+barWidth+borderOffset;if(rightLabelWidth<endX-ranges.mid){var midBarX=ranges.mid+(endX-ranges.mid-rightLabelWidth)/2;this._textLayers.push({text:labels.right,x:midBarX,y:y+this._fontSize});}else if(endX+barDotLineLength+rightLabelWidth<this._offsetWidth-this._leftPadding){this._textLayers.push({text:labels.right,x:endX+barDotLineLength+1,y:y+this._fontSize});hoverLinePath.moveTo(endX,y+Math.floor(height/2));hoverLinePath.arc(endX,y+Math.floor(height/2),2,0,2*Math.PI);hoverLinePath.moveTo(endX,y+Math.floor(height/2));hoverLinePath.lineTo(endX+barDotLineLength,y+Math.floor(height/2));}} -if(!this._calculator.startAtZero){var queueingRange=Network.RequestTimingView.calculateRequestTimeRanges(request,0).find(data=>data.name===Network.RequestTimeRangeNames.Total);var leftLabelWidth=labels?context.measureText(labels.left).width:0;var leftTextPlacedInBar=leftLabelWidth<ranges.mid-ranges.start;const wiskerTextPadding=13;var textOffset=(labels&&!leftTextPlacedInBar)?leftLabelWidth+wiskerTextPadding:0;var queueingStart=this._timeToPosition(queueingRange.start);if(ranges.start-textOffset>queueingStart){var wiskerPath=this._pathForStyle.get(this._wiskerStyle);wiskerPath.moveTo(queueingStart,y+Math.floor(height/2));wiskerPath.lineTo(ranges.start-textOffset,y+Math.floor(height/2));const wiskerHeight=height/2;wiskerPath.moveTo(queueingStart+borderOffset,y+wiskerHeight/2);wiskerPath.lineTo(queueingStart+borderOffset,y+height-wiskerHeight/2-1);}}} -_buildTimingBarLayers(node,y){var request=node.request();if(!request) -return;var ranges=Network.RequestTimingView.calculateRequestTimeRanges(request,0);for(var range of ranges){if(range.name===Network.RequestTimeRangeNames.Total||range.name===Network.RequestTimeRangeNames.Sending||range.end-range.start===0) -continue;var style=this._styleForTimeRangeName.get(range.name);var path=this._pathForStyle.get(style);var lineWidth=style.lineWidth||0;var height=this._getBarHeight(range.name);var middleBarY=y+Math.floor(this._rowHeight/2-height/2)+lineWidth/2;var start=this._timeToPosition(range.start);var end=this._timeToPosition(range.end);path.rect(start,middleBarY,end-start,height-lineWidth);}} -_decorateRow(context,node,y){context.save();context.beginPath();context.fillStyle=node.backgroundColor();context.rect(0,y,this._offsetWidth,this._rowHeight);context.fill();context.restore();}};Network.NetworkWaterfallColumn._LayerStyle;Network.NetworkWaterfallColumn._TextLayer;;Network.RequestCookiesView=class extends UI.VBox{constructor(request){super();this.registerRequiredCSS('network/requestCookiesView.css');this.element.classList.add('request-cookies-view');this._request=request;} -wasShown(){this._request.addEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged,this._refreshCookies,this);this._request.addEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged,this._refreshCookies,this);if(!this._gotCookies){if(!this._emptyWidget){this._emptyWidget=new UI.EmptyWidget(Common.UIString('This request has no cookies.'));this._emptyWidget.show(this.element);} -return;} -if(!this._cookiesTable) -this._buildCookiesTable();} -willHide(){this._request.removeEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged,this._refreshCookies,this);this._request.removeEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged,this._refreshCookies,this);} -get _gotCookies(){return(this._request.requestCookies&&this._request.requestCookies.length)||(this._request.responseCookies&&this._request.responseCookies.length);} -_buildCookiesTable(){this.detachChildWidgets();this._cookiesTable=new CookieTable.CookiesTable();this._cookiesTable.setCookieFolders([{folderName:Common.UIString('Request Cookies'),cookies:this._request.requestCookies},{folderName:Common.UIString('Response Cookies'),cookies:this._request.responseCookies}]);this._cookiesTable.show(this.element);} -_refreshCookies(){delete this._cookiesTable;if(!this._gotCookies||!this.isShowing()) -return;this._buildCookiesTable();}};;Network.RequestHeadersView=class extends UI.VBox{constructor(request){super();this.registerRequiredCSS('network/requestHeadersView.css');this.element.classList.add('request-headers-view');this._request=request;this._decodeRequestParameters=true;this._showRequestHeadersText=false;this._showResponseHeadersText=false;var root=new UI.TreeOutlineInShadow();root.registerRequiredCSS('network/requestHeadersTree.css');root.element.classList.add('request-headers-tree');root.setFocusable(false);root.makeDense();root.expandTreeElementsWhenArrowing=true;this.element.appendChild(root.element);var generalCategory=new Network.RequestHeadersView.Category(root,'general',Common.UIString('General'));generalCategory.hidden=false;this._urlItem=generalCategory.createLeaf();this._requestMethodItem=generalCategory.createLeaf();this._statusCodeItem=generalCategory.createLeaf();this._remoteAddressItem=generalCategory.createLeaf();this._remoteAddressItem.hidden=true;this._referrerPolicyItem=generalCategory.createLeaf();this._referrerPolicyItem.hidden=true;this._responseHeadersCategory=new Network.RequestHeadersView.Category(root,'responseHeaders','');this._requestHeadersCategory=new Network.RequestHeadersView.Category(root,'requestHeaders','');this._queryStringCategory=new Network.RequestHeadersView.Category(root,'queryString','');this._formDataCategory=new Network.RequestHeadersView.Category(root,'formData','');this._requestPayloadCategory=new Network.RequestHeadersView.Category(root,'requestPayload',Common.UIString('Request Payload'));} -wasShown(){this._request.addEventListener(SDK.NetworkRequest.Events.RemoteAddressChanged,this._refreshRemoteAddress,this);this._request.addEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged,this._refreshRequestHeaders,this);this._request.addEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged,this._refreshResponseHeaders,this);this._request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._refreshHTTPInformation,this);this._refreshURL();this._refreshQueryString();this._refreshRequestHeaders();this._refreshResponseHeaders();this._refreshHTTPInformation();this._refreshRemoteAddress();this._refreshReferrerPolicy();} -willHide(){this._request.removeEventListener(SDK.NetworkRequest.Events.RemoteAddressChanged,this._refreshRemoteAddress,this);this._request.removeEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged,this._refreshRequestHeaders,this);this._request.removeEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged,this._refreshResponseHeaders,this);this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._refreshHTTPInformation,this);} -_formatHeader(name,value){var fragment=createDocumentFragment();fragment.createChild('div','header-name').textContent=name+':';fragment.createChild('div','header-value source-code').textContent=value;return fragment;} -_formatParameter(value,className,decodeParameters){var errorDecoding=false;if(decodeParameters){value=value.replace(/\+/g,' ');if(value.indexOf('%')>=0){try{value=decodeURIComponent(value);}catch(e){errorDecoding=true;}}} -var div=createElementWithClass('div',className);if(value==='') -div.classList.add('empty-value');if(errorDecoding) -div.createChild('span','header-decode-error').textContent=Common.UIString('(unable to decode value)');else -div.textContent=value;return div;} -_refreshURL(){this._urlItem.title=this._formatHeader(Common.UIString('Request URL'),this._request.url());} -_refreshQueryString(){var queryString=this._request.queryString();var queryParameters=this._request.queryParameters;this._queryStringCategory.hidden=!queryParameters;if(queryParameters){this._refreshParams(Common.UIString('Query String Parameters'),queryParameters,queryString,this._queryStringCategory);}} -_refreshFormData(){this._formDataCategory.hidden=true;this._requestPayloadCategory.hidden=true;var formData=this._request.requestFormData;if(!formData) -return;var formParameters=this._request.formParameters;if(formParameters){this._formDataCategory.hidden=false;this._refreshParams(Common.UIString('Form Data'),formParameters,formData,this._formDataCategory);}else{this._requestPayloadCategory.hidden=false;try{var json=JSON.parse(formData);this._refreshRequestJSONPayload(json,formData);}catch(e){this._populateTreeElementWithSourceText(this._requestPayloadCategory,formData);}}} -_populateTreeElementWithSourceText(treeElement,sourceText){var sourceTextElement=createElementWithClass('span','header-value source-code');sourceTextElement.textContent=String(sourceText||'').trim();var sourceTreeElement=new UI.TreeElement(sourceTextElement);sourceTreeElement.selectable=false;treeElement.removeChildren();treeElement.appendChild(sourceTreeElement);} -_refreshParams(title,params,sourceText,paramsTreeElement){paramsTreeElement.removeChildren();paramsTreeElement.listItemElement.removeChildren();paramsTreeElement.listItemElement.createTextChild(title);var headerCount=createElementWithClass('span','header-count');headerCount.textContent=Common.UIString('\u00A0(%d)',params.length);paramsTreeElement.listItemElement.appendChild(headerCount);function toggleViewSource(event){paramsTreeElement[Network.RequestHeadersView._viewSourceSymbol]=!paramsTreeElement[Network.RequestHeadersView._viewSourceSymbol];this._refreshParams(title,params,sourceText,paramsTreeElement);event.consume();} -paramsTreeElement.listItemElement.appendChild(this._createViewSourceToggle(paramsTreeElement[Network.RequestHeadersView._viewSourceSymbol],toggleViewSource.bind(this)));if(paramsTreeElement[Network.RequestHeadersView._viewSourceSymbol]){this._populateTreeElementWithSourceText(paramsTreeElement,sourceText);return;} -var toggleTitle=this._decodeRequestParameters?Common.UIString('view URL encoded'):Common.UIString('view decoded');var toggleButton=this._createToggleButton(toggleTitle);toggleButton.addEventListener('click',this._toggleURLDecoding.bind(this),false);paramsTreeElement.listItemElement.appendChild(toggleButton);for(var i=0;i<params.length;++i){var paramNameValue=createDocumentFragment();if(params[i].name!==''){var name=this._formatParameter(params[i].name+':','header-name',this._decodeRequestParameters);var value=this._formatParameter(params[i].value,'header-value source-code',this._decodeRequestParameters);paramNameValue.appendChild(name);paramNameValue.appendChild(value);}else{paramNameValue.appendChild(this._formatParameter(Common.UIString('(empty)'),'empty-request-header',this._decodeRequestParameters));} -var paramTreeElement=new UI.TreeElement(paramNameValue);paramTreeElement.selectable=false;paramsTreeElement.appendChild(paramTreeElement);}} -_refreshRequestJSONPayload(parsedObject,sourceText){var treeElement=this._requestPayloadCategory;treeElement.removeChildren();var listItem=this._requestPayloadCategory.listItemElement;listItem.removeChildren();listItem.createTextChild(this._requestPayloadCategory.title);function toggleViewSource(event){treeElement[Network.RequestHeadersView._viewSourceSymbol]=!treeElement[Network.RequestHeadersView._viewSourceSymbol];this._refreshRequestJSONPayload(parsedObject,sourceText);event.consume();} -listItem.appendChild(this._createViewSourceToggle(treeElement[Network.RequestHeadersView._viewSourceSymbol],toggleViewSource.bind(this)));if(treeElement[Network.RequestHeadersView._viewSourceSymbol]){this._populateTreeElementWithSourceText(this._requestPayloadCategory,sourceText);}else{var object=SDK.RemoteObject.fromLocalObject(parsedObject);var section=new ObjectUI.ObjectPropertiesSection(object,object.description);section.expand();section.editable=false;treeElement.appendChild(new UI.TreeElement(section.element));}} -_createViewSourceToggle(viewSource,handler){var viewSourceToggleTitle=viewSource?Common.UIString('view parsed'):Common.UIString('view source');var viewSourceToggleButton=this._createToggleButton(viewSourceToggleTitle);viewSourceToggleButton.addEventListener('click',handler,false);return viewSourceToggleButton;} -_toggleURLDecoding(event){this._decodeRequestParameters=!this._decodeRequestParameters;this._refreshQueryString();this._refreshFormData();event.consume();} -_refreshRequestHeaders(){var treeElement=this._requestHeadersCategory;var headers=this._request.requestHeaders().slice();headers.sort(function(a,b){return a.name.toLowerCase().compareTo(b.name.toLowerCase());});var headersText=this._request.requestHeadersText();if(this._showRequestHeadersText&&headersText) -this._refreshHeadersText(Common.UIString('Request Headers'),headers.length,headersText,treeElement);else -this._refreshHeaders(Common.UIString('Request Headers'),headers,treeElement,headersText===undefined);if(headersText){var toggleButton=this._createHeadersToggleButton(this._showRequestHeadersText);toggleButton.addEventListener('click',this._toggleRequestHeadersText.bind(this),false);treeElement.listItemElement.appendChild(toggleButton);} -this._refreshFormData();} -_refreshResponseHeaders(){var treeElement=this._responseHeadersCategory;var headers=this._request.sortedResponseHeaders.slice();var headersText=this._request.responseHeadersText;if(this._showResponseHeadersText) -this._refreshHeadersText(Common.UIString('Response Headers'),headers.length,headersText,treeElement);else -this._refreshHeaders(Common.UIString('Response Headers'),headers,treeElement);if(headersText){var toggleButton=this._createHeadersToggleButton(this._showResponseHeadersText);toggleButton.addEventListener('click',this._toggleResponseHeadersText.bind(this),false);treeElement.listItemElement.appendChild(toggleButton);}} -_refreshHTTPInformation(){var requestMethodElement=this._requestMethodItem;requestMethodElement.hidden=!this._request.statusCode;var statusCodeElement=this._statusCodeItem;statusCodeElement.hidden=!this._request.statusCode;if(this._request.statusCode){var statusCodeFragment=createDocumentFragment();statusCodeFragment.createChild('div','header-name').textContent=Common.UIString('Status Code')+':';var statusCodeImage=statusCodeFragment.createChild('label','resource-status-image','dt-icon-label');statusCodeImage.title=this._request.statusCode+' '+this._request.statusText;if(this._request.statusCode<300||this._request.statusCode===304) -statusCodeImage.type='smallicon-green-ball';else if(this._request.statusCode<400) -statusCodeImage.type='smallicon-orange-ball';else -statusCodeImage.type='smallicon-red-ball';requestMethodElement.title=this._formatHeader(Common.UIString('Request Method'),this._request.requestMethod);var statusTextElement=statusCodeFragment.createChild('div','header-value source-code');var statusText=this._request.statusCode+' '+this._request.statusText;if(this._request.fetchedViaServiceWorker){statusText+=' '+Common.UIString('(from ServiceWorker)');statusTextElement.classList.add('status-from-cache');}else if(this._request.cached()){if(this._request.cachedInMemory()) -statusText+=' '+Common.UIString('(from memory cache)');else -statusText+=' '+Common.UIString('(from disk cache)');statusTextElement.classList.add('status-from-cache');} -statusTextElement.textContent=statusText;statusCodeElement.title=statusCodeFragment;}} -_refreshHeadersTitle(title,headersTreeElement,headersLength){headersTreeElement.listItemElement.removeChildren();headersTreeElement.listItemElement.createTextChild(title);var headerCount=Common.UIString('\u00A0(%d)',headersLength);headersTreeElement.listItemElement.createChild('span','header-count').textContent=headerCount;} -_refreshHeaders(title,headers,headersTreeElement,provisionalHeaders){headersTreeElement.removeChildren();var length=headers.length;this._refreshHeadersTitle(title,headersTreeElement,length);if(provisionalHeaders){var cautionText=Common.UIString('Provisional headers are shown');var cautionFragment=createDocumentFragment();cautionFragment.createChild('label','','dt-icon-label').type='smallicon-warning';cautionFragment.createChild('div','caution').textContent=cautionText;var cautionTreeElement=new UI.TreeElement(cautionFragment);cautionTreeElement.selectable=false;headersTreeElement.appendChild(cautionTreeElement);} -headersTreeElement.hidden=!length&&!provisionalHeaders;for(var i=0;i<length;++i){var headerTreeElement=new UI.TreeElement(this._formatHeader(headers[i].name,headers[i].value));headerTreeElement.selectable=false;headersTreeElement.appendChild(headerTreeElement);}} -_refreshHeadersText(title,count,headersText,headersTreeElement){this._populateTreeElementWithSourceText(headersTreeElement,headersText);this._refreshHeadersTitle(title,headersTreeElement,count);} -_refreshRemoteAddress(){var remoteAddress=this._request.remoteAddress();var treeElement=this._remoteAddressItem;treeElement.hidden=!remoteAddress;if(remoteAddress) -treeElement.title=this._formatHeader(Common.UIString('Remote Address'),remoteAddress);} -_refreshReferrerPolicy(){var referrerPolicy=this._request.referrerPolicy();var treeElement=this._referrerPolicyItem;treeElement.hidden=!referrerPolicy;if(referrerPolicy) -treeElement.title=this._formatHeader(Common.UIString('Referrer Policy'),referrerPolicy);} -_toggleRequestHeadersText(event){this._showRequestHeadersText=!this._showRequestHeadersText;this._refreshRequestHeaders();event.consume();} -_toggleResponseHeadersText(event){this._showResponseHeadersText=!this._showResponseHeadersText;this._refreshResponseHeaders();event.consume();} -_createToggleButton(title){var button=createElementWithClass('span','header-toggle');button.textContent=title;return button;} -_createHeadersToggleButton(isHeadersTextShown){var toggleTitle=isHeadersTextShown?Common.UIString('view parsed'):Common.UIString('view source');return this._createToggleButton(toggleTitle);}};Network.RequestHeadersView._viewSourceSymbol=Symbol('ViewSource');Network.RequestHeadersView.Category=class extends UI.TreeElement{constructor(root,name,title){super(title||'',true);this.selectable=false;this.toggleOnClick=true;this.hidden=true;this._expandedSetting=Common.settings.createSetting('request-info-'+name+'-category-expanded',true);this.expanded=this._expandedSetting.get();root.appendChild(this);} -createLeaf(){var leaf=new UI.TreeElement();leaf.selectable=false;this.appendChild(leaf);return leaf;} -onexpand(){this._expandedSetting.set(true);} -oncollapse(){this._expandedSetting.set(false);}};;Network.RequestHTMLView=class extends UI.VBox{constructor(dataURL){super();this._dataURL=dataURL;this.element.classList.add('html','request-view');} -wasShown(){this._createIFrame();} -willHide(){this.element.removeChildren();} -_createIFrame(){this.element.removeChildren();var iframe=createElement('iframe');iframe.setAttribute('sandbox','');iframe.setAttribute('src',this._dataURL);this.element.appendChild(iframe);}};;Network.RequestResponseView=class extends UI.VBox{constructor(request){super();this.element.classList.add('request-view');this.request=request;this._contentViewPromise=null;} -static _hasTextContent(request,contentData){if(request.resourceType().isTextType()) -return true;if(contentData.error) -return false;if(request.resourceType()===Common.resourceTypes.Other) -return!!contentData.content&&!contentData.encoded;return false;} -static async sourceViewForRequest(request){var sourceView=request[Network.RequestResponseView._sourceViewSymbol];if(sourceView!==undefined) -return sourceView;var contentData=await request.contentData();if(!Network.RequestResponseView._hasTextContent(request,contentData)){request[Network.RequestResponseView._sourceViewSymbol]=null;return null;} -var contentProvider=new Network.DecodingContentProvider(request);var highlighterType=request.resourceType().canonicalMimeType()||request.mimeType;sourceView=SourceFrame.ResourceSourceFrame.createSearchableView(contentProvider,highlighterType);request[Network.RequestResponseView._sourceViewSymbol]=sourceView;return sourceView;} -wasShown(){this.showPreview();} -async showPreview(){if(!this._contentViewPromise) -this._contentViewPromise=this.createPreview();var responseView=await this._contentViewPromise;if(this.element.contains(responseView.element)) -return null;responseView.show(this.element);return responseView;} -async createPreview(){var contentData=await this.request.contentData();var sourceView=await Network.RequestResponseView.sourceViewForRequest(this.request);if((!contentData.content||!sourceView)&&!contentData.error) -return new UI.EmptyWidget(Common.UIString('This request has no response data available.'));if(contentData.content&&sourceView) -return sourceView;return new UI.EmptyWidget(Common.UIString('Failed to load response data'));}};Network.RequestResponseView._sourceViewSymbol=Symbol('RequestResponseSourceView');Network.DecodingContentProvider=class{constructor(request){this._request=request;} -contentURL(){return this._request.contentURL();} -contentType(){return this._request.resourceType();} -contentEncoded(){return Promise.resolve(false);} -async requestContent(){var contentData=await this._request.contentData();return contentData.encoded?window.atob(contentData.content||''):contentData.content;} -searchInContent(query,caseSensitive,isRegex){return this._request.searchInContent(query,caseSensitive,isRegex);}};;Network.RequestPreviewView=class extends Network.RequestResponseView{constructor(request){super(request);} -async showPreview(){var view=await super.showPreview();if(!(view instanceof UI.SimpleView)) -return view;var toolbar=new UI.Toolbar('network-item-preview-toolbar',this.element);for(var item of view.syncToolbarItems()) -toolbar.appendToolbarItem(item);return view;} -async _htmlErrorPreview(){var contentData=await this.request.contentData();if(contentData.error) -return new UI.EmptyWidget(Common.UIString('Failed to load response data'));if(!this.request.hasErrorStatusCode()) -return null;var whitelist=new Set(['text/html','text/plain','application/xhtml+xml']);if(!whitelist.has(this.request.mimeType)) -return null;var encodedContent=contentData.encoded?contentData.content:btoa(contentData.content);var dataURL=Common.ContentProvider.contentAsDataURL(encodedContent,this.request.mimeType,true,'utf-8');return dataURL?new Network.RequestHTMLView(dataURL):null;} -async createPreview(){var htmlErrorPreview=await this._htmlErrorPreview();if(htmlErrorPreview) -return htmlErrorPreview;var provided=await SourceFrame.PreviewFactory.createPreview(this.request,this.request.mimeType);if(provided) -return provided;var sourceView=await Network.RequestResponseView.sourceViewForRequest(this.request);if(sourceView) -return sourceView;return new UI.EmptyWidget(Common.UIString('Preview not available'));}};;Network.RequestTimingView=class extends UI.VBox{constructor(request,calculator){super();this.element.classList.add('resource-timing-view');this._request=request;this._calculator=calculator;} -static _timeRangeTitle(name){switch(name){case Network.RequestTimeRangeNames.Push:return Common.UIString('Receiving Push');case Network.RequestTimeRangeNames.Queueing:return Common.UIString('Queueing');case Network.RequestTimeRangeNames.Blocking:return Common.UIString('Stalled');case Network.RequestTimeRangeNames.Connecting:return Common.UIString('Initial connection');case Network.RequestTimeRangeNames.DNS:return Common.UIString('DNS Lookup');case Network.RequestTimeRangeNames.Proxy:return Common.UIString('Proxy negotiation');case Network.RequestTimeRangeNames.ReceivingPush:return Common.UIString('Reading Push');case Network.RequestTimeRangeNames.Receiving:return Common.UIString('Content Download');case Network.RequestTimeRangeNames.Sending:return Common.UIString('Request sent');case Network.RequestTimeRangeNames.ServiceWorker:return Common.UIString('Request to ServiceWorker');case Network.RequestTimeRangeNames.ServiceWorkerPreparation:return Common.UIString('ServiceWorker Preparation');case Network.RequestTimeRangeNames.SSL:return Common.UIString('SSL');case Network.RequestTimeRangeNames.Total:return Common.UIString('Total');case Network.RequestTimeRangeNames.Waiting:return Common.UIString('Waiting (TTFB)');default:return Common.UIString(name);}} -static calculateRequestTimeRanges(request,navigationStart){var result=[];function addRange(name,start,end){if(start<Number.MAX_VALUE&&start<=end) -result.push({name:name,start:start,end:end});} -function firstPositive(numbers){for(var i=0;i<numbers.length;++i){if(numbers[i]>0) -return numbers[i];} -return undefined;} -function addOffsetRange(name,start,end){if(start>=0&&end>=0) -addRange(name,startTime+(start/1000),startTime+(end/1000));} -var timing=request.timing;if(!timing){var start=request.issueTime()!==-1?request.issueTime():request.startTime!==-1?request.startTime:0;var middle=(request.responseReceivedTime===-1)?Number.MAX_VALUE:request.responseReceivedTime;var end=(request.endTime===-1)?Number.MAX_VALUE:request.endTime;addRange(Network.RequestTimeRangeNames.Total,start,end);addRange(Network.RequestTimeRangeNames.Blocking,start,middle);addRange(Network.RequestTimeRangeNames.Receiving,middle,end);return result;} -var issueTime=request.issueTime();var startTime=timing.requestTime;var endTime=firstPositive([request.endTime,request.responseReceivedTime])||startTime;addRange(Network.RequestTimeRangeNames.Total,issueTime<startTime?issueTime:startTime,endTime);if(timing.pushStart){var pushEnd=timing.pushEnd||endTime;if(pushEnd>navigationStart) -addRange(Network.RequestTimeRangeNames.Push,Math.max(timing.pushStart,navigationStart),pushEnd);} -if(issueTime<startTime) -addRange(Network.RequestTimeRangeNames.Queueing,issueTime,startTime);var responseReceived=(request.responseReceivedTime-startTime)*1000;if(request.fetchedViaServiceWorker){addOffsetRange(Network.RequestTimeRangeNames.Blocking,0,timing.workerStart);addOffsetRange(Network.RequestTimeRangeNames.ServiceWorkerPreparation,timing.workerStart,timing.workerReady);addOffsetRange(Network.RequestTimeRangeNames.ServiceWorker,timing.workerReady,timing.sendEnd);addOffsetRange(Network.RequestTimeRangeNames.Waiting,timing.sendEnd,responseReceived);}else if(!timing.pushStart){var blockingEnd=firstPositive([timing.dnsStart,timing.connectStart,timing.sendStart,responseReceived])||0;addOffsetRange(Network.RequestTimeRangeNames.Blocking,0,blockingEnd);addOffsetRange(Network.RequestTimeRangeNames.Proxy,timing.proxyStart,timing.proxyEnd);addOffsetRange(Network.RequestTimeRangeNames.DNS,timing.dnsStart,timing.dnsEnd);addOffsetRange(Network.RequestTimeRangeNames.Connecting,timing.connectStart,timing.connectEnd);addOffsetRange(Network.RequestTimeRangeNames.SSL,timing.sslStart,timing.sslEnd);addOffsetRange(Network.RequestTimeRangeNames.Sending,timing.sendStart,timing.sendEnd);addOffsetRange(Network.RequestTimeRangeNames.Waiting,Math.max(timing.sendEnd,timing.connectEnd,timing.dnsEnd,timing.proxyEnd,blockingEnd),responseReceived);} -if(request.endTime!==-1){addRange(timing.pushStart?Network.RequestTimeRangeNames.ReceivingPush:Network.RequestTimeRangeNames.Receiving,request.responseReceivedTime,endTime);} -return result;} -static createTimingTable(request,calculator){var tableElement=createElementWithClass('table','network-timing-table');UI.appendStyle(tableElement,'network/networkTimingTable.css');var colgroup=tableElement.createChild('colgroup');colgroup.createChild('col','labels');colgroup.createChild('col','bars');colgroup.createChild('col','duration');var timeRanges=Network.RequestTimingView.calculateRequestTimeRanges(request,calculator.minimumBoundary());var startTime=timeRanges.map(r=>r.start).reduce((a,b)=>Math.min(a,b));var endTime=timeRanges.map(r=>r.end).reduce((a,b)=>Math.max(a,b));var scale=100/(endTime-startTime);var connectionHeader;var dataHeader;var queueingHeader;var totalDuration=0;var startTimeHeader=tableElement.createChild('thead','network-timing-start');var queuedCell=startTimeHeader.createChild('tr').createChild('td');var startedCell=startTimeHeader.createChild('tr').createChild('td');queuedCell.colSpan=startedCell.colSpan=2;queuedCell.createTextChild(Common.UIString('Queued at %s',calculator.formatValue(request.issueTime(),2)));startedCell.createTextChild(Common.UIString('Started at %s',calculator.formatValue(request.startTime,2)));for(var i=0;i<timeRanges.length;++i){var range=timeRanges[i];var rangeName=range.name;if(rangeName===Network.RequestTimeRangeNames.Total){totalDuration=range.end-range.start;continue;} -if(rangeName===Network.RequestTimeRangeNames.Push){createHeader(Common.UIString('Server Push'));}else if(rangeName===Network.RequestTimeRangeNames.Queueing){queueingHeader=tableElement.createChild('tr','network-timing-table-header');queueingHeader.createChild('td').createTextChild(Common.UIString('Resource Scheduling'));queueingHeader.createChild('td').createTextChild('');queueingHeader.createChild('td').createTextChild(Common.UIString('TIME'));}else if(Network.RequestTimingView.ConnectionSetupRangeNames.has(rangeName)){if(!connectionHeader) -connectionHeader=createHeader(Common.UIString('Connection Start'));}else{if(!dataHeader) -dataHeader=createHeader(Common.UIString('Request/Response'));} -var left=(scale*(range.start-startTime));var right=(scale*(endTime-range.end));var duration=range.end-range.start;var tr=tableElement.createChild('tr');tr.createChild('td').createTextChild(Network.RequestTimingView._timeRangeTitle(rangeName));var row=tr.createChild('td').createChild('div','network-timing-row');var bar=row.createChild('span','network-timing-bar '+rangeName);bar.style.left=left+'%';bar.style.right=right+'%';bar.textContent='\u200B';var label=tr.createChild('td').createChild('div','network-timing-bar-title');label.textContent=Number.secondsToString(duration,true);} -if(!request.finished){var cell=tableElement.createChild('tr').createChild('td','caution');cell.colSpan=3;cell.createTextChild(Common.UIString('CAUTION: request is not finished yet!'));} -var footer=tableElement.createChild('tr','network-timing-footer');var note=footer.createChild('td');note.colSpan=1;note.appendChild(UI.createDocumentationLink('network-performance/reference#timing-explanation',Common.UIString('Explanation')));footer.createChild('td');footer.createChild('td').createTextChild(Number.secondsToString(totalDuration,true));var serverTimings=request.serverTimings;if(!serverTimings) -return tableElement;var lastTimingRightEdge=right===undefined?100:right;var breakElement=tableElement.createChild('tr','network-timing-table-header').createChild('td');breakElement.colSpan=3;breakElement.createChild('hr','break');var serverHeader=tableElement.createChild('tr','network-timing-table-header');serverHeader.createChild('td').createTextChild(Common.UIString('Server Timing'));serverHeader.createChild('td');serverHeader.createChild('td').createTextChild(Common.UIString('TIME'));serverTimings.filter(item=>item.metric.toLowerCase()!=='total').forEach(item=>addTiming(item,lastTimingRightEdge));serverTimings.filter(item=>item.metric.toLowerCase()==='total').forEach(item=>addTiming(item,lastTimingRightEdge));return tableElement;function addTiming(serverTiming,right){var colorGenerator=new Common.Color.Generator({min:0,max:360,count:36},{min:50,max:80},80);var isTotal=serverTiming.metric.toLowerCase()==='total';var tr=tableElement.createChild('tr',isTotal?'network-timing-footer':'');var metric=tr.createChild('td','network-timing-metric');metric.createTextChild(serverTiming.description||serverTiming.metric);var row=tr.createChild('td').createChild('div','network-timing-row');if(serverTiming.value===null) -return;var left=scale*(endTime-startTime-(serverTiming.value/1000));if(left>=0){var bar=row.createChild('span','network-timing-bar server-timing');bar.style.left=left+'%';bar.style.right=right+'%';bar.textContent='\u200B';if(!isTotal) -bar.style.backgroundColor=colorGenerator.colorForID(serverTiming.metric);} -var label=tr.createChild('td').createChild('div','network-timing-bar-title');label.textContent=Number.millisToString(serverTiming.value,true);} -function createHeader(title){var dataHeader=tableElement.createChild('tr','network-timing-table-header');dataHeader.createChild('td').createTextChild(title);dataHeader.createChild('td').createTextChild('');dataHeader.createChild('td').createTextChild(Common.UIString('TIME'));return dataHeader;}} -wasShown(){this._request.addEventListener(SDK.NetworkRequest.Events.TimingChanged,this._refresh,this);this._request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._refresh,this);this._calculator.addEventListener(Network.NetworkTimeCalculator.Events.BoundariesChanged,this._refresh,this);this._refresh();} -willHide(){this._request.removeEventListener(SDK.NetworkRequest.Events.TimingChanged,this._refresh,this);this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._refresh,this);this._calculator.removeEventListener(Network.NetworkTimeCalculator.Events.BoundariesChanged,this._refresh,this);} -_refresh(){if(this._tableElement) -this._tableElement.remove();this._tableElement=Network.RequestTimingView.createTimingTable(this._request,this._calculator);this._tableElement.classList.add('resource-timing-table');this.element.appendChild(this._tableElement);}};Network.RequestTimeRangeNames={Push:'push',Queueing:'queueing',Blocking:'blocking',Connecting:'connecting',DNS:'dns',Proxy:'proxy',Receiving:'receiving',ReceivingPush:'receiving-push',Sending:'sending',ServiceWorker:'serviceworker',ServiceWorkerPreparation:'serviceworker-preparation',SSL:'ssl',Total:'total',Waiting:'waiting'};Network.RequestTimingView.ConnectionSetupRangeNames=new Set([Network.RequestTimeRangeNames.Queueing,Network.RequestTimeRangeNames.Blocking,Network.RequestTimeRangeNames.Connecting,Network.RequestTimeRangeNames.DNS,Network.RequestTimeRangeNames.Proxy,Network.RequestTimeRangeNames.SSL]);Network.RequestTimeRange;;Network.ResourceWebSocketFrameView=class extends UI.VBox{constructor(request){super();this.registerRequiredCSS('network/webSocketFrameView.css');this.element.classList.add('websocket-frame-view');this._request=request;this._splitWidget=new UI.SplitWidget(false,true,'resourceWebSocketFrameSplitViewState');this._splitWidget.show(this.element);var columns=([{id:'data',title:Common.UIString('Data'),sortable:false,weight:88},{id:'length',title:Common.UIString('Length'),sortable:false,align:DataGrid.DataGrid.Align.Right,weight:5},{id:'time',title:Common.UIString('Time'),sortable:true,weight:7}]);this._dataGrid=new DataGrid.SortableDataGrid(columns);this._dataGrid.setRowContextMenuCallback(onRowContextMenu.bind(this));this._dataGrid.setStickToBottom(true);this._dataGrid.setCellClass('websocket-frame-view-td');this._timeComparator=(Network.ResourceWebSocketFrameNodeTimeComparator);this._dataGrid.sortNodes(this._timeComparator,false);this._dataGrid.markColumnAsSortedBy('time',DataGrid.DataGrid.Order.Ascending);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortItems,this);this._dataGrid.setName('ResourceWebSocketFrameView');this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._onFrameSelected,this);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.DeselectedNode,this._onFrameDeselected,this);this._mainToolbar=new UI.Toolbar('');this._clearAllButton=new UI.ToolbarButton(Common.UIString('Clear All'),'largeicon-clear');this._clearAllButton.addEventListener(UI.ToolbarButton.Events.Click,this._clearFrames,this);this._mainToolbar.appendToolbarItem(this._clearAllButton);this._filterTypeCombobox=new UI.ToolbarComboBox(this._updateFilterSetting.bind(this));for(var filterItem of Network.ResourceWebSocketFrameView._filterTypes){var option=this._filterTypeCombobox.createOption(filterItem.label,filterItem.label,filterItem.name);this._filterTypeCombobox.addOption(option);} -this._mainToolbar.appendToolbarItem(this._filterTypeCombobox);this._filterType=null;var placeholder='Enter regex, for example: (web)?socket';this._filterTextInput=new UI.ToolbarInput(Common.UIString(placeholder),0.4);this._filterTextInput.addEventListener(UI.ToolbarInput.Event.TextChanged,this._updateFilterSetting,this);this._mainToolbar.appendToolbarItem(this._filterTextInput);this._filterRegex=null;var mainContainer=new UI.VBox();mainContainer.element.appendChild(this._mainToolbar.element);this._dataGrid.asWidget().show(mainContainer.element);this._splitWidget.setMainWidget(mainContainer);this._frameEmptyWidget=new UI.EmptyWidget(Common.UIString('Select frame to browse its content.'));this._splitWidget.setSidebarWidget(this._frameEmptyWidget);this._selectedNode=null;function onRowContextMenu(contextMenu,node){contextMenu.clipboardSection().appendItem(Common.UIString('Copy message'),InspectorFrontendHost.copyText.bind(InspectorFrontendHost,node.data.data));contextMenu.footerSection().appendItem(Common.UIString('Clear all'),this._clearFrames.bind(this));}} -static opCodeDescription(opCode,mask){var rawDescription=Network.ResourceWebSocketFrameView.opCodeDescriptions[opCode]||'';var localizedDescription=Common.UIString(rawDescription);return Common.UIString('%s (Opcode %d%s)',localizedDescription,opCode,(mask?', mask':''));} -wasShown(){this.refresh();this._request.addEventListener(SDK.NetworkRequest.Events.WebsocketFrameAdded,this._frameAdded,this);} -willHide(){this._request.removeEventListener(SDK.NetworkRequest.Events.WebsocketFrameAdded,this._frameAdded,this);} -_frameAdded(event){var frame=(event.data);if(!this._frameFilter(frame)) -return;this._dataGrid.insertChild(new Network.ResourceWebSocketFrameNode(this._request.url(),frame));} -_frameFilter(frame){if(this._filterType&&frame.type!==this._filterType) -return false;return!this._filterRegex||this._filterRegex.test(frame.text);} -_clearFrames(){this._request[Network.ResourceWebSocketFrameView._clearFrameOffsetSymbol]=this._request.frames().length;this.refresh();} -_updateFilterSetting(){var text=this._filterTextInput.value();var type=this._filterTypeCombobox.selectedOption().value;this._filterRegex=text?new RegExp(text,'i'):null;this._filterType=type==='all'?null:type;this.refresh();} -async _onFrameSelected(event){var selectedNode=(event.data);this._currentSelectedNode=selectedNode;var contentProvider=selectedNode.contentProvider();var content=await contentProvider.requestContent();var parsedJSON=await SourceFrame.JSONView.parseJSON(content);if(this._currentSelectedNode!==selectedNode) -return;if(parsedJSON) -this._splitWidget.setSidebarWidget(SourceFrame.JSONView.createSearchableView(parsedJSON));else -this._splitWidget.setSidebarWidget(new SourceFrame.ResourceSourceFrame(contentProvider));} -_onFrameDeselected(event){this._currentSelectedNode=null;this._splitWidget.setSidebarWidget(this._frameEmptyWidget);} -refresh(){this._dataGrid.rootNode().removeChildren();var url=this._request.url();var frames=this._request.frames();var offset=this._request[Network.ResourceWebSocketFrameView._clearFrameOffsetSymbol]||0;frames=frames.slice(offset);frames=frames.filter(this._frameFilter.bind(this));frames.forEach(frame=>this._dataGrid.insertChild(new Network.ResourceWebSocketFrameNode(url,frame)));} -_sortItems(){this._dataGrid.sortNodes(this._timeComparator,!this._dataGrid.isSortOrderAscending());}};Network.ResourceWebSocketFrameView.OpCodes={ContinuationFrame:0,TextFrame:1,BinaryFrame:2,ConnectionCloseFrame:8,PingFrame:9,PongFrame:10};Network.ResourceWebSocketFrameView.opCodeDescriptions=(function(){var opCodes=Network.ResourceWebSocketFrameView.OpCodes;var map=[];map[opCodes.ContinuationFrame]='Continuation Frame';map[opCodes.TextFrame]='Text Frame';map[opCodes.BinaryFrame]='Binary Frame';map[opCodes.ContinuationFrame]='Connection Close Frame';map[opCodes.PingFrame]='Ping Frame';map[opCodes.PongFrame]='Pong Frame';return map;})();Network.ResourceWebSocketFrameView._filterTypes=[{name:'all',label:Common.UIString('All')},{name:'send',label:Common.UIString('Send')},{name:'receive',label:Common.UIString('Receive')},];Network.ResourceWebSocketFrameNode=class extends DataGrid.SortableDataGridNode{constructor(url,frame){var dataText=frame.text;var length=frame.text.length;var time=new Date(frame.time*1000);var timeText=('0'+time.getHours()).substr(-2)+':'+('0'+time.getMinutes()).substr(-2)+':'+ -('0'+time.getSeconds()).substr(-2)+'.'+('00'+time.getMilliseconds()).substr(-3);var timeNode=createElement('div');timeNode.createTextChild(timeText);timeNode.title=time.toLocaleString();var isTextFrame=frame.opCode===Network.ResourceWebSocketFrameView.OpCodes.TextFrame;if(!isTextFrame) -dataText=Network.ResourceWebSocketFrameView.opCodeDescription(frame.opCode,frame.mask);super({data:dataText,length:length,time:timeNode});this._url=url;this._frame=frame;this._isTextFrame=isTextFrame;this._dataText=dataText;} -createCells(element){element.classList.toggle('websocket-frame-view-row-error',this._frame.type===SDK.NetworkRequest.WebSocketFrameType.Error);element.classList.toggle('websocket-frame-view-row-send',this._frame.type===SDK.NetworkRequest.WebSocketFrameType.Send);element.classList.toggle('websocket-frame-view-row-receive',this._frame.type===SDK.NetworkRequest.WebSocketFrameType.Receive);element.classList.toggle('websocket-frame-view-row-opcode',!this._isTextFrame);super.createCells(element);} -nodeSelfHeight(){return 21;} -contentProvider(){return Common.StaticContentProvider.fromString(this._url,Common.resourceTypes.WebSocket,this._dataText);}};Network.ResourceWebSocketFrameNodeTimeComparator=function(a,b){return a._frame.time-b._frame.time;};Network.ResourceWebSocketFrameView._clearFrameOffsetSymbol=Symbol('ClearFrameOffset');;Network.NetworkPanel=class extends UI.Panel{constructor(){super('network');this.registerRequiredCSS('network/networkPanel.css');this._networkLogShowOverviewSetting=Common.settings.createSetting('networkLogShowOverview',true);this._networkLogLargeRowsSetting=Common.settings.createSetting('networkLogLargeRows',false);this._networkRecordFilmStripSetting=Common.settings.createSetting('networkRecordFilmStripSetting',false);this._toggleRecordAction=(UI.actionRegistry.action('network.toggle-recording'));this._pendingStopTimer;this._networkItemView=null;this._filmStripView=null;this._filmStripRecorder=null;this._panelToolbar=new UI.Toolbar('',this.element);this._filterBar=new UI.FilterBar('networkPanel',true);this._filterBar.show(this.element);this.setDefaultFocusedChild(this._filterBar);this._filmStripPlaceholderElement=this.element.createChild('div','network-film-strip-placeholder');this._overviewPane=new PerfUI.TimelineOverviewPane('network');this._overviewPane.addEventListener(PerfUI.TimelineOverviewPane.Events.WindowChanged,this._onWindowChanged.bind(this));this._overviewPane.element.id='network-overview-panel';this._networkOverview=new Network.NetworkOverview();this._overviewPane.setOverviewControls([this._networkOverview]);this._overviewPlaceholderElement=this.element.createChild('div');this._calculator=new Network.NetworkTransferTimeCalculator();this._splitWidget=new UI.SplitWidget(true,false,'networkPanelSplitViewState');this._splitWidget.hideMain();this._splitWidget.show(this.element);this._progressBarContainer=createElement('div');this._searchableView=new UI.SearchableView(this);this._searchableView.setPlaceholder(Common.UIString('Find by filename or path'));this._networkLogView=new Network.NetworkLogView(this._filterBar,this._progressBarContainer,this._networkLogLargeRowsSetting);this._networkLogView.show(this._searchableView.element);this._splitWidget.setSidebarWidget(this._searchableView);this._detailsWidget=new UI.VBox();this._detailsWidget.element.classList.add('network-details-view');this._splitWidget.setMainWidget(this._detailsWidget);this._closeButtonElement=createElement('div','dt-close-button');this._closeButtonElement.addEventListener('click',this._showRequest.bind(this,null),false);this._networkLogShowOverviewSetting.addChangeListener(this._toggleShowOverview,this);this._networkLogLargeRowsSetting.addChangeListener(this._toggleLargerRequests,this);this._networkRecordFilmStripSetting.addChangeListener(this._toggleRecordFilmStrip,this);this._preserveLogSetting=Common.moduleSetting('network_log.preserve-log');this._offlineCheckbox=MobileThrottling.throttlingManager().createOfflineToolbarCheckbox();this._throttlingSelect=this._createThrottlingConditionsSelect();this._setupToolbarButtons();this._toggleRecord(true);this._toggleShowOverview();this._toggleLargerRequests();this._toggleRecordFilmStrip();this._updateUI();SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.WillReloadPage,this._willReloadPage,this);SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.Load,this._load,this);this._networkLogView.addEventListener(Network.NetworkLogView.Events.RequestSelected,this._onRequestSelected,this);this._networkLogView.addEventListener(Network.NetworkLogView.Events.SearchCountUpdated,this._onSearchCountUpdated,this);this._networkLogView.addEventListener(Network.NetworkLogView.Events.SearchIndexUpdated,this._onSearchIndexUpdated,this);NetworkLog.networkLog.addEventListener(NetworkLog.NetworkLog.Events.RequestAdded,this._onUpdateRequest,this);NetworkLog.networkLog.addEventListener(NetworkLog.NetworkLog.Events.RequestUpdated,this._onUpdateRequest,this);NetworkLog.networkLog.addEventListener(NetworkLog.NetworkLog.Events.Reset,this._onNetworkLogReset,this);} -static revealAndFilter(filters){var panel=Network.NetworkPanel._instance();var filterString='';for(var filter of filters) -filterString+=`${filter.filterType}:${filter.filterValue} `;panel._networkLogView.setTextFilterValue(filterString);UI.viewManager.showView('network');} -static _instance(){return(self.runtime.sharedInstance(Network.NetworkPanel));} -offlineCheckboxForTest(){return this._offlineCheckbox;} -throttlingSelectForTest(){return this._throttlingSelect;} -_onWindowChanged(event){var startTime=Math.max(this._calculator.minimumBoundary(),event.data.startTime/1000);var endTime=Math.min(this._calculator.maximumBoundary(),event.data.endTime/1000);this._networkLogView.setWindow(startTime,endTime);} -_setupToolbarButtons(){this._panelToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._toggleRecordAction));var clearButton=new UI.ToolbarButton(Common.UIString('Clear'),'largeicon-clear');clearButton.addEventListener(UI.ToolbarButton.Events.Click,()=>NetworkLog.networkLog.reset(),this);this._panelToolbar.appendToolbarItem(clearButton);this._panelToolbar.appendSeparator();var recordFilmStripButton=new UI.ToolbarSettingToggle(this._networkRecordFilmStripSetting,'largeicon-camera',Common.UIString('Capture screenshots'));this._panelToolbar.appendToolbarItem(recordFilmStripButton);this._panelToolbar.appendToolbarItem(this._filterBar.filterButton());this._panelToolbar.appendSeparator();this._panelToolbar.appendText(Common.UIString('View:'));var largerRequestsButton=new UI.ToolbarSettingToggle(this._networkLogLargeRowsSetting,'largeicon-large-list',Common.UIString('Use large request rows'),Common.UIString('Use small request rows'));this._panelToolbar.appendToolbarItem(largerRequestsButton);var showOverviewButton=new UI.ToolbarSettingToggle(this._networkLogShowOverviewSetting,'largeicon-waterfall',Common.UIString('Show overview'),Common.UIString('Hide overview'));this._panelToolbar.appendToolbarItem(showOverviewButton);if(Runtime.experiments.isEnabled('networkGroupingRequests')){this._panelToolbar.appendToolbarItem(new UI.ToolbarSettingCheckbox(Common.moduleSetting('network.group-by-frame'),'',Common.UIString('Group by frame')));} -this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(new UI.ToolbarSettingCheckbox(this._preserveLogSetting,Common.UIString('Do not clear log on page reload / navigation'),Common.UIString('Preserve log')));var disableCacheCheckbox=new UI.ToolbarSettingCheckbox(Common.moduleSetting('cacheDisabled'),Common.UIString('Disable cache (while DevTools is open)'),Common.UIString('Disable cache'));this._panelToolbar.appendToolbarItem(disableCacheCheckbox);this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(this._offlineCheckbox);this._panelToolbar.appendToolbarItem(this._throttlingSelect);this._panelToolbar.appendToolbarItem(new UI.ToolbarItem(this._progressBarContainer));} -_createThrottlingConditionsSelect(){var toolbarItem=new UI.ToolbarComboBox(null);toolbarItem.setMaxWidth(160);MobileThrottling.throttlingManager().decorateSelectWithNetworkThrottling(toolbarItem.selectElement());return toolbarItem;} -_toggleRecording(){if(!this._preserveLogSetting.get()&&!this._toggleRecordAction.toggled()) -NetworkLog.networkLog.reset();this._toggleRecord(!this._toggleRecordAction.toggled());} -_toggleRecord(toggled){this._toggleRecordAction.setToggled(toggled);this._networkLogView.setRecording(toggled);if(!toggled&&this._filmStripRecorder) -this._filmStripRecorder.stopRecording(this._filmStripAvailable.bind(this));NetworkLog.networkLog.setIsRecording(toggled);} -_filmStripAvailable(filmStripModel){if(!filmStripModel) -return;var calculator=this._networkLogView.timeCalculator();this._filmStripView.setModel(filmStripModel,calculator.minimumBoundary()*1000,calculator.boundarySpan()*1000);this._networkOverview.setFilmStripModel(filmStripModel);var timestamps=filmStripModel.frames().map(mapTimestamp);function mapTimestamp(frame){return frame.timestamp/1000;} -this._networkLogView.addFilmStripFrames(timestamps);} -_onNetworkLogReset(){Network.BlockedURLsPane.reset();if(!this._preserveLogSetting.get()){this._calculator.reset();this._overviewPane.reset();} -if(this._filmStripView) -this._resetFilmStripView();} -_willReloadPage(event){this._toggleRecord(true);if(this._pendingStopTimer){clearTimeout(this._pendingStopTimer);delete this._pendingStopTimer;} -if(this.isShowing()&&this._filmStripRecorder) -this._filmStripRecorder.startRecording();} -_load(event){if(this._filmStripRecorder&&this._filmStripRecorder.isRecording()){this._pendingStopTimer=setTimeout(this._stopFilmStripRecording.bind(this),Network.NetworkPanel.displayScreenshotDelay);}} -_stopFilmStripRecording(){this._filmStripRecorder.stopRecording(this._filmStripAvailable.bind(this));delete this._pendingStopTimer;} -_toggleLargerRequests(){this._updateUI();} -_toggleShowOverview(){var toggled=this._networkLogShowOverviewSetting.get();if(toggled) -this._overviewPane.show(this._overviewPlaceholderElement);else -this._overviewPane.detach();this.doResize();} -_toggleRecordFilmStrip(){var toggled=this._networkRecordFilmStripSetting.get();if(toggled&&!this._filmStripRecorder){this._filmStripView=new PerfUI.FilmStripView();this._filmStripView.setMode(PerfUI.FilmStripView.Modes.FrameBased);this._filmStripView.element.classList.add('network-film-strip');this._filmStripRecorder=new Network.NetworkPanel.FilmStripRecorder(this._networkLogView.timeCalculator(),this._filmStripView);this._filmStripView.show(this._filmStripPlaceholderElement);this._filmStripView.addEventListener(PerfUI.FilmStripView.Events.FrameSelected,this._onFilmFrameSelected,this);this._filmStripView.addEventListener(PerfUI.FilmStripView.Events.FrameEnter,this._onFilmFrameEnter,this);this._filmStripView.addEventListener(PerfUI.FilmStripView.Events.FrameExit,this._onFilmFrameExit,this);this._resetFilmStripView();} -if(!toggled&&this._filmStripRecorder){this._filmStripView.detach();this._filmStripView=null;this._filmStripRecorder=null;}} -_resetFilmStripView(){this._filmStripView.reset();this._filmStripView.setStatusText(Common.UIString('Hit %s to reload and capture filmstrip.',UI.shortcutRegistry.shortcutDescriptorsForAction('main.reload')[0].name));} -elementsToRestoreScrollPositionsFor(){return this._networkLogView.elementsToRestoreScrollPositionsFor();} -searchableView(){return this._searchableView;} -handleShortcut(event){if(this._networkItemView&&event.keyCode===UI.KeyboardShortcut.Keys.Esc.code){this._showRequest(null);event.handled=true;return;} -super.handleShortcut(event);} -wasShown(){UI.context.setFlavor(Network.NetworkPanel,this);} -willHide(){UI.context.setFlavor(Network.NetworkPanel,null);} -revealAndHighlightRequest(request){this._showRequest(null);if(request) -this._networkLogView.revealAndHighlightRequest(request);} -_onRowSizeChanged(event){this._updateUI();} -_onSearchCountUpdated(event){var count=(event.data);this._searchableView.updateSearchMatchesCount(count);} -_onSearchIndexUpdated(event){var index=(event.data);this._searchableView.updateCurrentMatchIndex(index);} -_onRequestSelected(event){var request=(event.data);this._showRequest(request);} -_showRequest(request){if(this._networkItemView){this._networkItemView.detach();this._networkItemView=null;} -if(request){this._networkItemView=new Network.NetworkItemView(request,this._networkLogView.timeCalculator());this._networkItemView.leftToolbar().appendToolbarItem(new UI.ToolbarItem(this._closeButtonElement));this._networkItemView.show(this._detailsWidget.element);this._splitWidget.showBoth();}else{this._splitWidget.hideMain();this._networkLogView.clearSelection();} -this._updateUI();} -_updateUI(){this._detailsWidget.element.classList.toggle('network-details-view-tall-header',this._networkLogLargeRowsSetting.get());this._networkLogView.switchViewMode(!this._splitWidget.isResizable());} -performSearch(searchConfig,shouldJump,jumpBackwards){this._networkLogView.performSearch(searchConfig,shouldJump,jumpBackwards);} -jumpToPreviousSearchResult(){this._networkLogView.jumpToPreviousSearchResult();} -supportsCaseSensitiveSearch(){return false;} -supportsRegexSearch(){return false;} -jumpToNextSearchResult(){this._networkLogView.jumpToNextSearchResult();} -searchCanceled(){this._networkLogView.searchCanceled();} -appendApplicableItems(event,contextMenu,target){function reveal(request){UI.viewManager.showView('network').then(this.revealAndHighlightRequest.bind(this,request));} -function appendRevealItem(request){contextMenu.revealSection().appendItem(Common.UIString('Reveal in Network panel'),reveal.bind(this,request));} -if(event.target.isSelfOrDescendant(this.element)) -return;if(target instanceof SDK.Resource){var resource=(target);if(resource.request) -appendRevealItem.call(this,resource.request);return;} -if(target instanceof Workspace.UISourceCode){var uiSourceCode=(target);var resource=Bindings.resourceForURL(uiSourceCode.url());if(resource&&resource.request) -appendRevealItem.call(this,resource.request);return;} -if(!(target instanceof SDK.NetworkRequest)) -return;var request=(target);if(this._networkItemView&&this._networkItemView.isShowing()&&this._networkItemView.request()===request) -return;appendRevealItem.call(this,request);} -_onFilmFrameSelected(event){var timestamp=(event.data);this._overviewPane.requestWindowTimes(0,timestamp);} -_onFilmFrameEnter(event){var timestamp=(event.data);this._networkOverview.selectFilmStripFrame(timestamp);this._networkLogView.selectFilmStripFrame(timestamp/1000);} -_onFilmFrameExit(event){this._networkOverview.clearFilmStripFrame();this._networkLogView.clearFilmStripFrame();} -_onUpdateRequest(event){var request=(event.data);this._calculator.updateBoundaries(request);this._overviewPane.setBounds(this._calculator.minimumBoundary()*1000,this._calculator.maximumBoundary()*1000);this._networkOverview.updateRequest(request);this._overviewPane.scheduleUpdate();}};Network.NetworkPanel.displayScreenshotDelay=1000;Network.NetworkPanel.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){Network.NetworkPanel._instance().appendApplicableItems(event,contextMenu,target);}};Network.NetworkPanel.RequestRevealer=class{reveal(request){if(!(request instanceof SDK.NetworkRequest)) -return Promise.reject(new Error('Internal error: not a network request'));var panel=Network.NetworkPanel._instance();return UI.viewManager.showView('network').then(panel.revealAndHighlightRequest.bind(panel,request));}};Network.NetworkPanel.FilmStripRecorder=class{constructor(timeCalculator,filmStripView){this._tracingManager=null;this._resourceTreeModel=null;this._timeCalculator=timeCalculator;this._filmStripView=filmStripView;this._tracingModel=null;this._callback=null;} -traceEventsCollected(events){if(this._tracingModel) -this._tracingModel.addEvents(events);} -tracingComplete(){if(!this._tracingModel||!this._tracingManager) -return;this._tracingModel.tracingComplete();this._tracingManager=null;this._callback(new SDK.FilmStripModel(this._tracingModel,this._timeCalculator.minimumBoundary()*1000));this._callback=null;if(this._resourceTreeModel) -this._resourceTreeModel.resumeReload();this._resourceTreeModel=null;} -tracingBufferUsage(){} -eventsRetrievalProgress(progress){} -startRecording(){this._filmStripView.reset();this._filmStripView.setStatusText(Common.UIString('Recording frames...'));var tracingManagers=SDK.targetManager.models(SDK.TracingManager);if(this._tracingManager||!tracingManagers.length) -return;this._tracingManager=tracingManagers[0];this._resourceTreeModel=this._tracingManager.target().model(SDK.ResourceTreeModel);if(this._tracingModel) -this._tracingModel.dispose();this._tracingModel=new SDK.TracingModel(new Bindings.TempFileBackingStorage());this._tracingManager.start(this,'-*,disabled-by-default-devtools.screenshot','');} -isRecording(){return!!this._tracingManager;} -stopRecording(callback){if(!this._tracingManager) -return;this._tracingManager.stop();if(this._resourceTreeModel) -this._resourceTreeModel.suspendReload();this._callback=callback;this._filmStripView.setStatusText(Common.UIString('Fetching frames...'));}};Network.NetworkPanel.RecordActionDelegate=class{handleAction(context,actionId){var panel=UI.context.flavor(Network.NetworkPanel);console.assert(panel&&panel instanceof Network.NetworkPanel);panel._toggleRecording();return true;}};;Runtime.cachedResources["network/blockedURLsPane.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.list {\n border: none !important;\n border-top: 1px solid #dadada !important;\n}\n\n.blocking-disabled {\n pointer-events: none;\n opacity: 0.8;\n}\n\n.editor-container {\n padding: 0 4px;\n}\n\n.no-blocked-urls, .blocked-urls {\n overflow-x: hidden;\n overflow-y: auto;\n}\n\n.no-blocked-urls {\n display: flex;\n justify-content: center;\n padding: 10px;\n}\n\n.no-blocked-urls > span {\n white-space: pre;\n}\n\n.blocked-url {\n display: flex;\n flex-direction: row;\n align-items: center;\n flex: auto;\n}\n\n.blocked-url-count {\n flex: none;\n padding-right: 9px;\n}\n\n.blocked-url-checkbox {\n margin-left: 8px;\n flex: none;\n}\n\n.blocked-url-label {\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n flex: auto;\n padding: 0 3px;\n}\n\n.blocked-url-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 7px 5px 0 5px;\n align-items: center;\n}\n\n.blocked-url-edit-value {\n -webkit-user-select: none;\n flex: 1 1 0px;\n}\n\n.blocked-url-edit-row input {\n width: 100%;\n text-align: inherit;\n height: 22px;\n}\n\n/*# sourceURL=network/blockedURLsPane.css */";Runtime.cachedResources["network/eventSourceMessagesView.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.event-source-messages-view .data-grid {\n flex: auto;\n border: none;\n}\n\n/*# sourceURL=network/eventSourceMessagesView.css */";Runtime.cachedResources["network/networkConfigView.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.network-config {\n padding: 12px;\n display: block;\n}\n\n.network-config-group {\n display: flex;\n margin-bottom: 10px;\n flex-wrap: wrap;\n flex: 0 0 auto;\n min-height: 30px;\n}\n\n.network-config-title {\n margin-right: 16px;\n width: 130px;\n}\n\n.network-config-fields {\n flex: 2 0 200px;\n}\n\n.panel-section-separator {\n height: 1px;\n margin-bottom: 10px;\n background: #f0f0f0;\n}\n\n/* Disable cache */\n\n.network-config-disable-cache {\n line-height: 28px;\n border-top: none;\n padding-top: 0;\n}\n\n/* Network throttling */\n\n.network-config-throttling .chrome-select {\n width: 100%;\n max-width: 250px;\n}\n\n.network-config-throttling > .network-config-title {\n line-height: 24px;\n}\n\n/* User agent */\n\n.network-config-ua > .network-config-title {\n line-height: 20px;\n}\n\n.network-config-ua label[is=\"dt-radio\"].checked > * {\n display: none\n}\n\n.network-config-ua input:not(.dt-radio-button) {\n display: block;\n width: calc(100% - 20px);\n max-width: 250px;\n}\n\n.network-config-ua input[readonly] {\n background-color: rgb(235, 235, 228);\n}\n\n.network-config-ua input[type=text], .network-config-ua .chrome-select {\n margin-top: 8px;\n}\n\n.network-config-ua .chrome-select {\n width: calc(100% - 20px);\n max-width: 250px;\n}\n\n.network-config-ua label[is=\"dt-radio\"] {\n display: block;\n}\n\n.network-config-ua-auto, .network-config-ua-custom {\n opacity: 0.5;\n}\n\n.network-config-ua-auto.checked, .network-config-ua-custom.checked {\n opacity: 1;\n}\n\n/*# sourceURL=network/networkConfigView.css */";Runtime.cachedResources["network/networkLogView.css"]="/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.network-log-grid.data-grid {\n border: none;\n flex: auto;\n}\n\n.network-summary-bar {\n flex: 0 0 27px;\n line-height: 27px;\n padding-left: 5px;\n background-color: #eee;\n border-top: 1px solid #ccc;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.network-summary-bar label[is=dt-icon-label] {\n margin-right: 6px;\n}\n\n.network-summary-bar > * {\n flex: none;\n}\n\n.network-log-grid.data-grid table.data {\n background: transparent;\n}\n\n.network-log-grid.data-grid td {\n height: 41px;\n border-left: 1px solid #e1e1e1;\n vertical-align: middle;\n}\n\n.network-log-grid.data-grid .corner {\n display: none;\n}\n\n.network-log-grid.data-grid.small td {\n height: 21px;\n}\n\n.network-waterfall-header, .network-log-grid.data-grid th {\n border-bottom: 1px solid rgb(205, 205, 205);\n border-left: 1px solid rgb(205, 205, 205);\n}\n\n.network-log-grid.data-grid th {\n background: white;\n}\n\n.network-waterfall-header, .network-log-grid.data-grid .header-container {\n height: 31px;\n}\n\n.network-log-grid.data-grid .data-container {\n top: 31px;\n}\n\n.network-waterfall-header.small, .network-log-grid.data-grid.small .header-container {\n height: 27px;\n}\n\n.network-log-grid.data-grid.small .data-container {\n top: 27px;\n}\n\n.network-log-grid.data-grid select {\n -webkit-appearance: none;\n border: none;\n width: 100%;\n color: inherit;\n}\n\n.network-log-grid.data-grid .name-column {\n cursor: pointer;\n}\n\n.network-log-grid.data-grid .waterfall-column {\n padding: 1px 0;\n}\n\n.network-log-grid.data-grid .waterfall-column .sort-order-icon-container {\n right: 15px;\n pointer-events: none;\n}\n\n.network-log-grid.data-grid th.sortable:active {\n background-image: none !important;\n}\n\n.network-cell-subtitle {\n font-weight: normal;\n color: gray;\n}\n\n.network-badge {\n margin-right: 4px;\n}\n\n.network-error-row,\n.network-error-row .network-cell-subtitle {\n color: rgb(230, 0, 0);\n}\n\n.initiator-column .devtools-link {\n color: inherit;\n}\n\n.network-log-grid.data-grid tr.selected,\n.network-log-grid.data-grid tr.selected .network-cell-subtitle,\n.network-log-grid.data-grid tr.selected .network-dim-cell {\n color: inherit !important;\n}\n\n.network-log-grid.data-grid:focus tr.selected,\n.network-log-grid.data-grid:focus tr.selected .network-cell-subtitle,\n.network-log-grid.data-grid:focus tr.selected .network-dim-cell {\n color: white !important;\n}\n\n.network-log-grid tr.highlighted-row {\n -webkit-animation: network-row-highlight-fadeout 2s 0s;\n}\n\n@-webkit-keyframes network-row-highlight-fadeout {\n from {background-color: rgba(255, 255, 120, 1); }\n to { background-color: rgba(255, 255, 120, 0); }\n}\n\n.network-header-subtitle {\n color: gray;\n}\n\n.network-log-grid.data-grid.small .network-cell-subtitle,\n.network-log-grid.data-grid.small .network-header-subtitle {\n display: none;\n}\n\n/* Resource preview icons */\n\n.network-log-grid.data-grid .icon {\n content: url(Images/resourcePlainIcon.png);\n}\n\n.network-log-grid.data-grid.small .icon {\n content: url(Images/resourcePlainIconSmall.png);\n}\n\n.network-log-grid.data-grid .icon.script {\n content: url(Images/resourceJSIcon.png);\n}\n\n.network-log-grid.data-grid.small .icon.script {\n content: url(Images/resourceDocumentIconSmall.png);\n}\n\n.network-log-grid.data-grid .icon.document {\n content: url(Images/resourceDocumentIcon.png);\n}\n\n.network-log-grid.data-grid.small .icon.document {\n content: url(Images/resourceDocumentIconSmall.png);\n}\n\n.network-log-grid.data-grid .icon.stylesheet {\n content: url(Images/resourceCSSIcon.png);\n}\n\n.network-log-grid.data-grid.small .icon.stylesheet {\n content: url(Images/resourceDocumentIconSmall.png);\n}\n\n.network-log-grid.data-grid .icon.media {\n content: url(Images/resourcePlainIcon.png); /* FIXME: media icon */\n}\n\n.network-log-grid.data-grid.small .icon.media {\n content: url(Images/resourcePlainIconSmall.png); /* FIXME: media icon */\n}\n.network-log-grid.data-grid .icon.texttrack {\n content: url(Images/resourcePlainIcon.png); /* FIXME: vtt icon */\n}\n\n.network-log-grid.data-grid.small .icon.texttrack {\n content: url(Images/resourcePlainIconSmall.png); /* FIXME: vtt icon */\n}\n\n.network-log-grid.data-grid .icon.image {\n position: relative;\n background-image: url(Images/resourcePlainIcon.png);\n background-repeat: no-repeat;\n content: \"\";\n}\n\n.network-log-grid.data-grid.small .icon.image {\n background-image: url(Images/resourcePlainIconSmall.png);\n content: \"\";\n}\n\n.network-log-grid.data-grid .icon {\n float: left;\n width: 32px;\n height: 32px;\n margin-top: 1px;\n margin-right: 3px;\n}\n\n.network-log-grid.data-grid.small .icon {\n width: 16px;\n height: 16px;\n}\n\n.network-log-grid.data-grid .image-network-icon-preview {\n position: absolute;\n margin: auto;\n top: 3px;\n bottom: 4px;\n left: 5px;\n right: 5px;\n max-width: 18px;\n max-height: 21px;\n min-width: 1px;\n min-height: 1px;\n}\n\n.network-log-grid.data-grid.small .image-network-icon-preview {\n top: 2px;\n bottom: 1px;\n left: 3px;\n right: 3px;\n max-width: 8px;\n max-height: 11px;\n}\n\n.network-dim-cell {\n color: grey;\n}\n\n.network-summary-bar .summary-red {\n color: red;\n}\n\n.network-frame-divider {\n width: 2px;\n background-color: #FCCC49;\n z-index: 10;\n visibility: hidden;\n}\n\n#network-container:not(.brief-mode) .data-container {\n overflow: hidden;\n}\n\n.network-summary-bar .summary-blue {\n color: blue;\n}\n\n.-theme-with-dark-background .network-summary-bar .summary-blue {\n color: #03A9F4;\n}\n\n.network-log-grid.data-grid .resources-dividers {\n z-index: 0;\n}\n\n.network-log-grid.data-grid .resources-dividers-label-bar {\n background-color: transparent;\n border: none;\n height: 30px;\n pointer-events: none;\n}\n\n#network-container {\n overflow: hidden;\n}\n\n.network-status-pane {\n color: #777;\n background-color: white;\n z-index: 500;\n display: flex;\n justify-content: center;\n align-items: center;\n text-align: center;\n padding: 0 20px;\n overflow: auto;\n}\n\n.network-status-pane > .recording-hint {\n font-size: 14px;\n text-align: center;\n line-height: 28px;\n}\n\n.network-waterfall-header {\n position: absolute;\n border-left: 0px;\n width: 100%;\n display: table;\n z-index: 200;\n}\n\n.network-waterfall-header:hover {\n background-color: hsla(0, 0%, 10%, 0.1);\n}\n\n.network-waterfall-header div {\n display: table-cell;\n line-height: 14px;\n margin: auto 0px;\n vertical-align: middle;\n text-align: left;\n font-weight: normal;\n padding: 0px 4px;\n}\n\n.network-waterfall-header .sort-order-icon-container {\n position: absolute;\n top: 1px;\n right: 0;\n bottom: 1px;\n display: flex;\n align-items: center;\n}\n\n.network-waterfall-header .sort-order-icon {\n align-items: center;\n margin-right: 4px;\n margin-bottom: -2px;\n}\n\n.network-frame-group-icon {\n display: inline-block;\n margin: -8px -2px;\n}\n\n.network-frame-group-badge {\n margin-right: 4px;\n}\n\n/*# sourceURL=network/networkLogView.css */";Runtime.cachedResources["network/networkManageCustomHeadersView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n.custom-headers-list {\n height: 272px;\n width: 250px;\n}\n\n.custom-headers-wrapper{\n margin: 10px;\n}\n\n.header {\n padding: 0 0 6px;\n font-size: 18px;\n font-weight: normal;\n flex: none;\n}\n\n.custom-headers-header {\n padding:2px;\n}\n\n.custom-headers-list-item {\n padding-left: 5px;\n}\n\n.editor-container {\n padding: 5px 0px 0px 5px;\n}\n\n.add-button {\n width: 150px;\n margin: auto;\n margin-top: 5px;\n}\n\n/*# sourceURL=network/networkManageCustomHeadersView.css */";Runtime.cachedResources["network/networkPanel.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.panel.network > .toolbar {\n position: relative;\n border-bottom: 1px solid #dadada;\n}\n\n.network-details-view {\n background: rgb(203, 203, 203);\n}\n\n.network-details-view-tall-header {\n margin-top: 4px;\n}\n\n.network-item-view {\n display: flex;\n background: white;\n}\n\n.network-item-preview-toolbar {\n border-top: 1px solid #ccc;\n background-color: #eee;\n}\n\n.resource-timing-view {\n display: block;\n margin: 6px;\n color: rgb(30%, 30%, 30%);\n}\n\n.resource-timing-table {\n width: 100% !important;\n}\n\n#network-overview-panel {\n flex: none;\n position: relative;\n}\n\n#network-overview-container {\n overflow: hidden;\n flex: auto;\n display: flex;\n flex-direction: column;\n position: relative;\n border-bottom: 1px solid #CDCDCD;\n}\n\n#network-overview-container canvas {\n width: 100%;\n height: 100%;\n}\n\n#network-overview-grid .resources-dividers-label-bar {\n pointer-events: auto;\n}\n\n.network .network-overview {\n flex: 0 0 60px;\n}\n\n.network-overview .overview-grid-window,\n.network-overview .overview-grid-dividers-background {\n height: 100%;\n}\n\n.network-overview .resources-dividers-label-bar {\n background-color: rgba(255, 255, 255, 0.95);\n}\n\n.network-overview .resources-dividers-label-bar .resources-divider {\n background-color: transparent;\n}\n\n.network-overview .resources-dividers {\n z-index: 250;\n}\n\n.request-view.html iframe {\n width: 100%;\n height: 100%;\n position: absolute;\n}\n\n.network-film-strip {\n border-bottom: solid 1px #cdcdcd;\n flex: none !important;\n}\n\n.network-film-strip-placeholder {\n flex-shrink: 0;\n}\n\n.network-blocked-urls {\n border-top: 1px solid #dadada;\n flex: 104px 0 0;\n}\n\n/*# sourceURL=network/networkPanel.css */";Runtime.cachedResources["network/networkTimingTable.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.network-timing-table {\n width: 380px;\n border-spacing: 0;\n padding-left: 10px;\n padding-right: 10px;\n line-height: initial;\n}\n\n.network-timing-start {\n border-top: 5px solid transparent;\n}\n.network-timing-table-header td, .network-timing-footer td {\n border-top: 10px solid transparent;\n}\n\n.network-timing-table-header td {\n color: #bbb;\n}\n\n.network-timing-table-header td:last-child {\n text-align: right;\n}\n\n.network-timing-table col.labels {\n width: 156px;\n}\n\n.network-timing-table col.duration {\n width: 80px;\n}\n\n.network-timing-table td {\n padding: 2px 0;\n}\n\n.network-timing-table td.caution {\n font-weight: bold;\n color: rgb(255, 128, 0);\n padding: 2px 0;\n}\n\n.network-timing-table hr.break {\n border: 0;\n height: 1px;\n background-image: linear-gradient(to right, #eee, #bbb, #eee);\n}\n\n.network-timing-footer td:last-child {\n font-weight: bold;\n text-align: right;\n}\n\n.network-timing-row {\n position: relative;\n height: 15px;\n}\n\n.network-timing-bar {\n position: absolute;\n min-width: 1px;\n top: 0;\n bottom: 0;\n}\n\n.network-timing-bar-title {\n color: #222;\n white-space: nowrap;\n text-align: right;\n}\n\n.network-timing-bar.queueing,\n.network-timing-bar.total {\n border: 1px solid rgba(0, 0, 0, 0.1);\n}\n\n.network-timing-bar.blocking, -theme-preserve {\n background-color: #AAAAAA;\n}\n\n.network-timing-bar.proxy, -theme-preserve {\n background-color: #A1887F;\n}\n\n.network-timing-bar.dns, -theme-preserve {\n background-color: #009688;\n}\n\n.network-timing-bar.connecting,\n.network-timing-bar.serviceworker,\n.network-timing-bar.serviceworker-preparation, -theme-preserve {\n background-color: #FF9800;\n}\n\n.network-timing-bar.ssl, -theme-preserve {\n background-color: #9C27B0;\n}\n\n.network-timing-bar.sending, -theme-preserve {\n background-color: #B0BEC5;\n}\n\n.network-timing-bar.waiting, -theme-preserve {\n background-color: #00C853;\n}\n\n.network-timing-bar.receiving, -theme-preserve,\n.network-timing-bar.receiving-push, -theme-preserve {\n background-color: #03A9F4;\n}\n\n.network-timing-bar.push, -theme-preserve {\n background-color: #8CDBff;\n}\n\n.network-timing-bar.server-timing, -theme-preserve {\n background-color: #ddd;\n}\n\n.network-timing-table td.network-timing-metric {\n white-space: nowrap;\n max-width: 150px;\n overflow-x: hidden;\n text-overflow: ellipsis;\n}\n\n.network-timing-bar.proxy,\n.network-timing-bar.dns,\n.network-timing-bar.ssl,\n.network-timing-bar.connecting,\n.network-timing-bar.blocking {\n height: 10px;\n margin: auto;\n}\n\n/*# sourceURL=network/networkTimingTable.css */";Runtime.cachedResources["network/networkWaterfallColumn.css"]="/* Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n.network-waterfall-v-scroll {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n overflow-x: hidden;\n margin-top: 31px;\n z-index: 200;\n}\n\n.network-waterfall-v-scroll.small {\n margin-top: 27px;\n}\n\n.network-waterfall-v-scroll-content {\n width: 15px;\n pointer-events: none;\n}\n\n/*# sourceURL=network/networkWaterfallColumn.css */";Runtime.cachedResources["network/requestCookiesView.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.request-cookies-view {\n display: flex;\n overflow: auto;\n margin: 12px;\n height: 100%;\n}\n\n.request-cookies-view .data-grid {\n flex: auto;\n height: 100%;\n}\n\n.request-cookies-view .data-grid .row-group {\n font-weight: bold;\n}\n\n/*# sourceURL=network/requestCookiesView.css */";Runtime.cachedResources["network/requestHeadersTree.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tree-outline > ol {\n padding-bottom: 5px;\n}\n\n.tree-outline > .parent {\n -webkit-user-select: none;\n font-weight: bold;\n color: #616161;\n margin-top: -1px;\n height: 20px;\n border-top: solid 1px #e0e0e0;\n display: flex;\n align-items: center;\n}\n\n.tree-outline li {\n display: block;\n}\n\n.tree-outline li:not(.parent) {\n margin-left: 10px;\n}\n\n.tree-outline li:not(.parent)::before {\n display: none;\n}\n\n.tree-outline .caution {\n margin-left: 4px;\n display: inline-block;\n font-weight: bold;\n}\n\n.tree-outline li.expanded .header-count {\n display: none;\n}\n\n.tree-outline li .header-toggle {\n display: none;\n}\n\n.tree-outline li .status-from-cache {\n color: gray;\n}\n\n.tree-outline li.expanded .header-toggle {\n display: inline;\n margin-left: 30px;\n font-weight: normal;\n color: rgb(45%, 45%, 45%);\n}\n\n.tree-outline li .header-toggle:hover {\n color: rgb(20%, 20%, 45%);\n cursor: pointer;\n}\n\n.tree-outline .header-name {\n color: rgb(33%, 33%, 33%);\n display: inline-block;\n margin-right: 0.5em;\n font-weight: bold;\n vertical-align: top;\n white-space: pre-wrap;\n}\n\n.tree-outline .header-value {\n display: inline;\n margin-right: 1em;\n white-space: pre-wrap;\n word-break: break-all;\n margin-top: 1px;\n}\n\n.tree-outline .empty-request-header {\n color: rgba(33%, 33%, 33%, 0.5);\n}\n\n/*# sourceURL=network/requestHeadersTree.css */";Runtime.cachedResources["network/requestHeadersView.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.request-headers-view {\n -webkit-user-select: text;\n overflow: auto;\n}\n\n.resource-status-image {\n margin-top: -2px;\n margin-right: 3px;\n}\n\n.request-headers-view .filter-input {\n outline: none !important;\n border: none;\n border-bottom: solid 1px #ccc;\n flex: 0 0 19px;\n padding: 0 4px;\n}\n\n.request-headers-tree {\n padding: 0 0 0 4px;\n flex-grow: 1;\n overflow-y: auto;\n margin: 0;\n}\n\n.header-decode-error {\n color: red;\n}\n\n.-theme-with-dark-background .header-decode-error {\n color: hsl(0, 100%, 65%);\n}\n\n/*# sourceURL=network/requestHeadersView.css */";Runtime.cachedResources["network/webSocketFrameView.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.websocket-frame-view {\n -webkit-user-select: text;\n}\n\n.websocket-frame-view .data-grid {\n flex: auto;\n border: none;\n}\n\n.websocket-frame-view .data-grid .data {\n background-image: none;\n}\n\n.websocket-frame-view-td {\n border-bottom: 1px solid #ccc;\n}\n\n.websocket-frame-view .data-grid tr.selected {\n background-color: #def;\n}\n\n.websocket-frame-view .data-grid td,\n.websocket-frame-view .data-grid th {\n border-left-color: #ccc;\n}\n\n.websocket-frame-view-row-send td:first-child::before {\n content: \"\\2B06 \";\n color: #080;\n}\n\n.websocket-frame-view-row-receive td:first-child::before {\n content: \"\\2B07 \";\n color: #E65100;\n}\n\n.data-grid:focus .websocket-frame-view-row-send.selected td:first-child::before,\n.data-grid:focus .websocket-frame-view-row-receive.selected td:first-child::before {\n color: white;\n}\n\n.websocket-frame-view-row-send {\n background-color: rgb(226, 247, 218);\n}\n\n.websocket-frame-view-row-opcode {\n background-color: rgb(255, 255, 232);\n color: rgb(170, 111, 71);\n}\n\n.websocket-frame-view-row-error {\n background-color: rgb(255, 237, 237);\n color: rgb(182, 0, 0);\n}\n\n.websocket-frame-view .toolbar {\n border-bottom: 1px solid #dadada;\n}\n\n/*# sourceURL=network/webSocketFrameView.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/network_priorities/network_priorities_module.js b/src/cobalt/debug/content/devtools/network_priorities/network_priorities_module.js deleted file mode 100644 index 8c0c264..0000000 --- a/src/cobalt/debug/content/devtools/network_priorities/network_priorities_module.js +++ /dev/null
@@ -1,4 +0,0 @@ -NetworkPriorities.uiLabelForPriority=function(priority){var map=NetworkPriorities.priorityUiLabelMap();return map.get(priority)||'';};NetworkPriorities.uiLabelToPriority=function(priorityLabel){var labelToPriorityMap=NetworkPriorities.uiLabelToPriority._uiLabelToPriorityMap;if(labelToPriorityMap) -return labelToPriorityMap.get(priorityLabel);labelToPriorityMap=new Map();NetworkPriorities.priorityUiLabelMap().forEach((value,key)=>labelToPriorityMap.set(value,key));NetworkPriorities.uiLabelToPriority._uiLabelToPriorityMap=labelToPriorityMap;return labelToPriorityMap.get(priorityLabel)||'';};NetworkPriorities.priorityUiLabelMap=function(){var map=NetworkPriorities.priorityUiLabelMap._priorityUiLabelMap;if(map) -return map;map=new Map();map.set(Protocol.Network.ResourcePriority.VeryLow,Common.UIString('Lowest'));map.set(Protocol.Network.ResourcePriority.Low,Common.UIString('Low'));map.set(Protocol.Network.ResourcePriority.Medium,Common.UIString('Medium'));map.set(Protocol.Network.ResourcePriority.High,Common.UIString('High'));map.set(Protocol.Network.ResourcePriority.VeryHigh,Common.UIString('Highest'));NetworkPriorities.priorityUiLabelMap._priorityUiLabelMap=map;return map;};NetworkPriorities.prioritySymbolToNumericMap=function(){var priorityMap=NetworkPriorities.prioritySymbolToNumericMap._symbolicToNumericPriorityMap;if(priorityMap) -return priorityMap;priorityMap=new Map();priorityMap.set(Protocol.Network.ResourcePriority.VeryLow,1);priorityMap.set(Protocol.Network.ResourcePriority.Low,2);priorityMap.set(Protocol.Network.ResourcePriority.Medium,3);priorityMap.set(Protocol.Network.ResourcePriority.High,4);priorityMap.set(Protocol.Network.ResourcePriority.VeryHigh,5);NetworkPriorities.prioritySymbolToNumericMap._symbolicToNumericPriorityMap=priorityMap;return priorityMap;};; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/object_ui/object_ui_module.js b/src/cobalt/debug/content/devtools/object_ui/object_ui_module.js deleted file mode 100644 index 420475b..0000000 --- a/src/cobalt/debug/content/devtools/object_ui/object_ui_module.js +++ /dev/null
@@ -1,342 +0,0 @@ -ObjectUI.CustomPreviewSection=class{constructor(object){this._sectionElement=createElementWithClass('span','custom-expandable-section');this._object=object;this._expanded=false;this._cachedContent=null;var customPreview=object.customPreview();try{var headerJSON=JSON.parse(customPreview.header);}catch(e){Common.console.error('Broken formatter: header is invalid json '+e);return;} -this._header=this._renderJSONMLTag(headerJSON);if(this._header.nodeType===Node.TEXT_NODE){Common.console.error('Broken formatter: header should be an element node.');return;} -if(customPreview.hasBody){this._header.classList.add('custom-expandable-section-header');this._header.addEventListener('click',this._onClick.bind(this),false);this._expandIcon=UI.Icon.create('smallicon-triangle-right','custom-expand-icon');this._header.insertBefore(this._expandIcon,this._header.firstChild);} -this._sectionElement.appendChild(this._header);} -element(){return this._sectionElement;} -_renderJSONMLTag(jsonML){if(!Array.isArray(jsonML)) -return createTextNode(jsonML+'');var array=(jsonML);return array[0]==='object'?this._layoutObjectTag(array):this._renderElement(array);} -_renderElement(object){var tagName=object.shift();if(!ObjectUI.CustomPreviewSection._tagsWhiteList.has(tagName)){Common.console.error('Broken formatter: element '+tagName+' is not allowed!');return createElement('span');} -var element=createElement((tagName));if((typeof object[0]==='object')&&!Array.isArray(object[0])){var attributes=object.shift();for(var key in attributes){var value=attributes[key];if((key!=='style')||(typeof value!=='string')) -continue;element.setAttribute(key,value);}} -this._appendJsonMLTags(element,object);return element;} -_layoutObjectTag(objectTag){objectTag.shift();var attributes=objectTag.shift();var remoteObject=this._object.runtimeModel().createRemoteObject((attributes));if(remoteObject.customPreview()) -return(new ObjectUI.CustomPreviewSection(remoteObject)).element();var sectionElement=ObjectUI.ObjectPropertiesSection.defaultObjectPresentation(remoteObject);sectionElement.classList.toggle('custom-expandable-section-standard-section',remoteObject.hasChildren);return sectionElement;} -_appendJsonMLTags(parentElement,jsonMLTags){for(var i=0;i<jsonMLTags.length;++i) -parentElement.appendChild(this._renderJSONMLTag(jsonMLTags[i]));} -_onClick(event){event.consume(true);if(this._cachedContent) -this._toggleExpand();else -this._loadBody();} -_toggleExpand(){this._expanded=!this._expanded;this._header.classList.toggle('expanded',this._expanded);this._cachedContent.classList.toggle('hidden',!this._expanded);if(this._expanded) -this._expandIcon.setIconType('smallicon-triangle-down');else -this._expandIcon.setIconType('smallicon-triangle-right');} -_loadBody(){function load(bindRemoteObject,formatter,config){function substituteObjectTagsInCustomPreview(jsonMLObject){if(!jsonMLObject||(typeof jsonMLObject!=='object')||(typeof jsonMLObject.splice!=='function')) -return;var obj=jsonMLObject.length;if(!(typeof obj==='number'&&obj>>>0===obj&&(obj>0||1/obj>0))) -return;var startIndex=1;if(jsonMLObject[0]==='object'){var attributes=jsonMLObject[1];var originObject=attributes['object'];var config=attributes['config'];if(typeof originObject==='undefined') -throw'Illegal format: obligatory attribute "object" isn\'t specified';jsonMLObject[1]=bindRemoteObject(originObject,config);startIndex=2;} -for(var i=startIndex;i<jsonMLObject.length;++i) -substituteObjectTagsInCustomPreview(jsonMLObject[i]);} -try{var body=formatter.body(this,config);substituteObjectTagsInCustomPreview(body);return body;}catch(e){console.error('Custom Formatter Failed: '+e);return null;}} -var customPreview=this._object.customPreview();var args=[{objectId:customPreview.bindRemoteObjectFunctionId},{objectId:customPreview.formatterObjectId}];if(customPreview.configObjectId) -args.push({objectId:customPreview.configObjectId});this._object.callFunctionJSON(load,args,onBodyLoaded.bind(this));function onBodyLoaded(bodyJsonML){if(!bodyJsonML) -return;this._cachedContent=this._renderJSONMLTag(bodyJsonML);this._sectionElement.appendChild(this._cachedContent);this._toggleExpand();}}};ObjectUI.CustomPreviewComponent=class{constructor(object){this._object=object;this._customPreviewSection=new ObjectUI.CustomPreviewSection(object);this.element=createElementWithClass('span','source-code');var shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'object_ui/customPreviewComponent.css');this.element.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),false);shadowRoot.appendChild(this._customPreviewSection.element());} -expandIfPossible(){if(this._object.customPreview().hasBody&&this._customPreviewSection) -this._customPreviewSection._loadBody();} -_contextMenuEventFired(event){var contextMenu=new UI.ContextMenu(event);if(this._customPreviewSection){contextMenu.revealSection().appendItem(Common.UIString('Show as JavaScript object'),this._disassemble.bind(this));} -contextMenu.appendApplicableItems(this._object);contextMenu.show();} -_disassemble(){this.element.shadowRoot.textContent='';this._customPreviewSection=null;this.element.shadowRoot.appendChild(ObjectUI.ObjectPropertiesSection.defaultObjectPresentation(this._object));}};ObjectUI.CustomPreviewSection._tagsWhiteList=new Set(['span','div','ol','li','table','tr','td']);;ObjectUI.ObjectPopoverHelper=class{constructor(linkifier,resultHighlightedAsDOM){this._linkifier=linkifier;this._resultHighlightedAsDOM=resultHighlightedAsDOM;} -dispose(){if(this._resultHighlightedAsDOM) -SDK.OverlayModel.hideDOMNodeHighlight();if(this._linkifier) -this._linkifier.dispose();} -static buildObjectPopover(result,popover){var fulfill;var promise=new Promise(x=>fulfill=x);function didGetFunctionProperties(funcObject,popoverContentElement,popoverValueElement,properties,internalProperties){if(internalProperties){for(var i=0;i<internalProperties.length;i++){if(internalProperties[i].name==='[[TargetFunction]]'){funcObject=internalProperties[i].value;break;}}} -ObjectUI.ObjectPropertiesSection.formatObjectAsFunction(funcObject,popoverValueElement,true);funcObject.debuggerModel().functionDetailsPromise(funcObject).then(didGetFunctionDetails.bind(null,popoverContentElement));} -function didGetFunctionDetails(popoverContentElement,response){if(!response){fulfill(null);return;} -var container=createElementWithClass('div','object-popover-container');var title=container.createChild('div','function-popover-title source-code');var functionName=title.createChild('span','function-name');functionName.textContent=UI.beautifyFunctionName(response.functionName);var rawLocation=response.location;var linkContainer=title.createChild('div','function-title-link-container');var sourceURL=rawLocation&&rawLocation.script()?rawLocation.script().sourceURL:null;var linkifier=null;if(rawLocation&&sourceURL){linkifier=new Components.Linkifier();linkContainer.appendChild(linkifier.linkifyRawLocation(rawLocation,sourceURL));} -container.appendChild(popoverContentElement);popover.contentElement.appendChild(container);fulfill(new ObjectUI.ObjectPopoverHelper(linkifier,false));} -var description=result.description.trimEnd(ObjectUI.ObjectPopoverHelper.MaxPopoverTextLength);var popoverContentElement=null;if(result.type!=='object'){popoverContentElement=createElement('span');UI.appendStyle(popoverContentElement,'object_ui/objectValue.css');UI.appendStyle(popoverContentElement,'object_ui/objectPopover.css');var valueElement=popoverContentElement.createChild('span','monospace object-value-'+result.type);valueElement.style.whiteSpace='pre';if(result.type==='string') -valueElement.createTextChildren('"',description,'"');else if(result.type!=='function') -valueElement.textContent=description;if(result.type==='function'){result.getOwnProperties(false,didGetFunctionProperties.bind(null,result,popoverContentElement,valueElement));return promise;} -popover.contentElement.appendChild(popoverContentElement);fulfill(new ObjectUI.ObjectPopoverHelper(null,false));}else{var linkifier=null;var resultHighlightedAsDOM=false;if(result.subtype==='node'){SDK.OverlayModel.highlightObjectAsDOMNode(result);resultHighlightedAsDOM=true;} -if(result.customPreview()){var customPreviewComponent=new ObjectUI.CustomPreviewComponent(result);customPreviewComponent.expandIfPossible();popoverContentElement=customPreviewComponent.element;}else{popoverContentElement=createElementWithClass('div','object-popover-content');UI.appendStyle(popoverContentElement,'object_ui/objectPopover.css');var titleElement=popoverContentElement.createChild('div','monospace object-popover-title');titleElement.createChild('span').textContent=description;linkifier=new Components.Linkifier();var section=new ObjectUI.ObjectPropertiesSection(result,'',linkifier);section.element.classList.add('object-popover-tree');section.titleLessMode();popoverContentElement.appendChild(section.element);} -popover.setMaxContentSize(new UI.Size(300,250));popover.setSizeBehavior(UI.GlassPane.SizeBehavior.SetExactSize);popover.contentElement.appendChild(popoverContentElement);fulfill(new ObjectUI.ObjectPopoverHelper(linkifier,resultHighlightedAsDOM));} -return promise;}};ObjectUI.ObjectPopoverHelper.MaxPopoverTextLength=10000;;ObjectUI.ObjectPropertiesSection=class extends UI.TreeOutlineInShadow{constructor(object,title,linkifier,emptyPlaceholder,ignoreHasOwnProperty,extraProperties){super();this._object=object;this._editable=true;this.hideOverflow();this.setFocusable(false);this._objectTreeElement=new ObjectUI.ObjectPropertiesSection.RootElement(object,linkifier,emptyPlaceholder,ignoreHasOwnProperty,extraProperties);this.appendChild(this._objectTreeElement);if(typeof title==='string'||!title){this.titleElement=this.element.createChild('span');this.titleElement.textContent=title||'';}else{this.titleElement=title;this.element.appendChild(title);} -this.element._section=this;this.registerRequiredCSS('object_ui/objectValue.css');this.registerRequiredCSS('object_ui/objectPropertiesSection.css');this.rootElement().childrenListElement.classList.add('source-code','object-properties-section');} -static defaultObjectPresentation(object,linkifier,skipProto){var componentRoot=createElementWithClass('span','source-code');var shadowRoot=UI.createShadowRootWithCoreStyles(componentRoot,'object_ui/objectValue.css');shadowRoot.appendChild(ObjectUI.ObjectPropertiesSection.createValueElement(object,false,true));if(!object.hasChildren) -return componentRoot;var objectPropertiesSection=new ObjectUI.ObjectPropertiesSection(object,componentRoot,linkifier);objectPropertiesSection.editable=false;if(skipProto) -objectPropertiesSection.skipProto();return objectPropertiesSection.element;} -static CompareProperties(propertyA,propertyB){var a=propertyA.name;var b=propertyB.name;if(a==='__proto__') -return 1;if(b==='__proto__') -return-1;if(!propertyA.enumerable&&propertyB.enumerable) -return 1;if(!propertyB.enumerable&&propertyA.enumerable) -return-1;if(a.startsWith('_')&&!b.startsWith('_')) -return 1;if(b.startsWith('_')&&!a.startsWith('_')) -return-1;if(propertyA.symbol&&!propertyB.symbol) -return 1;if(propertyB.symbol&&!propertyA.symbol) -return-1;return String.naturalOrderComparator(a,b);} -static createNameElement(name){var nameElement=createElementWithClass('span','name');if(/^\s|\s$|^$|\n/.test(name)) -nameElement.createTextChildren('"',name.replace(/\n/g,'\u21B5'),'"');else -nameElement.textContent=name;return nameElement;} -static valueElementForFunctionDescription(description,includePreview,defaultName){var valueElement=createElementWithClass('span','object-value-function');var text='';if(description){text=description.replace(/^function [gs]et /,'function ').replace(/^function [gs]et\(/,'function\(').replace(/^[gs]et /,'');} -defaultName=defaultName||'';var asyncMatch=text.match(/^(async\s+function)/);var isGenerator=text.startsWith('function*');var isGeneratorShorthand=text.startsWith('*');var isBasic=!isGenerator&&text.startsWith('function');var isClass=text.startsWith('class ')||text.startsWith('class{');var firstArrowIndex=text.indexOf('=>');var isArrow=!asyncMatch&&!isGenerator&&!isBasic&&!isClass&&firstArrowIndex>0;var textAfterPrefix;if(isClass){textAfterPrefix=text.substring('class'.length);var classNameMatch=/^[^{\s]+/.exec(textAfterPrefix.trim());var className=defaultName;if(classNameMatch) -className=classNameMatch[0].trim()||defaultName;addElements('class',textAfterPrefix,className);}else if(asyncMatch){textAfterPrefix=text.substring(asyncMatch[1].length);addElements('async \u0192',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isGenerator){textAfterPrefix=text.substring('function*'.length);addElements('\u0192*',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isGeneratorShorthand){textAfterPrefix=text.substring('*'.length);addElements('\u0192*',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isBasic){textAfterPrefix=text.substring('function'.length);addElements('\u0192',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isArrow){const maxArrowFunctionCharacterLength=60;var abbreviation=text;if(defaultName) -abbreviation=defaultName+'()';else if(text.length>maxArrowFunctionCharacterLength) -abbreviation=text.substring(0,firstArrowIndex+2)+' {\u2026}';addElements('',text,abbreviation);}else{addElements('\u0192',text,nameAndArguments(text));} -valueElement.title=description||'';return valueElement;function nameAndArguments(contents){var startOfArgumentsIndex=contents.indexOf('(');var endOfArgumentsMatch=contents.match(/\)\s*{/);if(startOfArgumentsIndex!==-1&&endOfArgumentsMatch&&endOfArgumentsMatch.index>startOfArgumentsIndex){var name=contents.substring(0,startOfArgumentsIndex).trim()||defaultName;var args=contents.substring(startOfArgumentsIndex,endOfArgumentsMatch.index+1);return name+args;} -return defaultName+'()';} -function addElements(prefix,body,abbreviation){const maxFunctionBodyLength=200;if(prefix.length) -valueElement.createChild('span','object-value-function-prefix').textContent=prefix+' ';if(includePreview) -valueElement.createTextChild(body.trim().trimEnd(maxFunctionBodyLength));else -valueElement.createTextChild(abbreviation.replace(/\n/g,' '));}} -static createValueElementWithCustomSupport(value,wasThrown,showPreview,parentElement,linkifier){if(value.customPreview()){var result=(new ObjectUI.CustomPreviewComponent(value)).element;result.classList.add('object-properties-section-custom-section');return result;} -return ObjectUI.ObjectPropertiesSection.createValueElement(value,wasThrown,showPreview,parentElement,linkifier);} -static createValueElement(value,wasThrown,showPreview,parentElement,linkifier){var valueElement;var type=value.type;var subtype=value.subtype;var description=value.description;if(type==='object'&&subtype==='internal#location'){var rawLocation=value.debuggerModel().createRawLocationByScriptId(value.value.scriptId,value.value.lineNumber,value.value.columnNumber);if(rawLocation&&linkifier) -return linkifier.linkifyRawLocation(rawLocation,'');valueElement=createUnknownInternalLocationElement();}else if(type==='string'&&typeof description==='string'){valueElement=createStringElement();}else if(type==='function'){valueElement=ObjectUI.ObjectPropertiesSection.valueElementForFunctionDescription(description);}else if(type==='object'&&subtype==='node'&&description){valueElement=createNodeElement();}else if(type==='number'&&description&&description.indexOf('e')!==-1){valueElement=createNumberWithExponentElement();if(parentElement) -parentElement.classList.add('hbox');}else{valueElement=createElementWithClass('span','object-value-'+(subtype||type));valueElement.title=description||'';if(Runtime.experiments.isEnabled('objectPreviews')&&value.preview&&showPreview){var previewFormatter=new ObjectUI.RemoteObjectPreviewFormatter();previewFormatter.appendObjectPreview(valueElement,value.preview,false);}else{valueElement.setTextContentTruncatedIfNeeded(description);}} -if(wasThrown){var wrapperElement=createElementWithClass('span','error value');wrapperElement.createTextChild('['+Common.UIString('Exception')+': ');wrapperElement.appendChild(valueElement);wrapperElement.createTextChild(']');return wrapperElement;} -valueElement.classList.add('value');return valueElement;function createUnknownInternalLocationElement(){var valueElement=createElementWithClass('span');valueElement.textContent='<'+Common.UIString('unknown')+'>';valueElement.title=description||'';return valueElement;} -function createStringElement(){var valueElement=createElementWithClass('span','object-value-string');valueElement.createChild('span','object-value-string-quote').textContent='"';valueElement.createTextChild('').setTextContentTruncatedIfNeeded(description.replace(/\n/g,'\u21B5'));valueElement.createChild('span','object-value-string-quote').textContent='"';valueElement.title=description||'';return valueElement;} -function createNodeElement(){var valueElement=createElementWithClass('span','object-value-node');Components.DOMPresentationUtils.createSpansForNodeTitle(valueElement,(description));valueElement.addEventListener('click',event=>{Common.Revealer.reveal(value);event.consume(true);},false);valueElement.addEventListener('mousemove',()=>SDK.OverlayModel.highlightObjectAsDOMNode(value),false);valueElement.addEventListener('mouseleave',()=>SDK.OverlayModel.hideDOMNodeHighlight(),false);return valueElement;} -function createNumberWithExponentElement(){var valueElement=createElementWithClass('span','object-value-number');var numberParts=description.split('e');valueElement.createChild('span','object-value-scientific-notation-mantissa').textContent=numberParts[0];valueElement.createChild('span','object-value-scientific-notation-exponent').textContent='e'+numberParts[1];valueElement.classList.add('object-value-scientific-notation-number');valueElement.title=description||'';return valueElement;}} -static formatObjectAsFunction(func,element,linkify,includePreview){func.debuggerModel().functionDetailsPromise(func).then(didGetDetails);function didGetDetails(response){if(linkify&&response&&response.location){element.classList.add('linkified');element.addEventListener('click',()=>Common.Revealer.reveal(response.location));} -var defaultName=includePreview?'':'anonymous';if(response&&response.functionName) -defaultName=response.functionName;var valueElement=ObjectUI.ObjectPropertiesSection.valueElementForFunctionDescription(func.description,includePreview,defaultName);element.appendChild(valueElement);}} -skipProto(){this._skipProto=true;} -expand(){this._objectTreeElement.expand();} -setEditable(value){this._editable=value;} -objectTreeElement(){return this._objectTreeElement;} -enableContextMenu(){this.element.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),false);} -_contextMenuEventFired(event){var contextMenu=new UI.ContextMenu(event);contextMenu.appendApplicableItems(this._object);contextMenu.show();} -titleLessMode(){this._objectTreeElement.listItemElement.classList.add('hidden');this._objectTreeElement.childrenListElement.classList.add('title-less-mode');this._objectTreeElement.expand();}};ObjectUI.ObjectPropertiesSection._arrayLoadThreshold=100;ObjectUI.ObjectPropertiesSection.RootElement=class extends UI.TreeElement{constructor(object,linkifier,emptyPlaceholder,ignoreHasOwnProperty,extraProperties){var contentElement=createElement('content');super(contentElement);this._object=object;this._extraProperties=extraProperties||[];this._ignoreHasOwnProperty=!!ignoreHasOwnProperty;this._emptyPlaceholder=emptyPlaceholder;this.setExpandable(true);this.selectable=false;this.toggleOnClick=true;this.listItemElement.classList.add('object-properties-section-root-element');this._linkifier=linkifier;} -onexpand(){if(this.treeOutline) -this.treeOutline.element.classList.add('expanded');} -oncollapse(){if(this.treeOutline) -this.treeOutline.element.classList.remove('expanded');} -ondblclick(e){return true;} -onpopulate(){ObjectUI.ObjectPropertyTreeElement._populate(this,this._object,!!this.treeOutline._skipProto,this._linkifier,this._emptyPlaceholder,this._ignoreHasOwnProperty,this._extraProperties);}};ObjectUI.ObjectPropertyTreeElement=class extends UI.TreeElement{constructor(property,linkifier){super();this.property=property;this.toggleOnClick=true;this.selectable=false;this._highlightChanges=[];this._linkifier=linkifier;} -static _populate(treeElement,value,skipProto,linkifier,emptyPlaceholder,flattenProtoChain,extraProperties,targetValue){if(value.arrayLength()>ObjectUI.ObjectPropertiesSection._arrayLoadThreshold){treeElement.removeChildren();ObjectUI.ArrayGroupingTreeElement._populateArray(treeElement,value,0,value.arrayLength()-1,linkifier);return;} -function callback(properties,internalProperties){treeElement.removeChildren();if(!properties) -return;extraProperties=extraProperties||[];for(var i=0;i<extraProperties.length;++i) -properties.push(extraProperties[i]);ObjectUI.ObjectPropertyTreeElement.populateWithProperties(treeElement,properties,internalProperties,skipProto,targetValue||value,linkifier,emptyPlaceholder);} -var generatePreview=Runtime.experiments.isEnabled('objectPreviews');if(flattenProtoChain) -value.getAllProperties(false,generatePreview,callback);else -SDK.RemoteObject.loadFromObjectPerProto(value,generatePreview,callback);} -static populateWithProperties(treeNode,properties,internalProperties,skipProto,value,linkifier,emptyPlaceholder){properties.sort(ObjectUI.ObjectPropertiesSection.CompareProperties);var tailProperties=[];var protoProperty=null;for(var i=0;i<properties.length;++i){var property=properties[i];property.parentObject=value;if(property.name==='__proto__'&&!property.isAccessorProperty()){protoProperty=property;continue;} -if(property.isOwn&&property.getter){var getterProperty=new SDK.RemoteObjectProperty('get '+property.name,property.getter,false);getterProperty.parentObject=value;tailProperties.push(getterProperty);} -if(property.isOwn&&property.setter){var setterProperty=new SDK.RemoteObjectProperty('set '+property.name,property.setter,false);setterProperty.parentObject=value;tailProperties.push(setterProperty);} -var canShowProperty=property.getter||!property.isAccessorProperty();if(canShowProperty&&property.name!=='__proto__') -treeNode.appendChild(new ObjectUI.ObjectPropertyTreeElement(property,linkifier));} -for(var i=0;i<tailProperties.length;++i) -treeNode.appendChild(new ObjectUI.ObjectPropertyTreeElement(tailProperties[i],linkifier));if(!skipProto&&protoProperty) -treeNode.appendChild(new ObjectUI.ObjectPropertyTreeElement(protoProperty,linkifier));if(internalProperties){for(var i=0;i<internalProperties.length;i++){internalProperties[i].parentObject=value;var treeElement=new ObjectUI.ObjectPropertyTreeElement(internalProperties[i],linkifier);if(internalProperties[i].name==='[[Entries]]'){treeElement.setExpandable(true);treeElement.expand();} -treeNode.appendChild(treeElement);}} -ObjectUI.ObjectPropertyTreeElement._appendEmptyPlaceholderIfNeeded(treeNode,emptyPlaceholder);} -static _appendEmptyPlaceholderIfNeeded(treeNode,emptyPlaceholder){if(treeNode.childCount()) -return;var title=createElementWithClass('div','gray-info-message');title.textContent=emptyPlaceholder||Common.UIString('No properties');var infoElement=new UI.TreeElement(title);treeNode.appendChild(infoElement);} -static createRemoteObjectAccessorPropertySpan(object,propertyPath,callback){var rootElement=createElement('span');var element=rootElement.createChild('span');element.textContent=Common.UIString('(...)');if(!object) -return rootElement;element.classList.add('object-value-calculate-value-button');element.title=Common.UIString('Invoke property getter');element.addEventListener('click',onInvokeGetterClick,false);function onInvokeGetterClick(event){event.consume();object.getProperty(propertyPath,callback);} -return rootElement;} -setSearchRegex(regex,additionalCssClassName){var cssClasses=UI.highlightedSearchResultClassName;if(additionalCssClassName) -cssClasses+=' '+additionalCssClassName;this.revertHighlightChanges();this._applySearch(regex,this.nameElement,cssClasses);var valueType=this.property.value.type;if(valueType!=='object') -this._applySearch(regex,this.valueElement,cssClasses);return!!this._highlightChanges.length;} -_applySearch(regex,element,cssClassName){var ranges=[];var content=element.textContent;regex.lastIndex=0;var match=regex.exec(content);while(match){ranges.push(new TextUtils.SourceRange(match.index,match[0].length));match=regex.exec(content);} -if(ranges.length) -UI.highlightRangesWithStyleClass(element,ranges,cssClassName,this._highlightChanges);} -revertHighlightChanges(){UI.revertDomChanges(this._highlightChanges);this._highlightChanges=[];} -onpopulate(){var propertyValue=(this.property.value);console.assert(propertyValue);var skipProto=this.treeOutline?this.treeOutline._skipProto:true;var targetValue=this.property.name!=='__proto__'?propertyValue:this.property.parentObject;ObjectUI.ObjectPropertyTreeElement._populate(this,propertyValue,skipProto,this._linkifier,undefined,undefined,undefined,targetValue);} -ondblclick(event){var inEditableElement=event.target.isSelfOrDescendant(this.valueElement)||(this.expandedValueElement&&event.target.isSelfOrDescendant(this.expandedValueElement));if(!this.property.value.customPreview()&&inEditableElement&&(this.property.writable||this.property.setter)) -this._startEditing();return false;} -onattach(){this.update();this._updateExpandable();} -onexpand(){this._showExpandedValueElement(true);} -oncollapse(){this._showExpandedValueElement(false);} -_showExpandedValueElement(value){if(!this.expandedValueElement) -return;if(value) -this.listItemElement.replaceChild(this.expandedValueElement,this.valueElement);else -this.listItemElement.replaceChild(this.valueElement,this.expandedValueElement);} -_createExpandedValueElement(value){var needsAlternateValue=value.hasChildren&&!value.customPreview()&&value.subtype!=='node'&&value.type!=='function'&&(value.type!=='object'||value.preview);if(!needsAlternateValue) -return null;var valueElement=createElementWithClass('span','value');if(value.description==='Object') -valueElement.textContent='';else -valueElement.setTextContentTruncatedIfNeeded(value.description||'');valueElement.classList.add('object-value-'+(value.subtype||value.type));valueElement.title=value.description||'';return valueElement;} -update(){this.nameElement=ObjectUI.ObjectPropertiesSection.createNameElement(this.property.name);if(!this.property.enumerable) -this.nameElement.classList.add('object-properties-section-dimmed');if(this.property.synthetic) -this.nameElement.classList.add('synthetic-property');this._updatePropertyPath();this.nameElement.addEventListener('contextmenu',this._contextMenuFired.bind(this,this.property),false);var separatorElement=createElementWithClass('span','object-properties-section-separator');separatorElement.textContent=': ';if(this.property.value){var showPreview=this.property.name!=='__proto__';this.valueElement=ObjectUI.ObjectPropertiesSection.createValueElementWithCustomSupport(this.property.value,this.property.wasThrown,showPreview,this.listItemElement,this._linkifier);this.valueElement.addEventListener('contextmenu',this._contextMenuFired.bind(this,this.property),false);}else if(this.property.getter){this.valueElement=ObjectUI.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan(this.property.parentObject,[this.property.name],this._onInvokeGetterClick.bind(this));}else{this.valueElement=createElementWithClass('span','object-value-undefined');this.valueElement.textContent=Common.UIString('<unreadable>');this.valueElement.title=Common.UIString('No property getter');} -var valueText=this.valueElement.textContent;if(this.property.value&&valueText&&!this.property.wasThrown) -this.expandedValueElement=this._createExpandedValueElement(this.property.value);this.listItemElement.removeChildren();this.listItemElement.appendChildren(this.nameElement,separatorElement,this.valueElement);} -_updatePropertyPath(){if(this.nameElement.title) -return;var useDotNotation=/^(_|\$|[A-Z])(_|\$|[A-Z]|\d)*$/i;var isInteger=/^[1-9]\d*$/;var name=this.property.name;var parentPath=this.parent.nameElement?this.parent.nameElement.title:'';if(useDotNotation.test(name)) -this.nameElement.title=parentPath+'.'+name;else if(isInteger.test(name)) -this.nameElement.title=parentPath+'['+name+']';else -this.nameElement.title=parentPath+'["'+name+'"]';} -_contextMenuFired(property,event){var contextMenu=new UI.ContextMenu(event);if(property.symbol) -contextMenu.appendApplicableItems(property.symbol);if(property.value) -contextMenu.appendApplicableItems(property.value);var copyPathHandler=InspectorFrontendHost.copyText.bind(InspectorFrontendHost,this.nameElement.title);contextMenu.clipboardSection().appendItem(Common.UIString('Copy property path'),copyPathHandler);contextMenu.show();} -_startEditing(){if(this._prompt||!this.treeOutline._editable||this._readOnly) -return;this._editableDiv=this.listItemElement.createChild('span');var text=this.property.value.description;if(this.property.value.type==='string'&&typeof text==='string') -text='"'+text+'"';this._editableDiv.setTextContentTruncatedIfNeeded(text,Common.UIString('<string is too large to edit>'));var originalContent=this._editableDiv.textContent;this.setExpandable(false);this.listItemElement.classList.add('editing-sub-part');this.valueElement.classList.add('hidden');this._prompt=new ObjectUI.ObjectPropertyPrompt();var proxyElement=this._prompt.attachAndStartEditing(this._editableDiv,this._editingCommitted.bind(this,originalContent));this.listItemElement.getComponentSelection().selectAllChildren(this._editableDiv);proxyElement.addEventListener('keydown',this._promptKeyDown.bind(this,originalContent),false);} -_editingEnded(){this._prompt.detach();delete this._prompt;this._editableDiv.remove();this._updateExpandable();this.listItemElement.scrollLeft=0;this.listItemElement.classList.remove('editing-sub-part');} -_editingCancelled(){this.valueElement.classList.remove('hidden');this._editingEnded();} -_editingCommitted(originalContent){var userInput=this._prompt.text();if(userInput===originalContent){this._editingCancelled();return;} -this._editingEnded();this._applyExpression(userInput);} -_promptKeyDown(originalContent,event){if(isEnterKey(event)){event.consume();this._editingCommitted(originalContent);return;} -if(event.key==='Escape'){event.consume();this._editingCancelled();return;}} -async _applyExpression(expression){var property=SDK.RemoteObject.toCallArgument(this.property.symbol||this.property.name);expression=SDK.RuntimeModel.wrapObjectLiteralExpressionIfNeeded(expression.trim());var errorPromise=expression?this.property.parentObject.setPropertyValue(property,expression):this.property.parentObject.deleteProperty(property);var error=await errorPromise;if(error){this.update();return;} -if(!expression){this.parent.removeChild(this);}else{var parent=this.parent;parent.invalidateChildren();parent.onpopulate();}} -_onInvokeGetterClick(result,wasThrown){if(!result) -return;this.property.value=result;this.property.wasThrown=wasThrown;this.update();this.invalidateChildren();this._updateExpandable();} -_updateExpandable(){if(this.property.value){this.setExpandable(!this.property.value.customPreview()&&this.property.value.hasChildren&&!this.property.wasThrown);}else{this.setExpandable(false);}}};ObjectUI.ArrayGroupingTreeElement=class extends UI.TreeElement{constructor(object,fromIndex,toIndex,propertyCount,linkifier){super(String.sprintf('[%d \u2026 %d]',fromIndex,toIndex),true);this.toggleOnClick=true;this.selectable=false;this._fromIndex=fromIndex;this._toIndex=toIndex;this._object=object;this._readOnly=true;this._propertyCount=propertyCount;this._linkifier=linkifier;} -static _populateArray(treeNode,object,fromIndex,toIndex,linkifier){ObjectUI.ArrayGroupingTreeElement._populateRanges(treeNode,object,fromIndex,toIndex,true,linkifier);} -static _populateRanges(treeNode,object,fromIndex,toIndex,topLevel,linkifier){object.callFunctionJSON(packRanges,[{value:fromIndex},{value:toIndex},{value:ObjectUI.ArrayGroupingTreeElement._bucketThreshold},{value:ObjectUI.ArrayGroupingTreeElement._sparseIterationThreshold},{value:ObjectUI.ArrayGroupingTreeElement._getOwnPropertyNamesThreshold}],callback);function packRanges(fromIndex,toIndex,bucketThreshold,sparseIterationThreshold,getOwnPropertyNamesThreshold){var ownPropertyNames=null;var consecutiveRange=(toIndex-fromIndex>=sparseIterationThreshold)&&ArrayBuffer.isView(this);var skipGetOwnPropertyNames=consecutiveRange&&(toIndex-fromIndex>=getOwnPropertyNamesThreshold);function*arrayIndexes(object){if(toIndex-fromIndex<sparseIterationThreshold){for(var i=fromIndex;i<=toIndex;++i){if(i in object) -yield i;}}else{ownPropertyNames=ownPropertyNames||Object.getOwnPropertyNames(object);for(var i=0;i<ownPropertyNames.length;++i){var name=ownPropertyNames[i];var index=name>>>0;if((''+index)===name&&fromIndex<=index&&index<=toIndex) -yield index;}}} -var count=0;if(consecutiveRange){count=toIndex-fromIndex+1;}else{for(var i of arrayIndexes(this)) -++count;} -var bucketSize=count;if(count<=bucketThreshold) -bucketSize=count;else -bucketSize=Math.pow(bucketThreshold,Math.ceil(Math.log(count)/Math.log(bucketThreshold))-1);var ranges=[];if(consecutiveRange){for(var i=fromIndex;i<=toIndex;i+=bucketSize){var groupStart=i;var groupEnd=groupStart+bucketSize-1;if(groupEnd>toIndex) -groupEnd=toIndex;ranges.push([groupStart,groupEnd,groupEnd-groupStart+1]);}}else{count=0;var groupStart=-1;var groupEnd=0;for(var i of arrayIndexes(this)){if(groupStart===-1) -groupStart=i;groupEnd=i;if(++count===bucketSize){ranges.push([groupStart,groupEnd,count]);count=0;groupStart=-1;}} -if(count>0) -ranges.push([groupStart,groupEnd,count]);} -return{ranges:ranges,skipGetOwnPropertyNames:skipGetOwnPropertyNames};} -function callback(result){if(!result) -return;var ranges=(result.ranges);if(ranges.length===1){ObjectUI.ArrayGroupingTreeElement._populateAsFragment(treeNode,object,ranges[0][0],ranges[0][1],linkifier);}else{for(var i=0;i<ranges.length;++i){var fromIndex=ranges[i][0];var toIndex=ranges[i][1];var count=ranges[i][2];if(fromIndex===toIndex) -ObjectUI.ArrayGroupingTreeElement._populateAsFragment(treeNode,object,fromIndex,toIndex,linkifier);else -treeNode.appendChild(new ObjectUI.ArrayGroupingTreeElement(object,fromIndex,toIndex,count,linkifier));}} -if(topLevel){ObjectUI.ArrayGroupingTreeElement._populateNonIndexProperties(treeNode,object,result.skipGetOwnPropertyNames,linkifier);}}} -static _populateAsFragment(treeNode,object,fromIndex,toIndex,linkifier){object.callFunction(buildArrayFragment,[{value:fromIndex},{value:toIndex},{value:ObjectUI.ArrayGroupingTreeElement._sparseIterationThreshold}],processArrayFragment.bind(this));function buildArrayFragment(fromIndex,toIndex,sparseIterationThreshold){var result=Object.create(null);if(toIndex-fromIndex<sparseIterationThreshold){for(var i=fromIndex;i<=toIndex;++i){if(i in this) -result[i]=this[i];}}else{var ownPropertyNames=Object.getOwnPropertyNames(this);for(var i=0;i<ownPropertyNames.length;++i){var name=ownPropertyNames[i];var index=name>>>0;if(String(index)===name&&fromIndex<=index&&index<=toIndex) -result[index]=this[index];}} -return result;} -function processArrayFragment(arrayFragment,wasThrown){if(!arrayFragment||wasThrown) -return;arrayFragment.getAllProperties(false,Runtime.experiments.isEnabled('objectPreviews'),processProperties.bind(this));} -function processProperties(properties,internalProperties){if(!properties) -return;properties.sort(ObjectUI.ObjectPropertiesSection.CompareProperties);for(var i=0;i<properties.length;++i){properties[i].parentObject=this._object;var childTreeElement=new ObjectUI.ObjectPropertyTreeElement(properties[i],linkifier);childTreeElement._readOnly=true;treeNode.appendChild(childTreeElement);}}} -static _populateNonIndexProperties(treeNode,object,skipGetOwnPropertyNames,linkifier){object.callFunction(buildObjectFragment,[{value:skipGetOwnPropertyNames}],processObjectFragment.bind(this));function buildObjectFragment(skipGetOwnPropertyNames){var result={__proto__:this.__proto__};if(skipGetOwnPropertyNames) -return result;var names=Object.getOwnPropertyNames(this);for(var i=0;i<names.length;++i){var name=names[i];if(String(name>>>0)===name&&name>>>0!==0xffffffff) -continue;var descriptor=Object.getOwnPropertyDescriptor(this,name);if(descriptor) -Object.defineProperty(result,name,descriptor);} -return result;} -function processObjectFragment(arrayFragment,wasThrown){if(!arrayFragment||wasThrown) -return;arrayFragment.getOwnProperties(Runtime.experiments.isEnabled('objectPreviews'),processProperties.bind(this));} -function processProperties(properties,internalProperties){if(!properties) -return;properties.sort(ObjectUI.ObjectPropertiesSection.CompareProperties);for(var i=0;i<properties.length;++i){properties[i].parentObject=this._object;var childTreeElement=new ObjectUI.ObjectPropertyTreeElement(properties[i],linkifier);childTreeElement._readOnly=true;treeNode.appendChild(childTreeElement);}}} -onpopulate(){if(this._propertyCount>=ObjectUI.ArrayGroupingTreeElement._bucketThreshold){ObjectUI.ArrayGroupingTreeElement._populateRanges(this,this._object,this._fromIndex,this._toIndex,false,this._linkifier);return;} -ObjectUI.ArrayGroupingTreeElement._populateAsFragment(this,this._object,this._fromIndex,this._toIndex,this._linkifier);} -onattach(){this.listItemElement.classList.add('object-properties-section-name');}};ObjectUI.ArrayGroupingTreeElement._bucketThreshold=100;ObjectUI.ArrayGroupingTreeElement._sparseIterationThreshold=250000;ObjectUI.ArrayGroupingTreeElement._getOwnPropertyNamesThreshold=500000;ObjectUI.ObjectPropertyPrompt=class extends UI.TextPrompt{constructor(){super();this.initialize(ObjectUI.JavaScriptAutocomplete.completionsForTextInCurrentContext);}};ObjectUI.ObjectPropertiesSectionExpandController=class{constructor(){this._expandedProperties=new Set();} -watchSection(id,section){section.addEventListener(UI.TreeOutline.Events.ElementAttached,this._elementAttached,this);section.addEventListener(UI.TreeOutline.Events.ElementExpanded,this._elementExpanded,this);section.addEventListener(UI.TreeOutline.Events.ElementCollapsed,this._elementCollapsed,this);section[ObjectUI.ObjectPropertiesSectionExpandController._treeOutlineId]=id;if(this._expandedProperties.has(id)) -section.expand();} -stopWatchSectionsWithId(id){for(var property of this._expandedProperties){if(property.startsWith(id+':')) -this._expandedProperties.delete(property);}} -_elementAttached(event){var element=(event.data);if(element.isExpandable()&&this._expandedProperties.has(this._propertyPath(element))) -element.expand();} -_elementExpanded(event){var element=(event.data);this._expandedProperties.add(this._propertyPath(element));} -_elementCollapsed(event){var element=(event.data);this._expandedProperties.delete(this._propertyPath(element));} -_propertyPath(treeElement){var cachedPropertyPath=treeElement[ObjectUI.ObjectPropertiesSectionExpandController._cachedPathSymbol];if(cachedPropertyPath) -return cachedPropertyPath;var current=treeElement;var rootElement=treeElement.treeOutline.objectTreeElement();var result;while(current!==rootElement){var currentName='';if(current.property) -currentName=current.property.name;else -currentName=typeof current.title==='string'?current.title:current.title.textContent;result=currentName+(result?'.'+result:'');current=current.parent;} -var treeOutlineId=treeElement.treeOutline[ObjectUI.ObjectPropertiesSectionExpandController._treeOutlineId];result=treeOutlineId+(result?':'+result:'');treeElement[ObjectUI.ObjectPropertiesSectionExpandController._cachedPathSymbol]=result;return result;}};ObjectUI.ObjectPropertiesSectionExpandController._cachedPathSymbol=Symbol('cachedPath');ObjectUI.ObjectPropertiesSectionExpandController._treeOutlineId=Symbol('treeOutlineId');ObjectUI.ObjectPropertiesSection.Renderer=class{render(object,options){if(!(object instanceof SDK.RemoteObject)) -return Promise.reject(new Error('Can\'t render '+object));options=options||{};var title=options.title;var section=new ObjectUI.ObjectPropertiesSection(object,title);if(!title) -section.titleLessMode();if(options.expanded) -section.expand();section.editable=!!options.editable;return Promise.resolve(section.element);}};;ObjectUI.JavaScriptAutocomplete={};ObjectUI.JavaScriptAutocomplete.CompletionGroup;ObjectUI.JavaScriptAutocomplete.completionsForTextInCurrentContext=function(text,query,force){var clippedExpression=ObjectUI.JavaScriptAutocomplete._clipExpression(text,true);var mapCompletionsPromise=ObjectUI.JavaScriptAutocomplete._mapCompletions(text,query);return ObjectUI.JavaScriptAutocomplete.completionsForExpression(clippedExpression,query,force).then(completions=>mapCompletionsPromise.then(mapCompletions=>mapCompletions.concat(completions)));};ObjectUI.JavaScriptAutocomplete._clipExpression=function(text,allowEndingBracket){var index;var stopChars=new Set('=:({;,!+-*/&|^<>`'.split(''));var whiteSpaceChars=new Set(' \r\n\t'.split(''));var continueChars=new Set('[. \r\n\t'.split(''));for(index=text.length-1;index>=0;index--){if(stopChars.has(text.charAt(index))) -break;if(whiteSpaceChars.has(text.charAt(index))&&!continueChars.has(text.charAt(index-1))) -break;} -var clippedExpression=text.substring(index+1).trim();var bracketCount=0;index=clippedExpression.length-1;while(index>=0){var character=clippedExpression.charAt(index);if(character===']') -bracketCount++;if(character==='['&&(index<clippedExpression.length-1||!allowEndingBracket)){bracketCount--;if(bracketCount<0) -break;} -index--;} -return clippedExpression.substring(index+1).trim();};ObjectUI.JavaScriptAutocomplete._mapCompletions=async function(text,query){var mapMatch=text.match(/\.\s*(get|set|delete)\s*\(\s*$/);var executionContext=UI.context.flavor(SDK.ExecutionContext);if(!executionContext||!mapMatch) -return[];var clippedExpression=ObjectUI.JavaScriptAutocomplete._clipExpression(text.substring(0,mapMatch.index));var result=await executionContext.evaluate({expression:clippedExpression,objectGroup:'completion',includeCommandLineAPI:true,silent:true,returnByValue:false,generatePreview:false},false,false);if(result.error||!!result.exceptionDetails||result.object.subtype!=='map') -return[];var properties=await result.object.getOwnPropertiesPromise(false);var internalProperties=properties.internalProperties||[];var entriesProperty=internalProperties.find(property=>property.name==='[[Entries]]');if(!entriesProperty) -return[];var keysObj=await entriesProperty.value.callFunctionJSONPromise(getEntries);return gotKeys(Object.keys(keysObj));function getEntries(){var result={__proto__:null};for(var i=0;i<this.length;i++){if(typeof this[i].key==='string') -result[this[i].key]=true;} -return result;} -function gotKeys(rawKeys){var caseSensitivePrefix=[];var caseInsensitivePrefix=[];var caseSensitiveAnywhere=[];var caseInsensitiveAnywhere=[];var quoteChar='"';if(query.startsWith('\'')) -quoteChar='\'';var endChar=')';if(mapMatch[0].indexOf('set')!==-1) -endChar=', ';var sorter=rawKeys.length<1000?String.naturalOrderComparator:undefined;var keys=rawKeys.sort(sorter).map(key=>quoteChar+key+quoteChar);for(var key of keys){if(key.length<query.length) -continue;if(query.length&&key.toLowerCase().indexOf(query.toLowerCase())===-1) -continue;var title=key.split('\n').join('\\n');var text=title+endChar;if(key.startsWith(query)) -caseSensitivePrefix.push({text:text,title:title,priority:4});else if(key.toLowerCase().startsWith(query.toLowerCase())) -caseInsensitivePrefix.push({text:text,title:title,priority:3});else if(key.indexOf(query)!==-1) -caseSensitiveAnywhere.push({text:text,title:title,priority:2});else -caseInsensitiveAnywhere.push({text:text,title:title,priority:1});} -var suggestions=caseSensitivePrefix.concat(caseInsensitivePrefix,caseSensitiveAnywhere,caseInsensitiveAnywhere);if(suggestions.length) -suggestions[0].subtitle=Common.UIString('Keys');return suggestions;}};ObjectUI.JavaScriptAutocomplete.completionsForExpression=async function(expressionString,query,force){var executionContext=UI.context.flavor(SDK.ExecutionContext);if(!executionContext) -return[];var lastIndex=expressionString.length-1;var dotNotation=(expressionString[lastIndex]==='.');var bracketNotation=(expressionString.length>1&&expressionString[lastIndex]==='[');if(dotNotation||bracketNotation) -expressionString=expressionString.substr(0,lastIndex);else -expressionString='';if((expressionString&&!isNaN(expressionString))||(!expressionString&&query&&!isNaN(query))) -return[];if(!query&&!expressionString&&!force) -return[];var selectedFrame=executionContext.debuggerModel.selectedCallFrame();if(!expressionString&&selectedFrame){return completionsOnPause(selectedFrame);}else{var result=await executionContext.evaluate({expression:expressionString,objectGroup:'completion',includeCommandLineAPI:true,silent:true,returnByValue:false,generatePreview:false},false,false);var completionGroups=await completionsOnGlobal(result);return receivedPropertyNames(completionGroups);} -async function completionsOnGlobal(result){if(result.error||!!result.exceptionDetails||!result.object) -return[];var object=result.object;while(object&&object.type==='object'&&object.subtype==='proxy'){var properties=await object.getOwnPropertiesPromise(false);var internalProperties=properties.internalProperties||[];var target=internalProperties.find(property=>property.name==='[[Target]]');object=target?target.value:null;} -if(!object) -return[];var completions=[];if(object.type==='object'||object.type==='function'){completions=await object.callFunctionJSONPromise(getCompletions,[SDK.RemoteObject.toCallArgument(object.subtype)]);}else if(object.type==='string'||object.type==='number'||object.type==='boolean'){var evaluateResult=await executionContext.evaluate({expression:'('+getCompletions+')("'+object.type+'")',objectGroup:'completion',includeCommandLineAPI:false,silent:true,returnByValue:true,generatePreview:false},false,false);if(evaluateResult.object&&!evaluateResult.exceptionDetails) -completions=evaluateResult.object.value;} -executionContext.runtimeModel.releaseObjectGroup('completion');if(!expressionString){var globalNames=await executionContext.globalLexicalScopeNames();if(completions.length) -completions[0].items=completions[0].items.concat(globalNames);else -completions.push({items:globalNames,title:Common.UIString('Lexical scope variables')});} -return completions;function getCompletions(type){var object;if(type==='string') -object=new String('');else if(type==='number') -object=new Number(0);else if(type==='boolean') -object=new Boolean(false);else -object=this;var result=[];try{for(var o=object;o;o=Object.getPrototypeOf(o)){if((type==='array'||type==='typedarray')&&o===object&&ArrayBuffer.isView(o)&&o.length>9999) -continue;var group={items:[],__proto__:null};try{if(typeof o==='object'&&o.constructor&&o.constructor.name) -group.title=o.constructor.name;}catch(ee){} -result[result.length]=group;var names=Object.getOwnPropertyNames(o);var isArray=Array.isArray(o);for(var i=0;i<names.length;++i){if(isArray&&/^[0-9]/.test(names[i])) -continue;group.items[group.items.length]=names[i];}}}catch(e){} -return result;}} -async function completionsOnPause(callFrame){var result=[{items:['this']}];var scopeChain=callFrame.scopeChain();var groupPromises=[];for(var scope of scopeChain){groupPromises.push(scope.object().getAllPropertiesPromise(false,false).then(result=>({properties:result.properties,name:scope.name()})));} -var fullScopes=await Promise.all(groupPromises);executionContext.runtimeModel.releaseObjectGroup('completion');for(var scope of fullScopes) -result.push({title:scope.name,items:scope.properties.map(property=>property.name)});return receivedPropertyNames(result);} -function receivedPropertyNames(completions){if(!completions) -return[];var propertyGroups=(completions);var includeCommandLineAPI=(!dotNotation&&!bracketNotation);if(includeCommandLineAPI){const commandLineAPI=['dir','dirxml','keys','values','profile','profileEnd','monitorEvents','unmonitorEvents','inspect','copy','clear','getEventListeners','debug','undebug','monitor','unmonitor','table','queryObjects','$','$$','$x'];propertyGroups.push({items:commandLineAPI});} -return ObjectUI.JavaScriptAutocomplete._completionsForQuery(dotNotation,bracketNotation,expressionString,query,propertyGroups);}};ObjectUI.JavaScriptAutocomplete._completionsForQuery=function(dotNotation,bracketNotation,expressionString,query,propertyGroups){if(bracketNotation){if(query.length&&query[0]==='\'') -var quoteUsed='\'';else -var quoteUsed='"';} -if(!expressionString){const keywords=['break','case','catch','continue','default','delete','do','else','finally','for','function','if','in','instanceof','new','return','switch','this','throw','try','typeof','var','void','while','with'];propertyGroups.push({title:Common.UIString('keywords'),items:keywords});} -var result=[];var lastGroupTitle;for(var group of propertyGroups){group.items.sort(itemComparator.bind(null,group.items.length>1000));var caseSensitivePrefix=[];var caseInsensitivePrefix=[];var caseSensitiveAnywhere=[];var caseInsensitiveAnywhere=[];for(var property of group.items){if(!bracketNotation&&!/^[a-zA-Z_$\u008F-\uFFFF][a-zA-Z0-9_$\u008F-\uFFFF]*$/.test(property)) -continue;if(bracketNotation){if(!/^[0-9]+$/.test(property)) -property=quoteUsed+property.escapeCharacters(quoteUsed+'\\')+quoteUsed;property+=']';} -if(property.length<query.length) -continue;if(query.length&&property.toLowerCase().indexOf(query.toLowerCase())===-1) -continue;var prop=property.split('\n').join('\\n');if(property.startsWith(query)) -caseSensitivePrefix.push({text:prop,priority:4});else if(property.toLowerCase().startsWith(query.toLowerCase())) -caseInsensitivePrefix.push({text:prop,priority:3});else if(property.indexOf(query)!==-1) -caseSensitiveAnywhere.push({text:prop,priority:2});else -caseInsensitiveAnywhere.push({text:prop,priority:1});} -var structuredGroup=caseSensitivePrefix.concat(caseInsensitivePrefix,caseSensitiveAnywhere,caseInsensitiveAnywhere);if(structuredGroup.length&&group.title!==lastGroupTitle){structuredGroup[0].subtitle=group.title;lastGroupTitle=group.title;} -result=result.concat(structuredGroup);result.forEach(item=>{if(item.text.endsWith(']')) -item.title=item.text.substring(0,item.text.length-1);});} -return result;function itemComparator(naturalOrder,a,b){var aStartsWithUnderscore=a.startsWith('_');var bStartsWithUnderscore=b.startsWith('_');if(aStartsWithUnderscore&&!bStartsWithUnderscore) -return 1;if(bStartsWithUnderscore&&!aStartsWithUnderscore) -return-1;return naturalOrder?String.naturalOrderComparator(a,b):a.localeCompare(b);}};;ObjectUI.RemoteObjectPreviewFormatter=class{static _objectPropertyComparator(a,b){return sortValue(a)-sortValue(b);function sortValue(property){var internalName=ObjectUI.RemoteObjectPreviewFormatter._internalName;if(property.name===internalName.PromiseStatus) -return 1;else if(property.name===internalName.PromiseValue) -return 2;else if(property.name===internalName.GeneratorStatus||internalName.PrimitiveValue) -return 3;else if(property.type!=='function') -return 4;return 5;}} -appendObjectPreview(parentElement,preview,isEntry){const previewExperimentEnabled=Runtime.experiments.isEnabled('objectPreviews');var description=preview.description;var subTypesWithoutValuePreview=new Set(['null','regexp','error','internal#entry']);if(preview.type!=='object'||subTypesWithoutValuePreview.has(preview.subtype)||(previewExperimentEnabled&&isEntry)){parentElement.appendChild(this.renderPropertyPreview(preview.type,preview.subtype,description));return;} -const isArrayOrTypedArray=preview.subtype==='array'||preview.subtype==='typedarray';if(description){var text;if(isArrayOrTypedArray){var arrayLength=SDK.RemoteObject.arrayLength(preview);var arrayLengthText=arrayLength>1?('('+arrayLength+')'):'';var arrayName=SDK.RemoteObject.arrayNameFromDescription(description);text=arrayName==='Array'?arrayLengthText:(arrayName+arrayLengthText);}else{var hideDescription=previewExperimentEnabled&&description==='Object';text=hideDescription?'':description;} -if(text.length>0) -parentElement.createChild('span','object-description').textContent=text+' ';} -var propertiesElement=parentElement.createChild('span','object-properties-preview source-code');propertiesElement.createTextChild(isArrayOrTypedArray?'[':'{');if(preview.entries) -this._appendEntriesPreview(propertiesElement,preview);else if(isArrayOrTypedArray) -this._appendArrayPropertiesPreview(propertiesElement,preview);else -this._appendObjectPropertiesPreview(propertiesElement,preview);if(preview.overflow){var ellipsisText=propertiesElement.textContent.length>1?',\u00a0\u2026':'\u2026';propertiesElement.createChild('span').textContent=ellipsisText;} -propertiesElement.createTextChild(isArrayOrTypedArray?']':'}');} -_abbreviateFullQualifiedClassName(description){var abbreviatedDescription=description.split('.');for(var i=0;i<abbreviatedDescription.length-1;++i) -abbreviatedDescription[i]=abbreviatedDescription[i].trimMiddle(3);return abbreviatedDescription.join('.');} -_appendObjectPropertiesPreview(parentElement,preview){var internalName=ObjectUI.RemoteObjectPreviewFormatter._internalName;var properties=preview.properties.filter(p=>p.type!=='accessor').stableSort(ObjectUI.RemoteObjectPreviewFormatter._objectPropertyComparator);for(var i=0;i<properties.length;++i){if(i>0) -parentElement.createTextChild(', ');var property=properties[i];var name=property.name;if(preview.subtype==='promise'&&name===internalName.PromiseStatus){parentElement.appendChild(this._renderDisplayName('<'+property.value+'>'));var nextProperty=i+1<properties.length?properties[i+1]:null;if(nextProperty&&nextProperty.name===internalName.PromiseValue){if(property.value!=='pending'){parentElement.createTextChild(': ');parentElement.appendChild(this._renderPropertyPreviewOrAccessor([nextProperty]));} -i++;}}else if(preview.subtype==='generator'&&name===internalName.GeneratorStatus){parentElement.appendChild(this._renderDisplayName('<'+property.value+'>'));}else if(name===internalName.PrimitiveValue){parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));}else{parentElement.appendChild(this._renderDisplayName(name));parentElement.createTextChild(': ');parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));}}} -_appendArrayPropertiesPreview(parentElement,preview){var arrayLength=SDK.RemoteObject.arrayLength(preview);var indexProperties=preview.properties.filter(p=>toArrayIndex(p.name)!==-1).stableSort(arrayEntryComparator);var otherProperties=preview.properties.filter(p=>toArrayIndex(p.name)===-1).stableSort(ObjectUI.RemoteObjectPreviewFormatter._objectPropertyComparator);function arrayEntryComparator(a,b){return toArrayIndex(a.name)-toArrayIndex(b.name);} -function toArrayIndex(name){var index=name>>>0;if(String(index)===name&&index<arrayLength) -return index;return-1;} -var canShowGaps=!preview.overflow;var lastNonEmptyArrayIndex=-1;var elementsAdded=false;for(var i=0;i<indexProperties.length;++i){if(elementsAdded) -parentElement.createTextChild(', ');var property=indexProperties[i];var index=toArrayIndex(property.name);if(canShowGaps&&index-lastNonEmptyArrayIndex>1){appendUndefined(index);parentElement.createTextChild(', ');} -if(!canShowGaps&&i!==index){parentElement.appendChild(this._renderDisplayName(property.name));parentElement.createTextChild(': ');} -parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));lastNonEmptyArrayIndex=index;elementsAdded=true;} -if(canShowGaps&&arrayLength-lastNonEmptyArrayIndex>1){if(elementsAdded) -parentElement.createTextChild(', ');appendUndefined(arrayLength);} -for(var i=0;i<otherProperties.length;++i){if(elementsAdded) -parentElement.createTextChild(', ');var property=otherProperties[i];parentElement.appendChild(this._renderDisplayName(property.name));parentElement.createTextChild(': ');parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));elementsAdded=true;} -function appendUndefined(index){var span=parentElement.createChild('span','object-value-undefined');var count=index-lastNonEmptyArrayIndex-1;span.textContent=count!==1?Common.UIString('empty × %d',count):Common.UIString('empty');elementsAdded=true;}} -_appendEntriesPreview(parentElement,preview){for(var i=0;i<preview.entries.length;++i){if(i>0) -parentElement.createTextChild(', ');var entry=preview.entries[i];if(entry.key){this.appendObjectPreview(parentElement,entry.key,true);parentElement.createTextChild(' => ');} -this.appendObjectPreview(parentElement,entry.value,true);}} -_renderDisplayName(name){var result=createElementWithClass('span','name');var needsQuotes=/^\s|\s$|^$|\n/.test(name);result.textContent=needsQuotes?'"'+name.replace(/\n/g,'\u21B5')+'"':name;return result;} -_renderPropertyPreviewOrAccessor(propertyPath){var property=propertyPath.peekLast();return this.renderPropertyPreview(property.type,(property.subtype),property.value);} -renderPropertyPreview(type,subtype,description){var span=createElementWithClass('span','object-value-'+(subtype||type));description=description||'';if(type==='accessor'){span.textContent='(...)';span.title=Common.UIString('The property is computed with a getter');return span;} -if(type==='function'){span.textContent='\u0192';return span;} -if(type==='object'&&subtype==='node'&&description){Components.DOMPresentationUtils.createSpansForNodeTitle(span,description);return span;} -if(type==='string'){span.createTextChildren('"',description.replace(/\n/g,'\u21B5'),'"');return span;} -if(type==='object'&&!subtype){var preview=this._abbreviateFullQualifiedClassName(description);if(preview==='Object') -preview='{\u2026}';span.textContent=preview;span.title=description;return span;} -span.textContent=description;return span;}};ObjectUI.RemoteObjectPreviewFormatter._internalName={GeneratorStatus:'[[GeneratorStatus]]',PrimitiveValue:'[[PrimitiveValue]]',PromiseStatus:'[[PromiseStatus]]',PromiseValue:'[[PromiseValue]]'};;Runtime.cachedResources["object_ui/customPreviewComponent.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.custom-expandable-section {\n display: inline-flex;\n flex-direction: column;\n}\n\n.custom-expand-icon {\n -webkit-user-select: none;\n opacity: 0.5;\n margin-right: 4px;\n margin-bottom: -2px;\n background: black;\n}\n\n.custom-expandable-section-standard-section {\n display: inline-flex;\n}\n/*# sourceURL=object_ui/customPreviewComponent.css */";Runtime.cachedResources["object_ui/objectPopover.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.object-popover-content {\n display: block;\n position: relative;\n overflow: hidden;\n flex: 1 1 auto;\n}\n\n.object-popover-title {\n text-overflow: ellipsis;\n overflow: hidden;\n white-space: nowrap;\n font-weight: bold;\n padding-left: 18px;\n padding-bottom: 2px;\n}\n\n.object-popover-tree {\n border-top: 1px solid rgb(184, 184, 184);\n overflow: auto;\n width: 100%;\n height: calc(100% - 13px);\n}\n\n.object-popover-container {\n display: inline-block;\n}\n\n.function-popover-title {\n border-bottom: 1px solid #AAA;\n margin-bottom: 3px;\n padding-bottom: 2px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n.function-popover-title .function-name {\n font-weight: bold;\n}\n\n.function-title-link-container {\n display: flex;\n align-items: center;\n position: relative;\n margin-left: 10px;\n}\n\n.function-title-link-container .devtools-link {\n white-space: nowrap;\n overflow: hidden;\n}\n\n.function-location-step-into {\n position: relative;\n height: 14px;\n transform: rotate(-90deg);\n}\n\n/*# sourceURL=object_ui/objectPopover.css */";Runtime.cachedResources["object_ui/objectPropertiesSection.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.object-properties-section-separator {\n flex-shrink: 0;\n padding-right: 5px;\n}\n\n.object-properties-section-dimmed {\n opacity: 0.6;\n}\n\n.object-properties-section {\n padding: 0 0 0px 0px;\n color: rgb(33,33,33) !important;\n display: flex;\n flex-direction: column;\n}\n\n.object-properties-section li {\n -webkit-user-select: text;\n}\n\n.object-properties-section li::before {\n top: -1px;\n}\n\n.object-properties-section li.editing-sub-part {\n padding: 3px 6px 8px;\n margin: -1px -6px -8px -6px;\n text-overflow: clip;\n}\n\n.object-properties-section li.editing {\n margin-left: 10px;\n text-overflow: clip;\n}\n\n.tree-outline ol.title-less-mode {\n padding-left: 0px;\n}\n\n.object-properties-section .synthetic-property {\n font-style: italic;\n}\n\n.object-properties-section-root-element {\n display: flex;\n flex-direction: row;\n}\n\n/*# sourceURL=object_ui/objectPropertiesSection.css */";Runtime.cachedResources["object_ui/objectValue.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.object-value-scientific-notation-exponent {\n flex-shrink: 0;\n}\n\n.object-value-scientific-notation-mantissa {\n overflow: hidden;\n text-overflow: ellipsis;\n flex-shrink: 1;\n min-width: 1ex;\n}\n\n.object-value-scientific-notation-number {\n display: flex !important;\n}\n\n.object-value-node:hover {\n background-color: rgba(56, 121, 217, 0.1);\n}\n\n.object-value-function-prefix,\n.object-value-boolean {\n color: rgb(13, 34, 170);\n}\n\n.object-value-function {\n font-style: italic;\n}\n\n.object-value-function.linkified:hover {\n background-color: rgba(0, 0, 0, 0.1);\n cursor: pointer;\n}\n\n.object-value-number {\n color: rgb(28, 0, 207);\n}\n\n.object-value-string,\n.object-value-regexp,\n.object-value-symbol {\n white-space: pre;\n unicode-bidi: -webkit-isolate;\n color: rgb(196, 26, 22);\n}\n\n.object-value-string-quote {\n color: #222;\n}\n\n.object-value-node {\n position: relative;\n vertical-align: baseline;\n color: rgb(48, 57, 66);\n display: inline-block;\n}\n\n.object-value-null,\n.object-value-undefined {\n color: rgb(128, 128, 128);\n}\n\n.object-value {\n text-overflow: ellipsis;\n overflow: hidden;\n -webkit-user-select: text;\n}\n\n.object-value-calculate-value-button:hover {\n text-decoration: underline;\n}\n\n.object-properties-section-custom-section {\n display: inline-flex;\n flex-direction: column;\n}\n\n.-theme-with-dark-background .object-value-number,\n:host-context(.-theme-with-dark-background) .object-value-number,\n.-theme-with-dark-background .object-value-boolean,\n:host-context(.-theme-with-dark-background) .object-value-boolean {\n color: hsl(252, 100%, 75%);\n}\n\n.object-properties-section .object-description {\n color: gray;\n}\n\n.object-properties-preview {\n white-space: nowrap;\n}\n\n.name {\n color: rgb(136, 19, 145);\n flex-shrink: 0;\n}\n\n.object-properties-preview .name {\n color: #565656;\n}\n\n/*# sourceURL=object_ui/objectValue.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/perf_ui/perf_ui_module.js b/src/cobalt/debug/content/devtools/perf_ui/perf_ui_module.js deleted file mode 100644 index 3610f00..0000000 --- a/src/cobalt/debug/content/devtools/perf_ui/perf_ui_module.js +++ /dev/null
@@ -1,433 +0,0 @@ -PerfUI.LineLevelProfile=class{constructor(){this._locationPool=new Bindings.LiveLocationPool();this.reset();} -static instance(){if(!PerfUI.LineLevelProfile._instance) -PerfUI.LineLevelProfile._instance=new PerfUI.LineLevelProfile();return PerfUI.LineLevelProfile._instance;} -appendCPUProfile(profile){var nodesToGo=[profile.profileHead];var sampleDuration=(profile.profileEndTime-profile.profileStartTime)/profile.totalHitCount;while(nodesToGo.length){var nodes=nodesToGo.pop().children;for(var i=0;i<nodes.length;++i){var node=nodes[i];nodesToGo.push(node);if(!node.url||!node.positionTicks) -continue;var fileInfo=this._files.get(node.url);if(!fileInfo){fileInfo=new Map();this._files.set(node.url,fileInfo);} -for(var j=0;j<node.positionTicks.length;++j){var lineInfo=node.positionTicks[j];var line=lineInfo.line;var time=lineInfo.ticks*sampleDuration;fileInfo.set(line,(fileInfo.get(line)||0)+time);}}} -this._scheduleUpdate();} -reset(){this._files=new Map();this._scheduleUpdate();} -_scheduleUpdate(){if(this._updateTimer) -return;this._updateTimer=setTimeout(()=>{this._updateTimer=null;this._doUpdate();},0);} -_doUpdate(){this._locationPool.disposeAll();Workspace.workspace.uiSourceCodes().forEach(uiSourceCode=>uiSourceCode.removeDecorationsForType(PerfUI.LineLevelProfile.LineDecorator.type));for(var fileInfo of this._files){var url=(fileInfo[0]);var uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);if(!uiSourceCode) -continue;var target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode)||SDK.targetManager.mainTarget();var debuggerModel=target?target.model(SDK.DebuggerModel):null;if(!debuggerModel) -continue;for(var lineInfo of fileInfo[1]){var line=lineInfo[0]-1;var time=lineInfo[1];var rawLocation=debuggerModel.createRawLocationByURL(url,line,0);if(rawLocation) -new PerfUI.LineLevelProfile.Presentation(rawLocation,time,this._locationPool);else if(uiSourceCode) -uiSourceCode.addLineDecoration(line,PerfUI.LineLevelProfile.LineDecorator.type,time);}}}};PerfUI.LineLevelProfile.Presentation=class{constructor(rawLocation,time,locationPool){this._time=time;Bindings.debuggerWorkspaceBinding.createLiveLocation(rawLocation,this.updateLocation.bind(this),locationPool);} -updateLocation(liveLocation){if(this._uiLocation) -this._uiLocation.uiSourceCode.removeDecorationsForType(PerfUI.LineLevelProfile.LineDecorator.type);this._uiLocation=liveLocation.uiLocation();if(this._uiLocation){this._uiLocation.uiSourceCode.addLineDecoration(this._uiLocation.lineNumber,PerfUI.LineLevelProfile.LineDecorator.type,this._time);}}};PerfUI.LineLevelProfile.LineDecorator=class{decorate(uiSourceCode,textEditor){var gutterType='CodeMirror-gutter-performance';var decorations=uiSourceCode.decorationsForType(PerfUI.LineLevelProfile.LineDecorator.type);textEditor.uninstallGutter(gutterType);if(!decorations||!decorations.size) -return;textEditor.installGutter(gutterType,false);for(var decoration of decorations){var time=(decoration.data());var text=Common.UIString('%.1f\xa0ms',time);var intensity=Number.constrain(Math.log10(1+2*time)/5,0.02,1);var element=createElementWithClass('div','text-editor-line-marker-performance');element.textContent=text;element.style.backgroundColor=`hsla(44, 100%, 50%, ${intensity.toFixed(3)})`;textEditor.setGutterDecoration(decoration.range().startLine,gutterType,element);}}};PerfUI.LineLevelProfile.LineDecorator.type='performance';;PerfUI.FilmStripView=class extends UI.HBox{constructor(){super(true);this.registerRequiredCSS('perf_ui/filmStripView.css');this.contentElement.classList.add('film-strip-view');this._statusLabel=this.contentElement.createChild('div','label');this.reset();this.setMode(PerfUI.FilmStripView.Modes.TimeBased);} -static _setImageData(imageElement,data){if(data) -imageElement.src='data:image/jpg;base64,'+data;} -setMode(mode){this._mode=mode;this.contentElement.classList.toggle('time-based',mode===PerfUI.FilmStripView.Modes.TimeBased);this.update();} -setModel(filmStripModel,zeroTime,spanTime){this._model=filmStripModel;this._zeroTime=zeroTime;this._spanTime=spanTime;var frames=filmStripModel.frames();if(!frames.length){this.reset();return;} -this.update();} -createFrameElement(frame){var time=frame.timestamp;var element=createElementWithClass('div','frame');element.title=Common.UIString('Doubleclick to zoom image. Click to view preceding requests.');element.createChild('div','time').textContent=Number.millisToString(time-this._zeroTime);var imageElement=element.createChild('div','thumbnail').createChild('img');element.addEventListener('mousedown',this._onMouseEvent.bind(this,PerfUI.FilmStripView.Events.FrameSelected,time),false);element.addEventListener('mouseenter',this._onMouseEvent.bind(this,PerfUI.FilmStripView.Events.FrameEnter,time),false);element.addEventListener('mouseout',this._onMouseEvent.bind(this,PerfUI.FilmStripView.Events.FrameExit,time),false);element.addEventListener('dblclick',this._onDoubleClick.bind(this,frame),false);return frame.imageDataPromise().then(PerfUI.FilmStripView._setImageData.bind(null,imageElement)).then(returnElement);function returnElement(){return element;}} -frameByTime(time){function comparator(time,frame){return time-frame.timestamp;} -var frames=this._model.frames();var index=Math.max(frames.upperBound(time,comparator)-1,0);return frames[index];} -update(){if(!this._model) -return;var frames=this._model.frames();if(!frames.length) -return;if(this._mode===PerfUI.FilmStripView.Modes.FrameBased){Promise.all(frames.map(this.createFrameElement.bind(this))).then(appendElements.bind(this));return;} -var width=this.contentElement.clientWidth;var scale=this._spanTime/width;this.createFrameElement(frames[0]).then(continueWhenFrameImageLoaded.bind(this));function continueWhenFrameImageLoaded(element0){var frameWidth=Math.ceil(UI.measurePreferredSize(element0,this.contentElement).width);if(!frameWidth) -return;var promises=[];for(var pos=frameWidth;pos<width;pos+=frameWidth){var time=pos*scale+this._zeroTime;promises.push(this.createFrameElement(this.frameByTime(time)).then(fixWidth));} -Promise.all(promises).then(appendElements.bind(this));function fixWidth(element){element.style.width=frameWidth+'px';return element;}} -function appendElements(elements){this.contentElement.removeChildren();for(var i=0;i<elements.length;++i) -this.contentElement.appendChild(elements[i]);}} -onResize(){if(this._mode===PerfUI.FilmStripView.Modes.FrameBased) -return;this.update();} -_onMouseEvent(eventName,timestamp){this.dispatchEventToListeners(eventName,timestamp);} -_onDoubleClick(filmStripFrame){new PerfUI.FilmStripView.Dialog(filmStripFrame,this._zeroTime);} -reset(){this._zeroTime=0;this.contentElement.removeChildren();this.contentElement.appendChild(this._statusLabel);} -setStatusText(text){this._statusLabel.textContent=text;}};PerfUI.FilmStripView.Events={FrameSelected:Symbol('FrameSelected'),FrameEnter:Symbol('FrameEnter'),FrameExit:Symbol('FrameExit'),};PerfUI.FilmStripView.Modes={TimeBased:'TimeBased',FrameBased:'FrameBased'};PerfUI.FilmStripView.Dialog=class extends UI.VBox{constructor(filmStripFrame,zeroTime){super(true);this.registerRequiredCSS('perf_ui/filmStripDialog.css');this.contentElement.classList.add('filmstrip-dialog');this.contentElement.tabIndex=0;this._frames=filmStripFrame.model().frames();this._index=filmStripFrame.index;this._zeroTime=zeroTime||filmStripFrame.model().zeroTime();this._imageElement=this.contentElement.createChild('img');var footerElement=this.contentElement.createChild('div','filmstrip-dialog-footer');footerElement.createChild('div','flex-auto');var prevButton=UI.createTextButton('\u25C0',this._onPrevFrame.bind(this));prevButton.title=Common.UIString('Previous frame');footerElement.appendChild(prevButton);this._timeLabel=footerElement.createChild('div','filmstrip-dialog-label');var nextButton=UI.createTextButton('\u25B6',this._onNextFrame.bind(this));nextButton.title=Common.UIString('Next frame');footerElement.appendChild(nextButton);footerElement.createChild('div','flex-auto');this.contentElement.addEventListener('keydown',this._keyDown.bind(this),false);this.setDefaultFocusedElement(this.contentElement);this._render();} -_resize(){if(!this._dialog){this._dialog=new UI.Dialog();this.show(this._dialog.contentElement);this._dialog.show();} -this._dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);} -_keyDown(event){switch(event.key){case'ArrowLeft':if(Host.isMac()&&event.metaKey) -this._onFirstFrame();else -this._onPrevFrame();break;case'ArrowRight':if(Host.isMac()&&event.metaKey) -this._onLastFrame();else -this._onNextFrame();break;case'Home':this._onFirstFrame();break;case'End':this._onLastFrame();break;}} -_onPrevFrame(){if(this._index>0) ---this._index;this._render();} -_onNextFrame(){if(this._index<this._frames.length-1) -++this._index;this._render();} -_onFirstFrame(){this._index=0;this._render();} -_onLastFrame(){this._index=this._frames.length-1;this._render();} -_render(){var frame=this._frames[this._index];this._timeLabel.textContent=Number.millisToString(frame.timestamp-this._zeroTime);return frame.imageDataPromise().then(PerfUI.FilmStripView._setImageData.bind(null,this._imageElement)).then(this._resize.bind(this));}};;PerfUI.ChartViewportDelegate=function(){};PerfUI.ChartViewportDelegate.prototype={requestWindowTimes(startTime,endTime){},updateRangeSelection(startTime,endTime){},setSize(width,height){},update(){}};PerfUI.ChartViewport=class extends UI.VBox{constructor(delegate){super();this.registerRequiredCSS('perf_ui/chartViewport.css');this._delegate=delegate;this.viewportElement=this.contentElement.createChild('div','fill');this.viewportElement.addEventListener('mousemove',this._updateCursorPosition.bind(this),false);this.viewportElement.addEventListener('mouseout',this._onMouseOut.bind(this),false);this.viewportElement.addEventListener('mousewheel',this._onMouseWheel.bind(this),false);this.viewportElement.addEventListener('keydown',this._onChartKeyDown.bind(this),false);this.viewportElement.addEventListener('keyup',this._onChartKeyUp.bind(this),false);UI.installDragHandle(this.viewportElement,this._startDragging.bind(this),this._dragging.bind(this),this._endDragging.bind(this),'-webkit-grabbing',null);UI.installDragHandle(this.viewportElement,this._startRangeSelection.bind(this),this._rangeSelectionDragging.bind(this),this._endRangeSelection.bind(this),'text',null);this._alwaysShowVerticalScroll=false;this._vScrollElement=this.contentElement.createChild('div','chart-viewport-v-scroll');this._vScrollContent=this._vScrollElement.createChild('div');this._vScrollElement.addEventListener('scroll',this._onScroll.bind(this),false);this._selectionOverlay=this.contentElement.createChild('div','chart-viewport-selection-overlay hidden');this._selectedTimeSpanLabel=this._selectionOverlay.createChild('div','time-span');this._cursorElement=this.contentElement.createChild('div','chart-cursor-element hidden');this.reset();} -alwaysShowVerticalScroll(){this._alwaysShowVerticalScroll=true;this._vScrollElement.classList.add('always-show-scrollbar');} -isDragging(){return this._isDragging;} -elementsToRestoreScrollPositionsFor(){return[this._vScrollElement];} -_updateScrollBar(){const showScroll=this._alwaysShowVerticalScroll||this._totalHeight>this._offsetHeight;if(this._vScrollElement.classList.contains('hidden')!==showScroll) -return;this._vScrollElement.classList.toggle('hidden',!showScroll);this._updateContentElementSize();} -onResize(){this._updateScrollBar();this._updateContentElementSize();this.scheduleUpdate();} -reset(){this._vScrollElement.scrollTop=0;this._scrollTop=0;this._rangeSelectionStart=0;this._rangeSelectionEnd=0;this._isDragging=false;this._dragStartPointX=0;this._dragStartPointY=0;this._dragStartScrollTop=0;this._timeWindowLeft=0;this._timeWindowRight=0;this._offsetWidth=0;this._offsetHeight=0;this._totalHeight=0;this._pendingAnimationTimeLeft=0;this._pendingAnimationTimeRight=0;this._updateContentElementSize();} -_updateContentElementSize(){var offsetWidth=this._vScrollElement.offsetLeft;if(!offsetWidth) -offsetWidth=this.contentElement.offsetWidth;this._offsetWidth=offsetWidth;this._offsetHeight=this.contentElement.offsetHeight;this._delegate.setSize(this._offsetWidth,this._offsetHeight);} -setContentHeight(totalHeight){this._totalHeight=totalHeight;this._vScrollContent.style.height=totalHeight+'px';this._updateScrollBar();if(this._scrollTop+this._offsetHeight<=totalHeight) -return;this._scrollTop=Math.max(0,totalHeight-this._offsetHeight);this._vScrollElement.scrollTop=this._scrollTop;} -setScrollOffset(offset,height){height=height||0;if(this._vScrollElement.scrollTop>offset) -this._vScrollElement.scrollTop=offset;else if(this._vScrollElement.scrollTop<offset-this._offsetHeight+height) -this._vScrollElement.scrollTop=offset-this._offsetHeight+height;} -scrollOffset(){return this._vScrollElement.scrollTop;} -setBoundaries(zeroTime,totalTime){this._minimumBoundary=zeroTime;this._totalTime=totalTime;} -_onMouseWheel(e){var doZoomInstead=e.shiftKey^(Common.moduleSetting('flamechartMouseWheelAction').get()==='zoom');var panVertically=!doZoomInstead&&(e.wheelDeltaY||Math.abs(e.wheelDeltaX)===120);var panHorizontally=doZoomInstead&&Math.abs(e.wheelDeltaX)>Math.abs(e.wheelDeltaY);if(panVertically){this._vScrollElement.scrollTop-=(e.wheelDeltaY||e.wheelDeltaX)/120*this._offsetHeight/8;}else if(panHorizontally){this._muteAnimation=true;this._handlePanGesture(-e.wheelDeltaX);this._muteAnimation=false;}else{const mouseWheelZoomSpeed=1/120;this._handleZoomGesture(Math.pow(1.2,-(e.wheelDeltaY||e.wheelDeltaX)*mouseWheelZoomSpeed)-1);} -e.consume(true);} -_startDragging(event){if(event.shiftKey) -return false;this._isDragging=true;this._dragStartPointX=event.pageX;this._dragStartPointY=event.pageY;this._dragStartScrollTop=this._vScrollElement.scrollTop;this.viewportElement.style.cursor='';return true;} -_dragging(event){var pixelShift=this._dragStartPointX-event.pageX;this._dragStartPointX=event.pageX;this._muteAnimation=true;this._handlePanGesture(pixelShift);this._muteAnimation=false;var pixelScroll=this._dragStartPointY-event.pageY;this._vScrollElement.scrollTop=this._dragStartScrollTop+pixelScroll;} -_endDragging(){this._isDragging=false;} -_startRangeSelection(event){if(!event.shiftKey) -return false;this._isDragging=true;this._selectionOffsetShiftX=event.offsetX-event.pageX;this._selectionOffsetShiftY=event.offsetY-event.pageY;this._selectionStartX=event.offsetX;var style=this._selectionOverlay.style;style.left=this._selectionStartX+'px';style.width='1px';this._selectedTimeSpanLabel.textContent='';this._selectionOverlay.classList.remove('hidden');return true;} -_endRangeSelection(){this._isDragging=false;} -hideRangeSelection(){this._selectionOverlay.classList.add('hidden');} -_rangeSelectionDragging(event){var x=Number.constrain(event.pageX+this._selectionOffsetShiftX,0,this._offsetWidth);var start=this.pixelToTime(this._selectionStartX);var end=this.pixelToTime(x);this._rangeSelectionStart=Math.min(start,end);this._rangeSelectionEnd=Math.max(start,end);this._updateRangeSelectionOverlay();this._delegate.updateRangeSelection(this._rangeSelectionStart,this._rangeSelectionEnd);} -_updateRangeSelectionOverlay(){var margin=100;var left=Number.constrain(this.timeToPosition(this._rangeSelectionStart),-margin,this._offsetWidth+margin);var right=Number.constrain(this.timeToPosition(this._rangeSelectionEnd),-margin,this._offsetWidth+margin);var style=this._selectionOverlay.style;style.left=left+'px';style.width=(right-left)+'px';var timeSpan=this._rangeSelectionEnd-this._rangeSelectionStart;this._selectedTimeSpanLabel.textContent=Number.preciseMillisToString(timeSpan,2);} -_onScroll(){this._scrollTop=this._vScrollElement.scrollTop;this.scheduleUpdate();} -_onMouseOut(){this._lastMouseOffsetX=-1;this._showCursor(false);} -_updateCursorPosition(e){this._showCursor(e.shiftKey);this._cursorElement.style.left=e.offsetX+'px';this._lastMouseOffsetX=e.offsetX;} -pixelToTime(x){return this.pixelToTimeOffset(x)+this._timeWindowLeft;} -pixelToTimeOffset(x){return x*(this._timeWindowRight-this._timeWindowLeft)/this._offsetWidth;} -timeToPosition(time){return Math.floor((time-this._timeWindowLeft)/(this._timeWindowRight-this._timeWindowLeft)*this._offsetWidth);} -timeToPixel(){return this._offsetWidth/(this._timeWindowRight-this._timeWindowLeft);} -_showCursor(visible){this._cursorElement.classList.toggle('hidden',!visible||this._isDragging);} -_onChartKeyDown(e){this._showCursor(e.shiftKey);this._handleZoomPanKeys(e);} -_onChartKeyUp(e){this._showCursor(e.shiftKey);} -_handleZoomPanKeys(e){if(!UI.KeyboardShortcut.hasNoModifiers(e)) -return;var zoomFactor=e.shiftKey?0.8:0.3;var panOffset=e.shiftKey?320:80;switch(e.code){case'KeyA':this._handlePanGesture(-panOffset);break;case'KeyD':this._handlePanGesture(panOffset);break;case'KeyW':this._handleZoomGesture(-zoomFactor);break;case'KeyS':this._handleZoomGesture(zoomFactor);break;default:return;} -e.consume(true);} -_handleZoomGesture(zoom){this._cancelAnimation();var bounds={left:this._timeWindowLeft,right:this._timeWindowRight};var cursorTime=this.pixelToTime(this._lastMouseOffsetX);bounds.left+=(bounds.left-cursorTime)*zoom;bounds.right+=(bounds.right-cursorTime)*zoom;this._requestWindowTimes(bounds);} -_handlePanGesture(offset){this._cancelAnimation();var bounds={left:this._timeWindowLeft,right:this._timeWindowRight};var timeOffset=Number.constrain(this.pixelToTimeOffset(offset),this._minimumBoundary-bounds.left,this._totalTime+this._minimumBoundary-bounds.right);bounds.left+=timeOffset;bounds.right+=timeOffset;this._requestWindowTimes(bounds);} -_requestWindowTimes(bounds){var maxBound=this._minimumBoundary+this._totalTime;if(bounds.left<this._minimumBoundary){bounds.right=Math.min(bounds.right+this._minimumBoundary-bounds.left,maxBound);bounds.left=this._minimumBoundary;}else if(bounds.right>maxBound){bounds.left=Math.max(bounds.left-bounds.right+maxBound,this._minimumBoundary);bounds.right=maxBound;} -if(bounds.right-bounds.left<PerfUI.FlameChart.MinimalTimeWindowMs) -return;this._delegate.requestWindowTimes(bounds.left,bounds.right);} -_cancelAnimation(){if(!this._cancelWindowTimesAnimation) -return;this._timeWindowLeft=this._pendingAnimationTimeLeft;this._timeWindowRight=this._pendingAnimationTimeRight;this._cancelWindowTimesAnimation();delete this._cancelWindowTimesAnimation;} -scheduleUpdate(){if(this._updateTimerId||this._cancelWindowTimesAnimation) -return;this._updateTimerId=this.element.window().requestAnimationFrame(()=>{this._updateTimerId=0;this._update();});} -_update(){this._delegate.update();} -setWindowTimes(startTime,endTime){this.hideRangeSelection();if(this._muteAnimation||this._timeWindowLeft===0||this._timeWindowRight===Infinity||(startTime===0&&endTime===Infinity)||(startTime===Infinity&&endTime===Infinity)){this._timeWindowLeft=startTime;this._timeWindowRight=endTime;this.scheduleUpdate();return;} -this._cancelAnimation();this._cancelWindowTimesAnimation=UI.animateFunction(this.element.window(),animateWindowTimes.bind(this),[{from:this._timeWindowLeft,to:startTime},{from:this._timeWindowRight,to:endTime}],5,()=>delete this._cancelWindowTimesAnimation);this._pendingAnimationTimeLeft=startTime;this._pendingAnimationTimeRight=endTime;function animateWindowTimes(startTime,endTime){this._timeWindowLeft=startTime;this._timeWindowRight=endTime;this._update();}}};;PerfUI.FlameChartDelegate=function(){};PerfUI.FlameChartDelegate.prototype={requestWindowTimes(startTime,endTime){},updateRangeSelection(startTime,endTime){},};PerfUI.FlameChart=class extends UI.VBox{constructor(dataProvider,flameChartDelegate,groupExpansionSetting){super(true);this.registerRequiredCSS('perf_ui/flameChart.css');this.contentElement.classList.add('flame-chart-main-pane');this._groupExpansionSetting=groupExpansionSetting;this._groupExpansionState=groupExpansionSetting&&groupExpansionSetting.get()||{};this._flameChartDelegate=flameChartDelegate;this._chartViewport=new PerfUI.ChartViewport(this);this._chartViewport.show(this.contentElement);this._dataProvider=dataProvider;this._calculator=new PerfUI.FlameChart.Calculator(dataProvider);this._viewportElement=this._chartViewport.viewportElement;this._canvas=(this._viewportElement.createChild('canvas'));this._canvas.tabIndex=1;this.setDefaultFocusedElement(this._canvas);this._canvas.addEventListener('mousemove',this._onMouseMove.bind(this),false);this._canvas.addEventListener('mouseout',this._onMouseOut.bind(this),false);this._canvas.addEventListener('click',this._onClick.bind(this),false);this._canvas.addEventListener('keydown',this._onKeyDown.bind(this),false);this._entryInfo=this._viewportElement.createChild('div','flame-chart-entry-info');this._markerHighlighElement=this._viewportElement.createChild('div','flame-chart-marker-highlight-element');this._highlightElement=this._viewportElement.createChild('div','flame-chart-highlight-element');this._selectedElement=this._viewportElement.createChild('div','flame-chart-selected-element');UI.installDragHandle(this._viewportElement,this._startDragging.bind(this),this._dragging.bind(this),this._endDragging.bind(this),null);this._rulerEnabled=true;this._windowLeft=0.0;this._windowRight=1.0;this._timeWindowLeft=dataProvider.minimumBoundary();this._timeWindowRight=this._timeWindowLeft+dataProvider.totalTime();this._rangeSelectionStart=0;this._rangeSelectionEnd=0;this._barHeight=17;this._textBaseline=5;this._textPadding=5;this._markerRadius=6;this._chartViewport.setWindowTimes(this._timeWindowLeft,this._timeWindowRight);this._headerLeftPadding=6;this._arrowSide=8;this._expansionArrowIndent=this._headerLeftPadding+this._arrowSide/2;this._headerLabelXPadding=3;this._headerLabelYPadding=2;this._highlightedMarkerIndex=-1;this._highlightedEntryIndex=-1;this._selectedEntryIndex=-1;this._rawTimelineDataLength=0;this._textWidth=new Map();this._lastMouseOffsetX=0;} -willHide(){this.hideHighlight();} -setBarHeight(value){this._barHeight=value;} -setTextBaseline(value){this._textBaseline=value;} -setTextPadding(value){this._textPadding=value;} -enableRuler(enable){this._rulerEnabled=enable;} -alwaysShowVerticalScroll(){this._chartViewport.alwaysShowVerticalScroll();} -highlightEntry(entryIndex){if(this._highlightedEntryIndex===entryIndex) -return;if(!this._dataProvider.entryColor(entryIndex)) -return;this._highlightedEntryIndex=entryIndex;this._updateElementPosition(this._highlightElement,this._highlightedEntryIndex);this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntryHighlighted,entryIndex);} -hideHighlight(){this._entryInfo.removeChildren();this._highlightedEntryIndex=-1;this._updateElementPosition(this._highlightElement,this._highlightedEntryIndex);this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntryHighlighted,-1);} -_resetCanvas(){var ratio=window.devicePixelRatio;var width=Math.round(this._offsetWidth*ratio);var height=Math.round(this._offsetHeight*ratio);this._canvas.width=width;this._canvas.height=height;this._canvas.style.width=`${width / ratio}px`;this._canvas.style.height=`${height / ratio}px`;} -requestWindowTimes(startTime,endTime){this._flameChartDelegate.requestWindowTimes(startTime,endTime);} -updateRangeSelection(startTime,endTime){this._flameChartDelegate.updateRangeSelection(startTime,endTime);} -setSize(width,height){this._offsetWidth=width;this._offsetHeight=height;} -_startDragging(event){this.hideHighlight();this._maxDragOffset=0;this._dragStartX=event.pageX;this._dragStartY=event.pageY;return true;} -_dragging(event){var dx=event.pageX-this._dragStartX;var dy=event.pageY-this._dragStartY;this._maxDragOffset=Math.max(this._maxDragOffset,Math.sqrt(dx*dx+dy*dy));} -_endDragging(event){this._updateHighlight();} -_timelineData(){if(!this._dataProvider) -return null;var timelineData=this._dataProvider.timelineData();if(timelineData!==this._rawTimelineData||timelineData.entryStartTimes.length!==this._rawTimelineDataLength) -this._processTimelineData(timelineData);return this._rawTimelineData;} -_revealEntry(entryIndex){var timelineData=this._timelineData();if(!timelineData) -return;var timeLeft=this._timeWindowLeft;var timeRight=this._timeWindowRight;var entryStartTime=timelineData.entryStartTimes[entryIndex];var entryTotalTime=timelineData.entryTotalTimes[entryIndex];var entryEndTime=entryStartTime+entryTotalTime;var minEntryTimeWindow=Math.min(entryTotalTime,timeRight-timeLeft);var level=timelineData.entryLevels[entryIndex];this._chartViewport.setScrollOffset(this._levelToOffset(level),this._levelHeight(level));var minVisibleWidthPx=30;var futurePixelToTime=(timeRight-timeLeft)/this._offsetWidth;minEntryTimeWindow=Math.max(minEntryTimeWindow,futurePixelToTime*minVisibleWidthPx);if(timeLeft>entryEndTime){var delta=timeLeft-entryEndTime+minEntryTimeWindow;this.requestWindowTimes(timeLeft-delta,timeRight-delta);}else if(timeRight<entryStartTime){var delta=entryStartTime-timeRight+minEntryTimeWindow;this.requestWindowTimes(timeLeft+delta,timeRight+delta);}} -setWindowTimes(startTime,endTime){this._chartViewport.setWindowTimes(startTime,endTime);this._timeWindowLeft=startTime;this._timeWindowRight=endTime;this._updateHighlight();} -_onMouseMove(event){this._lastMouseOffsetX=event.offsetX;this._lastMouseOffsetY=event.offsetY;if(!this._enabled()) -return;if(this._chartViewport.isDragging()) -return;if(this._coordinatesToGroupIndex(event.offsetX,event.offsetY)>=0){this.hideHighlight();this._viewportElement.style.cursor='pointer';return;} -this._updateHighlight();} -_updateHighlight(){var inDividersBar=this._lastMouseOffsetY<PerfUI.FlameChart.HeaderHeight;this._highlightedMarkerIndex=inDividersBar?this._markerIndexAtPosition(this._lastMouseOffsetX):-1;this._updateMarkerHighlight();var entryIndex=this._highlightedMarkerIndex===-1?this._coordinatesToEntryIndex(this._lastMouseOffsetX,this._lastMouseOffsetY):-1;if(entryIndex===-1){this.hideHighlight();return;} -if(this._chartViewport.isDragging()) -return;this._updatePopover(entryIndex);this._viewportElement.style.cursor=this._dataProvider.canJumpToEntry(entryIndex)?'pointer':'default';this.highlightEntry(entryIndex);} -_onMouseOut(){this._lastMouseOffsetX=-1;this._lastMouseOffsetY=-1;this.hideHighlight();} -_updatePopover(entryIndex){if(entryIndex===this._highlightedEntryIndex){this._updatePopoverOffset();return;} -this._entryInfo.removeChildren();var popoverElement=this._dataProvider.prepareHighlightedEntryInfo(entryIndex);if(popoverElement){this._entryInfo.appendChild(popoverElement);this._updatePopoverOffset();}} -_updatePopoverOffset(){var mouseX=this._lastMouseOffsetX;var mouseY=this._lastMouseOffsetY;var parentWidth=this._entryInfo.parentElement.clientWidth;var parentHeight=this._entryInfo.parentElement.clientHeight;var infoWidth=this._entryInfo.clientWidth;var infoHeight=this._entryInfo.clientHeight;var offsetX=10;var offsetY=6;var x;var y;for(var quadrant=0;quadrant<4;++quadrant){var dx=quadrant&2?-offsetX-infoWidth:offsetX;var dy=quadrant&1?-offsetY-infoHeight:offsetY;x=Number.constrain(mouseX+dx,0,parentWidth-infoWidth);y=Number.constrain(mouseY+dy,0,parentHeight-infoHeight);if(x>=mouseX||mouseX>=x+infoWidth||y>=mouseY||mouseY>=y+infoHeight) -break;} -this._entryInfo.style.left=x+'px';this._entryInfo.style.top=y+'px';} -_onClick(event){this.focus();var clickThreshold=5;if(this._maxDragOffset>clickThreshold) -return;var groupIndex=this._coordinatesToGroupIndex(event.offsetX,event.offsetY);if(groupIndex>=0){this._toggleGroupVisibility(groupIndex);return;} -this._chartViewport.hideRangeSelection();this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected,this._highlightedEntryIndex);} -_toggleGroupVisibility(groupIndex){if(!this._isGroupCollapsible(groupIndex)) -return;var groups=this._rawTimelineData.groups;var group=groups[groupIndex];group.expanded=!group.expanded;this._groupExpansionState[group.name]=group.expanded;if(this._groupExpansionSetting) -this._groupExpansionSetting.set(this._groupExpansionState);this._updateLevelPositions();this._updateHighlight();if(!group.expanded){var timelineData=this._timelineData();var level=timelineData.entryLevels[this._selectedEntryIndex];if(this._selectedEntryIndex>=0&&level>=group.startLevel&&(groupIndex>=groups.length-1||groups[groupIndex+1].startLevel>level)) -this._selectedEntryIndex=-1;} -this._updateHeight();this._resetCanvas();this._draw(this._offsetWidth,this._offsetHeight);} -_onKeyDown(e){this._handleSelectionNavigation(e);} -_handleSelectionNavigation(e){if(!UI.KeyboardShortcut.hasNoModifiers(e)) -return;if(this._selectedEntryIndex===-1) -return;var timelineData=this._timelineData();if(!timelineData) -return;function timeComparator(time,entryIndex){return time-timelineData.entryStartTimes[entryIndex];} -function entriesIntersect(entry1,entry2){var start1=timelineData.entryStartTimes[entry1];var start2=timelineData.entryStartTimes[entry2];var end1=start1+timelineData.entryTotalTimes[entry1];var end2=start2+timelineData.entryTotalTimes[entry2];return start1<end2&&start2<end1;} -var keys=UI.KeyboardShortcut.Keys;if(e.keyCode===keys.Left.code||e.keyCode===keys.Right.code){var level=timelineData.entryLevels[this._selectedEntryIndex];var levelIndexes=this._timelineLevels[level];var indexOnLevel=levelIndexes.lowerBound(this._selectedEntryIndex);indexOnLevel+=e.keyCode===keys.Left.code?-1:1;e.consume(true);if(indexOnLevel>=0&&indexOnLevel<levelIndexes.length) -this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected,levelIndexes[indexOnLevel]);return;} -if(e.keyCode===keys.Up.code||e.keyCode===keys.Down.code){e.consume(true);var level=timelineData.entryLevels[this._selectedEntryIndex];level+=e.keyCode===keys.Up.code?-1:1;if(level<0||level>=this._timelineLevels.length) -return;var entryTime=timelineData.entryStartTimes[this._selectedEntryIndex]+ -timelineData.entryTotalTimes[this._selectedEntryIndex]/2;var levelIndexes=this._timelineLevels[level];var indexOnLevel=levelIndexes.upperBound(entryTime,timeComparator)-1;if(!entriesIntersect(this._selectedEntryIndex,levelIndexes[indexOnLevel])){++indexOnLevel;if(indexOnLevel>=levelIndexes.length||!entriesIntersect(this._selectedEntryIndex,levelIndexes[indexOnLevel])) -return;} -this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected,levelIndexes[indexOnLevel]);}} -_coordinatesToEntryIndex(x,y){if(x<0||y<0) -return-1;var timelineData=this._timelineData();if(!timelineData) -return-1;y+=this._chartViewport.scrollOffset();var cursorLevel=this._visibleLevelOffsets.upperBound(y)-1;if(cursorLevel<0||!this._visibleLevels[cursorLevel]) -return-1;var offsetFromLevel=y-this._visibleLevelOffsets[cursorLevel];if(offsetFromLevel>this._levelHeight(cursorLevel)) -return-1;var entryStartTimes=timelineData.entryStartTimes;var entryTotalTimes=timelineData.entryTotalTimes;var entryIndexes=this._timelineLevels[cursorLevel];if(!entryIndexes||!entryIndexes.length) -return-1;function comparator(time,entryIndex){return time-entryStartTimes[entryIndex];} -var cursorTime=this._chartViewport.pixelToTime(x);var indexOnLevel=Math.max(entryIndexes.upperBound(cursorTime,comparator)-1,0);function checkEntryHit(entryIndex){if(entryIndex===undefined) -return false;var startTime=entryStartTimes[entryIndex];var startX=this._chartViewport.timeToPosition(startTime);var duration=entryTotalTimes[entryIndex];if(isNaN(duration)){var dx=startX-x;var dy=this._levelHeight(cursorLevel)/2-offsetFromLevel;return dx*dx+dy*dy<this._markerRadius*this._markerRadius;} -var endX=this._chartViewport.timeToPosition(startTime+duration);var barThresholdPx=3;return startX-barThresholdPx<x&&x<endX+barThresholdPx;} -var entryIndex=entryIndexes[indexOnLevel];if(checkEntryHit.call(this,entryIndex)) -return entryIndex;entryIndex=entryIndexes[indexOnLevel+1];if(checkEntryHit.call(this,entryIndex)) -return entryIndex;return-1;} -_coordinatesToGroupIndex(x,y){if(x<0||y<0) -return-1;y+=this._chartViewport.scrollOffset();var groups=this._rawTimelineData.groups||[];var group=this._groupOffsets.upperBound(y)-1;if(group<0||group>=groups.length||y-this._groupOffsets[group]>=groups[group].style.height) -return-1;var context=(this._canvas.getContext('2d'));context.save();context.font=groups[group].style.font;var right=this._headerLeftPadding+this._labelWidthForGroup(context,groups[group]);context.restore();if(x>right) -return-1;return group;} -_markerIndexAtPosition(x){var markers=this._timelineData().markers;if(!markers) -return-1;var accurracyOffsetPx=4;var time=this._chartViewport.pixelToTime(x);var leftTime=this._chartViewport.pixelToTime(x-accurracyOffsetPx);var rightTime=this._chartViewport.pixelToTime(x+accurracyOffsetPx);var left=this._markerIndexBeforeTime(leftTime);var markerIndex=-1;var distance=Infinity;for(var i=left;i<markers.length&&markers[i].startTime()<rightTime;i++){var nextDistance=Math.abs(markers[i].startTime()-time);if(nextDistance<distance){markerIndex=i;distance=nextDistance;}} -return markerIndex;} -_markerIndexBeforeTime(time){return this._timelineData().markers.lowerBound(time,(markerTimestamp,marker)=>markerTimestamp-marker.startTime());} -_draw(width,height){var timelineData=this._timelineData();if(!timelineData) -return;var context=(this._canvas.getContext('2d'));context.save();var ratio=window.devicePixelRatio;var top=this._chartViewport.scrollOffset();context.scale(ratio,ratio);context.translate(0,-top);var defaultFont='11px '+Host.fontFamily();context.font=defaultFont;var entryTotalTimes=timelineData.entryTotalTimes;var entryStartTimes=timelineData.entryStartTimes;var entryLevels=timelineData.entryLevels;var timeToPixel=this._chartViewport.timeToPixel();var titleIndices=[];var markerIndices=[];var textPadding=this._textPadding;var minTextWidth=2*textPadding+UI.measureTextWidth(context,'\u2026');var minVisibleBarLevel=Math.max(this._visibleLevelOffsets.upperBound(top)-1,0);var colorBuckets=new Map();for(var level=minVisibleBarLevel;level<this._dataProvider.maxStackDepth();++level){if(this._levelToOffset(level)>top+height) -break;if(!this._visibleLevels[level]) -continue;var levelIndexes=this._timelineLevels[level];var rightIndexOnLevel=levelIndexes.lowerBound(this._timeWindowRight,(time,entryIndex)=>time-entryStartTimes[entryIndex])-1;var lastDrawOffset=Infinity;for(var entryIndexOnLevel=rightIndexOnLevel;entryIndexOnLevel>=0;--entryIndexOnLevel){var entryIndex=levelIndexes[entryIndexOnLevel];var entryStartTime=entryStartTimes[entryIndex];var entryOffsetRight=entryStartTime+(entryTotalTimes[entryIndex]||0);if(entryOffsetRight<=this._timeWindowLeft) -break;var barX=this._timeToPositionClipped(entryStartTime);if(barX>=lastDrawOffset) -continue;lastDrawOffset=barX;var color=this._dataProvider.entryColor(entryIndex);var bucket=colorBuckets.get(color);if(!bucket){bucket=[];colorBuckets.set(color,bucket);} -bucket.push(entryIndex);}} -var colors=colorBuckets.keysArray();for(var c=0;c<colors.length;++c){var color=colors[c];var indexes=colorBuckets.get(color);context.beginPath();for(var i=0;i<indexes.length;++i){var entryIndex=indexes[i];var entryStartTime=entryStartTimes[entryIndex];var barX=this._timeToPositionClipped(entryStartTime);var duration=entryTotalTimes[entryIndex];var barLevel=entryLevels[entryIndex];var barHeight=this._levelHeight(barLevel);var barY=this._levelToOffset(barLevel);if(isNaN(duration)){context.moveTo(barX+this._markerRadius,barY+barHeight/2);context.arc(barX,barY+barHeight/2,this._markerRadius,0,Math.PI*2);markerIndices.push(entryIndex);continue;} -var barRight=this._timeToPositionClipped(entryStartTime+duration);var barWidth=Math.max(barRight-barX,1);if(color) -context.rect(barX,barY,barWidth-0.4,barHeight-1);if(barWidth>minTextWidth||this._dataProvider.forceDecoration(entryIndex)) -titleIndices.push(entryIndex);} -if(!color) -continue;context.fillStyle=color;context.fill();} -context.beginPath();for(var m=0;m<markerIndices.length;++m){var entryIndex=markerIndices[m];var entryStartTime=entryStartTimes[entryIndex];var barX=this._timeToPositionClipped(entryStartTime);var barLevel=entryLevels[entryIndex];var y=this._levelToOffset(barLevel)+this._levelHeight(barLevel)/2;context.moveTo(barX+this._markerRadius,y);context.arc(barX,y,this._markerRadius,0,Math.PI*2);} -context.strokeStyle='rgba(0, 0, 0, 0.2)';context.stroke();context.textBaseline='alphabetic';for(var i=0;i<titleIndices.length;++i){var entryIndex=titleIndices[i];var entryStartTime=entryStartTimes[entryIndex];var barX=this._timeToPositionClipped(entryStartTime);var barRight=Math.min(this._timeToPositionClipped(entryStartTime+entryTotalTimes[entryIndex]),width)+1;var barWidth=barRight-barX;var barLevel=entryLevels[entryIndex];var barY=this._levelToOffset(barLevel);var text=this._dataProvider.entryTitle(entryIndex);if(text&&text.length){context.font=this._dataProvider.entryFont(entryIndex)||defaultFont;text=UI.trimTextMiddle(context,text,barWidth-2*textPadding);} -var unclippedBarX=this._chartViewport.timeToPosition(entryStartTime);var barHeight=this._levelHeight(barLevel);if(this._dataProvider.decorateEntry(entryIndex,context,text,barX,barY,barWidth,barHeight,unclippedBarX,timeToPixel)) -continue;if(!text||!text.length) -continue;context.fillStyle=this._dataProvider.textColor(entryIndex);context.fillText(text,barX+textPadding,barY+barHeight-this._textBaseline);} -context.restore();this._drawGroupHeaders(width,height);this._drawFlowEvents(context,width,height);this._drawMarkers();var dividersData=PerfUI.TimelineGrid.calculateDividerOffsets(this._calculator);PerfUI.TimelineGrid.drawCanvasGrid(context,dividersData);if(this._rulerEnabled){PerfUI.TimelineGrid.drawCanvasHeaders(context,dividersData,time=>this._calculator.formatValue(time,dividersData.precision),3,PerfUI.FlameChart.HeaderHeight);} -this._updateElementPosition(this._highlightElement,this._highlightedEntryIndex);this._updateElementPosition(this._selectedElement,this._selectedEntryIndex);this._updateMarkerHighlight();} -_drawGroupHeaders(width,height){var context=(this._canvas.getContext('2d'));var top=this._chartViewport.scrollOffset();var ratio=window.devicePixelRatio;var groups=this._rawTimelineData.groups||[];if(!groups.length) -return;var groupOffsets=this._groupOffsets;var lastGroupOffset=Array.prototype.peekLast.call(groupOffsets);var colorUsage=UI.ThemeSupport.ColorUsage;context.save();context.scale(ratio,ratio);context.translate(0,-top);var defaultFont='11px '+Host.fontFamily();context.font=defaultFont;context.fillStyle=UI.themeSupport.patchColorText('#fff',colorUsage.Background);forEachGroup.call(this,(offset,index,group)=>{var paddingHeight=group.style.padding;if(paddingHeight<5) -return;context.fillRect(0,offset-paddingHeight+2,width,paddingHeight-4);});if(groups.length&&lastGroupOffset<top+height) -context.fillRect(0,lastGroupOffset+2,width,top+height-lastGroupOffset);context.strokeStyle=UI.themeSupport.patchColorText('#eee',colorUsage.Background);context.beginPath();forEachGroup.call(this,(offset,index,group,isFirst)=>{if(isFirst||group.style.padding<4) -return;hLine(offset-2.5);});hLine(lastGroupOffset+1.5);context.stroke();forEachGroup.call(this,(offset,index,group)=>{if(group.style.useFirstLineForOverview) -return;if(!this._isGroupCollapsible(index)||group.expanded){if(!group.style.shareHeaderLine){context.fillStyle=group.style.backgroundColor;context.fillRect(0,offset,width,group.style.height);} -return;} -var nextGroup=index+1;while(nextGroup<groups.length&&groups[nextGroup].style.nestingLevel>group.style.nestingLevel) -nextGroup++;var endLevel=nextGroup<groups.length?groups[nextGroup].startLevel:this._dataProvider.maxStackDepth();this._drawCollapsedOverviewForGroup(group,offset+1,endLevel);});context.save();forEachGroup.call(this,(offset,index,group)=>{context.font=group.style.font;if(this._isGroupCollapsible(index)&&!group.expanded||group.style.shareHeaderLine){var width=this._labelWidthForGroup(context,group)+2;context.fillStyle=Common.Color.parse(group.style.backgroundColor).setAlpha(0.8).asString(null);context.fillRect(this._headerLeftPadding-this._headerLabelXPadding,offset+this._headerLabelYPadding,width,group.style.height-2*this._headerLabelYPadding);} -context.fillStyle=group.style.color;context.fillText(group.name,Math.floor(this._expansionArrowIndent*(group.style.nestingLevel+1)+this._arrowSide),offset+group.style.height-this._textBaseline);});context.restore();context.fillStyle=UI.themeSupport.patchColorText('#6e6e6e',colorUsage.Foreground);context.beginPath();forEachGroup.call(this,(offset,index,group)=>{if(this._isGroupCollapsible(index)){drawExpansionArrow.call(this,this._expansionArrowIndent*(group.style.nestingLevel+1),offset+group.style.height-this._textBaseline-this._arrowSide/2,!!group.expanded);}});context.fill();context.strokeStyle=UI.themeSupport.patchColorText('#ddd',colorUsage.Background);context.beginPath();context.stroke();context.restore();function hLine(y){context.moveTo(0,y);context.lineTo(width,y);} -function drawExpansionArrow(x,y,expanded){var arrowHeight=this._arrowSide*Math.sqrt(3)/2;var arrowCenterOffset=Math.round(arrowHeight/2);context.save();context.translate(x,y);context.rotate(expanded?Math.PI/2:0);context.moveTo(-arrowCenterOffset,-this._arrowSide/2);context.lineTo(-arrowCenterOffset,this._arrowSide/2);context.lineTo(arrowHeight-arrowCenterOffset,0);context.restore();} -function forEachGroup(callback){var groupStack=[{nestingLevel:-1,visible:true}];for(var i=0;i<groups.length;++i){var groupTop=groupOffsets[i];var group=groups[i];if(groupTop-group.style.padding>top+height) -break;var firstGroup=true;while(groupStack.peekLast().nestingLevel>=group.style.nestingLevel){groupStack.pop();firstGroup=false;} -var parentGroupVisible=groupStack.peekLast().visible;var thisGroupVisible=parentGroupVisible&&(!this._isGroupCollapsible(i)||group.expanded);groupStack.push({nestingLevel:group.style.nestingLevel,visible:thisGroupVisible});if(!parentGroupVisible||groupTop+group.style.height<top) -continue;callback(groupTop,i,group,firstGroup);}}} -_labelWidthForGroup(context,group){return UI.measureTextWidth(context,group.name)+this._expansionArrowIndent*(group.style.nestingLevel+1)+ -2*this._headerLabelXPadding;} -_drawCollapsedOverviewForGroup(group,y,endLevel){var range=new Common.SegmentedRange(mergeCallback);var timeWindowRight=this._timeWindowRight;var timeWindowLeft=this._timeWindowLeft;var context=(this._canvas.getContext('2d'));var barHeight=group.style.height;var entryStartTimes=this._rawTimelineData.entryStartTimes;var entryTotalTimes=this._rawTimelineData.entryTotalTimes;var timeToPixel=this._chartViewport.timeToPixel();for(var level=group.startLevel;level<endLevel;++level){var levelIndexes=this._timelineLevels[level];var rightIndexOnLevel=levelIndexes.lowerBound(timeWindowRight,(time,entryIndex)=>time-entryStartTimes[entryIndex])-1;var lastDrawOffset=Infinity;for(var entryIndexOnLevel=rightIndexOnLevel;entryIndexOnLevel>=0;--entryIndexOnLevel){var entryIndex=levelIndexes[entryIndexOnLevel];var entryStartTime=entryStartTimes[entryIndex];var barX=this._timeToPositionClipped(entryStartTime);var entryEndTime=entryStartTime+entryTotalTimes[entryIndex];if(isNaN(entryEndTime)||barX>=lastDrawOffset) -continue;if(entryEndTime<=timeWindowLeft) -break;lastDrawOffset=barX;var color=this._dataProvider.entryColor(entryIndex);var endBarX=this._timeToPositionClipped(entryEndTime);if(group.style.useDecoratorsForOverview&&this._dataProvider.forceDecoration(entryIndex)){var unclippedBarX=this._chartViewport.timeToPosition(entryStartTime);var barWidth=endBarX-barX;context.beginPath();context.fillStyle=color;context.fillRect(barX,y,barWidth,barHeight-1);this._dataProvider.decorateEntry(entryIndex,context,'',barX,y,barWidth,barHeight,unclippedBarX,timeToPixel);continue;} -range.append(new Common.Segment(barX,endBarX,color));}} -var segments=range.segments().slice().sort((a,b)=>a.data.localeCompare(b.data));var lastColor;context.beginPath();for(var i=0;i<segments.length;++i){var segment=segments[i];if(lastColor!==segments[i].data){context.fill();context.beginPath();lastColor=segments[i].data;context.fillStyle=lastColor;} -context.rect(segment.begin,y,segment.end-segment.begin,barHeight-1);} -context.fill();function mergeCallback(a,b){return a.data===b.data&&a.end+0.4>b.end?a:null;}} -_drawFlowEvents(context,width,height){context.save();var ratio=window.devicePixelRatio;var top=this._chartViewport.scrollOffset();var arrowWidth=6;context.scale(ratio,ratio);context.translate(0,-top);context.fillStyle='#7f5050';context.strokeStyle='#7f5050';var td=this._timelineData();var endIndex=td.flowStartTimes.lowerBound(this._timeWindowRight);context.lineWidth=0.5;for(var i=0;i<endIndex;++i){if(!td.flowEndTimes[i]||td.flowEndTimes[i]<this._timeWindowLeft) -continue;var startX=this._chartViewport.timeToPosition(td.flowStartTimes[i]);var endX=this._chartViewport.timeToPosition(td.flowEndTimes[i]);var startLevel=td.flowStartLevels[i];var endLevel=td.flowEndLevels[i];var startY=this._levelToOffset(startLevel)+this._levelHeight(startLevel)/2;var endY=this._levelToOffset(endLevel)+this._levelHeight(endLevel)/2;var segment=Math.min((endX-startX)/4,40);var distanceTime=td.flowEndTimes[i]-td.flowStartTimes[i];var distanceY=(endY-startY)/10;var spread=30;var lineY=distanceTime<1?startY:spread+Math.max(0,startY+distanceY*(i%spread));var p=[];p.push({x:startX,y:startY});p.push({x:startX+arrowWidth,y:startY});p.push({x:startX+segment+2*arrowWidth,y:startY});p.push({x:startX+segment,y:lineY});p.push({x:startX+segment*2,y:lineY});p.push({x:endX-segment*2,y:lineY});p.push({x:endX-segment,y:lineY});p.push({x:endX-segment-2*arrowWidth,y:endY});p.push({x:endX-arrowWidth,y:endY});context.beginPath();context.moveTo(p[0].x,p[0].y);context.lineTo(p[1].x,p[1].y);context.bezierCurveTo(p[2].x,p[2].y,p[3].x,p[3].y,p[4].x,p[4].y);context.lineTo(p[5].x,p[5].y);context.bezierCurveTo(p[6].x,p[6].y,p[7].x,p[7].y,p[8].x,p[8].y);context.stroke();context.beginPath();context.arc(startX,startY,2,-Math.PI/2,Math.PI/2,false);context.fill();context.beginPath();context.moveTo(endX,endY);context.lineTo(endX-arrowWidth,endY-3);context.lineTo(endX-arrowWidth,endY+3);context.fill();} -context.restore();} -_drawMarkers(){var markers=this._timelineData().markers;var left=this._markerIndexBeforeTime(this._calculator.minimumBoundary());var rightBoundary=this._calculator.maximumBoundary();var timeToPixel=this._chartViewport.timeToPixel();var context=(this._canvas.getContext('2d'));context.save();var ratio=window.devicePixelRatio;context.scale(ratio,ratio);context.translate(0,3);var height=PerfUI.FlameChart.HeaderHeight-1;for(var i=left;i<markers.length;i++){var timestamp=markers[i].startTime();if(timestamp>rightBoundary) -break;markers[i].draw(context,this._calculator.computePosition(timestamp),height,timeToPixel);} -context.restore();} -_updateMarkerHighlight(){var element=this._markerHighlighElement;if(element.parentElement) -element.remove();var markerIndex=this._highlightedMarkerIndex;if(markerIndex===-1) -return;var marker=this._timelineData().markers[markerIndex];var barX=this._timeToPositionClipped(marker.startTime());element.title=marker.title();var style=element.style;style.left=barX+'px';style.backgroundColor=marker.color();this._viewportElement.appendChild(element);} -_processTimelineData(timelineData){if(!timelineData){this._timelineLevels=null;this._visibleLevelOffsets=null;this._visibleLevels=null;this._groupOffsets=null;this._rawTimelineData=null;this._rawTimelineDataLength=0;return;} -this._rawTimelineData=timelineData;this._rawTimelineDataLength=timelineData.entryStartTimes.length;var entryCounters=new Uint32Array(this._dataProvider.maxStackDepth()+1);for(var i=0;i<timelineData.entryLevels.length;++i) -++entryCounters[timelineData.entryLevels[i]];var levelIndexes=new Array(entryCounters.length);for(var i=0;i<levelIndexes.length;++i){levelIndexes[i]=new Uint32Array(entryCounters[i]);entryCounters[i]=0;} -for(var i=0;i<timelineData.entryLevels.length;++i){var level=timelineData.entryLevels[i];levelIndexes[level][entryCounters[level]++]=i;} -this._timelineLevels=levelIndexes;var groups=this._rawTimelineData.groups||[];for(var i=0;i<groups.length;++i){var expanded=this._groupExpansionState[groups[i].name];if(expanded!==undefined) -groups[i].expanded=expanded;} -this._updateLevelPositions();this._updateHeight();} -_updateLevelPositions(){var levelCount=this._dataProvider.maxStackDepth();var groups=this._rawTimelineData.groups||[];this._visibleLevelOffsets=new Uint32Array(levelCount+1);this._visibleLevelHeights=new Uint32Array(levelCount);this._visibleLevels=new Uint16Array(levelCount);this._groupOffsets=new Uint32Array(groups.length+1);var groupIndex=-1;var currentOffset=this._rulerEnabled?PerfUI.FlameChart.HeaderHeight:2;var visible=true;var groupStack=[{nestingLevel:-1,visible:true}];var lastGroupLevel=Math.max(levelCount,groups.length?groups.peekLast().startLevel+1:0);for(var level=0;level<lastGroupLevel;++level){var parentGroupIsVisible=true;while(groupIndex<groups.length-1&&level===groups[groupIndex+1].startLevel){++groupIndex;var style=groups[groupIndex].style;var nextLevel=true;while(groupStack.peekLast().nestingLevel>=style.nestingLevel){groupStack.pop();nextLevel=false;} -var thisGroupIsVisible=groupIndex>=0&&this._isGroupCollapsible(groupIndex)?groups[groupIndex].expanded:true;parentGroupIsVisible=groupStack.peekLast().visible;visible=thisGroupIsVisible&&parentGroupIsVisible;groupStack.push({nestingLevel:style.nestingLevel,visible:visible});if(parentGroupIsVisible) -currentOffset+=nextLevel?0:style.padding;this._groupOffsets[groupIndex]=currentOffset;if(parentGroupIsVisible&&!style.shareHeaderLine) -currentOffset+=style.height;} -var isFirstOnLevel=groupIndex>=0&&level===groups[groupIndex].startLevel;var thisLevelIsVisible=parentGroupIsVisible&&(visible||isFirstOnLevel&&groups[groupIndex].style.useFirstLineForOverview);if(level<levelCount){var height;if(groupIndex>=0){var group=groups[groupIndex];var style=group.style;height=isFirstOnLevel&&!style.shareHeaderLine||(style.collapsible&&!group.expanded)?style.height:(style.itemsHeight||this._barHeight);}else{height=this._barHeight;} -this._visibleLevels[level]=thisLevelIsVisible;this._visibleLevelOffsets[level]=currentOffset;this._visibleLevelHeights[level]=height;} -if(thisLevelIsVisible||(parentGroupIsVisible&&style.shareHeaderLine&&isFirstOnLevel)) -currentOffset+=this._visibleLevelHeights[level];} -if(groupIndex>=0) -this._groupOffsets[groupIndex+1]=currentOffset;this._visibleLevelOffsets[level]=currentOffset;} -_isGroupCollapsible(index){var groups=this._rawTimelineData.groups||[];var style=groups[index].style;if(!style.shareHeaderLine||!style.collapsible) -return!!style.collapsible;var isLastGroup=index+1>=groups.length;if(!isLastGroup&&groups[index+1].style.nestingLevel>style.nestingLevel) -return true;var nextGroupLevel=isLastGroup?this._dataProvider.maxStackDepth():groups[index+1].startLevel;if(nextGroupLevel!==groups[index].startLevel+1) -return true;return style.height!==style.itemsHeight;} -setSelectedEntry(entryIndex){if(entryIndex===-1&&!this._chartViewport.isDragging()) -this._chartViewport.hideRangeSelection();if(this._selectedEntryIndex===entryIndex) -return;this._selectedEntryIndex=entryIndex;this._revealEntry(entryIndex);this._updateElementPosition(this._selectedElement,this._selectedEntryIndex);} -_updateElementPosition(element,entryIndex){var elementMinWidthPx=2;if(element.parentElement) -element.remove();if(entryIndex===-1) -return;var timelineData=this._timelineData();var startTime=timelineData.entryStartTimes[entryIndex];var endTime=startTime+(timelineData.entryTotalTimes[entryIndex]||0);var barX=this._timeToPositionClipped(startTime);var barRight=this._timeToPositionClipped(endTime);if(barRight===0||barX===this._offsetWidth) -return;var barWidth=barRight-barX;var barCenter=barX+barWidth/2;barWidth=Math.max(barWidth,elementMinWidthPx);barX=barCenter-barWidth/2;var entryLevel=timelineData.entryLevels[entryIndex];var barY=this._levelToOffset(entryLevel)-this._chartViewport.scrollOffset();var barHeight=this._levelHeight(entryLevel);var style=element.style;style.left=barX+'px';style.top=barY+'px';style.width=barWidth+'px';style.height=barHeight-1+'px';this._viewportElement.appendChild(element);} -_timeToPositionClipped(time){return Number.constrain(this._chartViewport.timeToPosition(time),0,this._offsetWidth);} -_levelToOffset(level){return this._visibleLevelOffsets[level];} -_levelHeight(level){return this._visibleLevelHeights[level];} -_updateBoundaries(){this._totalTime=this._dataProvider.totalTime();this._minimumBoundary=this._dataProvider.minimumBoundary();var windowWidth=1;if(this._timeWindowRight!==Infinity){this._windowLeft=(this._timeWindowLeft-this._minimumBoundary)/this._totalTime;this._windowRight=(this._timeWindowRight-this._minimumBoundary)/this._totalTime;windowWidth=this._windowRight-this._windowLeft;}else if(this._timeWindowLeft===Infinity){this._windowLeft=Infinity;this._windowRight=Infinity;}else{this._windowLeft=0;this._windowRight=1;} -var totalPixels=Math.floor(this._offsetWidth/windowWidth);this._pixelWindowLeft=Math.floor(totalPixels*this._windowLeft);this._chartViewport.setBoundaries(this._minimumBoundary,this._totalTime);} -_updateHeight(){var height=this._levelToOffset(this._dataProvider.maxStackDepth());this._chartViewport.setContentHeight(height);} -onResize(){this.scheduleUpdate();} -update(){if(!this._timelineData()) -return;this._resetCanvas();this._updateHeight();this._updateBoundaries();this._calculator._updateBoundaries(this);this._draw(this._offsetWidth,this._offsetHeight);if(!this._chartViewport.isDragging()) -this._updateHighlight();} -reset(){this._chartViewport.reset();this._rawTimelineData=null;this._rawTimelineDataLength=0;this._highlightedMarkerIndex=-1;this._highlightedEntryIndex=-1;this._selectedEntryIndex=-1;this._textWidth=new Map();this._chartViewport.scheduleUpdate();} -scheduleUpdate(){this._chartViewport.scheduleUpdate();} -_enabled(){return this._rawTimelineDataLength!==0;}};PerfUI.FlameChart.HeaderHeight=15;PerfUI.FlameChart.MinimalTimeWindowMs=0.5;PerfUI.FlameChartDataProvider=function(){};PerfUI.FlameChart.Group;PerfUI.FlameChart.GroupStyle;PerfUI.FlameChart.TimelineData=class{constructor(entryLevels,entryTotalTimes,entryStartTimes,groups){this.entryLevels=entryLevels;this.entryTotalTimes=entryTotalTimes;this.entryStartTimes=entryStartTimes;this.groups=groups;this.markers=[];this.flowStartTimes=[];this.flowStartLevels=[];this.flowEndTimes=[];this.flowEndLevels=[];}};PerfUI.FlameChartDataProvider.prototype={minimumBoundary(){},totalTime(){},formatValue(value,precision){},maxStackDepth(){},timelineData(){},prepareHighlightedEntryInfo(entryIndex){},canJumpToEntry(entryIndex){},entryTitle(entryIndex){},entryFont(entryIndex){},entryColor(entryIndex){},decorateEntry(entryIndex,context,text,barX,barY,barWidth,barHeight,unclippedBarX,timeToPixelRatio){},forceDecoration(entryIndex){},textColor(entryIndex){},};PerfUI.FlameChartMarker=function(){};PerfUI.FlameChartMarker.prototype={startTime(){},color(){},title(){},draw(context,x,height,pixelsPerMillisecond){},};PerfUI.FlameChart.Events={EntrySelected:Symbol('EntrySelected'),EntryHighlighted:Symbol('EntryHighlighted')};PerfUI.FlameChart.Calculator=class{constructor(dataProvider){this._dataProvider=dataProvider;} -_updateBoundaries(mainPane){this._totalTime=mainPane._dataProvider.totalTime();this._zeroTime=mainPane._dataProvider.minimumBoundary();this._minimumBoundaries=this._zeroTime+mainPane._windowLeft*this._totalTime;this._maximumBoundaries=this._zeroTime+mainPane._windowRight*this._totalTime;this._width=mainPane._offsetWidth;this._timeToPixel=this._width/this.boundarySpan();} -computePosition(time){return Math.round((time-this._minimumBoundaries)*this._timeToPixel);} -formatValue(value,precision){return this._dataProvider.formatValue(value-this._zeroTime,precision);} -maximumBoundary(){return this._maximumBoundaries;} -minimumBoundary(){return this._minimumBoundaries;} -zeroTime(){return this._zeroTime;} -boundarySpan(){return this._maximumBoundaries-this._minimumBoundaries;}};;PerfUI.OverviewGrid=class{constructor(prefix){this.element=createElement('div');this.element.id=prefix+'-overview-container';this._grid=new PerfUI.TimelineGrid();this._grid.element.id=prefix+'-overview-grid';this._grid.setScrollTop(0);this.element.appendChild(this._grid.element);this._window=new PerfUI.OverviewGrid.Window(this.element,this._grid.dividersLabelBarElement);} -clientWidth(){return this.element.clientWidth;} -updateDividers(calculator){this._grid.updateDividers(calculator);} -addEventDividers(dividers){this._grid.addEventDividers(dividers);} -removeEventDividers(){this._grid.removeEventDividers();} -reset(){this._window.reset();} -windowLeft(){return this._window.windowLeft;} -windowRight(){return this._window.windowRight;} -setWindow(left,right){this._window._setWindow(left,right);} -addEventListener(eventType,listener,thisObject){return this._window.addEventListener(eventType,listener,thisObject);} -setClickHandler(clickHandler){this._window.setClickHandler(clickHandler);} -zoom(zoomFactor,referencePoint){this._window._zoom(zoomFactor,referencePoint);} -setResizeEnabled(enabled){this._window.setEnabled(enabled);}};PerfUI.OverviewGrid.MinSelectableSize=14;PerfUI.OverviewGrid.WindowScrollSpeedFactor=.3;PerfUI.OverviewGrid.ResizerOffset=3.5;PerfUI.OverviewGrid.Window=class extends Common.Object{constructor(parentElement,dividersLabelBarElement){super();this._parentElement=parentElement;UI.installDragHandle(this._parentElement,this._startWindowSelectorDragging.bind(this),this._windowSelectorDragging.bind(this),this._endWindowSelectorDragging.bind(this),'text',null);if(dividersLabelBarElement){UI.installDragHandle(dividersLabelBarElement,this._startWindowDragging.bind(this),this._windowDragging.bind(this),null,'-webkit-grabbing','-webkit-grab');} -this._parentElement.addEventListener('mousewheel',this._onMouseWheel.bind(this),true);this._parentElement.addEventListener('dblclick',this._resizeWindowMaximum.bind(this),true);UI.appendStyle(this._parentElement,'perf_ui/overviewGrid.css');this._leftResizeElement=parentElement.createChild('div','overview-grid-window-resizer');UI.installDragHandle(this._leftResizeElement,this._resizerElementStartDragging.bind(this),this._leftResizeElementDragging.bind(this),null,'ew-resize');this._rightResizeElement=parentElement.createChild('div','overview-grid-window-resizer');UI.installDragHandle(this._rightResizeElement,this._resizerElementStartDragging.bind(this),this._rightResizeElementDragging.bind(this),null,'ew-resize');this._leftCurtainElement=parentElement.createChild('div','window-curtain-left');this._rightCurtainElement=parentElement.createChild('div','window-curtain-right');this.reset();} -reset(){this.windowLeft=0.0;this.windowRight=1.0;this.setEnabled(true);this._updateCurtains();} -setEnabled(enabled){this._enabled=enabled;} -setClickHandler(clickHandler){this._clickHandler=clickHandler;} -_resizerElementStartDragging(event){if(!this._enabled) -return false;this._resizerParentOffsetLeft=event.pageX-event.offsetX-event.target.offsetLeft;event.stopPropagation();return true;} -_leftResizeElementDragging(event){this._resizeWindowLeft(event.pageX-this._resizerParentOffsetLeft);event.preventDefault();} -_rightResizeElementDragging(event){this._resizeWindowRight(event.pageX-this._resizerParentOffsetLeft);event.preventDefault();} -_startWindowSelectorDragging(event){if(!this._enabled) -return false;this._offsetLeft=this._parentElement.totalOffsetLeft();var position=event.x-this._offsetLeft;this._overviewWindowSelector=new PerfUI.OverviewGrid.WindowSelector(this._parentElement,position);return true;} -_windowSelectorDragging(event){this._overviewWindowSelector._updatePosition(event.x-this._offsetLeft);event.preventDefault();} -_endWindowSelectorDragging(event){var window=this._overviewWindowSelector._close(event.x-this._offsetLeft);delete this._overviewWindowSelector;var clickThreshold=3;if(window.end-window.start<clickThreshold){if(this._clickHandler&&this._clickHandler.call(null,event)) -return;var middle=window.end;window.start=Math.max(0,middle-PerfUI.OverviewGrid.MinSelectableSize/2);window.end=Math.min(this._parentElement.clientWidth,middle+PerfUI.OverviewGrid.MinSelectableSize/2);}else if(window.end-window.start<PerfUI.OverviewGrid.MinSelectableSize){if(this._parentElement.clientWidth-window.end>PerfUI.OverviewGrid.MinSelectableSize) -window.end=window.start+PerfUI.OverviewGrid.MinSelectableSize;else -window.start=window.end-PerfUI.OverviewGrid.MinSelectableSize;} -this._setWindowPosition(window.start,window.end);} -_startWindowDragging(event){this._dragStartPoint=event.pageX;this._dragStartLeft=this.windowLeft;this._dragStartRight=this.windowRight;event.stopPropagation();return true;} -_windowDragging(event){event.preventDefault();var delta=(event.pageX-this._dragStartPoint)/this._parentElement.clientWidth;if(this._dragStartLeft+delta<0) -delta=-this._dragStartLeft;if(this._dragStartRight+delta>1) -delta=1-this._dragStartRight;this._setWindow(this._dragStartLeft+delta,this._dragStartRight+delta);} -_resizeWindowLeft(start){if(start<10) -start=0;else if(start>this._rightResizeElement.offsetLeft-4) -start=this._rightResizeElement.offsetLeft-4;this._setWindowPosition(start,null);} -_resizeWindowRight(end){if(end>this._parentElement.clientWidth-10) -end=this._parentElement.clientWidth;else if(end<this._leftResizeElement.offsetLeft+PerfUI.OverviewGrid.MinSelectableSize) -end=this._leftResizeElement.offsetLeft+PerfUI.OverviewGrid.MinSelectableSize;this._setWindowPosition(null,end);} -_resizeWindowMaximum(){this._setWindowPosition(0,this._parentElement.clientWidth);} -_setWindow(windowLeft,windowRight){this.windowLeft=windowLeft;this.windowRight=windowRight;this._updateCurtains();this.dispatchEventToListeners(PerfUI.OverviewGrid.Events.WindowChanged);} -_updateCurtains(){var left=this.windowLeft;var right=this.windowRight;var width=right-left;var widthInPixels=width*this._parentElement.clientWidth;var minWidthInPixels=PerfUI.OverviewGrid.MinSelectableSize/2;if(widthInPixels<minWidthInPixels){var factor=minWidthInPixels/widthInPixels;left=((this.windowRight+this.windowLeft)-width*factor)/2;right=((this.windowRight+this.windowLeft)+width*factor)/2;} -this._leftResizeElement.style.left=(100*left).toFixed(2)+'%';this._rightResizeElement.style.left=(100*right).toFixed(2)+'%';this._leftCurtainElement.style.width=(100*left).toFixed(2)+'%';this._rightCurtainElement.style.width=(100*(1-right)).toFixed(2)+'%';} -_setWindowPosition(start,end){var clientWidth=this._parentElement.clientWidth;var windowLeft=typeof start==='number'?start/clientWidth:this.windowLeft;var windowRight=typeof end==='number'?end/clientWidth:this.windowRight;this._setWindow(windowLeft,windowRight);} -_onMouseWheel(event){if(!this._enabled) -return;if(typeof event.wheelDeltaY==='number'&&event.wheelDeltaY){const zoomFactor=1.1;const mouseWheelZoomSpeed=1/120;var reference=event.offsetX/event.target.clientWidth;this._zoom(Math.pow(zoomFactor,-event.wheelDeltaY*mouseWheelZoomSpeed),reference);} -if(typeof event.wheelDeltaX==='number'&&event.wheelDeltaX){var offset=Math.round(event.wheelDeltaX*PerfUI.OverviewGrid.WindowScrollSpeedFactor);var windowLeft=this._leftResizeElement.offsetLeft+PerfUI.OverviewGrid.ResizerOffset;var windowRight=this._rightResizeElement.offsetLeft+PerfUI.OverviewGrid.ResizerOffset;if(windowLeft-offset<0) -offset=windowLeft;if(windowRight-offset>this._parentElement.clientWidth) -offset=windowRight-this._parentElement.clientWidth;this._setWindowPosition(windowLeft-offset,windowRight-offset);event.preventDefault();}} -_zoom(factor,reference){var left=this.windowLeft;var right=this.windowRight;var windowSize=right-left;var newWindowSize=factor*windowSize;if(newWindowSize>1){newWindowSize=1;factor=newWindowSize/windowSize;} -left=reference+(left-reference)*factor;left=Number.constrain(left,0,1-newWindowSize);right=reference+(right-reference)*factor;right=Number.constrain(right,newWindowSize,1);this._setWindow(left,right);}};PerfUI.OverviewGrid.Events={WindowChanged:Symbol('WindowChanged')};PerfUI.OverviewGrid.WindowSelector=class{constructor(parent,position){this._startPosition=position;this._width=parent.offsetWidth;this._windowSelector=createElement('div');this._windowSelector.className='overview-grid-window-selector';this._windowSelector.style.left=this._startPosition+'px';this._windowSelector.style.right=this._width-this._startPosition+'px';parent.appendChild(this._windowSelector);} -_close(position){position=Math.max(0,Math.min(position,this._width));this._windowSelector.remove();return this._startPosition<position?{start:this._startPosition,end:position}:{start:position,end:this._startPosition};} -_updatePosition(position){position=Math.max(0,Math.min(position,this._width));if(position<this._startPosition){this._windowSelector.style.left=position+'px';this._windowSelector.style.right=this._width-this._startPosition+'px';}else{this._windowSelector.style.left=this._startPosition+'px';this._windowSelector.style.right=this._width-position+'px';}}};;PerfUI.PieChart=class{constructor(size,formatter,showTotal){this.element=createElement('div');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'perf_ui/pieChart.css');var root=this._shadowRoot.createChild('div','root');var svg=this._createSVGChild(root,'svg');this._group=this._createSVGChild(svg,'g');this._innerR=0.618;var strokeWidth=1/size;var circle=this._createSVGChild(this._group,'circle');circle.setAttribute('r',1);circle.setAttribute('stroke','hsl(0, 0%, 80%)');circle.setAttribute('fill','transparent');circle.setAttribute('stroke-width',strokeWidth);circle=this._createSVGChild(this._group,'circle');circle.setAttribute('r',this._innerR);circle.setAttribute('stroke','hsl(0, 0%, 80%)');circle.setAttribute('fill','transparent');circle.setAttribute('stroke-width',strokeWidth);this._foregroundElement=root.createChild('div','pie-chart-foreground');if(showTotal) -this._totalElement=this._foregroundElement.createChild('div','pie-chart-total');this._formatter=formatter;this._slices=[];this._lastAngle=-Math.PI/2;this._setSize(size);} -setTotal(totalValue){for(var i=0;i<this._slices.length;++i) -this._slices[i].remove();this._slices=[];this._totalValue=totalValue;this._lastAngle=-Math.PI/2;var totalString;if(totalValue) -totalString=this._formatter?this._formatter(totalValue):totalValue;else -totalString='';if(this._totalElement) -this._totalElement.textContent=totalString;} -_setSize(value){this._group.setAttribute('transform','scale('+(value/2)+') translate(1, 1) scale(0.99, 0.99)');var size=value+'px';this.element.style.width=size;this.element.style.height=size;} -addSlice(value,color){var sliceAngle=value/this._totalValue*2*Math.PI;if(!isFinite(sliceAngle)) -return;sliceAngle=Math.min(sliceAngle,2*Math.PI*0.9999);var path=this._createSVGChild(this._group,'path');var x1=Math.cos(this._lastAngle);var y1=Math.sin(this._lastAngle);this._lastAngle+=sliceAngle;var x2=Math.cos(this._lastAngle);var y2=Math.sin(this._lastAngle);var r2=this._innerR;var x3=x2*r2;var y3=y2*r2;var x4=x1*r2;var y4=y1*r2;var largeArc=sliceAngle>Math.PI?1:0;path.setAttribute('d',`M${x1},${y1} A1,1,0,${largeArc},1,${x2},${y2} L${x3},${y3} A${r2},${r2},0,${largeArc},0,${x4},${y4} Z`);path.setAttribute('fill',color);this._slices.push(path);} -_createSVGChild(parent,childType){var child=parent.ownerDocument.createElementNS('http://www.w3.org/2000/svg',childType);parent.appendChild(child);return child;}};;PerfUI.TimelineGrid=class{constructor(){this.element=createElement('div');UI.appendStyle(this.element,'perf_ui/timelineGrid.css');this._dividersElement=this.element.createChild('div','resources-dividers');this._gridHeaderElement=createElement('div');this._gridHeaderElement.classList.add('timeline-grid-header');this._eventDividersElement=this._gridHeaderElement.createChild('div','resources-event-dividers');this._dividersLabelBarElement=this._gridHeaderElement.createChild('div','resources-dividers-label-bar');this.element.appendChild(this._gridHeaderElement);} -static calculateDividerOffsets(calculator,freeZoneAtLeft){var minGridSlicePx=64;var clientWidth=calculator.computePosition(calculator.maximumBoundary());var dividersCount=clientWidth/minGridSlicePx;var gridSliceTime=calculator.boundarySpan()/dividersCount;var pixelsPerTime=clientWidth/calculator.boundarySpan();var logGridSliceTime=Math.ceil(Math.log(gridSliceTime)/Math.LN10);gridSliceTime=Math.pow(10,logGridSliceTime);if(gridSliceTime*pixelsPerTime>=5*minGridSlicePx) -gridSliceTime=gridSliceTime/5;if(gridSliceTime*pixelsPerTime>=2*minGridSlicePx) -gridSliceTime=gridSliceTime/2;var firstDividerTime=Math.ceil((calculator.minimumBoundary()-calculator.zeroTime())/gridSliceTime)*gridSliceTime+ -calculator.zeroTime();var lastDividerTime=calculator.maximumBoundary();lastDividerTime+=minGridSlicePx/pixelsPerTime;dividersCount=Math.ceil((lastDividerTime-firstDividerTime)/gridSliceTime);if(!gridSliceTime) -dividersCount=0;var offsets=[];for(var i=0;i<dividersCount;++i){var time=firstDividerTime+gridSliceTime*i;if(calculator.computePosition(time)<freeZoneAtLeft) -continue;offsets.push({position:Math.floor(calculator.computePosition(time)),time:time});} -return{offsets:offsets,precision:Math.max(0,-Math.floor(Math.log(gridSliceTime*1.01)/Math.LN10))};} -static drawCanvasGrid(context,dividersData){context.save();context.scale(window.devicePixelRatio,window.devicePixelRatio);var height=Math.floor(context.canvas.height/window.devicePixelRatio);context.strokeStyle=UI.themeSupport.patchColorText('rgba(0, 0, 0, 0.1)',UI.ThemeSupport.ColorUsage.Foreground);context.lineWidth=1;context.translate(0.5,0.5);context.beginPath();for(var offsetInfo of dividersData.offsets){context.moveTo(offsetInfo.position,0);context.lineTo(offsetInfo.position,height);} -context.stroke();context.restore();} -static drawCanvasHeaders(context,dividersData,formatTimeFunction,paddingTop,headerHeight,freeZoneAtLeft){context.save();context.scale(window.devicePixelRatio,window.devicePixelRatio);var width=Math.ceil(context.canvas.width/window.devicePixelRatio);context.beginPath();context.fillStyle=UI.themeSupport.patchColorText('rgba(255, 255, 255, 0.5)',UI.ThemeSupport.ColorUsage.Background);context.fillRect(0,0,width,headerHeight);context.fillStyle=UI.themeSupport.patchColorText('#333',UI.ThemeSupport.ColorUsage.Foreground);context.textBaseline='hanging';context.font='11px '+Host.fontFamily();var paddingRight=4;for(var offsetInfo of dividersData.offsets){var text=formatTimeFunction(offsetInfo.time);var textWidth=context.measureText(text).width;var textPosition=offsetInfo.position-textWidth-paddingRight;if(!freeZoneAtLeft||freeZoneAtLeft<textPosition) -context.fillText(text,textPosition,paddingTop);} -context.restore();} -get dividersElement(){return this._dividersElement;} -get dividersLabelBarElement(){return this._dividersLabelBarElement;} -removeDividers(){this._dividersElement.removeChildren();this._dividersLabelBarElement.removeChildren();} -updateDividers(calculator,freeZoneAtLeft){var dividersData=PerfUI.TimelineGrid.calculateDividerOffsets(calculator,freeZoneAtLeft);var dividerOffsets=dividersData.offsets;var precision=dividersData.precision;var dividersElementClientWidth=this._dividersElement.clientWidth;var divider=(this._dividersElement.firstChild);var dividerLabelBar=(this._dividersLabelBarElement.firstChild);for(var i=0;i<dividerOffsets.length;++i){if(!divider){divider=createElement('div');divider.className='resources-divider';this._dividersElement.appendChild(divider);dividerLabelBar=createElement('div');dividerLabelBar.className='resources-divider';var label=createElement('div');label.className='resources-divider-label';dividerLabelBar._labelElement=label;dividerLabelBar.appendChild(label);this._dividersLabelBarElement.appendChild(dividerLabelBar);} -var time=dividerOffsets[i].time;var position=dividerOffsets[i].position;dividerLabelBar._labelElement.textContent=calculator.formatValue(time,precision);var percentLeft=100*position/dividersElementClientWidth;divider.style.left=percentLeft+'%';dividerLabelBar.style.left=percentLeft+'%';divider=(divider.nextSibling);dividerLabelBar=(dividerLabelBar.nextSibling);} -while(divider){var nextDivider=divider.nextSibling;this._dividersElement.removeChild(divider);divider=nextDivider;} -while(dividerLabelBar){var nextDivider=dividerLabelBar.nextSibling;this._dividersLabelBarElement.removeChild(dividerLabelBar);dividerLabelBar=nextDivider;} -return true;} -addEventDivider(divider){this._eventDividersElement.appendChild(divider);} -addEventDividers(dividers){this._gridHeaderElement.removeChild(this._eventDividersElement);for(var divider of dividers) -this._eventDividersElement.appendChild(divider);this._gridHeaderElement.appendChild(this._eventDividersElement);} -removeEventDividers(){this._eventDividersElement.removeChildren();} -hideEventDividers(){this._eventDividersElement.classList.add('hidden');} -showEventDividers(){this._eventDividersElement.classList.remove('hidden');} -hideDividers(){this._dividersElement.classList.add('hidden');} -showDividers(){this._dividersElement.classList.remove('hidden');} -setScrollTop(scrollTop){this._dividersLabelBarElement.style.top=scrollTop+'px';this._eventDividersElement.style.top=scrollTop+'px';}};PerfUI.TimelineGrid.DividersData;PerfUI.TimelineGrid.Calculator=function(){};PerfUI.TimelineGrid.Calculator.prototype={computePosition(time){},formatValue(time,precision){},minimumBoundary(){},zeroTime(){},maximumBoundary(){},boundarySpan(){}};;PerfUI.TimelineOverviewPane=class extends UI.VBox{constructor(prefix){super();this.element.id=prefix+'-overview-pane';this._overviewCalculator=new PerfUI.TimelineOverviewCalculator();this._overviewGrid=new PerfUI.OverviewGrid(prefix);this.element.appendChild(this._overviewGrid.element);this._cursorArea=this._overviewGrid.element.createChild('div','overview-grid-cursor-area');this._cursorElement=this._overviewGrid.element.createChild('div','overview-grid-cursor-position');this._cursorArea.addEventListener('mousemove',this._onMouseMove.bind(this),true);this._cursorArea.addEventListener('mouseleave',this._hideCursor.bind(this),true);this._overviewGrid.setResizeEnabled(false);this._overviewGrid.addEventListener(PerfUI.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);this._overviewGrid.setClickHandler(this._onClick.bind(this));this._overviewControls=[];this._markers=new Map();this._overviewInfo=new PerfUI.TimelineOverviewPane.OverviewInfo(this._cursorElement);this._updateThrottler=new Common.Throttler(100);this._cursorEnabled=false;this._cursorPosition=0;this._lastWidth=0;} -_onMouseMove(event){if(!this._cursorEnabled) -return;this._cursorPosition=event.offsetX+event.target.offsetLeft;this._cursorElement.style.left=this._cursorPosition+'px';this._cursorElement.style.visibility='visible';this._overviewInfo.setContent(this._buildOverviewInfo());} -async _buildOverviewInfo(){var document=this.element.ownerDocument;var x=this._cursorPosition;var elements=await Promise.all(this._overviewControls.map(control=>control.overviewInfoPromise(x)));var fragment=document.createDocumentFragment();elements.remove(null);fragment.appendChildren.apply(fragment,elements);return fragment;} -_hideCursor(){this._cursorElement.style.visibility='hidden';this._overviewInfo.hide();} -wasShown(){this._update();} -willHide(){this._overviewInfo.hide();} -onResize(){var width=this.element.offsetWidth;if(width===this._lastWidth) -return;this._lastWidth=width;this.scheduleUpdate();} -setOverviewControls(overviewControls){for(var i=0;i<this._overviewControls.length;++i) -this._overviewControls[i].dispose();for(var i=0;i<overviewControls.length;++i){overviewControls[i].setCalculator(this._overviewCalculator);overviewControls[i].show(this._overviewGrid.element);} -this._overviewControls=overviewControls;this._update();} -setBounds(minimumBoundary,maximumBoundary){this._overviewCalculator.setBounds(minimumBoundary,maximumBoundary);this._overviewGrid.setResizeEnabled(true);this._cursorEnabled=true;} -scheduleUpdate(){this._updateThrottler.schedule(process.bind(this));function process(){this._update();return Promise.resolve();}} -_update(){if(!this.isShowing()) -return;this._overviewCalculator.setDisplayWidth(this._overviewGrid.clientWidth());for(var i=0;i<this._overviewControls.length;++i) -this._overviewControls[i].update();this._overviewGrid.updateDividers(this._overviewCalculator);this._updateMarkers();this._updateWindow();} -setMarkers(markers){this._markers=markers;} -_updateMarkers(){var filteredMarkers=new Map();for(var time of this._markers.keys()){var marker=this._markers.get(time);var position=Math.round(this._overviewCalculator.computePosition(time));if(filteredMarkers.has(position)) -continue;filteredMarkers.set(position,marker);marker.style.left=position+'px';} -this._overviewGrid.removeEventDividers();this._overviewGrid.addEventDividers(filteredMarkers.valuesArray());} -reset(){this._windowStartTime=0;this._windowEndTime=Infinity;this._overviewCalculator.reset();this._overviewGrid.reset();this._overviewGrid.setResizeEnabled(false);this._cursorEnabled=false;this._hideCursor();this._markers=new Map();for(var control of this._overviewControls) -control.reset();this._overviewInfo.hide();this.scheduleUpdate();} -_onClick(event){return this._overviewControls.some(control=>control.onClick(event));} -_onWindowChanged(event){if(this._muteOnWindowChanged) -return;if(!this._overviewControls.length) -return;var absoluteMin=this._overviewCalculator.minimumBoundary();var timeSpan=this._overviewCalculator.maximumBoundary()-absoluteMin;var windowTimes={startTime:absoluteMin+timeSpan*this._overviewGrid.windowLeft(),endTime:absoluteMin+timeSpan*this._overviewGrid.windowRight()};this._windowStartTime=windowTimes.startTime;this._windowEndTime=windowTimes.endTime;this.dispatchEventToListeners(PerfUI.TimelineOverviewPane.Events.WindowChanged,windowTimes);} -requestWindowTimes(startTime,endTime){if(startTime===this._windowStartTime&&endTime===this._windowEndTime) -return;this._windowStartTime=startTime;this._windowEndTime=endTime;this._updateWindow();this.dispatchEventToListeners(PerfUI.TimelineOverviewPane.Events.WindowChanged,{startTime:startTime,endTime:endTime});} -_updateWindow(){if(!this._overviewControls.length) -return;var absoluteMin=this._overviewCalculator.minimumBoundary();var timeSpan=this._overviewCalculator.maximumBoundary()-absoluteMin;var haveRecords=absoluteMin>0;var left=haveRecords&&this._windowStartTime?Math.min((this._windowStartTime-absoluteMin)/timeSpan,1):0;var right=haveRecords&&this._windowEndTime<Infinity?(this._windowEndTime-absoluteMin)/timeSpan:1;this._muteOnWindowChanged=true;this._overviewGrid.setWindow(left,right);this._muteOnWindowChanged=false;}};PerfUI.TimelineOverviewPane.Events={WindowChanged:Symbol('WindowChanged')};PerfUI.TimelineOverviewCalculator=class{constructor(){this.reset();} -computePosition(time){return(time-this._minimumBoundary)/this.boundarySpan()*this._workingArea;} -positionToTime(position){return position/this._workingArea*this.boundarySpan()+this._minimumBoundary;} -setBounds(minimumBoundary,maximumBoundary){this._minimumBoundary=minimumBoundary;this._maximumBoundary=maximumBoundary;} -setDisplayWidth(clientWidth){this._workingArea=clientWidth;} -reset(){this.setBounds(0,100);} -formatValue(value,precision){return Number.preciseMillisToString(value-this.zeroTime(),precision);} -maximumBoundary(){return this._maximumBoundary;} -minimumBoundary(){return this._minimumBoundary;} -zeroTime(){return this._minimumBoundary;} -boundarySpan(){return this._maximumBoundary-this._minimumBoundary;}};PerfUI.TimelineOverview=function(){};PerfUI.TimelineOverview.prototype={show(parentElement,insertBefore){},update(){},dispose(){},reset(){},overviewInfoPromise(x){},onClick(event){},};PerfUI.TimelineOverviewBase=class extends UI.VBox{constructor(){super();this._calculator=null;this._canvas=this.element.createChild('canvas','fill');this._context=this._canvas.getContext('2d');} -width(){return this._canvas.width;} -height(){return this._canvas.height;} -context(){return this._context;} -calculator(){return this._calculator;} -update(){this.resetCanvas();} -dispose(){this.detach();} -reset(){} -overviewInfoPromise(x){return Promise.resolve((null));} -setCalculator(calculator){this._calculator=calculator;} -onClick(event){return false;} -resetCanvas(){if(this.element.clientWidth) -this.setCanvasSize(this.element.clientWidth,this.element.clientHeight);} -setCanvasSize(width,height){this._canvas.width=width*window.devicePixelRatio;this._canvas.height=height*window.devicePixelRatio;}};PerfUI.TimelineOverviewPane.OverviewInfo=class{constructor(anchor){this._anchorElement=anchor;this._glassPane=new UI.GlassPane();this._glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.PierceContents);this._glassPane.setMarginBehavior(UI.GlassPane.MarginBehavior.Arrow);this._glassPane.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);this._visible=false;this._element=UI.createShadowRootWithCoreStyles(this._glassPane.contentElement,'perf_ui/timelineOverviewInfo.css').createChild('div','overview-info');} -async setContent(contentPromise){this._visible=true;var content=await contentPromise;if(!this._visible) -return;this._element.removeChildren();this._element.appendChild(content);this._glassPane.setContentAnchorBox(this._anchorElement.boxInWindow());if(!this._glassPane.isShowing()) -this._glassPane.show((this._anchorElement.ownerDocument));} -hide(){this._visible=false;this._glassPane.hide();}};;Runtime.cachedResources["perf_ui/chartViewport.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.chart-viewport-v-scroll {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n overflow-x: hidden;\n z-index: 200;\n padding-left: 1px;\n}\n\n.chart-viewport-v-scroll.always-show-scrollbar {\n overflow-y: scroll;\n}\n\n/* force non overlay scrollbars for Mac */\n:host-context(.platform-mac) .chart-viewport-v-scroll {\n right: 2px;\n top: 3px;\n bottom: 3px;\n}\n\n:host-context(.platform-mac) ::-webkit-scrollbar {\n width: 8px;\n}\n\n:host-context(.platform-mac) ::-webkit-scrollbar-thumb {\n background-color: hsla(0, 0%, 56%, 0.6);\n border-radius: 50px;\n}\n\n:host-context(.platform-mac) .chart-viewport-v-scroll:hover::-webkit-scrollbar-thumb {\n background-color: hsla(0, 0%, 25%, 0.6);\n}\n\n/* force non overlay scrollbars for Aura Overlay Scrollbar enabled */\n:host-context(.overlay-scrollbar-enabled) ::-webkit-scrollbar {\n width: 10px;\n}\n\n:host-context(.overlay-scrollbar-enabled) ::-webkit-scrollbar-thumb {\n background-color: hsla(0, 0%, 0%, 0.5);\n}\n\n:host-context(.overlay-scrollbar-enabled) .chart-viewport-v-scroll:hover::-webkit-scrollbar-thumb {\n background-color: hsla(0, 0%, 0%, 0.7);\n}\n\n.chart-viewport-selection-overlay {\n position: absolute;\n z-index: 100;\n background-color: rgba(56, 121, 217, 0.3);\n border-color: rgb(16, 81, 177);\n border-width: 0 1px;\n border-style: solid;\n pointer-events: none;\n top: 0;\n bottom: 0;\n text-align: center;\n}\n\n.chart-viewport-selection-overlay .time-span {\n white-space: nowrap;\n position: absolute;\n left: 0;\n right: 0;\n bottom: 0;\n}\n\n/*# sourceURL=perf_ui/chartViewport.css */";Runtime.cachedResources["perf_ui/filmStripView.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.film-strip-view {\n overflow-x: auto;\n overflow-y: hidden;\n align-content: flex-start;\n min-height: 81px;\n}\n\n.film-strip-view.time-based .frame .time {\n display: none;\n}\n\n.film-strip-view .label {\n margin: auto;\n font-size: 18px;\n color: #999;\n}\n\n.film-strip-view .frame {\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: 4px;\n flex: none;\n cursor: pointer;\n}\n\n.film-strip-view .frame-limit-reached {\n font-size: 24px;\n color: #888;\n justify-content: center;\n display: inline-flex;\n flex-direction: column;\n flex: none;\n}\n\n.film-strip-view .frame .thumbnail {\n min-width: 24px;\n display: flex;\n flex-direction: row;\n align-items: center;\n pointer-events: none;\n margin: 4px 0 2px;\n border: 2px solid transparent;\n}\n\n.film-strip-view .frame:hover .thumbnail {\n border-color: #FBCA46;\n}\n\n.film-strip-view .frame .thumbnail img {\n height: auto;\n width: auto;\n max-width: 80px;\n max-height: 50px;\n pointer-events: none;\n box-shadow: 0 0 3px #bbb;\n flex: 0 0 auto;\n}\n\n.film-strip-view .frame:hover .thumbnail img {\n box-shadow: none;\n}\n\n.film-strip-view .frame .time {\n font-size: 10px;\n margin-top: 2px;\n}\n\n/*# sourceURL=perf_ui/filmStripView.css */";Runtime.cachedResources["perf_ui/filmStripDialog.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n flex: none !important;\n}\n\n.filmstrip-dialog {\n margin: 12px;\n}\n\n.filmstrip-dialog > img {\n border: 1px solid #ddd;\n max-height: 80vh;\n max-width: 80vw;\n}\n\n.filmstrip-dialog-footer {\n display: flex;\n align-items: center;\n margin-top: 10px;\n}\n\n.filmstrip-dialog-label {\n margin: 8px 8px;\n}\n\n/*# sourceURL=perf_ui/filmStripDialog.css */";Runtime.cachedResources["perf_ui/flameChart.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.flame-chart-main-pane {\n overflow: hidden;\n}\n\n.flame-chart-marker-highlight-element {\n position: absolute;\n top: 1px;\n height: 18px;\n width: 6px;\n margin: 0 -3px;\n content: \"\";\n display: block;\n}\n\n.flame-chart-highlight-element {\n position: absolute;\n pointer-events: none;\n background-color: rgba(56, 121, 217, 0.1);\n}\n\n.flame-chart-selected-element {\n position: absolute;\n pointer-events: none;\n outline: 2px solid rgb(56, 121, 217);\n background-color: rgba(56, 121, 217, 0.1);\n}\n\n.chart-cursor-element {\n position: absolute;\n top: 0;\n bottom: 0;\n z-index: 100;\n width: 2px;\n background-color: rgb(56, 121, 217);\n pointer-events: none;\n}\n\n.flame-chart-entry-info:not(:empty) {\n z-index: 2000;\n position: absolute;\n background-color: white;\n pointer-events: none;\n padding: 4px 8px;\n white-space: nowrap;\n max-width: 80%;\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05),\n 0 2px 4px rgba(0, 0, 0, 0.2),\n 0 2px 6px rgba(0, 0, 0, 0.1);\n}\n\n.flame-chart-entry-info table tr td:empty {\n padding: 0;\n}\n\n.flame-chart-entry-info table tr td:not(:empty) {\n padding: 0 5px;\n white-space: nowrap;\n}\n\n.flame-chart-entry-info table tr td:first-child {\n font-weight: bold;\n}\n\n.flame-chart-entry-info table tr td span {\n margin-right: 5px;\n}\n\n/*# sourceURL=perf_ui/flameChart.css */";Runtime.cachedResources["perf_ui/overviewGrid.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.overview-grid-window-selector {\n position: absolute;\n top: 0;\n bottom: 0;\n background-color: rgba(125, 173, 217, 0.5);\n z-index: 250;\n pointer-events: none;\n}\n\n.overview-grid-window-resizer {\n position: absolute;\n top: -1px;\n height: 20px;\n width: 6px;\n margin-left: -3px;\n background-color: rgb(153, 153, 153);\n border: 1px solid white;\n z-index: 500;\n}\n\n.overview-grid-cursor-area {\n position: absolute;\n left: 0;\n right: 0;\n top: 20px;\n bottom: 0;\n z-index: 500;\n cursor: text;\n}\n\n.overview-grid-cursor-position {\n position: absolute;\n top: 0;\n bottom: 0;\n width: 2px;\n background-color: hsla(220, 95%, 50%, 0.7);\n z-index: 500;\n pointer-events: none;\n visibility: hidden;\n overflow: hidden;\n}\n\n.window-curtain-left, .window-curtain-right {\n background-color: hsla(0, 0%, 80%, 0.5);\n position: absolute;\n top: 0;\n height: 100%;\n z-index: 300;\n pointer-events: none;\n border: 1px none hsla(0, 0%, 70%, 0.5);\n}\n\n.window-curtain-left {\n left: 0;\n border-right-style: solid;\n}\n\n.window-curtain-right {\n right: 0;\n border-left-style: solid;\n}\n\n/*# sourceURL=perf_ui/overviewGrid.css */";Runtime.cachedResources["perf_ui/pieChart.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.root {\n position: relative;\n width: 100%;\n height: 100%;\n}\n\n.pie-chart-foreground {\n position: absolute;\n width: 100%;\n height: 100%;\n z-index: 10;\n top: 0;\n display: flex;\n}\n\n.pie-chart-total {\n margin: auto;\n padding: 2px 5px;\n background-color: rgba(255, 255, 255, 0.6);\n}\n\n/*# sourceURL=perf_ui/pieChart.css */";Runtime.cachedResources["perf_ui/timelineGrid.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.resources-dividers {\n position: absolute;\n left: 0;\n right: 0;\n top: 0;\n z-index: -100;\n bottom: 0;\n}\n\n.resources-event-dividers {\n position: absolute;\n left: 0;\n right: 0;\n height: 100%;\n top: 0;\n z-index: 300;\n pointer-events: none;\n}\n\n.resources-dividers-label-bar {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n background-color: rgba(255, 255, 255, 0.85);\n background-clip: padding-box;\n height: 20px;\n z-index: 200;\n pointer-events: none;\n overflow: hidden;\n}\n\n.resources-divider {\n position: absolute;\n width: 1px;\n top: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.1);\n}\n\n.resources-event-divider {\n position: absolute;\n width: 1px;\n top: 0;\n bottom: 0;\n z-index: 300;\n}\n\n.resources-divider-label {\n position: absolute;\n top: 4px;\n right: 3px;\n font-size: 80%;\n white-space: nowrap;\n pointer-events: none;\n}\n\n.timeline-grid-header {\n height: 20px;\n pointer-events: none;\n}\n\n/*# sourceURL=perf_ui/timelineGrid.css */";Runtime.cachedResources["perf_ui/timelineOverviewInfo.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.overview-info:not(:empty) {\n display: flex;\n background: white;\n box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2), 0 2px 4px rgba(0, 0, 0, 0.2), 0 2px 6px rgba(0, 0, 0, 0.1);\n padding: 3px;\n}\n\n.overview-info .frame .time {\n display: none;\n}\n\n.overview-info .frame .thumbnail img {\n max-width: 50vw;\n max-height: 50vh;\n}\n\n/*# sourceURL=perf_ui/timelineOverviewInfo.css */"; \ No newline at end of file
diff --git a/src/cobalt/debug/content/devtools/profiler/profiler_module.js b/src/cobalt/debug/content/devtools/profiler/profiler_module.js deleted file mode 100644 index 93fe660..0000000 --- a/src/cobalt/debug/content/devtools/profiler/profiler_module.js +++ /dev/null
@@ -1,1092 +0,0 @@ -Profiler.ProfileType=class extends Common.Object{constructor(id,name){super();this._id=id;this._name=name;this._profiles=[];this._profileBeingRecorded=null;this._nextProfileUid=1;if(!window.opener) -window.addEventListener('unload',this._clearTempStorage.bind(this),false);} -typeName(){return'';} -nextProfileUid(){return this._nextProfileUid;} -incrementProfileUid(){return this._nextProfileUid++;} -hasTemporaryView(){return false;} -fileExtension(){return null;} -get buttonTooltip(){return'';} -get id(){return this._id;} -get treeItemTitle(){return this._name;} -get name(){return this._name;} -buttonClicked(){return false;} -get description(){return'';} -isInstantProfile(){return false;} -isEnabled(){return true;} -getProfiles(){function isFinished(profile){return this._profileBeingRecorded!==profile;} -return this._profiles.filter(isFinished.bind(this));} -decorationElement(){return null;} -getProfile(uid){for(var i=0;i<this._profiles.length;++i){if(this._profiles[i].uid===uid) -return this._profiles[i];} -return null;} -loadFromFile(file){var name=file.name;var fileExtension=this.fileExtension();if(fileExtension&&name.endsWith(fileExtension)) -name=name.substr(0,name.length-fileExtension.length);var profile=this.createProfileLoadedFromFile(name);profile.setFromFile();this.setProfileBeingRecorded(profile);this.addProfile(profile);return profile.loadFromFile(file);} -createProfileLoadedFromFile(title){throw new Error('Needs implemented.');} -addProfile(profile){this._profiles.push(profile);this.dispatchEventToListeners(Profiler.ProfileType.Events.AddProfileHeader,profile);} -removeProfile(profile){var index=this._profiles.indexOf(profile);if(index===-1) -return;this._profiles.splice(index,1);this._disposeProfile(profile);} -_clearTempStorage(){for(var i=0;i<this._profiles.length;++i) -this._profiles[i].removeTempFile();} -profileBeingRecorded(){return this._profileBeingRecorded;} -setProfileBeingRecorded(profile){this._profileBeingRecorded=profile;} -profileBeingRecordedRemoved(){} -reset(){for(var profile of this._profiles.slice()) -this._disposeProfile(profile);this._profiles=[];this._nextProfileUid=1;} -_disposeProfile(profile){this.dispatchEventToListeners(Profiler.ProfileType.Events.RemoveProfileHeader,profile);profile.dispose();if(this._profileBeingRecorded===profile){this.profileBeingRecordedRemoved();this.setProfileBeingRecorded(null);}}};Profiler.ProfileType.Events={AddProfileHeader:Symbol('add-profile-header'),ProfileComplete:Symbol('profile-complete'),RemoveProfileHeader:Symbol('remove-profile-header'),ViewUpdated:Symbol('view-updated')};Profiler.ProfileType.DataDisplayDelegate=function(){};Profiler.ProfileType.DataDisplayDelegate.prototype={showProfile(profile){},showObject(snapshotObjectId,perspectiveName){}};;Profiler.ProfileHeader=class extends Common.Object{constructor(profileType,title){super();this._profileType=profileType;this.title=title;this.uid=profileType.incrementProfileUid();this._fromFile=false;} -setTitle(title){this.title=title;this.dispatchEventToListeners(Profiler.ProfileHeader.Events.ProfileTitleChanged,this);} -profileType(){return this._profileType;} -updateStatus(subtitle,wait){this.dispatchEventToListeners(Profiler.ProfileHeader.Events.UpdateStatus,new Profiler.ProfileHeader.StatusUpdate(subtitle,wait));} -createSidebarTreeElement(dataDisplayDelegate){throw new Error('Not implemented.');} -createView(dataDisplayDelegate){throw new Error('Not implemented.');} -removeTempFile(){if(this._tempFile) -this._tempFile.remove();} -dispose(){} -canSaveToFile(){return false;} -saveToFile(){throw new Error('Not implemented');} -loadFromFile(file){throw new Error('Not implemented');} -fromFile(){return this._fromFile;} -setFromFile(){this._fromFile=true;} -setProfile(profile){}};Profiler.ProfileHeader.StatusUpdate=class{constructor(subtitle,wait){this.subtitle=subtitle;this.wait=wait;}};Profiler.ProfileHeader.Events={UpdateStatus:Symbol('UpdateStatus'),ProfileReceived:Symbol('ProfileReceived'),ProfileTitleChanged:Symbol('ProfileTitleChanged')};;Profiler.ProfilesPanel=class extends UI.PanelWithSidebar{constructor(name,profileTypes,recordingActionId){super(name);this._profileTypes=profileTypes;this.registerRequiredCSS('ui/panelEnablerView.css');this.registerRequiredCSS('profiler/heapProfiler.css');this.registerRequiredCSS('profiler/profilesPanel.css');this.registerRequiredCSS('object_ui/objectValue.css');var mainContainer=new UI.VBox();this.splitWidget().setMainWidget(mainContainer);this.profilesItemTreeElement=new Profiler.ProfilesSidebarTreeElement(this);this._sidebarTree=new UI.TreeOutlineInShadow();this._sidebarTree.registerRequiredCSS('profiler/profilesSidebarTree.css');this._sidebarTree.element.classList.add('profiles-sidebar-tree-box');this.panelSidebarElement().appendChild(this._sidebarTree.element);this._sidebarTree.appendChild(this.profilesItemTreeElement);this.profileViews=createElement('div');this.profileViews.id='profile-views';this.profileViews.classList.add('vbox');mainContainer.element.appendChild(this.profileViews);this._toolbarElement=createElementWithClass('div','profiles-toolbar');mainContainer.element.insertBefore(this._toolbarElement,mainContainer.element.firstChild);this.panelSidebarElement().classList.add('profiles-tree-sidebar');var toolbarContainerLeft=createElementWithClass('div','profiles-toolbar');this.panelSidebarElement().insertBefore(toolbarContainerLeft,this.panelSidebarElement().firstChild);var toolbar=new UI.Toolbar('',toolbarContainerLeft);this._toggleRecordAction=(UI.actionRegistry.action(recordingActionId));this._toggleRecordButton=UI.Toolbar.createActionButton(this._toggleRecordAction);toolbar.appendToolbarItem(this._toggleRecordButton);this.clearResultsButton=new UI.ToolbarButton(Common.UIString('Clear all profiles'),'largeicon-clear');this.clearResultsButton.addEventListener(UI.ToolbarButton.Events.Click,this._reset,this);toolbar.appendToolbarItem(this.clearResultsButton);toolbar.appendSeparator();toolbar.appendToolbarItem(UI.Toolbar.createActionButtonForId('components.collect-garbage'));this._profileViewToolbar=new UI.Toolbar('',this._toolbarElement);this._profileGroups={};this._launcherView=new Profiler.ProfileLauncherView(this);this._launcherView.addEventListener(Profiler.ProfileLauncherView.Events.ProfileTypeSelected,this._onProfileTypeSelected,this);this._profileToView=[];this._typeIdToSidebarSection={};var types=this._profileTypes;for(var i=0;i<types.length;i++) -this._registerProfileType(types[i]);this._launcherView.restoreSelectedProfileType();this.profilesItemTreeElement.select();this._showLauncherView();this._createFileSelectorElement();this.element.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),false);this.contentElement.addEventListener('keydown',this._onKeyDown.bind(this),false);SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._onSuspendStateChanged,this);} -_onKeyDown(event){var handled=false;if(event.key==='ArrowDown'&&!event.altKey) -handled=this._sidebarTree.selectNext();else if(event.key==='ArrowUp'&&!event.altKey) -handled=this._sidebarTree.selectPrevious();if(handled) -event.consume(true);} -searchableView(){return this.visibleView&&this.visibleView.searchableView?this.visibleView.searchableView():null;} -_createFileSelectorElement(){if(this._fileSelectorElement) -this.element.removeChild(this._fileSelectorElement);this._fileSelectorElement=UI.createFileSelectorElement(this._loadFromFile.bind(this));Profiler.ProfilesPanel._fileSelectorElement=this._fileSelectorElement;this.element.appendChild(this._fileSelectorElement);} -_findProfileTypeByExtension(fileName){return this._profileTypes.find(type=>!!type.fileExtension()&&fileName.endsWith(type.fileExtension()||''))||null;} -async _loadFromFile(file){this._createFileSelectorElement();var profileType=this._findProfileTypeByExtension(file.name);if(!profileType){var extensions=new Set(this._profileTypes.map(type=>type.fileExtension()).filter(ext=>ext));Common.console.error(Common.UIString(`Can't load file. Supported file extensions: '%s'.`,Array.from(extensions).join(`', '`)));return;} -if(!!profileType.profileBeingRecorded()){Common.console.error(Common.UIString(`Can't load profile while another profile is being recorded.`));return;} -var error=await profileType.loadFromFile(file);if(error) -UI.MessageDialog.show(Common.UIString('Profile loading failed: %s.',error.message));} -toggleRecord(){if(!this._toggleRecordAction.enabled()) -return true;var type=this._selectedProfileType;var isProfiling=type.buttonClicked();this._updateToggleRecordAction(isProfiling);if(isProfiling){this._launcherView.profileStarted();if(type.hasTemporaryView()) -this.showProfile(type.profileBeingRecorded());}else{this._launcherView.profileFinished();} -return true;} -_onSuspendStateChanged(){this._updateToggleRecordAction(this._toggleRecordAction.toggled());} -_updateToggleRecordAction(toggled){var enable=toggled||!SDK.targetManager.allTargetsSuspended();this._toggleRecordAction.setEnabled(enable);this._toggleRecordAction.setToggled(toggled);if(enable) -this._toggleRecordButton.setTitle(this._selectedProfileType?this._selectedProfileType.buttonTooltip:'');else -this._toggleRecordButton.setTitle(UI.anotherProfilerActiveLabel());if(this._selectedProfileType) -this._launcherView.updateProfileType(this._selectedProfileType,enable);} -_profileBeingRecordedRemoved(){this._updateToggleRecordAction(false);this._launcherView.profileFinished();} -_onProfileTypeSelected(event){this._selectedProfileType=(event.data);this._updateProfileTypeSpecificUI();} -_updateProfileTypeSpecificUI(){this._updateToggleRecordAction(this._toggleRecordAction.toggled());} -_reset(){this._profileTypes.forEach(type=>type.reset());delete this.visibleView;this._profileGroups={};this._updateToggleRecordAction(false);this._launcherView.profileFinished();this._sidebarTree.element.classList.remove('some-expandable');this._launcherView.detach();this.profileViews.removeChildren();this._profileViewToolbar.removeToolbarItems();this.clearResultsButton.element.classList.remove('hidden');this.profilesItemTreeElement.select();this._showLauncherView();} -_showLauncherView(){this.closeVisibleView();this._profileViewToolbar.removeToolbarItems();this._launcherView.show(this.profileViews);this.visibleView=this._launcherView;this._toolbarElement.classList.add('hidden');} -_registerProfileType(profileType){this._launcherView.addProfileType(profileType);var profileTypeSection=new Profiler.ProfileTypeSidebarSection(this,profileType);this._typeIdToSidebarSection[profileType.id]=profileTypeSection;this._sidebarTree.appendChild(profileTypeSection);profileTypeSection.childrenListElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),false);function onAddProfileHeader(event){this._addProfileHeader((event.data));} -function onRemoveProfileHeader(event){this._removeProfileHeader((event.data));} -function profileComplete(event){this.showProfile((event.data));} -profileType.addEventListener(Profiler.ProfileType.Events.ViewUpdated,this._updateProfileTypeSpecificUI,this);profileType.addEventListener(Profiler.ProfileType.Events.AddProfileHeader,onAddProfileHeader,this);profileType.addEventListener(Profiler.ProfileType.Events.RemoveProfileHeader,onRemoveProfileHeader,this);profileType.addEventListener(Profiler.ProfileType.Events.ProfileComplete,profileComplete,this);var profiles=profileType.getProfiles();for(var i=0;i<profiles.length;i++) -this._addProfileHeader(profiles[i]);} -_handleContextMenuEvent(event){var contextMenu=new UI.ContextMenu(event);if(this.visibleView instanceof Profiler.HeapSnapshotView) -this.visibleView.populateContextMenu(contextMenu,event);if(this.panelSidebarElement().isSelfOrAncestor(event.srcElement)){contextMenu.defaultSection().appendItem(Common.UIString('Load\u2026'),this._fileSelectorElement.click.bind(this._fileSelectorElement));} -contextMenu.show();} -showLoadFromFileDialog(){this._fileSelectorElement.click();} -_addProfileHeader(profile){var profileType=profile.profileType();var typeId=profileType.id;this._typeIdToSidebarSection[typeId].addProfileHeader(profile);if(!this.visibleView||this.visibleView===this._launcherView) -this.showProfile(profile);} -_removeProfileHeader(profile){if(profile.profileType().profileBeingRecorded()===profile) -this._profileBeingRecordedRemoved();var i=this._indexOfViewForProfile(profile);if(i!==-1) -this._profileToView.splice(i,1);var profileType=profile.profileType();var typeId=profileType.id;var sectionIsEmpty=this._typeIdToSidebarSection[typeId].removeProfileHeader(profile);if(sectionIsEmpty){this.profilesItemTreeElement.select();this._showLauncherView();}} -showProfile(profile){if(!profile||(profile.profileType().profileBeingRecorded()===profile)&&!profile.profileType().hasTemporaryView()) -return null;var view=this.viewForProfile(profile);if(view===this.visibleView) -return view;this.closeVisibleView();view.show(this.profileViews);view.focus();this._toolbarElement.classList.remove('hidden');this.visibleView=view;var profileTypeSection=this._typeIdToSidebarSection[profile.profileType().id];var sidebarElement=profileTypeSection.sidebarElementForProfile(profile);sidebarElement.revealAndSelect();this._profileViewToolbar.removeToolbarItems();var toolbarItems=view.syncToolbarItems();for(var i=0;i<toolbarItems.length;++i) -this._profileViewToolbar.appendToolbarItem(toolbarItems[i]);return view;} -showObject(snapshotObjectId,perspectiveName){} -viewForProfile(profile){var index=this._indexOfViewForProfile(profile);if(index!==-1) -return this._profileToView[index].view;var view=profile.createView(this);view.element.classList.add('profile-view');this._profileToView.push({profile:profile,view:view});return view;} -_indexOfViewForProfile(profile){for(var i=0;i<this._profileToView.length;i++){if(this._profileToView[i].profile===profile) -return i;} -return-1;} -closeVisibleView(){if(this.visibleView) -this.visibleView.detach();delete this.visibleView;} -focus(){this._sidebarTree.focus();}};Profiler.ProfileTypeSidebarSection=class extends UI.TreeElement{constructor(dataDisplayDelegate,profileType){super(profileType.treeItemTitle.escapeHTML(),true);this.selectable=false;this._dataDisplayDelegate=dataDisplayDelegate;this._profileTreeElements=[];this._profileGroups={};this.expand();this.hidden=true;this.setCollapsible(false);} -addProfileHeader(profile){this.hidden=false;var profileType=profile.profileType();var sidebarParent=this;var profileTreeElement=profile.createSidebarTreeElement(this._dataDisplayDelegate);this._profileTreeElements.push(profileTreeElement);if(!profile.fromFile()&&profileType.profileBeingRecorded()!==profile){var profileTitle=profile.title;var group=this._profileGroups[profileTitle];if(!group){group=new Profiler.ProfileTypeSidebarSection.ProfileGroup();this._profileGroups[profileTitle]=group;} -group.profileSidebarTreeElements.push(profileTreeElement);var groupSize=group.profileSidebarTreeElements.length;if(groupSize===2){group.sidebarTreeElement=new Profiler.ProfileGroupSidebarTreeElement(this._dataDisplayDelegate,profile.title);var firstProfileTreeElement=group.profileSidebarTreeElements[0];var index=this.children().indexOf(firstProfileTreeElement);this.insertChild(group.sidebarTreeElement,index);var selected=firstProfileTreeElement.selected;this.removeChild(firstProfileTreeElement);group.sidebarTreeElement.appendChild(firstProfileTreeElement);if(selected) -firstProfileTreeElement.revealAndSelect();firstProfileTreeElement.setSmall(true);firstProfileTreeElement.setMainTitle(Common.UIString('Run %d',1));this.treeOutline.element.classList.add('some-expandable');} -if(groupSize>=2){sidebarParent=group.sidebarTreeElement;profileTreeElement.setSmall(true);profileTreeElement.setMainTitle(Common.UIString('Run %d',groupSize));}} -sidebarParent.appendChild(profileTreeElement);} -removeProfileHeader(profile){var index=this._sidebarElementIndex(profile);if(index===-1) -return false;var profileTreeElement=this._profileTreeElements[index];this._profileTreeElements.splice(index,1);var sidebarParent=this;var group=this._profileGroups[profile.title];if(group){var groupElements=group.profileSidebarTreeElements;groupElements.splice(groupElements.indexOf(profileTreeElement),1);if(groupElements.length===1){var pos=sidebarParent.children().indexOf((group.sidebarTreeElement));group.sidebarTreeElement.removeChild(groupElements[0]);this.insertChild(groupElements[0],pos);groupElements[0].setSmall(false);groupElements[0].setMainTitle(profile.title);this.removeChild(group.sidebarTreeElement);} -if(groupElements.length!==0) -sidebarParent=group.sidebarTreeElement;} -sidebarParent.removeChild(profileTreeElement);profileTreeElement.dispose();if(this.childCount()) -return false;this.hidden=true;return true;} -sidebarElementForProfile(profile){var index=this._sidebarElementIndex(profile);return index===-1?null:this._profileTreeElements[index];} -_sidebarElementIndex(profile){var elements=this._profileTreeElements;for(var i=0;i<elements.length;i++){if(elements[i].profile===profile) -return i;} -return-1;} -onattach(){this.listItemElement.classList.add('profiles-tree-section');}};Profiler.ProfileTypeSidebarSection.ProfileGroup=class{constructor(){this.profileSidebarTreeElements=[];this.sidebarTreeElement=null;}};Profiler.ProfileSidebarTreeElement=class extends UI.TreeElement{constructor(dataDisplayDelegate,profile,className){super('',false);this._iconElement=createElementWithClass('div','icon');this._titlesElement=createElementWithClass('div','titles no-subtitle');this._titleContainer=this._titlesElement.createChild('span','title-container');this._titleElement=this._titleContainer.createChild('span','title');this._subtitleElement=this._titlesElement.createChild('span','subtitle');this._titleElement.textContent=profile.title;this._className=className;this._small=false;this._dataDisplayDelegate=dataDisplayDelegate;this.profile=profile;profile.addEventListener(Profiler.ProfileHeader.Events.UpdateStatus,this._updateStatus,this);if(profile.canSaveToFile()) -this._createSaveLink();else -profile.addEventListener(Profiler.ProfileHeader.Events.ProfileReceived,this._onProfileReceived,this);} -_createSaveLink(){this._saveLinkElement=this._titleContainer.createChild('span','save-link');this._saveLinkElement.textContent=Common.UIString('Save');this._saveLinkElement.addEventListener('click',this._saveProfile.bind(this),false);} -_onProfileReceived(event){this._createSaveLink();} -_updateStatus(event){var statusUpdate=event.data;if(statusUpdate.subtitle!==null){this._subtitleElement.textContent=statusUpdate.subtitle||'';this._titlesElement.classList.toggle('no-subtitle',!statusUpdate.subtitle);} -if(typeof statusUpdate.wait==='boolean'&&this.listItemElement) -this.listItemElement.classList.toggle('wait',statusUpdate.wait);} -ondblclick(event){if(!this._editing) -this._startEditing((event.target));return false;} -_startEditing(eventTarget){var container=eventTarget.enclosingNodeOrSelfWithClass('title');if(!container) -return;var config=new UI.InplaceEditor.Config(this._editingCommitted.bind(this),this._editingCancelled.bind(this));this._editing=UI.InplaceEditor.startEditing(container,config);} -_editingCommitted(container,newTitle){delete this._editing;this.profile.setTitle(newTitle);} -_editingCancelled(){delete this._editing;} -dispose(){this.profile.removeEventListener(Profiler.ProfileHeader.Events.UpdateStatus,this._updateStatus,this);this.profile.removeEventListener(Profiler.ProfileHeader.Events.ProfileReceived,this._onProfileReceived,this);} -onselect(){this._dataDisplayDelegate.showProfile(this.profile);return true;} -ondelete(){this.profile.profileType().removeProfile(this.profile);return true;} -onattach(){if(this._className) -this.listItemElement.classList.add(this._className);if(this._small) -this.listItemElement.classList.add('small');this.listItemElement.appendChildren(this._iconElement,this._titlesElement);this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);} -_handleContextMenuEvent(event){var profile=this.profile;var contextMenu=new UI.ContextMenu(event);contextMenu.headerSection().appendItem(Common.UIString('Load\u2026'),Profiler.ProfilesPanel._fileSelectorElement.click.bind(Profiler.ProfilesPanel._fileSelectorElement));if(profile.canSaveToFile()) -contextMenu.saveSection().appendItem(Common.UIString('Save\u2026'),profile.saveToFile.bind(profile));contextMenu.footerSection().appendItem(Common.UIString('Delete'),this.ondelete.bind(this));contextMenu.show();} -_saveProfile(event){this.profile.saveToFile();} -setSmall(small){this._small=small;if(this.listItemElement) -this.listItemElement.classList.toggle('small',this._small);} -setMainTitle(title){this._titleElement.textContent=title;}};Profiler.ProfileGroupSidebarTreeElement=class extends UI.TreeElement{constructor(dataDisplayDelegate,title){super('',true);this.selectable=false;this._dataDisplayDelegate=dataDisplayDelegate;this._title=title;this.expand();this.toggleOnClick=true;} -onselect(){var hasChildren=this.childCount()>0;if(hasChildren) -this._dataDisplayDelegate.showProfile(this.lastChild().profile);return hasChildren;} -onattach(){this.listItemElement.classList.add('profile-group-sidebar-tree-item');this.listItemElement.createChild('div','icon');this.listItemElement.createChild('div','titles no-subtitle').createChild('span','title-container').createChild('span','title').textContent=this._title;}};Profiler.ProfilesSidebarTreeElement=class extends UI.TreeElement{constructor(panel){super('',false);this.selectable=true;this._panel=panel;} -onselect(){this._panel._showLauncherView();return true;} -onattach(){this.listItemElement.classList.add('profile-launcher-view-tree-item');this.listItemElement.createChild('div','icon');this.listItemElement.createChild('div','titles no-subtitle').createChild('span','title-container').createChild('span','title').textContent=Common.UIString('Profiles');}};Profiler.JSProfilerPanel=class extends Profiler.ProfilesPanel{constructor(){var registry=Profiler.ProfileTypeRegistry.instance;super('js_profiler',[registry.cpuProfileType],'profiler.js-toggle-recording');} -wasShown(){UI.context.setFlavor(Profiler.JSProfilerPanel,this);} -willHide(){UI.context.setFlavor(Profiler.JSProfilerPanel,null);} -handleAction(context,actionId){var panel=UI.context.flavor(Profiler.JSProfilerPanel);console.assert(panel&&panel instanceof Profiler.JSProfilerPanel);panel.toggleRecord();return true;}};;Profiler.ProfileView=class extends UI.SimpleView{constructor(){super(Common.UIString('Profile'));this._searchableView=new UI.SearchableView(this);this._searchableView.setPlaceholder(Common.UIString('Find by cost (>50ms), name or file'));this._searchableView.show(this.element);var columns=([]);columns.push({id:'self',title:this.columnHeader('self'),width:'120px',fixedWidth:true,sortable:true,sort:DataGrid.DataGrid.Order.Descending});columns.push({id:'total',title:this.columnHeader('total'),width:'120px',fixedWidth:true,sortable:true});columns.push({id:'function',title:Common.UIString('Function'),disclosure:true,sortable:true});this.dataGrid=new DataGrid.DataGrid(columns);this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortProfile,this);this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._nodeSelected.bind(this,true));this.dataGrid.addEventListener(DataGrid.DataGrid.Events.DeselectedNode,this._nodeSelected.bind(this,false));this.viewSelectComboBox=new UI.ToolbarComboBox(this._changeView.bind(this));this.focusButton=new UI.ToolbarButton(Common.UIString('Focus selected function'),'largeicon-visibility');this.focusButton.setEnabled(false);this.focusButton.addEventListener(UI.ToolbarButton.Events.Click,this._focusClicked,this);this.excludeButton=new UI.ToolbarButton(Common.UIString('Exclude selected function'),'largeicon-delete');this.excludeButton.setEnabled(false);this.excludeButton.addEventListener(UI.ToolbarButton.Events.Click,this._excludeClicked,this);this.resetButton=new UI.ToolbarButton(Common.UIString('Restore all functions'),'largeicon-refresh');this.resetButton.setEnabled(false);this.resetButton.addEventListener(UI.ToolbarButton.Events.Click,this._resetClicked,this);this._linkifier=new Components.Linkifier(Profiler.ProfileView._maxLinkLength);} -static buildPopoverTable(entryInfo){var table=createElement('table');for(var entry of entryInfo){var row=table.createChild('tr');row.createChild('td').textContent=entry.title;row.createChild('td').textContent=entry.value;} -return table;} -initialize(nodeFormatter,viewTypes){this._nodeFormatter=nodeFormatter;this._viewType=Common.settings.createSetting('profileView',Profiler.ProfileView.ViewTypes.Heavy);viewTypes=viewTypes||[Profiler.ProfileView.ViewTypes.Flame,Profiler.ProfileView.ViewTypes.Heavy,Profiler.ProfileView.ViewTypes.Tree];var optionNames=new Map([[Profiler.ProfileView.ViewTypes.Flame,Common.UIString('Chart')],[Profiler.ProfileView.ViewTypes.Heavy,Common.UIString('Heavy (Bottom Up)')],[Profiler.ProfileView.ViewTypes.Tree,Common.UIString('Tree (Top Down)')],]);var options=new Map(viewTypes.map(type=>[type,this.viewSelectComboBox.createOption(optionNames.get(type),'',type)]));var optionName=this._viewType.get()||viewTypes[0];var option=options.get(optionName)||options.get(viewTypes[0]);this.viewSelectComboBox.select(option);this._changeView();if(this._flameChart) -this._flameChart.update();} -focus(){if(this._flameChart) -this._flameChart.focus();else -super.focus();} -columnHeader(columnId){throw'Not implemented';} -selectRange(timeLeft,timeRight){if(!this._flameChart) -return;this._flameChart.selectRange(timeLeft,timeRight);} -syncToolbarItems(){return[this.viewSelectComboBox,this.focusButton,this.excludeButton,this.resetButton];} -_getBottomUpProfileDataGridTree(){if(!this._bottomUpProfileDataGridTree){this._bottomUpProfileDataGridTree=new Profiler.BottomUpProfileDataGridTree(this._nodeFormatter,this._searchableView,this.profile.root,this.adjustedTotal);} -return this._bottomUpProfileDataGridTree;} -_getTopDownProfileDataGridTree(){if(!this._topDownProfileDataGridTree){this._topDownProfileDataGridTree=new Profiler.TopDownProfileDataGridTree(this._nodeFormatter,this._searchableView,this.profile.root,this.adjustedTotal);} -return this._topDownProfileDataGridTree;} -willHide(){this._currentSearchResultIndex=-1;} -refresh(){var selectedProfileNode=this.dataGrid.selectedNode?this.dataGrid.selectedNode.profileNode:null;this.dataGrid.rootNode().removeChildren();var children=this.profileDataGridTree.children;var count=children.length;for(var index=0;index<count;++index) -this.dataGrid.rootNode().appendChild(children[index]);if(selectedProfileNode) -selectedProfileNode.selected=true;} -refreshVisibleData(){var child=this.dataGrid.rootNode().children[0];while(child){child.refresh();child=child.traverseNextNode(false,null,true);}} -searchableView(){return this._searchableView;} -supportsCaseSensitiveSearch(){return true;} -supportsRegexSearch(){return false;} -searchCanceled(){this._searchableElement.searchCanceled();} -performSearch(searchConfig,shouldJump,jumpBackwards){this._searchableElement.performSearch(searchConfig,shouldJump,jumpBackwards);} -jumpToNextSearchResult(){this._searchableElement.jumpToNextSearchResult();} -jumpToPreviousSearchResult(){this._searchableElement.jumpToPreviousSearchResult();} -linkifier(){return this._linkifier;} -createFlameChartDataProvider(){throw'Not implemented';} -_ensureFlameChartCreated(){if(this._flameChart) -return;this._dataProvider=this.createFlameChartDataProvider();this._flameChart=new Profiler.CPUProfileFlameChart(this._searchableView,this._dataProvider);this._flameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected,this._onEntrySelected.bind(this));} -_onEntrySelected(event){var entryIndex=event.data;var node=this._dataProvider._entryNodes[entryIndex];var debuggerModel=this._profileHeader._debuggerModel;if(!node||!node.scriptId||!debuggerModel) -return;var script=debuggerModel.scriptForId(node.scriptId);if(!script) -return;var location=(debuggerModel.createRawLocation(script,node.lineNumber,node.columnNumber));Common.Revealer.reveal(Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(location));} -_changeView(){if(!this.profile) -return;this._searchableView.closeSearch();if(this._visibleView) -this._visibleView.detach();this._viewType.set(this.viewSelectComboBox.selectedOption().value);switch(this._viewType.get()){case Profiler.ProfileView.ViewTypes.Flame:this._ensureFlameChartCreated();this._visibleView=this._flameChart;this._searchableElement=this._flameChart;break;case Profiler.ProfileView.ViewTypes.Tree:this.profileDataGridTree=this._getTopDownProfileDataGridTree();this._sortProfile();this._visibleView=this.dataGrid.asWidget();this._searchableElement=this.profileDataGridTree;break;case Profiler.ProfileView.ViewTypes.Heavy:this.profileDataGridTree=this._getBottomUpProfileDataGridTree();this._sortProfile();this._visibleView=this.dataGrid.asWidget();this._searchableElement=this.profileDataGridTree;break;} -var isFlame=this._viewType.get()===Profiler.ProfileView.ViewTypes.Flame;this.focusButton.setVisible(!isFlame);this.excludeButton.setVisible(!isFlame);this.resetButton.setVisible(!isFlame);this._visibleView.show(this._searchableView.element);} -_nodeSelected(selected){this.focusButton.setEnabled(selected);this.excludeButton.setEnabled(selected);} -_focusClicked(event){if(!this.dataGrid.selectedNode) -return;this.resetButton.setEnabled(true);this.profileDataGridTree.focus(this.dataGrid.selectedNode);this.refresh();this.refreshVisibleData();Host.userMetrics.actionTaken(Host.UserMetrics.Action.CpuProfileNodeFocused);} -_excludeClicked(event){var selectedNode=this.dataGrid.selectedNode;if(!selectedNode) -return;selectedNode.deselect();this.resetButton.setEnabled(true);this.profileDataGridTree.exclude(selectedNode);this.refresh();this.refreshVisibleData();Host.userMetrics.actionTaken(Host.UserMetrics.Action.CpuProfileNodeExcluded);} -_resetClicked(event){this.resetButton.setEnabled(false);this.profileDataGridTree.restore();this._linkifier.reset();this.refresh();this.refreshVisibleData();} -_sortProfile(){var sortAscending=this.dataGrid.isSortOrderAscending();var sortColumnId=this.dataGrid.sortColumnId();var sortProperty=sortColumnId==='function'?'functionName':sortColumnId||'';this.profileDataGridTree.sort(Profiler.ProfileDataGridTree.propertyComparator(sortProperty,sortAscending));this.refresh();}};Profiler.ProfileView._maxLinkLength=30;Profiler.ProfileView.ViewTypes={Flame:'Flame',Tree:'Tree',Heavy:'Heavy'};Profiler.WritableProfileHeader=class extends Profiler.ProfileHeader{constructor(debuggerModel,type,title){super(type,title||Common.UIString('Profile %d',type.nextProfileUid()));this._debuggerModel=debuggerModel;this._tempFile=null;} -_onChunkTransferred(reader){this.updateStatus(Common.UIString('Loading\u2026 %d%%',Number.bytesToString(this._jsonifiedProfile.length)));} -_onError(reader){this.updateStatus(Common.UIString(`File '%s' read error: %s`,reader.fileName(),reader.error().message));} -async write(text){this._jsonifiedProfile+=text;} -close(){} -dispose(){this.removeTempFile();} -createSidebarTreeElement(panel){return new Profiler.ProfileSidebarTreeElement(panel,this,'profile-sidebar-tree-item');} -canSaveToFile(){return!this.fromFile()&&this._protocolProfile;} -async saveToFile(){var fileOutputStream=new Bindings.FileOutputStream();this._fileName=this._fileName||`${this.profileType().typeName()}-${new Date().toISO8601Compact()}${this.profileType().fileExtension()}`;var accepted=await fileOutputStream.open(this._fileName);if(!accepted||!this._tempFile) -return;var data=await this._tempFile.read();if(data) -await fileOutputStream.write(data);fileOutputStream.close();} -async loadFromFile(file){this.updateStatus(Common.UIString('Loading\u2026'),true);var fileReader=new Bindings.ChunkedFileReader(file,10000000,this._onChunkTransferred.bind(this));this._jsonifiedProfile='';var success=await fileReader.read(this);if(!success){this._onError(fileReader);return new Error(Common.UIString('Failed to read file'));} -this.updateStatus(Common.UIString('Parsing\u2026'),true);var error=null;try{this._profile=(JSON.parse(this._jsonifiedProfile));this.setProfile(this._profile);this.updateStatus(Common.UIString('Loaded'),false);}catch(e){error=e;this.profileType().removeProfile(this);} -this._jsonifiedProfile=null;if(this.profileType().profileBeingRecorded()===this) -this.profileType().setProfileBeingRecorded(null);return error;} -setProtocolProfile(profile){this.setProfile(profile);this._protocolProfile=profile;this._tempFile=new Bindings.TempFile();this._tempFile.write([JSON.stringify(profile)]);if(this.canSaveToFile()) -this.dispatchEventToListeners(Profiler.ProfileHeader.Events.ProfileReceived);}};;Profiler.ProfileDataGridNode=class extends DataGrid.DataGridNode{constructor(profileNode,owningTree,hasChildren){super(null,hasChildren);this.profileNode=profileNode;this.tree=owningTree;this.childrenByCallUID=new Map();this.lastComparator=null;this.callUID=profileNode.callUID;this.self=profileNode.self;this.total=profileNode.total;this.functionName=UI.beautifyFunctionName(profileNode.functionName);this._deoptReason=profileNode.deoptReason||'';this.url=profileNode.url;} -static sort(gridNodeGroups,comparator,force){for(var gridNodeGroupIndex=0;gridNodeGroupIndex<gridNodeGroups.length;++gridNodeGroupIndex){var gridNodes=gridNodeGroups[gridNodeGroupIndex];var count=gridNodes.length;for(var index=0;index<count;++index){var gridNode=gridNodes[index];if(!force&&(!gridNode.expanded||gridNode.lastComparator===comparator)){if(gridNode.children.length) -gridNode.shouldRefreshChildren=true;continue;} -gridNode.lastComparator=comparator;var children=gridNode.children;var childCount=children.length;if(childCount){children.sort(comparator);for(var childIndex=0;childIndex<childCount;++childIndex) -children[childIndex].recalculateSiblings(childIndex);gridNodeGroups.push(children);}}}} -static merge(container,child,shouldAbsorb){container.self+=child.self;if(!shouldAbsorb) -container.total+=child.total;var children=container.children.slice();container.removeChildren();var count=children.length;for(var index=0;index<count;++index){if(!shouldAbsorb||children[index]!==child) -container.appendChild(children[index]);} -children=child.children.slice();count=children.length;for(var index=0;index<count;++index){var orphanedChild=children[index];var existingChild=container.childrenByCallUID.get(orphanedChild.callUID);if(existingChild) -existingChild.merge((orphanedChild),false);else -container.appendChild(orphanedChild);}} -static populate(container){if(container._populated) -return;container._populated=true;container.populateChildren();var currentComparator=container.tree.lastComparator;if(currentComparator) -container.sort(currentComparator,true);} -createCell(columnId){var cell;switch(columnId){case'self':cell=this._createValueCell(this.self,this.selfPercent);cell.classList.toggle('highlight',this._searchMatchedSelfColumn);break;case'total':cell=this._createValueCell(this.total,this.totalPercent);cell.classList.toggle('highlight',this._searchMatchedTotalColumn);break;case'function':cell=this.createTD(columnId);cell.classList.toggle('highlight',this._searchMatchedFunctionColumn);if(this._deoptReason){cell.classList.add('not-optimized');var warningIcon=UI.Icon.create('smallicon-warning','profile-warn-marker');warningIcon.title=Common.UIString('Not optimized: %s',this._deoptReason);cell.appendChild(warningIcon);} -cell.createTextChild(this.functionName);if(this.profileNode.scriptId==='0') -break;var urlElement=this.tree._formatter.linkifyNode(this);if(!urlElement) -break;urlElement.style.maxWidth='75%';cell.appendChild(urlElement);break;default:cell=super.createCell(columnId);break;} -return cell;} -_createValueCell(value,percent){var cell=createElementWithClass('td','numeric-column');var div=cell.createChild('div','profile-multiple-values');div.createChild('span').textContent=this.tree._formatter.formatValue(value,this);div.createChild('span','percent-column').textContent=this.tree._formatter.formatPercent(percent,this);return cell;} -sort(comparator,force){return Profiler.ProfileDataGridNode.sort([[this]],comparator,force);} -insertChild(profileDataGridNode,index){super.insertChild(profileDataGridNode,index);this.childrenByCallUID.set(profileDataGridNode.callUID,(profileDataGridNode));} -removeChild(profileDataGridNode){super.removeChild(profileDataGridNode);this.childrenByCallUID.delete(((profileDataGridNode)).callUID);} -removeChildren(){super.removeChildren();this.childrenByCallUID.clear();} -findChild(node){if(!node) -return null;return this.childrenByCallUID.get(node.callUID);} -get selfPercent(){return this.self/this.tree.total*100.0;} -get totalPercent(){return this.total/this.tree.total*100.0;} -populate(){Profiler.ProfileDataGridNode.populate(this);} -populateChildren(){} -save(){if(this._savedChildren) -return;this._savedSelf=this.self;this._savedTotal=this.total;this._savedChildren=this.children.slice();} -restore(){if(!this._savedChildren) -return;this.self=this._savedSelf;this.total=this._savedTotal;this.removeChildren();var children=this._savedChildren;var count=children.length;for(var index=0;index<count;++index){children[index].restore();this.appendChild(children[index]);}} -merge(child,shouldAbsorb){Profiler.ProfileDataGridNode.merge(this,child,shouldAbsorb);}};Profiler.ProfileDataGridTree=class{constructor(formatter,searchableView,total){this.tree=this;this.children=[];this._formatter=formatter;this._searchableView=searchableView;this.total=total;this.lastComparator=null;this.childrenByCallUID=new Map();this.deepSearch=true;} -static propertyComparator(property,isAscending){var comparator=Profiler.ProfileDataGridTree.propertyComparators[(isAscending?1:0)][property];if(!comparator){if(isAscending){comparator=function(lhs,rhs){if(lhs[property]<rhs[property]) -return-1;if(lhs[property]>rhs[property]) -return 1;return 0;};}else{comparator=function(lhs,rhs){if(lhs[property]>rhs[property]) -return-1;if(lhs[property]<rhs[property]) -return 1;return 0;};} -Profiler.ProfileDataGridTree.propertyComparators[(isAscending?1:0)][property]=comparator;} -return comparator;} -get expanded(){return true;} -appendChild(child){this.insertChild(child,this.children.length);} -insertChild(child,index){this.children.splice(index,0,child);this.childrenByCallUID.set(child.callUID,child);} -removeChildren(){this.children=[];this.childrenByCallUID.clear();} -populateChildren(){} -findChild(node){if(!node) -return null;return this.childrenByCallUID.get(node.callUID);} -sort(comparator,force){return Profiler.ProfileDataGridNode.sort([[this]],comparator,force);} -save(){if(this._savedChildren) -return;this._savedTotal=this.total;this._savedChildren=this.children.slice();} -restore(){if(!this._savedChildren) -return;this.children=this._savedChildren;this.total=this._savedTotal;var children=this.children;var count=children.length;for(var index=0;index<count;++index) -children[index].restore();this._savedChildren=null;} -_matchFunction(searchConfig){var query=searchConfig.query.trim();if(!query.length) -return null;var greaterThan=(query.startsWith('>'));var lessThan=(query.startsWith('<'));var equalTo=(query.startsWith('=')||((greaterThan||lessThan)&&query.indexOf('=')===1));var percentUnits=(query.endsWith('%'));var millisecondsUnits=(query.length>2&&query.endsWith('ms'));var secondsUnits=(!millisecondsUnits&&query.endsWith('s'));var queryNumber=parseFloat(query);if(greaterThan||lessThan||equalTo){if(equalTo&&(greaterThan||lessThan)) -queryNumber=parseFloat(query.substring(2));else -queryNumber=parseFloat(query.substring(1));} -var queryNumberMilliseconds=(secondsUnits?(queryNumber*1000):queryNumber);if(!isNaN(queryNumber)&&!(greaterThan||lessThan)) -equalTo=true;var matcher=createPlainTextSearchRegex(query,'i');function matchesQuery(profileDataGridNode){delete profileDataGridNode._searchMatchedSelfColumn;delete profileDataGridNode._searchMatchedTotalColumn;delete profileDataGridNode._searchMatchedFunctionColumn;if(percentUnits){if(lessThan){if(profileDataGridNode.selfPercent<queryNumber) -profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalPercent<queryNumber) -profileDataGridNode._searchMatchedTotalColumn=true;}else if(greaterThan){if(profileDataGridNode.selfPercent>queryNumber) -profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalPercent>queryNumber) -profileDataGridNode._searchMatchedTotalColumn=true;} -if(equalTo){if(profileDataGridNode.selfPercent===queryNumber) -profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalPercent===queryNumber) -profileDataGridNode._searchMatchedTotalColumn=true;}}else if(millisecondsUnits||secondsUnits){if(lessThan){if(profileDataGridNode.self<queryNumberMilliseconds) -profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.total<queryNumberMilliseconds) -profileDataGridNode._searchMatchedTotalColumn=true;}else if(greaterThan){if(profileDataGridNode.self>queryNumberMilliseconds) -profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.total>queryNumberMilliseconds) -profileDataGridNode._searchMatchedTotalColumn=true;} -if(equalTo){if(profileDataGridNode.self===queryNumberMilliseconds) -profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.total===queryNumberMilliseconds) -profileDataGridNode._searchMatchedTotalColumn=true;}} -if(profileDataGridNode.functionName.match(matcher)||(profileDataGridNode.url&&profileDataGridNode.url.match(matcher))) -profileDataGridNode._searchMatchedFunctionColumn=true;if(profileDataGridNode._searchMatchedSelfColumn||profileDataGridNode._searchMatchedTotalColumn||profileDataGridNode._searchMatchedFunctionColumn){profileDataGridNode.refresh();return true;} -return false;} -return matchesQuery;} -performSearch(searchConfig,shouldJump,jumpBackwards){this.searchCanceled();var matchesQuery=this._matchFunction(searchConfig);if(!matchesQuery) -return;this._searchResults=[];const deepSearch=this.deepSearch;for(var current=this.children[0];current;current=current.traverseNextNode(!deepSearch,null,!deepSearch)){if(matchesQuery(current)) -this._searchResults.push({profileNode:current});} -this._searchResultIndex=jumpBackwards?0:this._searchResults.length-1;this._searchableView.updateSearchMatchesCount(this._searchResults.length);this._searchableView.updateCurrentMatchIndex(this._searchResultIndex);} -searchCanceled(){if(this._searchResults){for(var i=0;i<this._searchResults.length;++i){var profileNode=this._searchResults[i].profileNode;delete profileNode._searchMatchedSelfColumn;delete profileNode._searchMatchedTotalColumn;delete profileNode._searchMatchedFunctionColumn;profileNode.refresh();}} -this._searchResults=[];this._searchResultIndex=-1;} -jumpToNextSearchResult(){if(!this._searchResults||!this._searchResults.length) -return;this._searchResultIndex=(this._searchResultIndex+1)%this._searchResults.length;this._jumpToSearchResult(this._searchResultIndex);} -jumpToPreviousSearchResult(){if(!this._searchResults||!this._searchResults.length) -return;this._searchResultIndex=(this._searchResultIndex-1+this._searchResults.length)%this._searchResults.length;this._jumpToSearchResult(this._searchResultIndex);} -supportsCaseSensitiveSearch(){return true;} -supportsRegexSearch(){return false;} -_jumpToSearchResult(index){var searchResult=this._searchResults[index];if(!searchResult) -return;var profileNode=searchResult.profileNode;profileNode.revealAndSelect();this._searchableView.updateCurrentMatchIndex(index);}};Profiler.ProfileDataGridTree.propertyComparators=[{},{}];Profiler.ProfileDataGridNode.Formatter=function(){};Profiler.ProfileDataGridNode.Formatter.prototype={formatValue(value,node){},formatPercent(value,node){},linkifyNode(node){}};;Profiler.BottomUpProfileDataGridNode=class extends Profiler.ProfileDataGridNode{constructor(profileNode,owningTree){super(profileNode,owningTree,!!profileNode.parent&&!!profileNode.parent.parent);this._remainingNodeInfos=[];} -static _sharedPopulate(container){var remainingNodeInfos=container._remainingNodeInfos;var count=remainingNodeInfos.length;for(var index=0;index<count;++index){var nodeInfo=remainingNodeInfos[index];var ancestor=nodeInfo.ancestor;var focusNode=nodeInfo.focusNode;var child=container.findChild(ancestor);if(child){var totalAccountedFor=nodeInfo.totalAccountedFor;child.self+=focusNode.self;if(!totalAccountedFor) -child.total+=focusNode.total;}else{child=new Profiler.BottomUpProfileDataGridNode(ancestor,(container.tree));if(ancestor!==focusNode){child.self=focusNode.self;child.total=focusNode.total;} -container.appendChild(child);} -var parent=ancestor.parent;if(parent&&parent.parent){nodeInfo.ancestor=parent;child._remainingNodeInfos.push(nodeInfo);}} -delete container._remainingNodeInfos;} -_takePropertiesFromProfileDataGridNode(profileDataGridNode){this.save();this.self=profileDataGridNode.self;this.total=profileDataGridNode.total;} -_keepOnlyChild(child){this.save();this.removeChildren();this.appendChild(child);} -_exclude(aCallUID){if(this._remainingNodeInfos) -this.populate();this.save();var children=this.children;var index=this.children.length;while(index--) -children[index]._exclude(aCallUID);var child=this.childrenByCallUID.get(aCallUID);if(child) -this.merge(child,true);} -restore(){super.restore();if(!this.children.length) -this.setHasChildren(this._willHaveChildren(this.profileNode));} -merge(child,shouldAbsorb){this.self-=child.self;super.merge(child,shouldAbsorb);} -populateChildren(){Profiler.BottomUpProfileDataGridNode._sharedPopulate(this);} -_willHaveChildren(profileNode){return!!(profileNode.parent&&profileNode.parent.parent);}};Profiler.BottomUpProfileDataGridTree=class extends Profiler.ProfileDataGridTree{constructor(formatter,searchableView,rootProfileNode,total){super(formatter,searchableView,total);this.deepSearch=false;var profileNodeUIDs=0;var profileNodeGroups=[[],[rootProfileNode]];var visitedProfileNodesForCallUID=new Map();this._remainingNodeInfos=[];for(var profileNodeGroupIndex=0;profileNodeGroupIndex<profileNodeGroups.length;++profileNodeGroupIndex){var parentProfileNodes=profileNodeGroups[profileNodeGroupIndex];var profileNodes=profileNodeGroups[++profileNodeGroupIndex];var count=profileNodes.length;for(var index=0;index<count;++index){var profileNode=profileNodes[index];if(!profileNode.UID) -profileNode.UID=++profileNodeUIDs;if(profileNode.parent){var visitedNodes=visitedProfileNodesForCallUID.get(profileNode.callUID);var totalAccountedFor=false;if(!visitedNodes){visitedNodes=new Set();visitedProfileNodesForCallUID.set(profileNode.callUID,visitedNodes);}else{var parentCount=parentProfileNodes.length;for(var parentIndex=0;parentIndex<parentCount;++parentIndex){if(visitedNodes.has(parentProfileNodes[parentIndex].UID)){totalAccountedFor=true;break;}}} -visitedNodes.add(profileNode.UID);this._remainingNodeInfos.push({ancestor:profileNode,focusNode:profileNode,totalAccountedFor:totalAccountedFor});} -var children=profileNode.children;if(children.length){profileNodeGroups.push(parentProfileNodes.concat([profileNode]));profileNodeGroups.push(children);}}} -Profiler.ProfileDataGridNode.populate(this);return this;} -focus(profileDataGridNode){if(!profileDataGridNode) -return;this.save();var currentNode=profileDataGridNode;var focusNode=profileDataGridNode;while(currentNode.parent&&(currentNode instanceof Profiler.ProfileDataGridNode)){currentNode._takePropertiesFromProfileDataGridNode(profileDataGridNode);focusNode=currentNode;currentNode=currentNode.parent;if(currentNode instanceof Profiler.ProfileDataGridNode) -currentNode._keepOnlyChild(focusNode);} -this.children=[focusNode];this.total=profileDataGridNode.total;} -exclude(profileDataGridNode){if(!profileDataGridNode) -return;this.save();var excludedCallUID=profileDataGridNode.callUID;var excludedTopLevelChild=this.childrenByCallUID.get(excludedCallUID);if(excludedTopLevelChild) -this.children.remove(excludedTopLevelChild);var children=this.children;var count=children.length;for(var index=0;index<count;++index) -children[index]._exclude(excludedCallUID);if(this.lastComparator) -this.sort(this.lastComparator,true);} -populateChildren(){Profiler.BottomUpProfileDataGridNode._sharedPopulate(this);}};;Profiler.TopDownProfileDataGridNode=class extends Profiler.ProfileDataGridNode{constructor(profileNode,owningTree){var hasChildren=!!(profileNode.children&&profileNode.children.length);super(profileNode,owningTree,hasChildren);this._remainingChildren=profileNode.children;} -static _sharedPopulate(container){var children=container._remainingChildren;var childrenLength=children.length;for(var i=0;i<childrenLength;++i){container.appendChild(new Profiler.TopDownProfileDataGridNode(children[i],(container.tree)));} -container._remainingChildren=null;} -static _excludeRecursively(container,aCallUID){if(container._remainingChildren) -container.populate();container.save();var children=container.children;var index=container.children.length;while(index--) -Profiler.TopDownProfileDataGridNode._excludeRecursively(children[index],aCallUID);var child=container.childrenByCallUID.get(aCallUID);if(child) -Profiler.ProfileDataGridNode.merge(container,child,true);} -populateChildren(){Profiler.TopDownProfileDataGridNode._sharedPopulate(this);}};Profiler.TopDownProfileDataGridTree=class extends Profiler.ProfileDataGridTree{constructor(formatter,searchableView,rootProfileNode,total){super(formatter,searchableView,total);this._remainingChildren=rootProfileNode.children;Profiler.ProfileDataGridNode.populate(this);} -focus(profileDataGridNode){if(!profileDataGridNode) -return;this.save();profileDataGridNode.savePosition();this.children=[profileDataGridNode];this.total=profileDataGridNode.total;} -exclude(profileDataGridNode){if(!profileDataGridNode) -return;this.save();Profiler.TopDownProfileDataGridNode._excludeRecursively(this,profileDataGridNode.callUID);if(this.lastComparator) -this.sort(this.lastComparator,true);} -restore(){if(!this._savedChildren) -return;this.children[0].restorePosition();super.restore();} -populateChildren(){Profiler.TopDownProfileDataGridNode._sharedPopulate(this);}};;Profiler.ProfileFlameChartDataProvider=class{constructor(){PerfUI.FlameChartDataProvider.call(this);this._colorGenerator=Profiler.ProfileFlameChartDataProvider.colorGenerator();} -static colorGenerator(){if(!Profiler.ProfileFlameChartDataProvider._colorGenerator){var colorGenerator=new Common.Color.Generator({min:30,max:330},{min:50,max:80,count:5},{min:80,max:90,count:3});colorGenerator.setColorForID('(idle)','hsl(0, 0%, 94%)');colorGenerator.setColorForID('(program)','hsl(0, 0%, 80%)');colorGenerator.setColorForID('(garbage collector)','hsl(0, 0%, 80%)');Profiler.ProfileFlameChartDataProvider._colorGenerator=colorGenerator;} -return Profiler.ProfileFlameChartDataProvider._colorGenerator;} -minimumBoundary(){return this._cpuProfile.profileStartTime;} -totalTime(){return this._cpuProfile.profileHead.total;} -formatValue(value,precision){return Number.preciseMillisToString(value,precision);} -maxStackDepth(){return this._maxStackDepth;} -timelineData(){return this._timelineData||this._calculateTimelineData();} -_calculateTimelineData(){throw'Not implemented.';} -prepareHighlightedEntryInfo(entryIndex){throw'Not implemented.';} -canJumpToEntry(entryIndex){return this._entryNodes[entryIndex].scriptId!=='0';} -entryTitle(entryIndex){var node=this._entryNodes[entryIndex];return UI.beautifyFunctionName(node.functionName);} -entryFont(entryIndex){if(!this._font){this._font='11px '+Host.fontFamily();this._boldFont='bold '+this._font;} -const node=this._entryNodes[entryIndex];return node.deoptReason?this._boldFont:this._font;} -entryColor(entryIndex){var node=this._entryNodes[entryIndex];return this._colorGenerator.colorForID(node.url||(node.scriptId!=='0'?node.scriptId:node.functionName));} -decorateEntry(entryIndex,context,text,barX,barY,barWidth,barHeight){return false;} -forceDecoration(entryIndex){return false;} -textColor(entryIndex){return'#333';}};Profiler.CPUProfileFlameChart=class extends UI.VBox{constructor(searchableView,dataProvider){super();this.element.id='cpu-flame-chart';this._searchableView=searchableView;this._overviewPane=new Profiler.CPUProfileFlameChart.OverviewPane(dataProvider);this._overviewPane.show(this.element);this._mainPane=new PerfUI.FlameChart(dataProvider,this._overviewPane);this._mainPane.setBarHeight(15);this._mainPane.setTextBaseline(4);this._mainPane.setTextPadding(2);this._mainPane.show(this.element);this._mainPane.addEventListener(PerfUI.FlameChart.Events.EntrySelected,this._onEntrySelected,this);this._overviewPane.addEventListener(PerfUI.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);this._dataProvider=dataProvider;this._searchResults=[];} -focus(){this._mainPane.focus();} -_onWindowChanged(event){var windowLeft=event.data.windowTimeLeft;var windowRight=event.data.windowTimeRight;this._mainPane.setWindowTimes(windowLeft,windowRight);} -selectRange(timeLeft,timeRight){this._overviewPane._selectRange(timeLeft,timeRight);} -_onEntrySelected(event){this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected,event.data);} -update(){this._overviewPane.update();this._mainPane.update();} -performSearch(searchConfig,shouldJump,jumpBackwards){var matcher=createPlainTextSearchRegex(searchConfig.query,searchConfig.caseSensitive?'':'i');var selectedEntryIndex=this._searchResultIndex!==-1?this._searchResults[this._searchResultIndex]:-1;this._searchResults=[];var entriesCount=this._dataProvider._entryNodes.length;for(var index=0;index<entriesCount;++index){if(this._dataProvider.entryTitle(index).match(matcher)) -this._searchResults.push(index);} -if(this._searchResults.length){this._searchResultIndex=this._searchResults.indexOf(selectedEntryIndex);if(this._searchResultIndex===-1) -this._searchResultIndex=jumpBackwards?this._searchResults.length-1:0;this._mainPane.setSelectedEntry(this._searchResults[this._searchResultIndex]);}else{this.searchCanceled();} -this._searchableView.updateSearchMatchesCount(this._searchResults.length);this._searchableView.updateCurrentMatchIndex(this._searchResultIndex);} -searchCanceled(){this._mainPane.setSelectedEntry(-1);this._searchResults=[];this._searchResultIndex=-1;} -jumpToNextSearchResult(){this._searchResultIndex=(this._searchResultIndex+1)%this._searchResults.length;this._mainPane.setSelectedEntry(this._searchResults[this._searchResultIndex]);this._searchableView.updateCurrentMatchIndex(this._searchResultIndex);} -jumpToPreviousSearchResult(){this._searchResultIndex=(this._searchResultIndex-1+this._searchResults.length)%this._searchResults.length;this._mainPane.setSelectedEntry(this._searchResults[this._searchResultIndex]);this._searchableView.updateCurrentMatchIndex(this._searchResultIndex);} -supportsCaseSensitiveSearch(){return true;} -supportsRegexSearch(){return false;}};Profiler.CPUProfileFlameChart.OverviewCalculator=class{constructor(dataProvider){this._dataProvider=dataProvider;} -_updateBoundaries(overviewPane){this._minimumBoundaries=overviewPane._dataProvider.minimumBoundary();var totalTime=overviewPane._dataProvider.totalTime();this._maximumBoundaries=this._minimumBoundaries+totalTime;this._xScaleFactor=overviewPane._overviewContainer.clientWidth/totalTime;} -computePosition(time){return(time-this._minimumBoundaries)*this._xScaleFactor;} -formatValue(value,precision){return this._dataProvider.formatValue(value-this._minimumBoundaries,precision);} -maximumBoundary(){return this._maximumBoundaries;} -minimumBoundary(){return this._minimumBoundaries;} -zeroTime(){return this._minimumBoundaries;} -boundarySpan(){return this._maximumBoundaries-this._minimumBoundaries;}};Profiler.CPUProfileFlameChart.OverviewPane=class extends UI.VBox{constructor(dataProvider){super();this.element.classList.add('cpu-profile-flame-chart-overview-pane');this._overviewContainer=this.element.createChild('div','cpu-profile-flame-chart-overview-container');this._overviewGrid=new PerfUI.OverviewGrid('cpu-profile-flame-chart');this._overviewGrid.element.classList.add('fill');this._overviewCanvas=this._overviewContainer.createChild('canvas','cpu-profile-flame-chart-overview-canvas');this._overviewContainer.appendChild(this._overviewGrid.element);this._overviewCalculator=new Profiler.CPUProfileFlameChart.OverviewCalculator(dataProvider);this._dataProvider=dataProvider;this._overviewGrid.addEventListener(PerfUI.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);} -requestWindowTimes(windowStartTime,windowEndTime){this._selectRange(windowStartTime,windowEndTime);} -updateRangeSelection(startTime,endTime){} -_selectRange(timeLeft,timeRight){var startTime=this._dataProvider.minimumBoundary();var totalTime=this._dataProvider.totalTime();this._overviewGrid.setWindow((timeLeft-startTime)/totalTime,(timeRight-startTime)/totalTime);} -_onWindowChanged(event){var startTime=this._dataProvider.minimumBoundary();var totalTime=this._dataProvider.totalTime();var data={windowTimeLeft:startTime+this._overviewGrid.windowLeft()*totalTime,windowTimeRight:startTime+this._overviewGrid.windowRight()*totalTime};this.dispatchEventToListeners(PerfUI.OverviewGrid.Events.WindowChanged,data);} -_timelineData(){return this._dataProvider.timelineData();} -onResize(){this._scheduleUpdate();} -_scheduleUpdate(){if(this._updateTimerId) -return;this._updateTimerId=this.element.window().requestAnimationFrame(this.update.bind(this));} -update(){this._updateTimerId=0;var timelineData=this._timelineData();if(!timelineData) -return;this._resetCanvas(this._overviewContainer.clientWidth,this._overviewContainer.clientHeight-PerfUI.FlameChart.HeaderHeight);this._overviewCalculator._updateBoundaries(this);this._overviewGrid.updateDividers(this._overviewCalculator);this._drawOverviewCanvas();} -_drawOverviewCanvas(){var canvasWidth=this._overviewCanvas.width;var canvasHeight=this._overviewCanvas.height;var drawData=this._calculateDrawData(canvasWidth);var context=this._overviewCanvas.getContext('2d');var ratio=window.devicePixelRatio;var offsetFromBottom=ratio;var lineWidth=1;var yScaleFactor=canvasHeight/(this._dataProvider.maxStackDepth()*1.1);context.lineWidth=lineWidth;context.translate(0.5,0.5);context.strokeStyle='rgba(20,0,0,0.4)';context.fillStyle='rgba(214,225,254,0.8)';context.moveTo(-lineWidth,canvasHeight+lineWidth);context.lineTo(-lineWidth,Math.round(canvasHeight-drawData[0]*yScaleFactor-offsetFromBottom));var value;for(var x=0;x<canvasWidth;++x){value=Math.round(canvasHeight-drawData[x]*yScaleFactor-offsetFromBottom);context.lineTo(x,value);} -context.lineTo(canvasWidth+lineWidth,value);context.lineTo(canvasWidth+lineWidth,canvasHeight+lineWidth);context.fill();context.stroke();context.closePath();} -_calculateDrawData(width){var dataProvider=this._dataProvider;var timelineData=this._timelineData();var entryStartTimes=timelineData.entryStartTimes;var entryTotalTimes=timelineData.entryTotalTimes;var entryLevels=timelineData.entryLevels;var length=entryStartTimes.length;var minimumBoundary=this._dataProvider.minimumBoundary();var drawData=new Uint8Array(width);var scaleFactor=width/dataProvider.totalTime();for(var entryIndex=0;entryIndex<length;++entryIndex){var start=Math.floor((entryStartTimes[entryIndex]-minimumBoundary)*scaleFactor);var finish=Math.floor((entryStartTimes[entryIndex]-minimumBoundary+entryTotalTimes[entryIndex])*scaleFactor);for(var x=start;x<=finish;++x) -drawData[x]=Math.max(drawData[x],entryLevels[entryIndex]+1);} -return drawData;} -_resetCanvas(width,height){var ratio=window.devicePixelRatio;this._overviewCanvas.width=width*ratio;this._overviewCanvas.height=height*ratio;this._overviewCanvas.style.width=width+'px';this._overviewCanvas.style.height=height+'px';}};;Profiler.CPUProfileView=class extends Profiler.ProfileView{constructor(profileHeader){super();this._profileHeader=profileHeader;this.profile=profileHeader.profileModel();this.adjustedTotal=this.profile.profileHead.total;this.adjustedTotal-=this.profile.idleNode?this.profile.idleNode.total:0;this.initialize(new Profiler.CPUProfileView.NodeFormatter(this));} -wasShown(){super.wasShown();var lineLevelProfile=PerfUI.LineLevelProfile.instance();lineLevelProfile.reset();lineLevelProfile.appendCPUProfile(this.profile);} -columnHeader(columnId){switch(columnId){case'self':return Common.UIString('Self Time');case'total':return Common.UIString('Total Time');} -return'';} -createFlameChartDataProvider(){return new Profiler.CPUFlameChartDataProvider(this.profile,this._profileHeader._cpuProfilerModel);}};Profiler.CPUProfileType=class extends Profiler.ProfileType{constructor(){super(Profiler.CPUProfileType.TypeId,Common.UIString('Record JavaScript CPU Profile'));this._recording=false;Profiler.CPUProfileType.instance=this;SDK.targetManager.addModelListener(SDK.CPUProfilerModel,SDK.CPUProfilerModel.Events.ConsoleProfileFinished,this._consoleProfileFinished,this);} -profileBeingRecorded(){return(super.profileBeingRecorded());} -typeName(){return'CPU';} -fileExtension(){return'.cpuprofile';} -get buttonTooltip(){return this._recording?Common.UIString('Stop CPU profiling'):Common.UIString('Start CPU profiling');} -buttonClicked(){if(this._recording){this.stopRecordingProfile();return false;}else{this.startRecordingProfile();return true;}} -get treeItemTitle(){return Common.UIString('CPU PROFILES');} -get description(){return Common.UIString('CPU profiles show where the execution time is spent in your page\'s JavaScript functions.');} -_consoleProfileFinished(event){var data=(event.data);var cpuProfile=(data.cpuProfile);var profile=new Profiler.CPUProfileHeader(data.cpuProfilerModel,this,data.title);profile.setProtocolProfile(cpuProfile);this.addProfile(profile);} -startRecordingProfile(){var cpuProfilerModel=UI.context.flavor(SDK.CPUProfilerModel);if(this.profileBeingRecorded()||!cpuProfilerModel) -return;var profile=new Profiler.CPUProfileHeader(cpuProfilerModel,this);this.setProfileBeingRecorded(profile);SDK.targetManager.suspendAllTargets();this.addProfile(profile);profile.updateStatus(Common.UIString('Recording\u2026'));this._recording=true;cpuProfilerModel.startRecording();Host.userMetrics.actionTaken(Host.UserMetrics.Action.ProfilesCPUProfileTaken);} -async stopRecordingProfile(){this._recording=false;if(!this.profileBeingRecorded()||!this.profileBeingRecorded()._cpuProfilerModel) -return;var profile=await this.profileBeingRecorded()._cpuProfilerModel.stopRecording();var recordedProfile=this.profileBeingRecorded();if(recordedProfile){console.assert(profile);recordedProfile.setProtocolProfile(profile);recordedProfile.updateStatus('');this.setProfileBeingRecorded(null);} -await SDK.targetManager.resumeAllTargets();this.dispatchEventToListeners(Profiler.ProfileType.Events.ProfileComplete,recordedProfile);} -createProfileLoadedFromFile(title){return new Profiler.CPUProfileHeader(null,this,title);} -profileBeingRecordedRemoved(){this.stopRecordingProfile();}};Profiler.CPUProfileType.TypeId='CPU';Profiler.CPUProfileHeader=class extends Profiler.WritableProfileHeader{constructor(cpuProfilerModel,type,title){super(cpuProfilerModel&&cpuProfilerModel.debuggerModel(),type,title);this._cpuProfilerModel=cpuProfilerModel;} -createView(){return new Profiler.CPUProfileView(this);} -protocolProfile(){return this._protocolProfile;} -profileModel(){return this._profileModel;} -setProfile(profile){this._profileModel=new SDK.CPUProfileDataModel(profile);}};Profiler.CPUProfileView.NodeFormatter=class{constructor(profileView){this._profileView=profileView;} -formatValue(value){return Common.UIString('%.1f\xa0ms',value);} -formatPercent(value,node){return node.profileNode===this._profileView.profile.idleNode?'':Common.UIString('%.2f\xa0%%',value);} -linkifyNode(node){var cpuProfilerModel=this._profileView._profileHeader._cpuProfilerModel;return this._profileView.linkifier().maybeLinkifyConsoleCallFrame(cpuProfilerModel?cpuProfilerModel.target():null,node.profileNode.callFrame,'profile-node-file');}};Profiler.CPUFlameChartDataProvider=class extends Profiler.ProfileFlameChartDataProvider{constructor(cpuProfile,cpuProfilerModel){super();this._cpuProfile=cpuProfile;this._cpuProfilerModel=cpuProfilerModel;} -_calculateTimelineData(){var entries=[];var stack=[];var maxDepth=5;function onOpenFrame(){stack.push(entries.length);entries.push(null);} -function onCloseFrame(depth,node,startTime,totalTime,selfTime){var index=stack.pop();entries[index]=new Profiler.CPUFlameChartDataProvider.ChartEntry(depth,totalTime,startTime,selfTime,node);maxDepth=Math.max(maxDepth,depth);} -this._cpuProfile.forEachFrame(onOpenFrame,onCloseFrame);var entryNodes=new Array(entries.length);var entryLevels=new Uint16Array(entries.length);var entryTotalTimes=new Float32Array(entries.length);var entrySelfTimes=new Float32Array(entries.length);var entryStartTimes=new Float64Array(entries.length);for(var i=0;i<entries.length;++i){var entry=entries[i];entryNodes[i]=entry.node;entryLevels[i]=entry.depth;entryTotalTimes[i]=entry.duration;entryStartTimes[i]=entry.startTime;entrySelfTimes[i]=entry.selfTime;} -this._maxStackDepth=maxDepth+1;this._timelineData=new PerfUI.FlameChart.TimelineData(entryLevels,entryTotalTimes,entryStartTimes,null);this._entryNodes=entryNodes;this._entrySelfTimes=entrySelfTimes;return this._timelineData;} -prepareHighlightedEntryInfo(entryIndex){var timelineData=this._timelineData;var node=this._entryNodes[entryIndex];if(!node) -return null;var entryInfo=[];function pushEntryInfoRow(title,value){entryInfo.push({title:title,value:value});} -function millisecondsToString(ms){if(ms===0) -return'0';if(ms<1000) -return Common.UIString('%.1f\xa0ms',ms);return Number.secondsToString(ms/1000,true);} -var name=UI.beautifyFunctionName(node.functionName);pushEntryInfoRow(Common.UIString('Name'),name);var selfTime=millisecondsToString(this._entrySelfTimes[entryIndex]);var totalTime=millisecondsToString(timelineData.entryTotalTimes[entryIndex]);pushEntryInfoRow(Common.UIString('Self time'),selfTime);pushEntryInfoRow(Common.UIString('Total time'),totalTime);var linkifier=new Components.Linkifier();var link=linkifier.maybeLinkifyConsoleCallFrame(this._cpuProfilerModel&&this._cpuProfilerModel.target(),node.callFrame);if(link) -pushEntryInfoRow(Common.UIString('URL'),link.textContent);linkifier.dispose();pushEntryInfoRow(Common.UIString('Aggregated self time'),Number.secondsToString(node.self/1000,true));pushEntryInfoRow(Common.UIString('Aggregated total time'),Number.secondsToString(node.total/1000,true));if(node.deoptReason) -pushEntryInfoRow(Common.UIString('Not optimized'),node.deoptReason);return Profiler.ProfileView.buildPopoverTable(entryInfo);}};Profiler.CPUFlameChartDataProvider.ChartEntry=class{constructor(depth,duration,startTime,selfTime,node){this.depth=depth;this.duration=duration;this.startTime=startTime;this.selfTime=selfTime;this.node=node;}};;Profiler.HeapProfileView=class extends Profiler.ProfileView{constructor(profileHeader){super();this._profileHeader=profileHeader;this.profile=new Profiler.SamplingHeapProfileModel(profileHeader._profile||profileHeader.protocolProfile());this.adjustedTotal=this.profile.total;var views=[Profiler.ProfileView.ViewTypes.Flame,Profiler.ProfileView.ViewTypes.Heavy,Profiler.ProfileView.ViewTypes.Tree];this.initialize(new Profiler.HeapProfileView.NodeFormatter(this),views);} -columnHeader(columnId){switch(columnId){case'self':return Common.UIString('Self Size (bytes)');case'total':return Common.UIString('Total Size (bytes)');} -return'';} -createFlameChartDataProvider(){return new Profiler.HeapFlameChartDataProvider(this.profile,this._profileHeader._heapProfilerModel);}};Profiler.SamplingHeapProfileType=class extends Profiler.ProfileType{constructor(){super(Profiler.SamplingHeapProfileType.TypeId,Common.UIString('Record allocation profile'));this._recording=false;Profiler.SamplingHeapProfileType.instance=this;} -profileBeingRecorded(){return(super.profileBeingRecorded());} -typeName(){return'Heap';} -fileExtension(){return'.heapprofile';} -get buttonTooltip(){return this._recording?Common.UIString('Stop heap profiling'):Common.UIString('Start heap profiling');} -buttonClicked(){var wasRecording=this._recording;if(wasRecording) -this.stopRecordingProfile();else -this.startRecordingProfile();return!wasRecording;} -get treeItemTitle(){return Common.UIString('ALLOCATION PROFILES');} -get description(){return Common.UIString('Allocation profiles show memory allocations from your JavaScript functions.');} -startRecordingProfile(){var heapProfilerModel=UI.context.flavor(SDK.HeapProfilerModel);if(this.profileBeingRecorded()||!heapProfilerModel) -return;var profile=new Profiler.SamplingHeapProfileHeader(heapProfilerModel,this);this.setProfileBeingRecorded(profile);SDK.targetManager.suspendAllTargets();this.addProfile(profile);profile.updateStatus(Common.UIString('Recording\u2026'));this._recording=true;heapProfilerModel.startSampling();} -async stopRecordingProfile(){this._recording=false;if(!this.profileBeingRecorded()||!this.profileBeingRecorded()._heapProfilerModel) -return;var profile=await this.profileBeingRecorded()._heapProfilerModel.stopSampling();var recordedProfile=this.profileBeingRecorded();if(recordedProfile){console.assert(profile);recordedProfile.setProtocolProfile(profile);recordedProfile.updateStatus('');this.setProfileBeingRecorded(null);} -await SDK.targetManager.resumeAllTargets();this.dispatchEventToListeners(Profiler.ProfileType.Events.ProfileComplete,recordedProfile);} -createProfileLoadedFromFile(title){return new Profiler.SamplingHeapProfileHeader(null,this,title);} -profileBeingRecordedRemoved(){this.stopRecordingProfile();}};Profiler.SamplingHeapProfileType.TypeId='SamplingHeap';Profiler.SamplingHeapProfileHeader=class extends Profiler.WritableProfileHeader{constructor(heapProfilerModel,type,title){super(heapProfilerModel&&heapProfilerModel.debuggerModel(),type,title||Common.UIString('Profile %d',type.nextProfileUid()));this._heapProfilerModel=heapProfilerModel;} -createView(){return new Profiler.HeapProfileView(this);} -protocolProfile(){return this._protocolProfile;}};Profiler.SamplingHeapProfileNode=class extends SDK.ProfileNode{constructor(node){var callFrame=node.callFrame||({functionName:node['functionName'],scriptId:node['scriptId'],url:node['url'],lineNumber:node['lineNumber']-1,columnNumber:node['columnNumber']-1});super(callFrame);this.self=node.selfSize;}};Profiler.SamplingHeapProfileModel=class extends SDK.ProfileTreeModel{constructor(profile){super();this.initialize(translateProfileTree(profile.head));function translateProfileTree(root){var resultRoot=new Profiler.SamplingHeapProfileNode(root);var targetNodeStack=[resultRoot];var sourceNodeStack=[root];while(sourceNodeStack.length){var sourceNode=sourceNodeStack.pop();var parentNode=targetNodeStack.pop();parentNode.children=sourceNode.children.map(child=>new Profiler.SamplingHeapProfileNode(child));sourceNodeStack.push.apply(sourceNodeStack,sourceNode.children);targetNodeStack.push.apply(targetNodeStack,parentNode.children);} -return resultRoot;}}};Profiler.HeapProfileView.NodeFormatter=class{constructor(profileView){this._profileView=profileView;} -formatValue(value){return Number.withThousandsSeparator(value);} -formatPercent(value,node){return Common.UIString('%.2f\xa0%%',value);} -linkifyNode(node){var heapProfilerModel=this._profileView._profileHeader._heapProfilerModel;return this._profileView.linkifier().maybeLinkifyConsoleCallFrame(heapProfilerModel?heapProfilerModel.target():null,node.profileNode.callFrame,'profile-node-file');}};Profiler.HeapFlameChartDataProvider=class extends Profiler.ProfileFlameChartDataProvider{constructor(profile,heapProfilerModel){super();this._profile=profile;this._heapProfilerModel=heapProfilerModel;} -minimumBoundary(){return 0;} -totalTime(){return this._profile.root.total;} -formatValue(value,precision){return Common.UIString('%s\xa0KB',Number.withThousandsSeparator(value/1e3));} -_calculateTimelineData(){function nodesCount(node){return node.children.reduce((count,node)=>count+nodesCount(node),1);} -var count=nodesCount(this._profile.root);var entryNodes=new Array(count);var entryLevels=new Uint16Array(count);var entryTotalTimes=new Float32Array(count);var entryStartTimes=new Float64Array(count);var depth=0;var maxDepth=0;var position=0;var index=0;function addNode(node){var start=position;entryNodes[index]=node;entryLevels[index]=depth;entryTotalTimes[index]=node.total;entryStartTimes[index]=position;++index;++depth;node.children.forEach(addNode);--depth;maxDepth=Math.max(maxDepth,depth);position=start+node.total;} -addNode(this._profile.root);this._maxStackDepth=maxDepth+1;this._entryNodes=entryNodes;this._timelineData=new PerfUI.FlameChart.TimelineData(entryLevels,entryTotalTimes,entryStartTimes,null);return this._timelineData;} -prepareHighlightedEntryInfo(entryIndex){var node=this._entryNodes[entryIndex];if(!node) -return null;var entryInfo=[];function pushEntryInfoRow(title,value){entryInfo.push({title:title,value:value});} -pushEntryInfoRow(Common.UIString('Name'),UI.beautifyFunctionName(node.functionName));pushEntryInfoRow(Common.UIString('Self size'),Number.bytesToString(node.self));pushEntryInfoRow(Common.UIString('Total size'),Number.bytesToString(node.total));var linkifier=new Components.Linkifier();var link=linkifier.maybeLinkifyConsoleCallFrame(this._heapProfilerModel?this._heapProfilerModel.target():null,node.callFrame);if(link) -pushEntryInfoRow(Common.UIString('URL'),link.textContent);linkifier.dispose();return Profiler.ProfileView.buildPopoverTable(entryInfo);}};;Profiler.HeapSnapshotWorkerProxy=class extends Common.Object{constructor(eventHandler){super();this._eventHandler=eventHandler;this._nextObjectId=1;this._nextCallId=1;this._callbacks=new Map();this._previousCallbacks=new Set();this._worker=new Common.Worker('heap_snapshot_worker');this._worker.onmessage=this._messageReceived.bind(this);} -createLoader(profileUid,snapshotReceivedCallback){var objectId=this._nextObjectId++;var proxy=new Profiler.HeapSnapshotLoaderProxy(this,objectId,profileUid,snapshotReceivedCallback);this._postMessage({callId:this._nextCallId++,disposition:'create',objectId:objectId,methodName:'HeapSnapshotWorker.HeapSnapshotLoader'});return proxy;} -dispose(){this._worker.terminate();if(this._interval) -clearInterval(this._interval);} -disposeObject(objectId){this._postMessage({callId:this._nextCallId++,disposition:'dispose',objectId:objectId});} -evaluateForTest(script,callback){var callId=this._nextCallId++;this._callbacks.set(callId,callback);this._postMessage({callId:callId,disposition:'evaluateForTest',source:script});} -callFactoryMethod(callback,objectId,methodName,proxyConstructor){var callId=this._nextCallId++;var methodArguments=Array.prototype.slice.call(arguments,4);var newObjectId=this._nextObjectId++;function wrapCallback(remoteResult){callback(remoteResult?new proxyConstructor(this,newObjectId):null);} -if(callback){this._callbacks.set(callId,wrapCallback.bind(this));this._postMessage({callId:callId,disposition:'factory',objectId:objectId,methodName:methodName,methodArguments:methodArguments,newObjectId:newObjectId});return null;}else{this._postMessage({callId:callId,disposition:'factory',objectId:objectId,methodName:methodName,methodArguments:methodArguments,newObjectId:newObjectId});return new proxyConstructor(this,newObjectId);}} -callMethod(callback,objectId,methodName){var callId=this._nextCallId++;var methodArguments=Array.prototype.slice.call(arguments,3);if(callback) -this._callbacks.set(callId,callback);this._postMessage({callId:callId,disposition:'method',objectId:objectId,methodName:methodName,methodArguments:methodArguments});} -startCheckingForLongRunningCalls(){if(this._interval) -return;this._checkLongRunningCalls();this._interval=setInterval(this._checkLongRunningCalls.bind(this),300);} -_checkLongRunningCalls(){for(var callId of this._previousCallbacks){if(!this._callbacks.has(callId)) -this._previousCallbacks.delete(callId);} -var hasLongRunningCalls=!!this._previousCallbacks.size;this.dispatchEventToListeners(Profiler.HeapSnapshotWorkerProxy.Events.Wait,hasLongRunningCalls);for(var callId of this._callbacks.keysArray()) -this._previousCallbacks.add(callId);} -_messageReceived(event){var data=event.data;if(data.eventName){if(this._eventHandler) -this._eventHandler(data.eventName,data.data);return;} -if(data.error){if(data.errorMethodName){Common.console.error(Common.UIString('An error occurred when a call to method \'%s\' was requested',data.errorMethodName));} -Common.console.error(data['errorCallStack']);this._callbacks.delete(data.callId);return;} -if(!this._callbacks.has(data.callId)) -return;var callback=this._callbacks.get(data.callId);this._callbacks.delete(data.callId);callback(data.result);} -_postMessage(message){this._worker.postMessage(message);}};Profiler.HeapSnapshotWorkerProxy.Events={Wait:Symbol('Wait')};Profiler.HeapSnapshotProxyObject=class{constructor(worker,objectId){this._worker=worker;this._objectId=objectId;} -_callWorker(workerMethodName,args){args.splice(1,0,this._objectId);return this._worker[workerMethodName].apply(this._worker,args);} -dispose(){this._worker.disposeObject(this._objectId);} -disposeWorker(){this._worker.dispose();} -callFactoryMethod(callback,methodName,proxyConstructor,var_args){return this._callWorker('callFactoryMethod',Array.prototype.slice.call(arguments,0));} -_callMethodPromise(methodName,var_args){var args=Array.prototype.slice.call(arguments);return new Promise(resolve=>this._callWorker('callMethod',[resolve,...args]));}};Profiler.HeapSnapshotLoaderProxy=class extends Profiler.HeapSnapshotProxyObject{constructor(worker,objectId,profileUid,snapshotReceivedCallback){super(worker,objectId);this._profileUid=profileUid;this._snapshotReceivedCallback=snapshotReceivedCallback;} -write(chunk){return this._callMethodPromise('write',chunk);} -async close(){await this._callMethodPromise('close');var snapshotProxy=await new Promise(resolve=>this.callFactoryMethod(resolve,'buildSnapshot',Profiler.HeapSnapshotProxy));this.dispose();snapshotProxy.setProfileUid(this._profileUid);await snapshotProxy.updateStaticData();this._snapshotReceivedCallback(snapshotProxy);}};Profiler.HeapSnapshotProxy=class extends Profiler.HeapSnapshotProxyObject{constructor(worker,objectId){super(worker,objectId);this._staticData=null;} -search(searchConfig,filter){return this._callMethodPromise('search',searchConfig,filter);} -aggregatesWithFilter(filter){return this._callMethodPromise('aggregatesWithFilter',filter);} -aggregatesForDiff(){return this._callMethodPromise('aggregatesForDiff');} -calculateSnapshotDiff(baseSnapshotId,baseSnapshotAggregates){return this._callMethodPromise('calculateSnapshotDiff',baseSnapshotId,baseSnapshotAggregates);} -nodeClassName(snapshotObjectId){return this._callMethodPromise('nodeClassName',snapshotObjectId);} -createEdgesProvider(nodeIndex){return this.callFactoryMethod(null,'createEdgesProvider',Profiler.HeapSnapshotProviderProxy,nodeIndex);} -createRetainingEdgesProvider(nodeIndex){return this.callFactoryMethod(null,'createRetainingEdgesProvider',Profiler.HeapSnapshotProviderProxy,nodeIndex);} -createAddedNodesProvider(baseSnapshotId,className){return this.callFactoryMethod(null,'createAddedNodesProvider',Profiler.HeapSnapshotProviderProxy,baseSnapshotId,className);} -createDeletedNodesProvider(nodeIndexes){return this.callFactoryMethod(null,'createDeletedNodesProvider',Profiler.HeapSnapshotProviderProxy,nodeIndexes);} -createNodesProvider(filter){return this.callFactoryMethod(null,'createNodesProvider',Profiler.HeapSnapshotProviderProxy,filter);} -createNodesProviderForClass(className,nodeFilter){return this.callFactoryMethod(null,'createNodesProviderForClass',Profiler.HeapSnapshotProviderProxy,className,nodeFilter);} -allocationTracesTops(){return this._callMethodPromise('allocationTracesTops');} -allocationNodeCallers(nodeId){return this._callMethodPromise('allocationNodeCallers',nodeId);} -allocationStack(nodeIndex){return this._callMethodPromise('allocationStack',nodeIndex);} -dispose(){throw new Error('Should never be called');} -get nodeCount(){return this._staticData.nodeCount;} -get rootNodeIndex(){return this._staticData.rootNodeIndex;} -async updateStaticData(){this._staticData=await this._callMethodPromise('updateStaticData');} -getStatistics(){return this._callMethodPromise('getStatistics');} -getSamples(){return this._callMethodPromise('getSamples');} -get totalSize(){return this._staticData.totalSize;} -get uid(){return this._profileUid;} -setProfileUid(profileUid){this._profileUid=profileUid;} -maxJSObjectId(){return this._staticData.maxJSObjectId;}};Profiler.HeapSnapshotProviderProxy=class extends Profiler.HeapSnapshotP